blob: 0cada0474169b8f089970a97054f518a143ff5a8 [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
5 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +00006 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +00007 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +00008 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +00009 * was re-ported from NetBSD and debianized.
10 *
Eric Andersencb57d552001-06-28 07:25:16 +000011 * This code is derived from software contributed to Berkeley by
12 * Kenneth Almquist.
13 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000014 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersendf82f612001-06-28 07:46:40 +000015 *
Eric Andersen81fe1232003-07-29 06:38:40 +000016 * Original BSD copyright notice is retained at the end of this file.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
37#define IFS_BROKEN
38
39#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000040
Denis Vlasenkob012b102007-02-19 22:43:01 +000041#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000042# ifndef _GNU_SOURCE
43# define _GNU_SOURCE
44# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000045#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000046
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000047#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000048//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000050#include <paths.h>
51#include <setjmp.h>
52#include <fnmatch.h>
Mike Frysinger98c52642009-04-02 10:02:37 +000053#include "math.h"
Denis Vlasenko61befda2008-11-25 01:36:03 +000054
55#if defined SINGLE_APPLET_MAIN
56/* STANDALONE does not make sense, and won't compile */
57#undef CONFIG_FEATURE_SH_STANDALONE
58#undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000059#undef IF_FEATURE_SH_STANDALONE
60#undef IF_NOT_FEATURE_SH_STANDALONE(...)
Denis Vlasenko61befda2008-11-25 01:36:03 +000061#define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000062#define IF_FEATURE_SH_STANDALONE(...)
63#define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000064#endif
65
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000066#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000067# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000068#endif
69
Denis Vlasenkob012b102007-02-19 22:43:01 +000070#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000071# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000072#endif
73
Denis Vlasenkob012b102007-02-19 22:43:01 +000074
Denis Vlasenko01631112007-12-16 17:20:38 +000075/* ============ Hash table sizes. Configurable. */
76
77#define VTABSIZE 39
78#define ATABSIZE 39
79#define CMDTABLESIZE 31 /* should be prime */
80
81
Denis Vlasenkob012b102007-02-19 22:43:01 +000082/* ============ Shell options */
83
84static const char *const optletters_optnames[] = {
85 "e" "errexit",
86 "f" "noglob",
87 "I" "ignoreeof",
88 "i" "interactive",
89 "m" "monitor",
90 "n" "noexec",
91 "s" "stdin",
92 "x" "xtrace",
93 "v" "verbose",
94 "C" "noclobber",
95 "a" "allexport",
96 "b" "notify",
97 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000098 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +000099#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000100 ,"\0" "nolog"
101 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000102#endif
103};
104
105#define optletters(n) optletters_optnames[(n)][0]
106#define optnames(n) (&optletters_optnames[(n)][1])
107
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000108enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109
Eric Andersenc470f442003-07-28 09:56:35 +0000110
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000112
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000113static const char homestr[] ALIGN1 = "HOME";
114static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200115static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000116
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000117/*
Eric Andersenc470f442003-07-28 09:56:35 +0000118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000120 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000121 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
125 */
Eric Andersenc470f442003-07-28 09:56:35 +0000126struct jmploc {
127 jmp_buf loc;
128};
Denis Vlasenko01631112007-12-16 17:20:38 +0000129
130struct globals_misc {
131 /* pid of main shell */
132 int rootpid;
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
134 int shlvl;
135#define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
137
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
140
141 char *arg0; /* value of $0 */
142
143 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000144
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200145 volatile int suppress_int; /* counter */
146 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000147 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200148 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000149 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000150 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000151#define EXINT 0 /* SIGINT received */
152#define EXERROR 1 /* a generic error */
153#define EXSHELLPROC 2 /* execute a shell procedure */
154#define EXEXEC 3 /* command execution failed */
155#define EXEXIT 4 /* exit the shell */
156#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000157
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000159 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000160
161 char optlist[NOPTS];
162#define eflag optlist[0]
163#define fflag optlist[1]
164#define Iflag optlist[2]
165#define iflag optlist[3]
166#define mflag optlist[4]
167#define nflag optlist[5]
168#define sflag optlist[6]
169#define xflag optlist[7]
170#define vflag optlist[8]
171#define Cflag optlist[9]
172#define aflag optlist[10]
173#define bflag optlist[11]
174#define uflag optlist[12]
175#define viflag optlist[13]
176#if DEBUG
177#define nolog optlist[14]
178#define debug optlist[15]
179#endif
180
181 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000182 /*
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000186 */
187 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000188#define S_DFL 1 /* default signal handling (SIG_DFL) */
189#define S_CATCH 2 /* signal is caught */
190#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000191#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000192
Denis Vlasenko01631112007-12-16 17:20:38 +0000193 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000194 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000195 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200196 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000197
198 /* Rarely referenced stuff */
199#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000200 /* Random number generators */
201 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
202 uint32_t random_LCG; /* LCG (fast but weak) */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000203#endif
204 pid_t backgndpid; /* pid of last background process */
205 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000206};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000207extern struct globals_misc *const ash_ptr_to_globals_misc;
208#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000209#define rootpid (G_misc.rootpid )
210#define shlvl (G_misc.shlvl )
211#define minusc (G_misc.minusc )
212#define curdir (G_misc.curdir )
213#define physdir (G_misc.physdir )
214#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000215#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000216#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200217#define suppress_int (G_misc.suppress_int )
218#define pending_int (G_misc.pending_int )
219#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000220#define isloginsh (G_misc.isloginsh )
221#define nullstr (G_misc.nullstr )
222#define optlist (G_misc.optlist )
223#define sigmode (G_misc.sigmode )
224#define gotsig (G_misc.gotsig )
225#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200226#define trap_ptr (G_misc.trap_ptr )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000227#define random_galois_LFSR (G_misc.random_galois_LFSR)
228#define random_LCG (G_misc.random_LCG )
229#define backgndpid (G_misc.backgndpid )
230#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000231#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000232 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
233 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000234 curdir = nullstr; \
235 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200236 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000237} while (0)
238
239
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000240/* ============ DEBUG */
241#if DEBUG
242static void trace_printf(const char *fmt, ...);
243static void trace_vprintf(const char *fmt, va_list va);
244# define TRACE(param) trace_printf param
245# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000246# define close(fd) do { \
247 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000248 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200249 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000250 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000251} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252#else
253# define TRACE(param)
254# define TRACEV(param)
255#endif
256
257
Denis Vlasenko559691a2008-10-05 18:39:31 +0000258/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000259#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
260
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200261/* C99 says: "char" declaration may be signed or unsigned by default */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000262#define signed_char2int(sc) ((int)(signed char)(sc))
263
Denis Vlasenko559691a2008-10-05 18:39:31 +0000264static int isdigit_str9(const char *str)
265{
266 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
267 while (--maxlen && isdigit(*str))
268 str++;
269 return (*str == '\0');
270}
Denis Vlasenko01631112007-12-16 17:20:38 +0000271
Denis Vlasenko559691a2008-10-05 18:39:31 +0000272
273/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000274/*
Eric Andersen2870d962001-07-02 17:27:21 +0000275 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000276 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
279 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000280#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200281 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000282 xbarrier(); \
283} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000284
285/*
286 * Called to raise an exception. Since C doesn't include exceptions, we
287 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000288 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000289 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000290static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000291static void
292raise_exception(int e)
293{
294#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000295 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000296 abort();
297#endif
298 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000299 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000300 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000302#if DEBUG
303#define raise_exception(e) do { \
304 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
305 raise_exception(e); \
306} while (0)
307#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308
309/*
310 * Called from trap.c when a SIGINT is received. (If the user specifies
311 * that SIGINT is to be trapped or ignored using the trap builtin, then
312 * this routine is not called.) Suppressint is nonzero when interrupts
313 * are held using the INT_OFF macro. (The test for iflag is just
314 * defensive programming.)
315 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000316static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317static void
318raise_interrupt(void)
319{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000320 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000321
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200322 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000323 /* Signal is not automatically unmasked after it is raised,
324 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000325 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200326 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000327
Denis Vlasenko4b875702009-03-19 13:30:04 +0000328 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
330 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000331 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000332 signal(SIGINT, SIG_DFL);
333 raise(SIGINT);
334 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000335 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000336 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 /* NOTREACHED */
339}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000340#if DEBUG
341#define raise_interrupt() do { \
342 TRACE(("raising interrupt on line %d\n", __LINE__)); \
343 raise_interrupt(); \
344} while (0)
345#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000347static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000348int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000350 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200351 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000352 raise_interrupt();
353 }
354}
355#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000356static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000357force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000358{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000359 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200360 suppress_int = 0;
361 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000362 raise_interrupt();
363}
364#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000365
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200366#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000367
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000368#define RESTORE_INT(v) do { \
369 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200370 suppress_int = (v); \
371 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000372 raise_interrupt(); \
373} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000374
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000375
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000376/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000377
Eric Andersenc470f442003-07-28 09:56:35 +0000378static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000380{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000381 INT_OFF;
382 fputs(p, file);
383 INT_ON;
384}
385
386static void
387flush_stdout_stderr(void)
388{
389 INT_OFF;
390 fflush(stdout);
391 fflush(stderr);
392 INT_ON;
393}
394
395static void
396flush_stderr(void)
397{
398 INT_OFF;
399 fflush(stderr);
400 INT_ON;
401}
402
403static void
404outcslow(int c, FILE *dest)
405{
406 INT_OFF;
407 putc(c, dest);
408 fflush(dest);
409 INT_ON;
410}
411
412static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
413static int
414out1fmt(const char *fmt, ...)
415{
416 va_list ap;
417 int r;
418
419 INT_OFF;
420 va_start(ap, fmt);
421 r = vprintf(fmt, ap);
422 va_end(ap);
423 INT_ON;
424 return r;
425}
426
427static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
428static int
429fmtstr(char *outbuf, size_t length, const char *fmt, ...)
430{
431 va_list ap;
432 int ret;
433
434 va_start(ap, fmt);
435 INT_OFF;
436 ret = vsnprintf(outbuf, length, fmt, ap);
437 va_end(ap);
438 INT_ON;
439 return ret;
440}
441
442static void
443out1str(const char *p)
444{
445 outstr(p, stdout);
446}
447
448static void
449out2str(const char *p)
450{
451 outstr(p, stderr);
452 flush_stderr();
453}
454
455
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000456/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000457
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000458/* control characters in argument strings */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200459#define CTLESC ((unsigned char)'\201') /* escape next character */
460#define CTLVAR ((unsigned char)'\202') /* variable defn */
461#define CTLENDVAR ((unsigned char)'\203')
462#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000463#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200465#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466#define CTLENDARI ((unsigned char)'\207')
467#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000468
469/* variable substitution byte (follows CTLVAR) */
470#define VSTYPE 0x0f /* type of variable substitution */
471#define VSNUL 0x10 /* colon--treat the empty string as unset */
472#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
473
474/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000475#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476#define VSMINUS 0x2 /* ${var-text} */
477#define VSPLUS 0x3 /* ${var+text} */
478#define VSQUESTION 0x4 /* ${var?message} */
479#define VSASSIGN 0x5 /* ${var=text} */
480#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482#define VSTRIMLEFT 0x8 /* ${var#pattern} */
483#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484#define VSLENGTH 0xa /* ${#var} */
485#if ENABLE_ASH_BASH_COMPAT
486#define VSSUBSTR 0xc /* ${var:position:length} */
487#define VSREPLACE 0xd /* ${var/pattern/replacement} */
488#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
489#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000490
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000491static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
493};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000494
Denis Vlasenko559691a2008-10-05 18:39:31 +0000495#define NCMD 0
496#define NPIPE 1
497#define NREDIR 2
498#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000499#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000500#define NAND 5
501#define NOR 6
502#define NSEMI 7
503#define NIF 8
504#define NWHILE 9
505#define NUNTIL 10
506#define NFOR 11
507#define NCASE 12
508#define NCLIST 13
509#define NDEFUN 14
510#define NARG 15
511#define NTO 16
512#if ENABLE_ASH_BASH_COMPAT
513#define NTO2 17
514#endif
515#define NCLOBBER 18
516#define NFROM 19
517#define NFROMTO 20
518#define NAPPEND 21
519#define NTOFD 22
520#define NFROMFD 23
521#define NHERE 24
522#define NXHERE 25
523#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000524#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000525
526union node;
527
528struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000529 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530 union node *assign;
531 union node *args;
532 union node *redirect;
533};
534
535struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000536 smallint type;
537 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000538 struct nodelist *cmdlist;
539};
540
541struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000542 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000543 union node *n;
544 union node *redirect;
545};
546
547struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000548 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000549 union node *ch1;
550 union node *ch2;
551};
552
553struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000554 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000555 union node *test;
556 union node *ifpart;
557 union node *elsepart;
558};
559
560struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000561 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000562 union node *args;
563 union node *body;
564 char *var;
565};
566
567struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000568 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000569 union node *expr;
570 union node *cases;
571};
572
573struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000574 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000575 union node *next;
576 union node *pattern;
577 union node *body;
578};
579
580struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000581 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000582 union node *next;
583 char *text;
584 struct nodelist *backquote;
585};
586
Denis Vlasenko559691a2008-10-05 18:39:31 +0000587/* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
590 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000591struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000592 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593 union node *next;
594 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000595 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596 union node *fname;
597 char *expfname;
598};
599
600struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000601 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000602 union node *next;
603 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000604 int dupfd;
605 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000606 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000607};
608
609struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000610 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000611 union node *next;
612 int fd;
613 union node *doc;
614};
615
616struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000617 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000618 union node *com;
619};
620
621union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000622 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000623 struct ncmd ncmd;
624 struct npipe npipe;
625 struct nredir nredir;
626 struct nbinary nbinary;
627 struct nif nif;
628 struct nfor nfor;
629 struct ncase ncase;
630 struct nclist nclist;
631 struct narg narg;
632 struct nfile nfile;
633 struct ndup ndup;
634 struct nhere nhere;
635 struct nnot nnot;
636};
637
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200638/*
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
641 */
642#define NODE_EOF ((union node *) -1L)
643
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000644struct nodelist {
645 struct nodelist *next;
646 union node *n;
647};
648
649struct funcnode {
650 int count;
651 union node n;
652};
653
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000654/*
655 * Free a parse tree.
656 */
657static void
658freefunc(struct funcnode *f)
659{
660 if (f && --f->count < 0)
661 free(f);
662}
663
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000664
665/* ============ Debugging output */
666
667#if DEBUG
668
669static FILE *tracefile;
670
671static void
672trace_printf(const char *fmt, ...)
673{
674 va_list va;
675
676 if (debug != 1)
677 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000678 if (DEBUG_TIME)
679 fprintf(tracefile, "%u ", (int) time(NULL));
680 if (DEBUG_PID)
681 fprintf(tracefile, "[%u] ", (int) getpid());
682 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000684 va_start(va, fmt);
685 vfprintf(tracefile, fmt, va);
686 va_end(va);
687}
688
689static void
690trace_vprintf(const char *fmt, va_list va)
691{
692 if (debug != 1)
693 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000694 if (DEBUG_TIME)
695 fprintf(tracefile, "%u ", (int) time(NULL));
696 if (DEBUG_PID)
697 fprintf(tracefile, "[%u] ", (int) getpid());
698 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000700 vfprintf(tracefile, fmt, va);
701}
702
703static void
704trace_puts(const char *s)
705{
706 if (debug != 1)
707 return;
708 fputs(s, tracefile);
709}
710
711static void
712trace_puts_quoted(char *s)
713{
714 char *p;
715 char c;
716
717 if (debug != 1)
718 return;
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
721 switch (*p) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '"': c = '"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
732 backslash:
733 putc('\\', tracefile);
734 putc(c, tracefile);
735 break;
736 default:
737 if (*p >= ' ' && *p <= '~')
738 putc(*p, tracefile);
739 else {
740 putc('\\', tracefile);
741 putc(*p >> 6 & 03, tracefile);
742 putc(*p >> 3 & 07, tracefile);
743 putc(*p & 07, tracefile);
744 }
745 break;
746 }
747 }
748 putc('"', tracefile);
749}
750
751static void
752trace_puts_args(char **ap)
753{
754 if (debug != 1)
755 return;
756 if (!*ap)
757 return;
758 while (1) {
759 trace_puts_quoted(*ap);
760 if (!*++ap) {
761 putc('\n', tracefile);
762 break;
763 }
764 putc(' ', tracefile);
765 }
766}
767
768static void
769opentrace(void)
770{
771 char s[100];
772#ifdef O_APPEND
773 int flags;
774#endif
775
776 if (debug != 1) {
777 if (tracefile)
778 fflush(tracefile);
779 /* leave open because libedit might be using it */
780 return;
781 }
782 strcpy(s, "./trace");
783 if (tracefile) {
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
786 debug = 0;
787 return;
788 }
789 } else {
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
793 debug = 0;
794 return;
795 }
796 }
797#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000798 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000799 if (flags >= 0)
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
801#endif
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
804}
805
806static void
807indent(int amount, char *pfx, FILE *fp)
808{
809 int i;
810
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
813 fputs(pfx, fp);
814 putc('\t', fp);
815 }
816}
817
818/* little circular references here... */
819static void shtree(union node *n, int ind, char *pfx, FILE *fp);
820
821static void
822sharg(union node *arg, FILE *fp)
823{
824 char *p;
825 struct nodelist *bqlist;
826 int subtype;
827
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
830 abort();
831 }
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
834 switch (*p) {
835 case CTLESC:
836 putc(*++p, fp);
837 break;
838 case CTLVAR:
839 putc('$', fp);
840 putc('{', fp);
841 subtype = *++p;
842 if (subtype == VSLENGTH)
843 putc('#', fp);
844
845 while (*p != '=')
846 putc(*p++, fp);
847
848 if (subtype & VSNUL)
849 putc(':', fp);
850
851 switch (subtype & VSTYPE) {
852 case VSNORMAL:
853 putc('}', fp);
854 break;
855 case VSMINUS:
856 putc('-', fp);
857 break;
858 case VSPLUS:
859 putc('+', fp);
860 break;
861 case VSQUESTION:
862 putc('?', fp);
863 break;
864 case VSASSIGN:
865 putc('=', fp);
866 break;
867 case VSTRIMLEFT:
868 putc('#', fp);
869 break;
870 case VSTRIMLEFTMAX:
871 putc('#', fp);
872 putc('#', fp);
873 break;
874 case VSTRIMRIGHT:
875 putc('%', fp);
876 break;
877 case VSTRIMRIGHTMAX:
878 putc('%', fp);
879 putc('%', fp);
880 break;
881 case VSLENGTH:
882 break;
883 default:
884 out1fmt("<subtype %d>", subtype);
885 }
886 break;
887 case CTLENDVAR:
888 putc('}', fp);
889 break;
890 case CTLBACKQ:
891 case CTLBACKQ|CTLQUOTE:
892 putc('$', fp);
893 putc('(', fp);
894 shtree(bqlist->n, -1, NULL, fp);
895 putc(')', fp);
896 break;
897 default:
898 putc(*p, fp);
899 break;
900 }
901 }
902}
903
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200904static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000905shcmd(union node *cmd, FILE *fp)
906{
907 union node *np;
908 int first;
909 const char *s;
910 int dftfd;
911
912 first = 1;
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000914 if (!first)
915 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000916 sharg(np, fp);
917 first = 0;
918 }
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000920 if (!first)
921 putc(' ', fp);
922 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000923 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000927#if ENABLE_ASH_BASH_COMPAT
928 case NTO2:
929#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000930 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000931 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000935 }
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
938 fputs(s, fp);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
941 } else {
942 sharg(np->nfile.fname, fp);
943 }
944 first = 0;
945 }
946}
947
948static void
949shtree(union node *n, int ind, char *pfx, FILE *fp)
950{
951 struct nodelist *lp;
952 const char *s;
953
954 if (n == NULL)
955 return;
956
957 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200958
959 if (n == NODE_EOF) {
960 fputs("<EOF>", fp);
961 return;
962 }
963
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000964 switch (n->type) {
965 case NSEMI:
966 s = "; ";
967 goto binop;
968 case NAND:
969 s = " && ";
970 goto binop;
971 case NOR:
972 s = " || ";
973 binop:
974 shtree(n->nbinary.ch1, ind, NULL, fp);
975 /* if (ind < 0) */
976 fputs(s, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
978 break;
979 case NCMD:
980 shcmd(n, fp);
981 if (ind >= 0)
982 putc('\n', fp);
983 break;
984 case NPIPE:
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200986 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000987 if (lp->next)
988 fputs(" | ", fp);
989 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000990 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000991 fputs(" &", fp);
992 if (ind >= 0)
993 putc('\n', fp);
994 break;
995 default:
996 fprintf(fp, "<node type %d>", n->type);
997 if (ind >= 0)
998 putc('\n', fp);
999 break;
1000 }
1001}
1002
1003static void
1004showtree(union node *n)
1005{
1006 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001007 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001008}
1009
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010#endif /* DEBUG */
1011
1012
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001013/* ============ Parser data */
1014
1015/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1017 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001018struct strlist {
1019 struct strlist *next;
1020 char *text;
1021};
1022
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001023struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001024
Denis Vlasenkob012b102007-02-19 22:43:01 +00001025struct strpush {
1026 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001027 char *prev_string;
1028 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001029#if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1031#endif
1032 char *string; /* remember the string since it may change */
1033};
1034
1035struct parsefile {
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1045};
1046
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001047static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001048static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001049static int startlinno; /* line # where last token started */
1050static char *commandname; /* currently executing command */
1051static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001052static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001053
1054
1055/* ============ Message printing */
1056
1057static void
1058ash_vmsg(const char *msg, va_list ap)
1059{
1060 fprintf(stderr, "%s: ", arg0);
1061 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001064 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001065 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001066 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001069}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001070
1071/*
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1075 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001076static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077static void
1078ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001079{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080#if DEBUG
1081 if (msg) {
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1083 TRACEV((msg, ap));
1084 TRACE(("\") pid=%d\n", getpid()));
1085 } else
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1087 if (msg)
1088#endif
1089 ash_vmsg(msg, ap);
1090
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1093 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001094}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001095
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001096static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097static void
1098ash_msg_and_raise_error(const char *msg, ...)
1099{
1100 va_list ap;
1101
1102 va_start(ap, msg);
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1104 /* NOTREACHED */
1105 va_end(ap);
1106}
1107
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001108static void raise_error_syntax(const char *) NORETURN;
1109static void
1110raise_error_syntax(const char *msg)
1111{
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1113 /* NOTREACHED */
1114}
1115
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001116static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001117static void
1118ash_msg_and_raise(int cond, const char *msg, ...)
1119{
1120 va_list ap;
1121
1122 va_start(ap, msg);
1123 ash_vmsg_and_raise(cond, msg, ap);
1124 /* NOTREACHED */
1125 va_end(ap);
1126}
1127
1128/*
1129 * error/warning routines for external builtins
1130 */
1131static void
1132ash_msg(const char *fmt, ...)
1133{
1134 va_list ap;
1135
1136 va_start(ap, fmt);
1137 ash_vmsg(fmt, ap);
1138 va_end(ap);
1139}
1140
1141/*
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1145 */
1146static const char *
1147errmsg(int e, const char *em)
1148{
1149 if (e == ENOENT || e == ENOTDIR) {
1150 return em;
1151 }
1152 return strerror(e);
1153}
1154
1155
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001156/* ============ Memory allocation */
1157
1158/*
1159 * It appears that grabstackstr() will barf with such alignments
1160 * because stalloc() will return a string allocated in a new stackblock.
1161 */
1162#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1163enum {
1164 /* Most machines require the value returned from malloc to be aligned
1165 * in some way. The following macro will get this right
1166 * on many machines. */
1167 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1168 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001169 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001170};
1171
1172struct stack_block {
1173 struct stack_block *prev;
1174 char space[MINSIZE];
1175};
1176
1177struct stackmark {
1178 struct stack_block *stackp;
1179 char *stacknxt;
1180 size_t stacknleft;
1181 struct stackmark *marknext;
1182};
1183
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001184
Denis Vlasenko01631112007-12-16 17:20:38 +00001185struct globals_memstack {
1186 struct stack_block *g_stackp; // = &stackbase;
1187 struct stackmark *markp;
1188 char *g_stacknxt; // = stackbase.space;
1189 char *sstrend; // = stackbase.space + MINSIZE;
1190 size_t g_stacknleft; // = MINSIZE;
1191 int herefd; // = -1;
1192 struct stack_block stackbase;
1193};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001194extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1195#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001196#define g_stackp (G_memstack.g_stackp )
1197#define markp (G_memstack.markp )
1198#define g_stacknxt (G_memstack.g_stacknxt )
1199#define sstrend (G_memstack.sstrend )
1200#define g_stacknleft (G_memstack.g_stacknleft)
1201#define herefd (G_memstack.herefd )
1202#define stackbase (G_memstack.stackbase )
1203#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001204 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1205 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001206 g_stackp = &stackbase; \
1207 g_stacknxt = stackbase.space; \
1208 g_stacknleft = MINSIZE; \
1209 sstrend = stackbase.space + MINSIZE; \
1210 herefd = -1; \
1211} while (0)
1212
1213#define stackblock() ((void *)g_stacknxt)
1214#define stackblocksize() g_stacknleft
1215
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001216
1217static void *
1218ckrealloc(void * p, size_t nbytes)
1219{
1220 p = realloc(p, nbytes);
1221 if (!p)
1222 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1223 return p;
1224}
1225
1226static void *
1227ckmalloc(size_t nbytes)
1228{
1229 return ckrealloc(NULL, nbytes);
1230}
1231
Denis Vlasenko597906c2008-02-20 16:38:54 +00001232static void *
1233ckzalloc(size_t nbytes)
1234{
1235 return memset(ckmalloc(nbytes), 0, nbytes);
1236}
1237
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001238/*
1239 * Make a copy of a string in safe storage.
1240 */
1241static char *
1242ckstrdup(const char *s)
1243{
1244 char *p = strdup(s);
1245 if (!p)
1246 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1247 return p;
1248}
1249
1250/*
1251 * Parse trees for commands are allocated in lifo order, so we use a stack
1252 * to make this more efficient, and also to avoid all sorts of exception
1253 * handling code to handle interrupts in the middle of a parse.
1254 *
1255 * The size 504 was chosen because the Ultrix malloc handles that size
1256 * well.
1257 */
1258static void *
1259stalloc(size_t nbytes)
1260{
1261 char *p;
1262 size_t aligned;
1263
1264 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001265 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001266 size_t len;
1267 size_t blocksize;
1268 struct stack_block *sp;
1269
1270 blocksize = aligned;
1271 if (blocksize < MINSIZE)
1272 blocksize = MINSIZE;
1273 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1274 if (len < blocksize)
1275 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1276 INT_OFF;
1277 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001278 sp->prev = g_stackp;
1279 g_stacknxt = sp->space;
1280 g_stacknleft = blocksize;
1281 sstrend = g_stacknxt + blocksize;
1282 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001283 INT_ON;
1284 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001285 p = g_stacknxt;
1286 g_stacknxt += aligned;
1287 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001288 return p;
1289}
1290
Denis Vlasenko597906c2008-02-20 16:38:54 +00001291static void *
1292stzalloc(size_t nbytes)
1293{
1294 return memset(stalloc(nbytes), 0, nbytes);
1295}
1296
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001297static void
1298stunalloc(void *p)
1299{
1300#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001301 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001302 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001303 abort();
1304 }
1305#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001306 g_stacknleft += g_stacknxt - (char *)p;
1307 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001308}
1309
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001310/*
1311 * Like strdup but works with the ash stack.
1312 */
1313static char *
1314ststrdup(const char *p)
1315{
1316 size_t len = strlen(p) + 1;
1317 return memcpy(stalloc(len), p, len);
1318}
1319
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001320static void
1321setstackmark(struct stackmark *mark)
1322{
Denis Vlasenko01631112007-12-16 17:20:38 +00001323 mark->stackp = g_stackp;
1324 mark->stacknxt = g_stacknxt;
1325 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001326 mark->marknext = markp;
1327 markp = mark;
1328}
1329
1330static void
1331popstackmark(struct stackmark *mark)
1332{
1333 struct stack_block *sp;
1334
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001335 if (!mark->stackp)
1336 return;
1337
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338 INT_OFF;
1339 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001340 while (g_stackp != mark->stackp) {
1341 sp = g_stackp;
1342 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001343 free(sp);
1344 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001345 g_stacknxt = mark->stacknxt;
1346 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001347 sstrend = mark->stacknxt + mark->stacknleft;
1348 INT_ON;
1349}
1350
1351/*
1352 * When the parser reads in a string, it wants to stick the string on the
1353 * stack and only adjust the stack pointer when it knows how big the
1354 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1355 * of space on top of the stack and stackblocklen returns the length of
1356 * this block. Growstackblock will grow this space by at least one byte,
1357 * possibly moving it (like realloc). Grabstackblock actually allocates the
1358 * part of the block that has been used.
1359 */
1360static void
1361growstackblock(void)
1362{
1363 size_t newlen;
1364
Denis Vlasenko01631112007-12-16 17:20:38 +00001365 newlen = g_stacknleft * 2;
1366 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001367 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1368 if (newlen < 128)
1369 newlen += 128;
1370
Denis Vlasenko01631112007-12-16 17:20:38 +00001371 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001372 struct stack_block *oldstackp;
1373 struct stackmark *xmark;
1374 struct stack_block *sp;
1375 struct stack_block *prevstackp;
1376 size_t grosslen;
1377
1378 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001379 oldstackp = g_stackp;
1380 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001381 prevstackp = sp->prev;
1382 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1383 sp = ckrealloc(sp, grosslen);
1384 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001385 g_stackp = sp;
1386 g_stacknxt = sp->space;
1387 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001388 sstrend = sp->space + newlen;
1389
1390 /*
1391 * Stack marks pointing to the start of the old block
1392 * must be relocated to point to the new block
1393 */
1394 xmark = markp;
1395 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001396 xmark->stackp = g_stackp;
1397 xmark->stacknxt = g_stacknxt;
1398 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001399 xmark = xmark->marknext;
1400 }
1401 INT_ON;
1402 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001403 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001404 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001405 char *p = stalloc(newlen);
1406
1407 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 g_stacknxt = memcpy(p, oldspace, oldlen);
1409 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001410 }
1411}
1412
1413static void
1414grabstackblock(size_t len)
1415{
1416 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001417 g_stacknxt += len;
1418 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001419}
1420
1421/*
1422 * The following routines are somewhat easier to use than the above.
1423 * The user declares a variable of type STACKSTR, which may be declared
1424 * to be a register. The macro STARTSTACKSTR initializes things. Then
1425 * the user uses the macro STPUTC to add characters to the string. In
1426 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1427 * grown as necessary. When the user is done, she can just leave the
1428 * string there and refer to it using stackblock(). Or she can allocate
1429 * the space for it using grabstackstr(). If it is necessary to allow
1430 * someone else to use the stack temporarily and then continue to grow
1431 * the string, the user should use grabstack to allocate the space, and
1432 * then call ungrabstr(p) to return to the previous mode of operation.
1433 *
1434 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1435 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1436 * is space for at least one character.
1437 */
1438static void *
1439growstackstr(void)
1440{
1441 size_t len = stackblocksize();
1442 if (herefd >= 0 && len >= 1024) {
1443 full_write(herefd, stackblock(), len);
1444 return stackblock();
1445 }
1446 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001447 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001448}
1449
1450/*
1451 * Called from CHECKSTRSPACE.
1452 */
1453static char *
1454makestrspace(size_t newlen, char *p)
1455{
Denis Vlasenko01631112007-12-16 17:20:38 +00001456 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001457 size_t size = stackblocksize();
1458
1459 for (;;) {
1460 size_t nleft;
1461
1462 size = stackblocksize();
1463 nleft = size - len;
1464 if (nleft >= newlen)
1465 break;
1466 growstackblock();
1467 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001468 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001469}
1470
1471static char *
1472stack_nputstr(const char *s, size_t n, char *p)
1473{
1474 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001475 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001476 return p;
1477}
1478
1479static char *
1480stack_putstr(const char *s, char *p)
1481{
1482 return stack_nputstr(s, strlen(s), p);
1483}
1484
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001485static char *
1486_STPUTC(int c, char *p)
1487{
1488 if (p == sstrend)
1489 p = growstackstr();
1490 *p++ = c;
1491 return p;
1492}
1493
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001494#define STARTSTACKSTR(p) ((p) = stackblock())
1495#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001496#define CHECKSTRSPACE(n, p) do { \
1497 char *q = (p); \
1498 size_t l = (n); \
1499 size_t m = sstrend - q; \
1500 if (l > m) \
1501 (p) = makestrspace(l, q); \
1502} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001503#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001504#define STACKSTRNUL(p) do { \
1505 if ((p) == sstrend) \
1506 (p) = growstackstr(); \
1507 *(p) = '\0'; \
1508} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001509#define STUNPUTC(p) (--(p))
1510#define STTOPC(p) ((p)[-1])
1511#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001512
1513#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001514#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001515#define stackstrend() ((void *)sstrend)
1516
1517
1518/* ============ String helpers */
1519
1520/*
1521 * prefix -- see if pfx is a prefix of string.
1522 */
1523static char *
1524prefix(const char *string, const char *pfx)
1525{
1526 while (*pfx) {
1527 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001528 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001529 }
1530 return (char *) string;
1531}
1532
1533/*
1534 * Check for a valid number. This should be elsewhere.
1535 */
1536static int
1537is_number(const char *p)
1538{
1539 do {
1540 if (!isdigit(*p))
1541 return 0;
1542 } while (*++p != '\0');
1543 return 1;
1544}
1545
1546/*
1547 * Convert a string of digits to an integer, printing an error message on
1548 * failure.
1549 */
1550static int
1551number(const char *s)
1552{
1553 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001554 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001555 return atoi(s);
1556}
1557
1558/*
1559 * Produce a possibly single quoted string suitable as input to the shell.
1560 * The return string is allocated on the stack.
1561 */
1562static char *
1563single_quote(const char *s)
1564{
1565 char *p;
1566
1567 STARTSTACKSTR(p);
1568
1569 do {
1570 char *q;
1571 size_t len;
1572
1573 len = strchrnul(s, '\'') - s;
1574
1575 q = p = makestrspace(len + 3, p);
1576
1577 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001578 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001579 *q++ = '\'';
1580 s += len;
1581
1582 STADJUST(q - p, p);
1583
1584 len = strspn(s, "'");
1585 if (!len)
1586 break;
1587
1588 q = p = makestrspace(len + 3, p);
1589
1590 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001591 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001592 *q++ = '"';
1593 s += len;
1594
1595 STADJUST(q - p, p);
1596 } while (*s);
1597
1598 USTPUTC(0, p);
1599
1600 return stackblock();
1601}
1602
1603
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001604/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605
1606static char **argptr; /* argument list for builtin commands */
1607static char *optionarg; /* set by nextopt (like getopt) */
1608static char *optptr; /* used by nextopt */
1609
1610/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001611 * XXX - should get rid of. Have all builtins use getopt(3).
1612 * The library getopt must have the BSD extension static variable
1613 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001614 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001615 * Standard option processing (a la getopt) for builtin routines.
1616 * The only argument that is passed to nextopt is the option string;
1617 * the other arguments are unnecessary. It returns the character,
1618 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001619 */
1620static int
1621nextopt(const char *optstring)
1622{
1623 char *p;
1624 const char *q;
1625 char c;
1626
1627 p = optptr;
1628 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001629 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001630 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001631 if (p == NULL)
1632 return '\0';
1633 if (*p != '-')
1634 return '\0';
1635 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001636 return '\0';
1637 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001638 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001639 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001640 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001641 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001642 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001643 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001644 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001645 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001646 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001647 if (*++q == ':')
1648 q++;
1649 }
1650 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001651 if (*p == '\0') {
1652 p = *argptr++;
1653 if (p == NULL)
1654 ash_msg_and_raise_error("no arg for -%c option", c);
1655 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 optionarg = p;
1657 p = NULL;
1658 }
1659 optptr = p;
1660 return c;
1661}
1662
1663
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001664/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001665
Denis Vlasenko01631112007-12-16 17:20:38 +00001666/*
1667 * The parsefile structure pointed to by the global variable parsefile
1668 * contains information about the current file being read.
1669 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001670struct shparam {
1671 int nparam; /* # of positional parameters (without $0) */
1672#if ENABLE_ASH_GETOPTS
1673 int optind; /* next parameter to be processed by getopts */
1674 int optoff; /* used by getopts */
1675#endif
1676 unsigned char malloced; /* if parameter list dynamically allocated */
1677 char **p; /* parameter list */
1678};
1679
1680/*
1681 * Free the list of positional parameters.
1682 */
1683static void
1684freeparam(volatile struct shparam *param)
1685{
Denis Vlasenko01631112007-12-16 17:20:38 +00001686 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001687 char **ap, **ap1;
1688 ap = ap1 = param->p;
1689 while (*ap)
1690 free(*ap++);
1691 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001692 }
1693}
1694
1695#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001696static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001697#endif
1698
1699struct var {
1700 struct var *next; /* next entry in hash list */
1701 int flags; /* flags are defined above */
1702 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001703 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001704 /* the variable gets set/unset */
1705};
1706
1707struct localvar {
1708 struct localvar *next; /* next local variable in list */
1709 struct var *vp; /* the variable that was made local */
1710 int flags; /* saved flags */
1711 const char *text; /* saved text */
1712};
1713
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001714/* flags */
1715#define VEXPORT 0x01 /* variable is exported */
1716#define VREADONLY 0x02 /* variable cannot be modified */
1717#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1718#define VTEXTFIXED 0x08 /* text is statically allocated */
1719#define VSTACK 0x10 /* text is allocated on the stack */
1720#define VUNSET 0x20 /* the variable is not set */
1721#define VNOFUNC 0x40 /* don't call the callback function */
1722#define VNOSET 0x80 /* do not set variable - just readonly test */
1723#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001724#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001725# define VDYNAMIC 0x200 /* dynamic variable */
1726#else
1727# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001728#endif
1729
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001730#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001731static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001732#define defifs (defifsvar + 4)
1733#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001734static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001735#endif
1736
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001737
Denis Vlasenko01631112007-12-16 17:20:38 +00001738/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001739#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001740static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001741change_lc_all(const char *value)
1742{
1743 if (value && *value != '\0')
1744 setlocale(LC_ALL, value);
1745}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001746static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001747change_lc_ctype(const char *value)
1748{
1749 if (value && *value != '\0')
1750 setlocale(LC_CTYPE, value);
1751}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001752#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001753#if ENABLE_ASH_MAIL
1754static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001755static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001756#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001757static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001758#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001759static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001760#endif
1761
Denis Vlasenko01631112007-12-16 17:20:38 +00001762static const struct {
1763 int flags;
1764 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001765 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001766} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001767#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001768 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001770 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001771#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001773 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001775#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001776 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1777 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1778 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001780#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001781 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#endif
1783#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001784 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#endif
1786#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001787 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#endif
1790#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001791 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#endif
1793};
1794
Denis Vlasenko0b769642008-07-24 07:54:57 +00001795struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001796
1797struct globals_var {
1798 struct shparam shellparam; /* $@ current positional parameters */
1799 struct redirtab *redirlist;
1800 int g_nullredirs;
1801 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1802 struct var *vartab[VTABSIZE];
1803 struct var varinit[ARRAY_SIZE(varinit_data)];
1804};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001805extern struct globals_var *const ash_ptr_to_globals_var;
1806#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001807#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001808//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001809#define g_nullredirs (G_var.g_nullredirs )
1810#define preverrout_fd (G_var.preverrout_fd)
1811#define vartab (G_var.vartab )
1812#define varinit (G_var.varinit )
1813#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001814 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001815 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1816 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001817 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1818 varinit[i].flags = varinit_data[i].flags; \
1819 varinit[i].text = varinit_data[i].text; \
1820 varinit[i].func = varinit_data[i].func; \
1821 } \
1822} while (0)
1823
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001824#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001825#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001826# define vmail (&vifs)[1]
1827# define vmpath (&vmail)[1]
1828# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001829#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001830# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001831#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001832#define vps1 (&vpath)[1]
1833#define vps2 (&vps1)[1]
1834#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836# define voptind (&vps4)[1]
1837# if ENABLE_ASH_RANDOM_SUPPORT
1838# define vrandom (&voptind)[1]
1839# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001840#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001841# if ENABLE_ASH_RANDOM_SUPPORT
1842# define vrandom (&vps4)[1]
1843# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845
1846/*
1847 * The following macros access the values of the above variables.
1848 * They have to skip over the name. They return the null string
1849 * for unset variables.
1850 */
1851#define ifsval() (vifs.text + 4)
1852#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001853#if ENABLE_ASH_MAIL
1854# define mailval() (vmail.text + 5)
1855# define mpathval() (vmpath.text + 9)
1856# define mpathset() ((vmpath.flags & VUNSET) == 0)
1857#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001858#define pathval() (vpath.text + 5)
1859#define ps1val() (vps1.text + 4)
1860#define ps2val() (vps2.text + 4)
1861#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001862#if ENABLE_ASH_GETOPTS
1863# define optindval() (voptind.text + 7)
1864#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001865
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001866
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1868#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1869
Denis Vlasenko01631112007-12-16 17:20:38 +00001870#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001871static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001872getoptsreset(const char *value)
1873{
1874 shellparam.optind = number(value);
1875 shellparam.optoff = -1;
1876}
1877#endif
1878
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001879/*
1880 * Return of a legal variable name (a letter or underscore followed by zero or
1881 * more letters, underscores, and digits).
1882 */
1883static char *
1884endofname(const char *name)
1885{
1886 char *p;
1887
1888 p = (char *) name;
1889 if (!is_name(*p))
1890 return p;
1891 while (*++p) {
1892 if (!is_in_name(*p))
1893 break;
1894 }
1895 return p;
1896}
1897
1898/*
1899 * Compares two strings up to the first = or '\0'. The first
1900 * string must be terminated by '='; the second may be terminated by
1901 * either '=' or '\0'.
1902 */
1903static int
1904varcmp(const char *p, const char *q)
1905{
1906 int c, d;
1907
1908 while ((c = *p) == (d = *q)) {
1909 if (!c || c == '=')
1910 goto out;
1911 p++;
1912 q++;
1913 }
1914 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001915 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001916 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001917 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001918 out:
1919 return c - d;
1920}
1921
1922static int
1923varequal(const char *a, const char *b)
1924{
1925 return !varcmp(a, b);
1926}
1927
1928/*
1929 * Find the appropriate entry in the hash table from the name.
1930 */
1931static struct var **
1932hashvar(const char *p)
1933{
1934 unsigned hashval;
1935
1936 hashval = ((unsigned char) *p) << 4;
1937 while (*p && *p != '=')
1938 hashval += (unsigned char) *p++;
1939 return &vartab[hashval % VTABSIZE];
1940}
1941
1942static int
1943vpcmp(const void *a, const void *b)
1944{
1945 return varcmp(*(const char **)a, *(const char **)b);
1946}
1947
1948/*
1949 * This routine initializes the builtin variables.
1950 */
1951static void
1952initvar(void)
1953{
1954 struct var *vp;
1955 struct var *end;
1956 struct var **vpp;
1957
1958 /*
1959 * PS1 depends on uid
1960 */
1961#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1962 vps1.text = "PS1=\\w \\$ ";
1963#else
1964 if (!geteuid())
1965 vps1.text = "PS1=# ";
1966#endif
1967 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001968 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001969 do {
1970 vpp = hashvar(vp->text);
1971 vp->next = *vpp;
1972 *vpp = vp;
1973 } while (++vp < end);
1974}
1975
1976static struct var **
1977findvar(struct var **vpp, const char *name)
1978{
1979 for (; *vpp; vpp = &(*vpp)->next) {
1980 if (varequal((*vpp)->text, name)) {
1981 break;
1982 }
1983 }
1984 return vpp;
1985}
1986
1987/*
1988 * Find the value of a variable. Returns NULL if not set.
1989 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001990static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001991lookupvar(const char *name)
1992{
1993 struct var *v;
1994
1995 v = *findvar(hashvar(name), name);
1996 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001997#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001998 /*
1999 * Dynamic variables are implemented roughly the same way they are
2000 * in bash. Namely, they're "special" so long as they aren't unset.
2001 * As soon as they're unset, they're no longer dynamic, and dynamic
2002 * lookup will no longer happen at that point. -- PFM.
2003 */
2004 if ((v->flags & VDYNAMIC))
2005 (*v->func)(NULL);
2006#endif
2007 if (!(v->flags & VUNSET))
2008 return strchrnul(v->text, '=') + 1;
2009 }
2010 return NULL;
2011}
2012
2013/*
2014 * Search the environment of a builtin command.
2015 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002016static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002017bltinlookup(const char *name)
2018{
2019 struct strlist *sp;
2020
2021 for (sp = cmdenviron; sp; sp = sp->next) {
2022 if (varequal(sp->text, name))
2023 return strchrnul(sp->text, '=') + 1;
2024 }
2025 return lookupvar(name);
2026}
2027
2028/*
2029 * Same as setvar except that the variable and value are passed in
2030 * the first argument as name=value. Since the first argument will
2031 * be actually stored in the table, it should not be a string that
2032 * will go away.
2033 * Called with interrupts off.
2034 */
2035static void
2036setvareq(char *s, int flags)
2037{
2038 struct var *vp, **vpp;
2039
2040 vpp = hashvar(s);
2041 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2042 vp = *findvar(vpp, s);
2043 if (vp) {
2044 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2045 const char *n;
2046
2047 if (flags & VNOSAVE)
2048 free(s);
2049 n = vp->text;
2050 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2051 }
2052
2053 if (flags & VNOSET)
2054 return;
2055
2056 if (vp->func && (flags & VNOFUNC) == 0)
2057 (*vp->func)(strchrnul(s, '=') + 1);
2058
2059 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2060 free((char*)vp->text);
2061
2062 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2063 } else {
2064 if (flags & VNOSET)
2065 return;
2066 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002067 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002068 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002069 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002070 *vpp = vp;
2071 }
2072 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2073 s = ckstrdup(s);
2074 vp->text = s;
2075 vp->flags = flags;
2076}
2077
2078/*
2079 * Set the value of a variable. The flags argument is ored with the
2080 * flags of the variable. If val is NULL, the variable is unset.
2081 */
2082static void
2083setvar(const char *name, const char *val, int flags)
2084{
2085 char *p, *q;
2086 size_t namelen;
2087 char *nameeq;
2088 size_t vallen;
2089
2090 q = endofname(name);
2091 p = strchrnul(q, '=');
2092 namelen = p - name;
2093 if (!namelen || p != q)
2094 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2095 vallen = 0;
2096 if (val == NULL) {
2097 flags |= VUNSET;
2098 } else {
2099 vallen = strlen(val);
2100 }
2101 INT_OFF;
2102 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002103 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002104 if (val) {
2105 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002106 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002107 }
2108 *p = '\0';
2109 setvareq(nameeq, flags | VNOSAVE);
2110 INT_ON;
2111}
2112
2113#if ENABLE_ASH_GETOPTS
2114/*
2115 * Safe version of setvar, returns 1 on success 0 on failure.
2116 */
2117static int
2118setvarsafe(const char *name, const char *val, int flags)
2119{
2120 int err;
2121 volatile int saveint;
2122 struct jmploc *volatile savehandler = exception_handler;
2123 struct jmploc jmploc;
2124
2125 SAVE_INT(saveint);
2126 if (setjmp(jmploc.loc))
2127 err = 1;
2128 else {
2129 exception_handler = &jmploc;
2130 setvar(name, val, flags);
2131 err = 0;
2132 }
2133 exception_handler = savehandler;
2134 RESTORE_INT(saveint);
2135 return err;
2136}
2137#endif
2138
2139/*
2140 * Unset the specified variable.
2141 */
2142static int
2143unsetvar(const char *s)
2144{
2145 struct var **vpp;
2146 struct var *vp;
2147 int retval;
2148
2149 vpp = findvar(hashvar(s), s);
2150 vp = *vpp;
2151 retval = 2;
2152 if (vp) {
2153 int flags = vp->flags;
2154
2155 retval = 1;
2156 if (flags & VREADONLY)
2157 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002158#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002159 vp->flags &= ~VDYNAMIC;
2160#endif
2161 if (flags & VUNSET)
2162 goto ok;
2163 if ((flags & VSTRFIXED) == 0) {
2164 INT_OFF;
2165 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2166 free((char*)vp->text);
2167 *vpp = vp->next;
2168 free(vp);
2169 INT_ON;
2170 } else {
2171 setvar(s, 0, 0);
2172 vp->flags &= ~VEXPORT;
2173 }
2174 ok:
2175 retval = 0;
2176 }
2177 out:
2178 return retval;
2179}
2180
2181/*
2182 * Process a linked list of variable assignments.
2183 */
2184static void
2185listsetvar(struct strlist *list_set_var, int flags)
2186{
2187 struct strlist *lp = list_set_var;
2188
2189 if (!lp)
2190 return;
2191 INT_OFF;
2192 do {
2193 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002194 lp = lp->next;
2195 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002196 INT_ON;
2197}
2198
2199/*
2200 * Generate a list of variables satisfying the given conditions.
2201 */
2202static char **
2203listvars(int on, int off, char ***end)
2204{
2205 struct var **vpp;
2206 struct var *vp;
2207 char **ep;
2208 int mask;
2209
2210 STARTSTACKSTR(ep);
2211 vpp = vartab;
2212 mask = on | off;
2213 do {
2214 for (vp = *vpp; vp; vp = vp->next) {
2215 if ((vp->flags & mask) == on) {
2216 if (ep == stackstrend())
2217 ep = growstackstr();
2218 *ep++ = (char *) vp->text;
2219 }
2220 }
2221 } while (++vpp < vartab + VTABSIZE);
2222 if (ep == stackstrend())
2223 ep = growstackstr();
2224 if (end)
2225 *end = ep;
2226 *ep++ = NULL;
2227 return grabstackstr(ep);
2228}
2229
2230
2231/* ============ Path search helper
2232 *
2233 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002234 * of the path before the first call; path_advance will update
2235 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002236 * the possible path expansions in sequence. If an option (indicated by
2237 * a percent sign) appears in the path entry then the global variable
2238 * pathopt will be set to point to it; otherwise pathopt will be set to
2239 * NULL.
2240 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002241static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002242
2243static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002245{
2246 const char *p;
2247 char *q;
2248 const char *start;
2249 size_t len;
2250
2251 if (*path == NULL)
2252 return NULL;
2253 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002254 for (p = start; *p && *p != ':' && *p != '%'; p++)
2255 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002256 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2257 while (stackblocksize() < len)
2258 growstackblock();
2259 q = stackblock();
2260 if (p != start) {
2261 memcpy(q, start, p - start);
2262 q += p - start;
2263 *q++ = '/';
2264 }
2265 strcpy(q, name);
2266 pathopt = NULL;
2267 if (*p == '%') {
2268 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002269 while (*p && *p != ':')
2270 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002271 }
2272 if (*p == ':')
2273 *path = p + 1;
2274 else
2275 *path = NULL;
2276 return stalloc(len);
2277}
2278
2279
2280/* ============ Prompt */
2281
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002282static smallint doprompt; /* if set, prompt the user */
2283static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002284
2285#if ENABLE_FEATURE_EDITING
2286static line_input_t *line_input_state;
2287static const char *cmdedit_prompt;
2288static void
2289putprompt(const char *s)
2290{
2291 if (ENABLE_ASH_EXPAND_PRMT) {
2292 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002293 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002294 return;
2295 }
2296 cmdedit_prompt = s;
2297}
2298#else
2299static void
2300putprompt(const char *s)
2301{
2302 out2str(s);
2303}
2304#endif
2305
2306#if ENABLE_ASH_EXPAND_PRMT
2307/* expandstr() needs parsing machinery, so it is far away ahead... */
2308static const char *expandstr(const char *ps);
2309#else
2310#define expandstr(s) s
2311#endif
2312
2313static void
2314setprompt(int whichprompt)
2315{
2316 const char *prompt;
2317#if ENABLE_ASH_EXPAND_PRMT
2318 struct stackmark smark;
2319#endif
2320
2321 needprompt = 0;
2322
2323 switch (whichprompt) {
2324 case 1:
2325 prompt = ps1val();
2326 break;
2327 case 2:
2328 prompt = ps2val();
2329 break;
2330 default: /* 0 */
2331 prompt = nullstr;
2332 }
2333#if ENABLE_ASH_EXPAND_PRMT
2334 setstackmark(&smark);
2335 stalloc(stackblocksize());
2336#endif
2337 putprompt(expandstr(prompt));
2338#if ENABLE_ASH_EXPAND_PRMT
2339 popstackmark(&smark);
2340#endif
2341}
2342
2343
2344/* ============ The cd and pwd commands */
2345
2346#define CD_PHYSICAL 1
2347#define CD_PRINT 2
2348
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002349static int
2350cdopt(void)
2351{
2352 int flags = 0;
2353 int i, j;
2354
2355 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002356 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002357 if (i != j) {
2358 flags ^= CD_PHYSICAL;
2359 j = i;
2360 }
2361 }
2362
2363 return flags;
2364}
2365
2366/*
2367 * Update curdir (the name of the current directory) in response to a
2368 * cd command.
2369 */
2370static const char *
2371updatepwd(const char *dir)
2372{
2373 char *new;
2374 char *p;
2375 char *cdcomppath;
2376 const char *lim;
2377
2378 cdcomppath = ststrdup(dir);
2379 STARTSTACKSTR(new);
2380 if (*dir != '/') {
2381 if (curdir == nullstr)
2382 return 0;
2383 new = stack_putstr(curdir, new);
2384 }
2385 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002386 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002387 if (*dir != '/') {
2388 if (new[-1] != '/')
2389 USTPUTC('/', new);
2390 if (new > lim && *lim == '/')
2391 lim++;
2392 } else {
2393 USTPUTC('/', new);
2394 cdcomppath++;
2395 if (dir[1] == '/' && dir[2] != '/') {
2396 USTPUTC('/', new);
2397 cdcomppath++;
2398 lim++;
2399 }
2400 }
2401 p = strtok(cdcomppath, "/");
2402 while (p) {
2403 switch (*p) {
2404 case '.':
2405 if (p[1] == '.' && p[2] == '\0') {
2406 while (new > lim) {
2407 STUNPUTC(new);
2408 if (new[-1] == '/')
2409 break;
2410 }
2411 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002412 }
2413 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002414 break;
2415 /* fall through */
2416 default:
2417 new = stack_putstr(p, new);
2418 USTPUTC('/', new);
2419 }
2420 p = strtok(0, "/");
2421 }
2422 if (new > lim)
2423 STUNPUTC(new);
2424 *new = 0;
2425 return stackblock();
2426}
2427
2428/*
2429 * Find out what the current directory is. If we already know the current
2430 * directory, this routine returns immediately.
2431 */
2432static char *
2433getpwd(void)
2434{
Denis Vlasenko01631112007-12-16 17:20:38 +00002435 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002436 return dir ? dir : nullstr;
2437}
2438
2439static void
2440setpwd(const char *val, int setold)
2441{
2442 char *oldcur, *dir;
2443
2444 oldcur = dir = curdir;
2445
2446 if (setold) {
2447 setvar("OLDPWD", oldcur, VEXPORT);
2448 }
2449 INT_OFF;
2450 if (physdir != nullstr) {
2451 if (physdir != oldcur)
2452 free(physdir);
2453 physdir = nullstr;
2454 }
2455 if (oldcur == val || !val) {
2456 char *s = getpwd();
2457 physdir = s;
2458 if (!val)
2459 dir = s;
2460 } else
2461 dir = ckstrdup(val);
2462 if (oldcur != dir && oldcur != nullstr) {
2463 free(oldcur);
2464 }
2465 curdir = dir;
2466 INT_ON;
2467 setvar("PWD", dir, VEXPORT);
2468}
2469
2470static void hashcd(void);
2471
2472/*
2473 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2474 * know that the current directory has changed.
2475 */
2476static int
2477docd(const char *dest, int flags)
2478{
2479 const char *dir = 0;
2480 int err;
2481
2482 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2483
2484 INT_OFF;
2485 if (!(flags & CD_PHYSICAL)) {
2486 dir = updatepwd(dest);
2487 if (dir)
2488 dest = dir;
2489 }
2490 err = chdir(dest);
2491 if (err)
2492 goto out;
2493 setpwd(dir, 1);
2494 hashcd();
2495 out:
2496 INT_ON;
2497 return err;
2498}
2499
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002500static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002501cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002502{
2503 const char *dest;
2504 const char *path;
2505 const char *p;
2506 char c;
2507 struct stat statb;
2508 int flags;
2509
2510 flags = cdopt();
2511 dest = *argptr;
2512 if (!dest)
2513 dest = bltinlookup(homestr);
2514 else if (LONE_DASH(dest)) {
2515 dest = bltinlookup("OLDPWD");
2516 flags |= CD_PRINT;
2517 }
2518 if (!dest)
2519 dest = nullstr;
2520 if (*dest == '/')
2521 goto step7;
2522 if (*dest == '.') {
2523 c = dest[1];
2524 dotdot:
2525 switch (c) {
2526 case '\0':
2527 case '/':
2528 goto step6;
2529 case '.':
2530 c = dest[2];
2531 if (c != '.')
2532 goto dotdot;
2533 }
2534 }
2535 if (!*dest)
2536 dest = ".";
2537 path = bltinlookup("CDPATH");
2538 if (!path) {
2539 step6:
2540 step7:
2541 p = dest;
2542 goto docd;
2543 }
2544 do {
2545 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002546 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002547 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2548 if (c && c != ':')
2549 flags |= CD_PRINT;
2550 docd:
2551 if (!docd(p, flags))
2552 goto out;
2553 break;
2554 }
2555 } while (path);
2556 ash_msg_and_raise_error("can't cd to %s", dest);
2557 /* NOTREACHED */
2558 out:
2559 if (flags & CD_PRINT)
2560 out1fmt(snlfmt, curdir);
2561 return 0;
2562}
2563
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002564static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002565pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002566{
2567 int flags;
2568 const char *dir = curdir;
2569
2570 flags = cdopt();
2571 if (flags) {
2572 if (physdir == nullstr)
2573 setpwd(dir, 0);
2574 dir = physdir;
2575 }
2576 out1fmt(snlfmt, dir);
2577 return 0;
2578}
2579
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002580
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002581/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002582
Denis Vlasenko834dee72008-10-07 09:18:30 +00002583
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002584#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002585/* buffer for top level input file */
2586#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002587
Eric Andersenc470f442003-07-28 09:56:35 +00002588/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002589#define CWORD 0 /* character is nothing special */
2590#define CNL 1 /* newline character */
2591#define CBACK 2 /* a backslash character */
2592#define CSQUOTE 3 /* single quote */
2593#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002594#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002595#define CBQUOTE 6 /* backwards single quote */
2596#define CVAR 7 /* a dollar sign */
2597#define CENDVAR 8 /* a '}' character */
2598#define CLP 9 /* a left paren in arithmetic */
2599#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002600#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002601#define CCTL 12 /* like CWORD, except it must be escaped */
2602#define CSPCL 13 /* these terminate a word */
2603#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002604
Denis Vlasenko131ae172007-02-18 13:00:19 +00002605#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002606#define SYNBASE 130
2607#define PEOF -130
2608#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002609#define PEOA_OR_PEOF PEOA
2610#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002611#define SYNBASE 129
2612#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002613#define PEOA_OR_PEOF PEOF
2614#endif
2615
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002616/* number syntax index */
2617#define BASESYNTAX 0 /* not in quotes */
2618#define DQSYNTAX 1 /* in double quotes */
2619#define SQSYNTAX 2 /* in single quotes */
2620#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002621#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002622
Denis Vlasenko131ae172007-02-18 13:00:19 +00002623#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002624#define USE_SIT_FUNCTION
2625#endif
2626
Mike Frysinger98c52642009-04-02 10:02:37 +00002627#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002628static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002629#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002630 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002631#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002632 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2633 { CNL, CNL, CNL, CNL }, /* 2, \n */
2634 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2635 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2636 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2637 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2638 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2639 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2640 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2641 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2642 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002643#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002644 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2645 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2646 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002647#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002648};
Eric Andersenc470f442003-07-28 09:56:35 +00002649#else
2650static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002651#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002652 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002653#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002654 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2655 { CNL, CNL, CNL }, /* 2, \n */
2656 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2657 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2658 { CVAR, CVAR, CWORD }, /* 5, $ */
2659 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2660 { CSPCL, CWORD, CWORD }, /* 7, ( */
2661 { CSPCL, CWORD, CWORD }, /* 8, ) */
2662 { CBACK, CBACK, CCTL }, /* 9, \ */
2663 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2664 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002665#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002666 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2667 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2668 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002669#endif
2670};
Mike Frysinger98c52642009-04-02 10:02:37 +00002671#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002672
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002673#ifdef USE_SIT_FUNCTION
2674
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002675static int
2676SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002677{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002678 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002679#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002680 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002681 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2682 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2683 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2684 11, 3 /* "}~" */
2685 };
2686#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002687 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002688 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2689 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2690 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2691 10, 2 /* "}~" */
2692 };
2693#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002694 const char *s;
2695 int indx;
2696
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002697 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002698 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002699 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002700#if ENABLE_ASH_ALIAS
2701 if (c == PEOA) { /* 2^8+1 */
2702 indx = 0;
2703 } else
2704#endif
2705 {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02002706 if ((unsigned char)c >= CTLESC
2707 && (unsigned char)c <= CTLQUOTEMARK
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 ) {
2709 return CCTL;
2710 }
2711 s = strchrnul(spec_symbls, c);
2712 if (*s == '\0') {
2713 return CWORD;
2714 }
2715 indx = syntax_index_table[s - spec_symbls];
2716 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002717 return S_I_T[indx][syntax];
2718}
2719
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002720#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002721
Denis Vlasenko131ae172007-02-18 13:00:19 +00002722#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002723#define CSPCL_CIGN_CIGN_CIGN 0
2724#define CSPCL_CWORD_CWORD_CWORD 1
2725#define CNL_CNL_CNL_CNL 2
2726#define CWORD_CCTL_CCTL_CWORD 3
2727#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2728#define CVAR_CVAR_CWORD_CVAR 5
2729#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2730#define CSPCL_CWORD_CWORD_CLP 7
2731#define CSPCL_CWORD_CWORD_CRP 8
2732#define CBACK_CBACK_CCTL_CBACK 9
2733#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2734#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2735#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2736#define CWORD_CWORD_CWORD_CWORD 13
2737#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002738#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002739#define CSPCL_CWORD_CWORD_CWORD 0
2740#define CNL_CNL_CNL_CNL 1
2741#define CWORD_CCTL_CCTL_CWORD 2
2742#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2743#define CVAR_CVAR_CWORD_CVAR 4
2744#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2745#define CSPCL_CWORD_CWORD_CLP 6
2746#define CSPCL_CWORD_CWORD_CRP 7
2747#define CBACK_CBACK_CCTL_CBACK 8
2748#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2749#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2750#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2751#define CWORD_CWORD_CWORD_CWORD 12
2752#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002753#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002754
2755static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002756 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002757 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002758#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002759 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2760#endif
2761 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2763 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2764 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2765 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2766 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2767 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2768 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2769 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002770 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2899 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2900 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002923 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002924 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2926 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002928 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002929 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2930 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2931 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2934 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2936 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2937 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2950 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2953 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2981 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2982 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2983 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2986 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3014 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3015 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3016 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003017};
3018
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003019#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003020
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003021#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003022
Eric Andersen2870d962001-07-02 17:27:21 +00003023
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003024/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003025
Denis Vlasenko131ae172007-02-18 13:00:19 +00003026#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003027
3028#define ALIASINUSE 1
3029#define ALIASDEAD 2
3030
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003031struct alias {
3032 struct alias *next;
3033 char *name;
3034 char *val;
3035 int flag;
3036};
3037
Denis Vlasenko01631112007-12-16 17:20:38 +00003038
3039static struct alias **atab; // [ATABSIZE];
3040#define INIT_G_alias() do { \
3041 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3042} while (0)
3043
Eric Andersen2870d962001-07-02 17:27:21 +00003044
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003045static struct alias **
3046__lookupalias(const char *name) {
3047 unsigned int hashval;
3048 struct alias **app;
3049 const char *p;
3050 unsigned int ch;
3051
3052 p = name;
3053
3054 ch = (unsigned char)*p;
3055 hashval = ch << 4;
3056 while (ch) {
3057 hashval += ch;
3058 ch = (unsigned char)*++p;
3059 }
3060 app = &atab[hashval % ATABSIZE];
3061
3062 for (; *app; app = &(*app)->next) {
3063 if (strcmp(name, (*app)->name) == 0) {
3064 break;
3065 }
3066 }
3067
3068 return app;
3069}
3070
3071static struct alias *
3072lookupalias(const char *name, int check)
3073{
3074 struct alias *ap = *__lookupalias(name);
3075
3076 if (check && ap && (ap->flag & ALIASINUSE))
3077 return NULL;
3078 return ap;
3079}
3080
3081static struct alias *
3082freealias(struct alias *ap)
3083{
3084 struct alias *next;
3085
3086 if (ap->flag & ALIASINUSE) {
3087 ap->flag |= ALIASDEAD;
3088 return ap;
3089 }
3090
3091 next = ap->next;
3092 free(ap->name);
3093 free(ap->val);
3094 free(ap);
3095 return next;
3096}
Eric Andersencb57d552001-06-28 07:25:16 +00003097
Eric Andersenc470f442003-07-28 09:56:35 +00003098static void
3099setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003100{
3101 struct alias *ap, **app;
3102
3103 app = __lookupalias(name);
3104 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003106 if (ap) {
3107 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003108 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003109 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003110 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003111 ap->flag &= ~ALIASDEAD;
3112 } else {
3113 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003114 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003115 ap->name = ckstrdup(name);
3116 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003117 /*ap->flag = 0; - ckzalloc did it */
3118 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003119 *app = ap;
3120 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003121 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003122}
3123
Eric Andersenc470f442003-07-28 09:56:35 +00003124static int
3125unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003126{
Eric Andersencb57d552001-06-28 07:25:16 +00003127 struct alias **app;
3128
3129 app = __lookupalias(name);
3130
3131 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003132 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003133 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003134 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003135 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003136 }
3137
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003138 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003139}
3140
Eric Andersenc470f442003-07-28 09:56:35 +00003141static void
3142rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003143{
Eric Andersencb57d552001-06-28 07:25:16 +00003144 struct alias *ap, **app;
3145 int i;
3146
Denis Vlasenkob012b102007-02-19 22:43:01 +00003147 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003148 for (i = 0; i < ATABSIZE; i++) {
3149 app = &atab[i];
3150 for (ap = *app; ap; ap = *app) {
3151 *app = freealias(*app);
3152 if (ap == *app) {
3153 app = &ap->next;
3154 }
3155 }
3156 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003157 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003158}
3159
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003160static void
3161printalias(const struct alias *ap)
3162{
3163 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3164}
3165
Eric Andersencb57d552001-06-28 07:25:16 +00003166/*
3167 * TODO - sort output
3168 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003169static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003170aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003171{
3172 char *n, *v;
3173 int ret = 0;
3174 struct alias *ap;
3175
Denis Vlasenko68404f12008-03-17 09:00:54 +00003176 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003177 int i;
3178
Denis Vlasenko68404f12008-03-17 09:00:54 +00003179 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003180 for (ap = atab[i]; ap; ap = ap->next) {
3181 printalias(ap);
3182 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003183 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003184 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003185 }
3186 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003187 v = strchr(n+1, '=');
3188 if (v == NULL) { /* n+1: funny ksh stuff */
3189 ap = *__lookupalias(n);
3190 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003191 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003192 ret = 1;
3193 } else
3194 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003195 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003196 *v++ = '\0';
3197 setalias(n, v);
3198 }
3199 }
3200
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003201 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003202}
3203
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003204static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003205unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003206{
3207 int i;
3208
3209 while ((i = nextopt("a")) != '\0') {
3210 if (i == 'a') {
3211 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003212 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003213 }
3214 }
3215 for (i = 0; *argptr; argptr++) {
3216 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003217 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003218 i = 1;
3219 }
3220 }
3221
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003222 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003223}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003224
Denis Vlasenko131ae172007-02-18 13:00:19 +00003225#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003226
Eric Andersenc470f442003-07-28 09:56:35 +00003227
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003228/* ============ jobs.c */
3229
3230/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3231#define FORK_FG 0
3232#define FORK_BG 1
3233#define FORK_NOJOB 2
3234
3235/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003236#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3237#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3238#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003239
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003240/*
3241 * A job structure contains information about a job. A job is either a
3242 * single process or a set of processes contained in a pipeline. In the
3243 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3244 * array of pids.
3245 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246struct procstat {
3247 pid_t pid; /* process id */
3248 int status; /* last process status from wait() */
3249 char *cmd; /* text of command being run */
3250};
3251
3252struct job {
3253 struct procstat ps0; /* status of process */
3254 struct procstat *ps; /* status or processes when more than one */
3255#if JOBS
3256 int stopstatus; /* status of a stopped job */
3257#endif
3258 uint32_t
3259 nprocs: 16, /* number of processes */
3260 state: 8,
3261#define JOBRUNNING 0 /* at least one proc running */
3262#define JOBSTOPPED 1 /* all procs are stopped */
3263#define JOBDONE 2 /* all procs are completed */
3264#if JOBS
3265 sigint: 1, /* job was killed by SIGINT */
3266 jobctl: 1, /* job running under job control */
3267#endif
3268 waited: 1, /* true if this entry has been waited for */
3269 used: 1, /* true if this entry is in used */
3270 changed: 1; /* true if status has changed */
3271 struct job *prev_job; /* previous job */
3272};
3273
Denis Vlasenko68404f12008-03-17 09:00:54 +00003274static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003275#if !JOBS
3276#define forkshell(job, node, mode) forkshell(job, mode)
3277#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003278static int forkshell(struct job *, union node *, int);
3279static int waitforjob(struct job *);
3280
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003281#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003282enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003283#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003284#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003285static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003286static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003287#endif
3288
3289/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003290 * Ignore a signal.
3291 */
3292static void
3293ignoresig(int signo)
3294{
3295 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3296 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3297 /* No, need to do it */
3298 signal(signo, SIG_IGN);
3299 }
3300 sigmode[signo - 1] = S_HARD_IGN;
3301}
3302
3303/*
3304 * Signal handler. Only one usage site - in setsignal()
3305 */
3306static void
3307onsig(int signo)
3308{
3309 gotsig[signo - 1] = 1;
3310
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003311 if (signo == SIGINT && !trap[SIGINT]) {
3312 if (!suppress_int) {
3313 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003314 raise_interrupt(); /* does not return */
3315 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003316 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003317 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003318 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003319 }
3320}
3321
3322/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003323 * Set the signal handler for the specified signal. The routine figures
3324 * out what it should be set to.
3325 */
3326static void
3327setsignal(int signo)
3328{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 char *t;
3330 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 struct sigaction act;
3332
3333 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003334 new_act = S_DFL;
3335 if (t != NULL) { /* trap for this sig is set */
3336 new_act = S_CATCH;
3337 if (t[0] == '\0') /* trap is "": ignore this sig */
3338 new_act = S_IGN;
3339 }
3340
3341 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003342 switch (signo) {
3343 case SIGINT:
3344 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003346 break;
3347 case SIGQUIT:
3348#if DEBUG
3349 if (debug)
3350 break;
3351#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003352 /* man bash:
3353 * "In all cases, bash ignores SIGQUIT. Non-builtin
3354 * commands run by bash have signal handlers
3355 * set to the values inherited by the shell
3356 * from its parent". */
3357 new_act = S_IGN;
3358 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 case SIGTERM:
3360 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 break;
3363#if JOBS
3364 case SIGTSTP:
3365 case SIGTTOU:
3366 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003367 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 break;
3369#endif
3370 }
3371 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003372//TODO: if !rootshell, we reset SIGQUIT to DFL,
3373//whereas we have to restore it to what shell got on entry
3374//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375
3376 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003377 cur_act = *t;
3378 if (cur_act == 0) {
3379 /* current setting is not yet known */
3380 if (sigaction(signo, NULL, &act)) {
3381 /* pretend it worked; maybe we should give a warning,
3382 * but other shells don't. We don't alter sigmode,
3383 * so we retry every time.
3384 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003385 return;
3386 }
3387 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003388 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003389 if (mflag
3390 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3391 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003392 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003393 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 }
3395 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003396 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003398
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003399 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003400 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401 case S_CATCH:
3402 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003403 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3404 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405 break;
3406 case S_IGN:
3407 act.sa_handler = SIG_IGN;
3408 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003409 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003410 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003411
3412 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003413}
3414
3415/* mode flags for set_curjob */
3416#define CUR_DELETE 2
3417#define CUR_RUNNING 1
3418#define CUR_STOPPED 0
3419
3420/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003421#define DOWAIT_NONBLOCK WNOHANG
3422#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003423
3424#if JOBS
3425/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003426static int initialpgrp; //references:2
3427static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428#endif
3429/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003430static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003431/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003432static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003433/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003434static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003435/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003436static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003437
3438static void
3439set_curjob(struct job *jp, unsigned mode)
3440{
3441 struct job *jp1;
3442 struct job **jpp, **curp;
3443
3444 /* first remove from list */
3445 jpp = curp = &curjob;
3446 do {
3447 jp1 = *jpp;
3448 if (jp1 == jp)
3449 break;
3450 jpp = &jp1->prev_job;
3451 } while (1);
3452 *jpp = jp1->prev_job;
3453
3454 /* Then re-insert in correct position */
3455 jpp = curp;
3456 switch (mode) {
3457 default:
3458#if DEBUG
3459 abort();
3460#endif
3461 case CUR_DELETE:
3462 /* job being deleted */
3463 break;
3464 case CUR_RUNNING:
3465 /* newly created job or backgrounded job,
3466 put after all stopped jobs. */
3467 do {
3468 jp1 = *jpp;
3469#if JOBS
3470 if (!jp1 || jp1->state != JOBSTOPPED)
3471#endif
3472 break;
3473 jpp = &jp1->prev_job;
3474 } while (1);
3475 /* FALLTHROUGH */
3476#if JOBS
3477 case CUR_STOPPED:
3478#endif
3479 /* newly stopped job - becomes curjob */
3480 jp->prev_job = *jpp;
3481 *jpp = jp;
3482 break;
3483 }
3484}
3485
3486#if JOBS || DEBUG
3487static int
3488jobno(const struct job *jp)
3489{
3490 return jp - jobtab + 1;
3491}
3492#endif
3493
3494/*
3495 * Convert a job name to a job structure.
3496 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003497#if !JOBS
3498#define getjob(name, getctl) getjob(name)
3499#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003500static struct job *
3501getjob(const char *name, int getctl)
3502{
3503 struct job *jp;
3504 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003505 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003506 unsigned num;
3507 int c;
3508 const char *p;
3509 char *(*match)(const char *, const char *);
3510
3511 jp = curjob;
3512 p = name;
3513 if (!p)
3514 goto currentjob;
3515
3516 if (*p != '%')
3517 goto err;
3518
3519 c = *++p;
3520 if (!c)
3521 goto currentjob;
3522
3523 if (!p[1]) {
3524 if (c == '+' || c == '%') {
3525 currentjob:
3526 err_msg = "No current job";
3527 goto check;
3528 }
3529 if (c == '-') {
3530 if (jp)
3531 jp = jp->prev_job;
3532 err_msg = "No previous job";
3533 check:
3534 if (!jp)
3535 goto err;
3536 goto gotit;
3537 }
3538 }
3539
3540 if (is_number(p)) {
3541 num = atoi(p);
3542 if (num < njobs) {
3543 jp = jobtab + num - 1;
3544 if (jp->used)
3545 goto gotit;
3546 goto err;
3547 }
3548 }
3549
3550 match = prefix;
3551 if (*p == '?') {
3552 match = strstr;
3553 p++;
3554 }
3555
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003556 found = NULL;
3557 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003558 if (match(jp->ps[0].cmd, p)) {
3559 if (found)
3560 goto err;
3561 found = jp;
3562 err_msg = "%s: ambiguous";
3563 }
3564 jp = jp->prev_job;
3565 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003566 if (!found)
3567 goto err;
3568 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003569
3570 gotit:
3571#if JOBS
3572 err_msg = "job %s not created under job control";
3573 if (getctl && jp->jobctl == 0)
3574 goto err;
3575#endif
3576 return jp;
3577 err:
3578 ash_msg_and_raise_error(err_msg, name);
3579}
3580
3581/*
3582 * Mark a job structure as unused.
3583 */
3584static void
3585freejob(struct job *jp)
3586{
3587 struct procstat *ps;
3588 int i;
3589
3590 INT_OFF;
3591 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3592 if (ps->cmd != nullstr)
3593 free(ps->cmd);
3594 }
3595 if (jp->ps != &jp->ps0)
3596 free(jp->ps);
3597 jp->used = 0;
3598 set_curjob(jp, CUR_DELETE);
3599 INT_ON;
3600}
3601
3602#if JOBS
3603static void
3604xtcsetpgrp(int fd, pid_t pgrp)
3605{
3606 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003607 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003608}
3609
3610/*
3611 * Turn job control on and off.
3612 *
3613 * Note: This code assumes that the third arg to ioctl is a character
3614 * pointer, which is true on Berkeley systems but not System V. Since
3615 * System V doesn't have job control yet, this isn't a problem now.
3616 *
3617 * Called with interrupts off.
3618 */
3619static void
3620setjobctl(int on)
3621{
3622 int fd;
3623 int pgrp;
3624
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003625 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003626 return;
3627 if (on) {
3628 int ofd;
3629 ofd = fd = open(_PATH_TTY, O_RDWR);
3630 if (fd < 0) {
3631 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3632 * That sometimes helps to acquire controlling tty.
3633 * Obviously, a workaround for bugs when someone
3634 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003635 fd = 2;
3636 while (!isatty(fd))
3637 if (--fd < 0)
3638 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003639 }
3640 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003641 if (ofd >= 0)
3642 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003643 if (fd < 0)
3644 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003645 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003646 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003647 do { /* while we are in the background */
3648 pgrp = tcgetpgrp(fd);
3649 if (pgrp < 0) {
3650 out:
3651 ash_msg("can't access tty; job control turned off");
3652 mflag = on = 0;
3653 goto close;
3654 }
3655 if (pgrp == getpgrp())
3656 break;
3657 killpg(0, SIGTTIN);
3658 } while (1);
3659 initialpgrp = pgrp;
3660
3661 setsignal(SIGTSTP);
3662 setsignal(SIGTTOU);
3663 setsignal(SIGTTIN);
3664 pgrp = rootpid;
3665 setpgid(0, pgrp);
3666 xtcsetpgrp(fd, pgrp);
3667 } else {
3668 /* turning job control off */
3669 fd = ttyfd;
3670 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003671 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003672 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003673 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674 setpgid(0, pgrp);
3675 setsignal(SIGTSTP);
3676 setsignal(SIGTTOU);
3677 setsignal(SIGTTIN);
3678 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003679 if (fd >= 0)
3680 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681 fd = -1;
3682 }
3683 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003684 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003685}
3686
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003687static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003688killcmd(int argc, char **argv)
3689{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003690 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003691 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003692 do {
3693 if (argv[i][0] == '%') {
3694 struct job *jp = getjob(argv[i], 0);
3695 unsigned pid = jp->ps[0].pid;
3696 /* Enough space for ' -NNN<nul>' */
3697 argv[i] = alloca(sizeof(int)*3 + 3);
3698 /* kill_main has matching code to expect
3699 * leading space. Needed to not confuse
3700 * negative pids with "kill -SIGNAL_NO" syntax */
3701 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003702 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003703 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003704 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003705 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003706}
3707
3708static void
3709showpipe(struct job *jp, FILE *out)
3710{
3711 struct procstat *sp;
3712 struct procstat *spend;
3713
3714 spend = jp->ps + jp->nprocs;
3715 for (sp = jp->ps + 1; sp < spend; sp++)
3716 fprintf(out, " | %s", sp->cmd);
3717 outcslow('\n', out);
3718 flush_stdout_stderr();
3719}
3720
3721
3722static int
3723restartjob(struct job *jp, int mode)
3724{
3725 struct procstat *ps;
3726 int i;
3727 int status;
3728 pid_t pgid;
3729
3730 INT_OFF;
3731 if (jp->state == JOBDONE)
3732 goto out;
3733 jp->state = JOBRUNNING;
3734 pgid = jp->ps->pid;
3735 if (mode == FORK_FG)
3736 xtcsetpgrp(ttyfd, pgid);
3737 killpg(pgid, SIGCONT);
3738 ps = jp->ps;
3739 i = jp->nprocs;
3740 do {
3741 if (WIFSTOPPED(ps->status)) {
3742 ps->status = -1;
3743 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003744 ps++;
3745 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003746 out:
3747 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3748 INT_ON;
3749 return status;
3750}
3751
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003752static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003753fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003754{
3755 struct job *jp;
3756 FILE *out;
3757 int mode;
3758 int retval;
3759
3760 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3761 nextopt(nullstr);
3762 argv = argptr;
3763 out = stdout;
3764 do {
3765 jp = getjob(*argv, 1);
3766 if (mode == FORK_BG) {
3767 set_curjob(jp, CUR_RUNNING);
3768 fprintf(out, "[%d] ", jobno(jp));
3769 }
3770 outstr(jp->ps->cmd, out);
3771 showpipe(jp, out);
3772 retval = restartjob(jp, mode);
3773 } while (*argv && *++argv);
3774 return retval;
3775}
3776#endif
3777
3778static int
3779sprint_status(char *s, int status, int sigonly)
3780{
3781 int col;
3782 int st;
3783
3784 col = 0;
3785 if (!WIFEXITED(status)) {
3786#if JOBS
3787 if (WIFSTOPPED(status))
3788 st = WSTOPSIG(status);
3789 else
3790#endif
3791 st = WTERMSIG(status);
3792 if (sigonly) {
3793 if (st == SIGINT || st == SIGPIPE)
3794 goto out;
3795#if JOBS
3796 if (WIFSTOPPED(status))
3797 goto out;
3798#endif
3799 }
3800 st &= 0x7f;
3801 col = fmtstr(s, 32, strsignal(st));
3802 if (WCOREDUMP(status)) {
3803 col += fmtstr(s + col, 16, " (core dumped)");
3804 }
3805 } else if (!sigonly) {
3806 st = WEXITSTATUS(status);
3807 if (st)
3808 col = fmtstr(s, 16, "Done(%d)", st);
3809 else
3810 col = fmtstr(s, 16, "Done");
3811 }
3812 out:
3813 return col;
3814}
3815
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003817dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003818{
3819 int pid;
3820 int status;
3821 struct job *jp;
3822 struct job *thisjob;
3823 int state;
3824
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003825 TRACE(("dowait(0x%x) called\n", wait_flags));
3826
3827 /* Do a wait system call. If job control is compiled in, we accept
3828 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3829 * NB: _not_ safe_waitpid, we need to detect EINTR */
3830 pid = waitpid(-1, &status,
3831 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003832 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3833 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003834 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003835 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003836
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003837 INT_OFF;
3838 thisjob = NULL;
3839 for (jp = curjob; jp; jp = jp->prev_job) {
3840 struct procstat *sp;
3841 struct procstat *spend;
3842 if (jp->state == JOBDONE)
3843 continue;
3844 state = JOBDONE;
3845 spend = jp->ps + jp->nprocs;
3846 sp = jp->ps;
3847 do {
3848 if (sp->pid == pid) {
3849 TRACE(("Job %d: changing status of proc %d "
3850 "from 0x%x to 0x%x\n",
3851 jobno(jp), pid, sp->status, status));
3852 sp->status = status;
3853 thisjob = jp;
3854 }
3855 if (sp->status == -1)
3856 state = JOBRUNNING;
3857#if JOBS
3858 if (state == JOBRUNNING)
3859 continue;
3860 if (WIFSTOPPED(sp->status)) {
3861 jp->stopstatus = sp->status;
3862 state = JOBSTOPPED;
3863 }
3864#endif
3865 } while (++sp < spend);
3866 if (thisjob)
3867 goto gotjob;
3868 }
3869#if JOBS
3870 if (!WIFSTOPPED(status))
3871#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003872 jobless--;
3873 goto out;
3874
3875 gotjob:
3876 if (state != JOBRUNNING) {
3877 thisjob->changed = 1;
3878
3879 if (thisjob->state != state) {
3880 TRACE(("Job %d: changing state from %d to %d\n",
3881 jobno(thisjob), thisjob->state, state));
3882 thisjob->state = state;
3883#if JOBS
3884 if (state == JOBSTOPPED) {
3885 set_curjob(thisjob, CUR_STOPPED);
3886 }
3887#endif
3888 }
3889 }
3890
3891 out:
3892 INT_ON;
3893
3894 if (thisjob && thisjob == job) {
3895 char s[48 + 1];
3896 int len;
3897
3898 len = sprint_status(s, status, 1);
3899 if (len) {
3900 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003901 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003902 out2str(s);
3903 }
3904 }
3905 return pid;
3906}
3907
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003908static int
3909blocking_wait_with_raise_on_sig(struct job *job)
3910{
3911 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003912 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003913 raise_exception(EXSIG);
3914 return pid;
3915}
3916
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003917#if JOBS
3918static void
3919showjob(FILE *out, struct job *jp, int mode)
3920{
3921 struct procstat *ps;
3922 struct procstat *psend;
3923 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003924 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925 char s[80];
3926
3927 ps = jp->ps;
3928
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003929 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930 /* just output process (group) id of pipeline */
3931 fprintf(out, "%d\n", ps->pid);
3932 return;
3933 }
3934
3935 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003936 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937
3938 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003939 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003940 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003941 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003942
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003943 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944 col += fmtstr(s + col, 16, "%d ", ps->pid);
3945
3946 psend = ps + jp->nprocs;
3947
3948 if (jp->state == JOBRUNNING) {
3949 strcpy(s + col, "Running");
3950 col += sizeof("Running") - 1;
3951 } else {
3952 int status = psend[-1].status;
3953 if (jp->state == JOBSTOPPED)
3954 status = jp->stopstatus;
3955 col += sprint_status(s + col, status, 0);
3956 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003957 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003958
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003959 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3960 * or prints several "PID | <cmdN>" lines,
3961 * depending on SHOW_PIDS bit.
3962 * We do not print status of individual processes
3963 * between PID and <cmdN>. bash does it, but not very well:
3964 * first line shows overall job status, not process status,
3965 * making it impossible to know 1st process status.
3966 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003967 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003968 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003970 s[0] = '\0';
3971 col = 33;
3972 if (mode & SHOW_PIDS)
3973 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003974 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003975 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3976 if (ps != jp->ps)
3977 fprintf(out, "| ");
3978 fprintf(out, "%s", ps->cmd);
3979 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003980 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003981 }
3982 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003983
3984 jp->changed = 0;
3985
3986 if (jp->state == JOBDONE) {
3987 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3988 freejob(jp);
3989 }
3990}
3991
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003992/*
3993 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3994 * statuses have changed since the last call to showjobs.
3995 */
3996static void
3997showjobs(FILE *out, int mode)
3998{
3999 struct job *jp;
4000
Denys Vlasenko883cea42009-07-11 15:31:59 +02004001 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004003 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004004 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005 continue;
4006
4007 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004008 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004009 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004010 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011 }
4012}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004013
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004014static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004015jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004016{
4017 int mode, m;
4018
4019 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004020 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004021 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004022 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004023 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004024 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004025 }
4026
4027 argv = argptr;
4028 if (*argv) {
4029 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004030 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004031 while (*++argv);
4032 } else
4033 showjobs(stdout, mode);
4034
4035 return 0;
4036}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004037#endif /* JOBS */
4038
4039static int
4040getstatus(struct job *job)
4041{
4042 int status;
4043 int retval;
4044
4045 status = job->ps[job->nprocs - 1].status;
4046 retval = WEXITSTATUS(status);
4047 if (!WIFEXITED(status)) {
4048#if JOBS
4049 retval = WSTOPSIG(status);
4050 if (!WIFSTOPPED(status))
4051#endif
4052 {
4053 /* XXX: limits number of signals */
4054 retval = WTERMSIG(status);
4055#if JOBS
4056 if (retval == SIGINT)
4057 job->sigint = 1;
4058#endif
4059 }
4060 retval += 128;
4061 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004062 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004063 jobno(job), job->nprocs, status, retval));
4064 return retval;
4065}
4066
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004067static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004068waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004069{
4070 struct job *job;
4071 int retval;
4072 struct job *jp;
4073
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004074 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004075 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076
4077 nextopt(nullstr);
4078 retval = 0;
4079
4080 argv = argptr;
4081 if (!*argv) {
4082 /* wait for all jobs */
4083 for (;;) {
4084 jp = curjob;
4085 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004086 if (!jp) /* no running procs */
4087 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004088 if (jp->state == JOBRUNNING)
4089 break;
4090 jp->waited = 1;
4091 jp = jp->prev_job;
4092 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004093 /* man bash:
4094 * "When bash is waiting for an asynchronous command via
4095 * the wait builtin, the reception of a signal for which a trap
4096 * has been set will cause the wait builtin to return immediately
4097 * with an exit status greater than 128, immediately after which
4098 * the trap is executed."
4099 * Do we do it that way? */
4100 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004101 }
4102 }
4103
4104 retval = 127;
4105 do {
4106 if (**argv != '%') {
4107 pid_t pid = number(*argv);
4108 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004109 while (1) {
4110 if (!job)
4111 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004112 if (job->ps[job->nprocs - 1].pid == pid)
4113 break;
4114 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004115 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004116 } else
4117 job = getjob(*argv, 0);
4118 /* loop until process terminated or stopped */
4119 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004120 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121 job->waited = 1;
4122 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004123 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124 } while (*++argv);
4125
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004126 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004127 return retval;
4128}
4129
4130static struct job *
4131growjobtab(void)
4132{
4133 size_t len;
4134 ptrdiff_t offset;
4135 struct job *jp, *jq;
4136
4137 len = njobs * sizeof(*jp);
4138 jq = jobtab;
4139 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4140
4141 offset = (char *)jp - (char *)jq;
4142 if (offset) {
4143 /* Relocate pointers */
4144 size_t l = len;
4145
4146 jq = (struct job *)((char *)jq + l);
4147 while (l) {
4148 l -= sizeof(*jp);
4149 jq--;
4150#define joff(p) ((struct job *)((char *)(p) + l))
4151#define jmove(p) (p) = (void *)((char *)(p) + offset)
4152 if (joff(jp)->ps == &jq->ps0)
4153 jmove(joff(jp)->ps);
4154 if (joff(jp)->prev_job)
4155 jmove(joff(jp)->prev_job);
4156 }
4157 if (curjob)
4158 jmove(curjob);
4159#undef joff
4160#undef jmove
4161 }
4162
4163 njobs += 4;
4164 jobtab = jp;
4165 jp = (struct job *)((char *)jp + len);
4166 jq = jp + 3;
4167 do {
4168 jq->used = 0;
4169 } while (--jq >= jp);
4170 return jp;
4171}
4172
4173/*
4174 * Return a new job structure.
4175 * Called with interrupts off.
4176 */
4177static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004178makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004179{
4180 int i;
4181 struct job *jp;
4182
4183 for (i = njobs, jp = jobtab; ; jp++) {
4184 if (--i < 0) {
4185 jp = growjobtab();
4186 break;
4187 }
4188 if (jp->used == 0)
4189 break;
4190 if (jp->state != JOBDONE || !jp->waited)
4191 continue;
4192#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004193 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004194 continue;
4195#endif
4196 freejob(jp);
4197 break;
4198 }
4199 memset(jp, 0, sizeof(*jp));
4200#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004201 /* jp->jobctl is a bitfield.
4202 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004203 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004204 jp->jobctl = 1;
4205#endif
4206 jp->prev_job = curjob;
4207 curjob = jp;
4208 jp->used = 1;
4209 jp->ps = &jp->ps0;
4210 if (nprocs > 1) {
4211 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4212 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004213 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 jobno(jp)));
4215 return jp;
4216}
4217
4218#if JOBS
4219/*
4220 * Return a string identifying a command (to be printed by the
4221 * jobs command).
4222 */
4223static char *cmdnextc;
4224
4225static void
4226cmdputs(const char *s)
4227{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004228 static const char vstype[VSTYPE + 1][3] = {
4229 "", "}", "-", "+", "?", "=",
4230 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004231 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004232 };
4233
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004234 const char *p, *str;
4235 char c, cc[2] = " ";
4236 char *nextc;
4237 int subtype = 0;
4238 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004239
4240 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4241 p = s;
4242 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004243 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004244 switch (c) {
4245 case CTLESC:
4246 c = *p++;
4247 break;
4248 case CTLVAR:
4249 subtype = *p++;
4250 if ((subtype & VSTYPE) == VSLENGTH)
4251 str = "${#";
4252 else
4253 str = "${";
4254 if (!(subtype & VSQUOTE) == !(quoted & 1))
4255 goto dostr;
4256 quoted ^= 1;
4257 c = '"';
4258 break;
4259 case CTLENDVAR:
4260 str = "\"}" + !(quoted & 1);
4261 quoted >>= 1;
4262 subtype = 0;
4263 goto dostr;
4264 case CTLBACKQ:
4265 str = "$(...)";
4266 goto dostr;
4267 case CTLBACKQ+CTLQUOTE:
4268 str = "\"$(...)\"";
4269 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004270#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004271 case CTLARI:
4272 str = "$((";
4273 goto dostr;
4274 case CTLENDARI:
4275 str = "))";
4276 goto dostr;
4277#endif
4278 case CTLQUOTEMARK:
4279 quoted ^= 1;
4280 c = '"';
4281 break;
4282 case '=':
4283 if (subtype == 0)
4284 break;
4285 if ((subtype & VSTYPE) != VSNORMAL)
4286 quoted <<= 1;
4287 str = vstype[subtype & VSTYPE];
4288 if (subtype & VSNUL)
4289 c = ':';
4290 else
4291 goto checkstr;
4292 break;
4293 case '\'':
4294 case '\\':
4295 case '"':
4296 case '$':
4297 /* These can only happen inside quotes */
4298 cc[0] = c;
4299 str = cc;
4300 c = '\\';
4301 break;
4302 default:
4303 break;
4304 }
4305 USTPUTC(c, nextc);
4306 checkstr:
4307 if (!str)
4308 continue;
4309 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004310 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004311 USTPUTC(c, nextc);
4312 }
4313 }
4314 if (quoted & 1) {
4315 USTPUTC('"', nextc);
4316 }
4317 *nextc = 0;
4318 cmdnextc = nextc;
4319}
4320
4321/* cmdtxt() and cmdlist() call each other */
4322static void cmdtxt(union node *n);
4323
4324static void
4325cmdlist(union node *np, int sep)
4326{
4327 for (; np; np = np->narg.next) {
4328 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004329 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330 cmdtxt(np);
4331 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004332 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004333 }
4334}
4335
4336static void
4337cmdtxt(union node *n)
4338{
4339 union node *np;
4340 struct nodelist *lp;
4341 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004342
4343 if (!n)
4344 return;
4345 switch (n->type) {
4346 default:
4347#if DEBUG
4348 abort();
4349#endif
4350 case NPIPE:
4351 lp = n->npipe.cmdlist;
4352 for (;;) {
4353 cmdtxt(lp->n);
4354 lp = lp->next;
4355 if (!lp)
4356 break;
4357 cmdputs(" | ");
4358 }
4359 break;
4360 case NSEMI:
4361 p = "; ";
4362 goto binop;
4363 case NAND:
4364 p = " && ";
4365 goto binop;
4366 case NOR:
4367 p = " || ";
4368 binop:
4369 cmdtxt(n->nbinary.ch1);
4370 cmdputs(p);
4371 n = n->nbinary.ch2;
4372 goto donode;
4373 case NREDIR:
4374 case NBACKGND:
4375 n = n->nredir.n;
4376 goto donode;
4377 case NNOT:
4378 cmdputs("!");
4379 n = n->nnot.com;
4380 donode:
4381 cmdtxt(n);
4382 break;
4383 case NIF:
4384 cmdputs("if ");
4385 cmdtxt(n->nif.test);
4386 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004387 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004388 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004389 cmdputs("; else ");
4390 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004391 } else {
4392 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004393 }
4394 p = "; fi";
4395 goto dotail;
4396 case NSUBSHELL:
4397 cmdputs("(");
4398 n = n->nredir.n;
4399 p = ")";
4400 goto dotail;
4401 case NWHILE:
4402 p = "while ";
4403 goto until;
4404 case NUNTIL:
4405 p = "until ";
4406 until:
4407 cmdputs(p);
4408 cmdtxt(n->nbinary.ch1);
4409 n = n->nbinary.ch2;
4410 p = "; done";
4411 dodo:
4412 cmdputs("; do ");
4413 dotail:
4414 cmdtxt(n);
4415 goto dotail2;
4416 case NFOR:
4417 cmdputs("for ");
4418 cmdputs(n->nfor.var);
4419 cmdputs(" in ");
4420 cmdlist(n->nfor.args, 1);
4421 n = n->nfor.body;
4422 p = "; done";
4423 goto dodo;
4424 case NDEFUN:
4425 cmdputs(n->narg.text);
4426 p = "() { ... }";
4427 goto dotail2;
4428 case NCMD:
4429 cmdlist(n->ncmd.args, 1);
4430 cmdlist(n->ncmd.redirect, 0);
4431 break;
4432 case NARG:
4433 p = n->narg.text;
4434 dotail2:
4435 cmdputs(p);
4436 break;
4437 case NHERE:
4438 case NXHERE:
4439 p = "<<...";
4440 goto dotail2;
4441 case NCASE:
4442 cmdputs("case ");
4443 cmdputs(n->ncase.expr->narg.text);
4444 cmdputs(" in ");
4445 for (np = n->ncase.cases; np; np = np->nclist.next) {
4446 cmdtxt(np->nclist.pattern);
4447 cmdputs(") ");
4448 cmdtxt(np->nclist.body);
4449 cmdputs(";; ");
4450 }
4451 p = "esac";
4452 goto dotail2;
4453 case NTO:
4454 p = ">";
4455 goto redir;
4456 case NCLOBBER:
4457 p = ">|";
4458 goto redir;
4459 case NAPPEND:
4460 p = ">>";
4461 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004462#if ENABLE_ASH_BASH_COMPAT
4463 case NTO2:
4464#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004465 case NTOFD:
4466 p = ">&";
4467 goto redir;
4468 case NFROM:
4469 p = "<";
4470 goto redir;
4471 case NFROMFD:
4472 p = "<&";
4473 goto redir;
4474 case NFROMTO:
4475 p = "<>";
4476 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004477 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004478 cmdputs(p);
4479 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004480 cmdputs(utoa(n->ndup.dupfd));
4481 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004482 }
4483 n = n->nfile.fname;
4484 goto donode;
4485 }
4486}
4487
4488static char *
4489commandtext(union node *n)
4490{
4491 char *name;
4492
4493 STARTSTACKSTR(cmdnextc);
4494 cmdtxt(n);
4495 name = stackblock();
4496 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4497 name, cmdnextc, cmdnextc));
4498 return ckstrdup(name);
4499}
4500#endif /* JOBS */
4501
4502/*
4503 * Fork off a subshell. If we are doing job control, give the subshell its
4504 * own process group. Jp is a job structure that the job is to be added to.
4505 * N is the command that will be evaluated by the child. Both jp and n may
4506 * be NULL. The mode parameter can be one of the following:
4507 * FORK_FG - Fork off a foreground process.
4508 * FORK_BG - Fork off a background process.
4509 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4510 * process group even if job control is on.
4511 *
4512 * When job control is turned off, background processes have their standard
4513 * input redirected to /dev/null (except for the second and later processes
4514 * in a pipeline).
4515 *
4516 * Called with interrupts off.
4517 */
4518/*
4519 * Clear traps on a fork.
4520 */
4521static void
4522clear_traps(void)
4523{
4524 char **tp;
4525
4526 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004527 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004528 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004529 if (trap_ptr == trap)
4530 free(*tp);
4531 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004532 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004533 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004534 setsignal(tp - trap);
4535 INT_ON;
4536 }
4537 }
4538}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004539
4540/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004542
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004543/* Called after fork(), in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004544#if !JOBS
4545# define forkchild(jp, n, mode) forkchild(jp, mode)
4546#endif
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004547static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004548forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004549{
4550 int oldlvl;
4551
4552 TRACE(("Child shell %d\n", getpid()));
4553 oldlvl = shlvl;
4554 shlvl++;
4555
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004556 /* man bash: "Non-builtin commands run by bash have signal handlers
4557 * set to the values inherited by the shell from its parent".
4558 * Do we do it correctly? */
4559
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004560 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004561
4562 if (mode == FORK_NOJOB /* is it `xxx` ? */
4563 && n && n->type == NCMD /* is it single cmd? */
4564 /* && n->ncmd.args->type == NARG - always true? */
4565 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4566 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4567 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4568 ) {
4569 TRACE(("Trap hack\n"));
4570 /* Awful hack for `trap` or $(trap).
4571 *
4572 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4573 * contains an example where "trap" is executed in a subshell:
4574 *
4575 * save_traps=$(trap)
4576 * ...
4577 * eval "$save_traps"
4578 *
4579 * Standard does not say that "trap" in subshell shall print
4580 * parent shell's traps. It only says that its output
4581 * must have suitable form, but then, in the above example
4582 * (which is not supposed to be normative), it implies that.
4583 *
4584 * bash (and probably other shell) does implement it
4585 * (traps are reset to defaults, but "trap" still shows them),
4586 * but as a result, "trap" logic is hopelessly messed up:
4587 *
4588 * # trap
4589 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4590 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4591 * # true | trap <--- trap is in subshell - no output (ditto)
4592 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4593 * trap -- 'echo Ho' SIGWINCH
4594 * # echo `(trap)` <--- in subshell in subshell - output
4595 * trap -- 'echo Ho' SIGWINCH
4596 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4597 * trap -- 'echo Ho' SIGWINCH
4598 *
4599 * The rules when to forget and when to not forget traps
4600 * get really complex and nonsensical.
4601 *
4602 * Our solution: ONLY bare $(trap) or `trap` is special.
4603 */
Denys Vlasenko726e1a02009-09-25 02:58:20 +02004604 /* This is needed to prevent EXIT trap firing and such */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004605 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004606 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004607 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004608#if JOBS
4609 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004610 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4612 pid_t pgrp;
4613
4614 if (jp->nprocs == 0)
4615 pgrp = getpid();
4616 else
4617 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004618 /* this can fail because we are doing it in the parent also */
4619 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004620 if (mode == FORK_FG)
4621 xtcsetpgrp(ttyfd, pgrp);
4622 setsignal(SIGTSTP);
4623 setsignal(SIGTTOU);
4624 } else
4625#endif
4626 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004627 /* man bash: "When job control is not in effect,
4628 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004629 ignoresig(SIGINT);
4630 ignoresig(SIGQUIT);
4631 if (jp->nprocs == 0) {
4632 close(0);
4633 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004634 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004635 }
4636 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004637 if (!oldlvl) {
4638 if (iflag) { /* why if iflag only? */
4639 setsignal(SIGINT);
4640 setsignal(SIGTERM);
4641 }
4642 /* man bash:
4643 * "In all cases, bash ignores SIGQUIT. Non-builtin
4644 * commands run by bash have signal handlers
4645 * set to the values inherited by the shell
4646 * from its parent".
4647 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004648 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004649 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004650#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004651 if (n && n->type == NCMD
4652 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4653 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004654 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004655 /* "jobs": we do not want to clear job list for it,
4656 * instead we remove only _its_ own_ job from job list.
4657 * This makes "jobs .... | cat" more useful.
4658 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004659 freejob(curjob);
4660 return;
4661 }
4662#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004663 for (jp = curjob; jp; jp = jp->prev_job)
4664 freejob(jp);
4665 jobless = 0;
4666}
4667
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004668/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004669#if !JOBS
4670#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4671#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004672static void
4673forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4674{
4675 TRACE(("In parent shell: child = %d\n", pid));
4676 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004677 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4678 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004679 jobless++;
4680 return;
4681 }
4682#if JOBS
4683 if (mode != FORK_NOJOB && jp->jobctl) {
4684 int pgrp;
4685
4686 if (jp->nprocs == 0)
4687 pgrp = pid;
4688 else
4689 pgrp = jp->ps[0].pid;
4690 /* This can fail because we are doing it in the child also */
4691 setpgid(pid, pgrp);
4692 }
4693#endif
4694 if (mode == FORK_BG) {
4695 backgndpid = pid; /* set $! */
4696 set_curjob(jp, CUR_RUNNING);
4697 }
4698 if (jp) {
4699 struct procstat *ps = &jp->ps[jp->nprocs++];
4700 ps->pid = pid;
4701 ps->status = -1;
4702 ps->cmd = nullstr;
4703#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004704 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004705 ps->cmd = commandtext(n);
4706#endif
4707 }
4708}
4709
4710static int
4711forkshell(struct job *jp, union node *n, int mode)
4712{
4713 int pid;
4714
4715 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4716 pid = fork();
4717 if (pid < 0) {
4718 TRACE(("Fork failed, errno=%d", errno));
4719 if (jp)
4720 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004721 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004722 }
4723 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004724 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004725 else
4726 forkparent(jp, n, mode, pid);
4727 return pid;
4728}
4729
4730/*
4731 * Wait for job to finish.
4732 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004733 * Under job control we have the problem that while a child process
4734 * is running interrupts generated by the user are sent to the child
4735 * but not to the shell. This means that an infinite loop started by
4736 * an interactive user may be hard to kill. With job control turned off,
4737 * an interactive user may place an interactive program inside a loop.
4738 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004739 * these interrupts to also abort the loop. The approach we take here
4740 * is to have the shell ignore interrupt signals while waiting for a
4741 * foreground process to terminate, and then send itself an interrupt
4742 * signal if the child process was terminated by an interrupt signal.
4743 * Unfortunately, some programs want to do a bit of cleanup and then
4744 * exit on interrupt; unless these processes terminate themselves by
4745 * sending a signal to themselves (instead of calling exit) they will
4746 * confuse this approach.
4747 *
4748 * Called with interrupts off.
4749 */
4750static int
4751waitforjob(struct job *jp)
4752{
4753 int st;
4754
4755 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004756
4757 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004758 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004759 /* In non-interactive shells, we _can_ get
4760 * a keyboard signal here and be EINTRed,
4761 * but we just loop back, waiting for command to complete.
4762 *
4763 * man bash:
4764 * "If bash is waiting for a command to complete and receives
4765 * a signal for which a trap has been set, the trap
4766 * will not be executed until the command completes."
4767 *
4768 * Reality is that even if trap is not set, bash
4769 * will not act on the signal until command completes.
4770 * Try this. sleep5intoff.c:
4771 * #include <signal.h>
4772 * #include <unistd.h>
4773 * int main() {
4774 * sigset_t set;
4775 * sigemptyset(&set);
4776 * sigaddset(&set, SIGINT);
4777 * sigaddset(&set, SIGQUIT);
4778 * sigprocmask(SIG_BLOCK, &set, NULL);
4779 * sleep(5);
4780 * return 0;
4781 * }
4782 * $ bash -c './sleep5intoff; echo hi'
4783 * ^C^C^C^C <--- pressing ^C once a second
4784 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004785 * $ bash -c './sleep5intoff; echo hi'
4786 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4787 * $ _
4788 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004789 dowait(DOWAIT_BLOCK, jp);
4790 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004791 INT_ON;
4792
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004793 st = getstatus(jp);
4794#if JOBS
4795 if (jp->jobctl) {
4796 xtcsetpgrp(ttyfd, rootpid);
4797 /*
4798 * This is truly gross.
4799 * If we're doing job control, then we did a TIOCSPGRP which
4800 * caused us (the shell) to no longer be in the controlling
4801 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4802 * intuit from the subprocess exit status whether a SIGINT
4803 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4804 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004805 if (jp->sigint) /* TODO: do the same with all signals */
4806 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004807 }
4808 if (jp->state == JOBDONE)
4809#endif
4810 freejob(jp);
4811 return st;
4812}
4813
4814/*
4815 * return 1 if there are stopped jobs, otherwise 0
4816 */
4817static int
4818stoppedjobs(void)
4819{
4820 struct job *jp;
4821 int retval;
4822
4823 retval = 0;
4824 if (job_warning)
4825 goto out;
4826 jp = curjob;
4827 if (jp && jp->state == JOBSTOPPED) {
4828 out2str("You have stopped jobs.\n");
4829 job_warning = 2;
4830 retval++;
4831 }
4832 out:
4833 return retval;
4834}
4835
4836
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004837/* ============ redir.c
4838 *
4839 * Code for dealing with input/output redirection.
4840 */
4841
4842#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004843#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004844
4845/*
4846 * Open a file in noclobber mode.
4847 * The code was copied from bash.
4848 */
4849static int
4850noclobberopen(const char *fname)
4851{
4852 int r, fd;
4853 struct stat finfo, finfo2;
4854
4855 /*
4856 * If the file exists and is a regular file, return an error
4857 * immediately.
4858 */
4859 r = stat(fname, &finfo);
4860 if (r == 0 && S_ISREG(finfo.st_mode)) {
4861 errno = EEXIST;
4862 return -1;
4863 }
4864
4865 /*
4866 * If the file was not present (r != 0), make sure we open it
4867 * exclusively so that if it is created before we open it, our open
4868 * will fail. Make sure that we do not truncate an existing file.
4869 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4870 * file was not a regular file, we leave O_EXCL off.
4871 */
4872 if (r != 0)
4873 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4874 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4875
4876 /* If the open failed, return the file descriptor right away. */
4877 if (fd < 0)
4878 return fd;
4879
4880 /*
4881 * OK, the open succeeded, but the file may have been changed from a
4882 * non-regular file to a regular file between the stat and the open.
4883 * We are assuming that the O_EXCL open handles the case where FILENAME
4884 * did not exist and is symlinked to an existing file between the stat
4885 * and open.
4886 */
4887
4888 /*
4889 * If we can open it and fstat the file descriptor, and neither check
4890 * revealed that it was a regular file, and the file has not been
4891 * replaced, return the file descriptor.
4892 */
4893 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4894 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4895 return fd;
4896
4897 /* The file has been replaced. badness. */
4898 close(fd);
4899 errno = EEXIST;
4900 return -1;
4901}
4902
4903/*
4904 * Handle here documents. Normally we fork off a process to write the
4905 * data to a pipe. If the document is short, we can stuff the data in
4906 * the pipe without forking.
4907 */
4908/* openhere needs this forward reference */
4909static void expandhere(union node *arg, int fd);
4910static int
4911openhere(union node *redir)
4912{
4913 int pip[2];
4914 size_t len = 0;
4915
4916 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004917 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004918 if (redir->type == NHERE) {
4919 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004920 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004921 full_write(pip[1], redir->nhere.doc->narg.text, len);
4922 goto out;
4923 }
4924 }
4925 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004926 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004927 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004928 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4929 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4930 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4931 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932 signal(SIGPIPE, SIG_DFL);
4933 if (redir->type == NHERE)
4934 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004935 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004936 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004937 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004938 }
4939 out:
4940 close(pip[1]);
4941 return pip[0];
4942}
4943
4944static int
4945openredirect(union node *redir)
4946{
4947 char *fname;
4948 int f;
4949
4950 switch (redir->nfile.type) {
4951 case NFROM:
4952 fname = redir->nfile.expfname;
4953 f = open(fname, O_RDONLY);
4954 if (f < 0)
4955 goto eopen;
4956 break;
4957 case NFROMTO:
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4960 if (f < 0)
4961 goto ecreate;
4962 break;
4963 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004964#if ENABLE_ASH_BASH_COMPAT
4965 case NTO2:
4966#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004967 /* Take care of noclobber mode. */
4968 if (Cflag) {
4969 fname = redir->nfile.expfname;
4970 f = noclobberopen(fname);
4971 if (f < 0)
4972 goto ecreate;
4973 break;
4974 }
4975 /* FALLTHROUGH */
4976 case NCLOBBER:
4977 fname = redir->nfile.expfname;
4978 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4979 if (f < 0)
4980 goto ecreate;
4981 break;
4982 case NAPPEND:
4983 fname = redir->nfile.expfname;
4984 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4985 if (f < 0)
4986 goto ecreate;
4987 break;
4988 default:
4989#if DEBUG
4990 abort();
4991#endif
4992 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004993/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004994// case NTOFD:
4995// case NFROMFD:
4996// f = -1;
4997// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004998 case NHERE:
4999 case NXHERE:
5000 f = openhere(redir);
5001 break;
5002 }
5003
5004 return f;
5005 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005006 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005007 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005008 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005009}
5010
5011/*
5012 * Copy a file descriptor to be >= to. Returns -1
5013 * if the source file descriptor is closed, EMPTY if there are no unused
5014 * file descriptors left.
5015 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005016/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5017 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005018enum {
5019 COPYFD_EXACT = (int)~(INT_MAX),
5020 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5021};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005022static int
5023copyfd(int from, int to)
5024{
5025 int newfd;
5026
Denis Vlasenko5a867312008-07-24 19:46:38 +00005027 if (to & COPYFD_EXACT) {
5028 to &= ~COPYFD_EXACT;
5029 /*if (from != to)*/
5030 newfd = dup2(from, to);
5031 } else {
5032 newfd = fcntl(from, F_DUPFD, to);
5033 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005034 if (newfd < 0) {
5035 if (errno == EMFILE)
5036 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005037 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005038 ash_msg_and_raise_error("%d: %m", from);
5039 }
5040 return newfd;
5041}
5042
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005043/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044struct two_fd_t {
5045 int orig, copy;
5046};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005047struct redirtab {
5048 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005049 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005050 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005051 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005052};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005053#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005054
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005055static int need_to_remember(struct redirtab *rp, int fd)
5056{
5057 int i;
5058
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005059 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005060 return 0;
5061
5062 for (i = 0; i < rp->pair_count; i++) {
5063 if (rp->two_fd[i].orig == fd) {
5064 /* already remembered */
5065 return 0;
5066 }
5067 }
5068 return 1;
5069}
5070
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005071/* "hidden" fd is a fd used to read scripts, or a copy of such */
5072static int is_hidden_fd(struct redirtab *rp, int fd)
5073{
5074 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005075 struct parsefile *pf;
5076
5077 if (fd == -1)
5078 return 0;
5079 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005080 while (pf) {
5081 if (fd == pf->fd) {
5082 return 1;
5083 }
5084 pf = pf->prev;
5085 }
5086 if (!rp)
5087 return 0;
5088 fd |= COPYFD_RESTORE;
5089 for (i = 0; i < rp->pair_count; i++) {
5090 if (rp->two_fd[i].copy == fd) {
5091 return 1;
5092 }
5093 }
5094 return 0;
5095}
5096
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005097/*
5098 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5099 * old file descriptors are stashed away so that the redirection can be
5100 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5101 * standard output, and the standard error if it becomes a duplicate of
5102 * stdout, is saved in memory.
5103 */
5104/* flags passed to redirect */
5105#define REDIR_PUSH 01 /* save previous values of file descriptors */
5106#define REDIR_SAVEFD2 03 /* set preverrout */
5107static void
5108redirect(union node *redir, int flags)
5109{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005110 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005111 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005112 int i;
5113 int fd;
5114 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005116
Denis Vlasenko01631112007-12-16 17:20:38 +00005117 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005118 if (!redir) {
5119 return;
5120 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005121
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005122 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005123 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005124 INT_OFF;
5125 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005126 union node *tmp = redir;
5127 do {
5128 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005129#if ENABLE_ASH_BASH_COMPAT
5130 if (redir->nfile.type == NTO2)
5131 sv_pos++;
5132#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005133 tmp = tmp->nfile.next;
5134 } while (tmp);
5135 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005136 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005137 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005138 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005139 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005140 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005141 while (sv_pos > 0) {
5142 sv_pos--;
5143 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5144 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005145 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005146
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005147 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005148 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005149 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005150 int right_fd = redir->ndup.dupfd;
5151 /* redirect from/to same file descriptor? */
5152 if (right_fd == fd)
5153 continue;
5154 /* echo >&10 and 10 is a fd opened to the sh script? */
5155 if (is_hidden_fd(sv, right_fd)) {
5156 errno = EBADF; /* as if it is closed */
5157 ash_msg_and_raise_error("%d: %m", right_fd);
5158 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005159 newfd = -1;
5160 } else {
5161 newfd = openredirect(redir); /* always >= 0 */
5162 if (fd == newfd) {
5163 /* Descriptor wasn't open before redirect.
5164 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005165 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005166 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005167 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005168 continue;
5169 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005170 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005171#if ENABLE_ASH_BASH_COMPAT
5172 redirect_more:
5173#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005175 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005177/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5178 * are closed in popredir() in the child, preventing them from leaking
5179 * into child. (popredir() also cleans up the mess in case of failures)
5180 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 if (i == -1) {
5182 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005183 if (i != EBADF) {
5184 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005185 if (newfd >= 0)
5186 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005187 errno = i;
5188 ash_msg_and_raise_error("%d: %m", fd);
5189 /* NOTREACHED */
5190 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005191 /* EBADF: it is not open - good, remember to close it */
5192 remember_to_close:
5193 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005194 } else { /* fd is open, save its copy */
5195 /* "exec fd>&-" should not close fds
5196 * which point to script file(s).
5197 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005198 if (is_hidden_fd(sv, fd))
5199 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005200 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005201 if (fd == 2)
5202 copied_fd2 = i;
5203 sv->two_fd[sv_pos].orig = fd;
5204 sv->two_fd[sv_pos].copy = i;
5205 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005206 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005207 if (newfd < 0) {
5208 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005209 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005210 /* Don't want to trigger debugging */
5211 if (fd != -1)
5212 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005213 } else {
5214 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005215 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005216 } else if (fd != newfd) { /* move newfd to fd */
5217 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005218#if ENABLE_ASH_BASH_COMPAT
5219 if (!(redir->nfile.type == NTO2 && fd == 2))
5220#endif
5221 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005222 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005223#if ENABLE_ASH_BASH_COMPAT
5224 if (redir->nfile.type == NTO2 && fd == 1) {
5225 /* We already redirected it to fd 1, now copy it to 2 */
5226 newfd = 1;
5227 fd = 2;
5228 goto redirect_more;
5229 }
5230#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005231 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005232
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005233 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005234 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5235 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005236}
5237
5238/*
5239 * Undo the effects of the last redirection.
5240 */
5241static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005242popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005243{
5244 struct redirtab *rp;
5245 int i;
5246
Denis Vlasenko01631112007-12-16 17:20:38 +00005247 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005248 return;
5249 INT_OFF;
5250 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005251 for (i = 0; i < rp->pair_count; i++) {
5252 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005253 int copy = rp->two_fd[i].copy;
5254 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005255 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005256 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005257 continue;
5258 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005259 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005260 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005261 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005262 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005263 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005264 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005265 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 }
5267 }
5268 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005269 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005270 free(rp);
5271 INT_ON;
5272}
5273
5274/*
5275 * Undo all redirections. Called on error or interrupt.
5276 */
5277
5278/*
5279 * Discard all saved file descriptors.
5280 */
5281static void
5282clearredir(int drop)
5283{
5284 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005285 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005286 if (!redirlist)
5287 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005288 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005289 }
5290}
5291
5292static int
5293redirectsafe(union node *redir, int flags)
5294{
5295 int err;
5296 volatile int saveint;
5297 struct jmploc *volatile savehandler = exception_handler;
5298 struct jmploc jmploc;
5299
5300 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005301 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5302 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005303 if (!err) {
5304 exception_handler = &jmploc;
5305 redirect(redir, flags);
5306 }
5307 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005308 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005309 longjmp(exception_handler->loc, 1);
5310 RESTORE_INT(saveint);
5311 return err;
5312}
5313
5314
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005315/* ============ Routines to expand arguments to commands
5316 *
5317 * We have to deal with backquotes, shell variables, and file metacharacters.
5318 */
5319
Mike Frysinger98c52642009-04-02 10:02:37 +00005320#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005321static arith_t
5322ash_arith(const char *s)
5323{
5324 arith_eval_hooks_t math_hooks;
5325 arith_t result;
5326 int errcode = 0;
5327
5328 math_hooks.lookupvar = lookupvar;
5329 math_hooks.setvar = setvar;
5330 math_hooks.endofname = endofname;
5331
5332 INT_OFF;
5333 result = arith(s, &errcode, &math_hooks);
5334 if (errcode < 0) {
5335 if (errcode == -3)
5336 ash_msg_and_raise_error("exponent less than 0");
5337 if (errcode == -2)
5338 ash_msg_and_raise_error("divide by zero");
5339 if (errcode == -5)
5340 ash_msg_and_raise_error("expression recursion loop detected");
5341 raise_error_syntax(s);
5342 }
5343 INT_ON;
5344
5345 return result;
5346}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005347#endif
5348
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005349/*
5350 * expandarg flags
5351 */
5352#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5353#define EXP_TILDE 0x2 /* do normal tilde expansion */
5354#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5355#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5356#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5357#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5358#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5359#define EXP_WORD 0x80 /* expand word in parameter expansion */
5360#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5361/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005362 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005363 */
5364#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5365#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5366#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5367#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5368#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5369
5370/*
5371 * Structure specifying which parts of the string should be searched
5372 * for IFS characters.
5373 */
5374struct ifsregion {
5375 struct ifsregion *next; /* next region in list */
5376 int begoff; /* offset of start of region */
5377 int endoff; /* offset of end of region */
5378 int nulonly; /* search for nul bytes only */
5379};
5380
5381struct arglist {
5382 struct strlist *list;
5383 struct strlist **lastp;
5384};
5385
5386/* output of current string */
5387static char *expdest;
5388/* list of back quote expressions */
5389static struct nodelist *argbackq;
5390/* first struct in list of ifs regions */
5391static struct ifsregion ifsfirst;
5392/* last struct in list */
5393static struct ifsregion *ifslastp;
5394/* holds expanded arg list */
5395static struct arglist exparg;
5396
5397/*
5398 * Our own itoa().
5399 */
5400static int
5401cvtnum(arith_t num)
5402{
5403 int len;
5404
5405 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005406 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005407 STADJUST(len, expdest);
5408 return len;
5409}
5410
5411static size_t
5412esclen(const char *start, const char *p)
5413{
5414 size_t esc = 0;
5415
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005416 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005417 esc++;
5418 }
5419 return esc;
5420}
5421
5422/*
5423 * Remove any CTLESC characters from a string.
5424 */
5425static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005426rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005427{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005428 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005429
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005430 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005431 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005432 unsigned protect_against_glob;
5433 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434
5435 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005436 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005437 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 q = p;
5440 r = str;
5441 if (flag & RMESCAPE_ALLOC) {
5442 size_t len = p - str;
5443 size_t fulllen = len + strlen(p) + 1;
5444
5445 if (flag & RMESCAPE_GROW) {
5446 r = makestrspace(fulllen, expdest);
5447 } else if (flag & RMESCAPE_HEAP) {
5448 r = ckmalloc(fulllen);
5449 } else {
5450 r = stalloc(fulllen);
5451 }
5452 q = r;
5453 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005454 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005455 }
5456 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005457
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5459 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 while (*p) {
5462 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5464// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5465// Note: both inquotes and protect_against_glob only affect whether
5466// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 inquotes = ~inquotes;
5468 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470 continue;
5471 }
5472 if (*p == '\\') {
5473 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 goto copy;
5476 }
5477 if (*p == CTLESC) {
5478 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005479 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005480 *q++ = '\\';
5481 }
5482 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005483 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 copy:
5485 *q++ = *p++;
5486 }
5487 *q = '\0';
5488 if (flag & RMESCAPE_GROW) {
5489 expdest = r;
5490 STADJUST(q - r + 1, expdest);
5491 }
5492 return r;
5493}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005494#define pmatch(a, b) !fnmatch((a), (b), 0)
5495
5496/*
5497 * Prepare a pattern for a expmeta (internal glob(3)) call.
5498 *
5499 * Returns an stalloced string.
5500 */
5501static char *
5502preglob(const char *pattern, int quoted, int flag)
5503{
5504 flag |= RMESCAPE_GLOB;
5505 if (quoted) {
5506 flag |= RMESCAPE_QUOTED;
5507 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005508 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005509}
5510
5511/*
5512 * Put a string on the stack.
5513 */
5514static void
5515memtodest(const char *p, size_t len, int syntax, int quotes)
5516{
5517 char *q = expdest;
5518
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005519 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005520
5521 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005522 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005523 if (!c)
5524 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005525 if (quotes) {
5526 int n = SIT(c, syntax);
5527 if (n == CCTL || n == CBACK)
5528 USTPUTC(CTLESC, q);
5529 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 USTPUTC(c, q);
5531 }
5532
5533 expdest = q;
5534}
5535
5536static void
5537strtodest(const char *p, int syntax, int quotes)
5538{
5539 memtodest(p, strlen(p), syntax, quotes);
5540}
5541
5542/*
5543 * Record the fact that we have to scan this region of the
5544 * string for IFS characters.
5545 */
5546static void
5547recordregion(int start, int end, int nulonly)
5548{
5549 struct ifsregion *ifsp;
5550
5551 if (ifslastp == NULL) {
5552 ifsp = &ifsfirst;
5553 } else {
5554 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005555 ifsp = ckzalloc(sizeof(*ifsp));
5556 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005557 ifslastp->next = ifsp;
5558 INT_ON;
5559 }
5560 ifslastp = ifsp;
5561 ifslastp->begoff = start;
5562 ifslastp->endoff = end;
5563 ifslastp->nulonly = nulonly;
5564}
5565
5566static void
5567removerecordregions(int endoff)
5568{
5569 if (ifslastp == NULL)
5570 return;
5571
5572 if (ifsfirst.endoff > endoff) {
5573 while (ifsfirst.next != NULL) {
5574 struct ifsregion *ifsp;
5575 INT_OFF;
5576 ifsp = ifsfirst.next->next;
5577 free(ifsfirst.next);
5578 ifsfirst.next = ifsp;
5579 INT_ON;
5580 }
5581 if (ifsfirst.begoff > endoff)
5582 ifslastp = NULL;
5583 else {
5584 ifslastp = &ifsfirst;
5585 ifsfirst.endoff = endoff;
5586 }
5587 return;
5588 }
5589
5590 ifslastp = &ifsfirst;
5591 while (ifslastp->next && ifslastp->next->begoff < endoff)
5592 ifslastp=ifslastp->next;
5593 while (ifslastp->next != NULL) {
5594 struct ifsregion *ifsp;
5595 INT_OFF;
5596 ifsp = ifslastp->next->next;
5597 free(ifslastp->next);
5598 ifslastp->next = ifsp;
5599 INT_ON;
5600 }
5601 if (ifslastp->endoff > endoff)
5602 ifslastp->endoff = endoff;
5603}
5604
5605static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005606exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607{
5608 char c;
5609 char *name;
5610 struct passwd *pw;
5611 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005612 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613 int startloc;
5614
5615 name = p + 1;
5616
5617 while ((c = *++p) != '\0') {
5618 switch (c) {
5619 case CTLESC:
5620 return startp;
5621 case CTLQUOTEMARK:
5622 return startp;
5623 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005624 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005625 goto done;
5626 break;
5627 case '/':
5628 case CTLENDVAR:
5629 goto done;
5630 }
5631 }
5632 done:
5633 *p = '\0';
5634 if (*name == '\0') {
5635 home = lookupvar(homestr);
5636 } else {
5637 pw = getpwnam(name);
5638 if (pw == NULL)
5639 goto lose;
5640 home = pw->pw_dir;
5641 }
5642 if (!home || !*home)
5643 goto lose;
5644 *p = c;
5645 startloc = expdest - (char *)stackblock();
5646 strtodest(home, SQSYNTAX, quotes);
5647 recordregion(startloc, expdest - (char *)stackblock(), 0);
5648 return p;
5649 lose:
5650 *p = c;
5651 return startp;
5652}
5653
5654/*
5655 * Execute a command inside back quotes. If it's a builtin command, we
5656 * want to save its output in a block obtained from malloc. Otherwise
5657 * we fork off a subprocess and get the output of the command via a pipe.
5658 * Should be called with interrupts off.
5659 */
5660struct backcmd { /* result of evalbackcmd */
5661 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005663 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664 struct job *jp; /* job structure for command */
5665};
5666
5667/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005668static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005670static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005672static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005673evalbackcmd(union node *n, struct backcmd *result)
5674{
5675 int saveherefd;
5676
5677 result->fd = -1;
5678 result->buf = NULL;
5679 result->nleft = 0;
5680 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005681 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005683
5684 saveherefd = herefd;
5685 herefd = -1;
5686
5687 {
5688 int pip[2];
5689 struct job *jp;
5690
5691 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005692 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005693 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5695 FORCE_INT_ON;
5696 close(pip[0]);
5697 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005698 /*close(1);*/
5699 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 close(pip[1]);
5701 }
5702 eflag = 0;
5703 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5704 /* NOTREACHED */
5705 }
5706 close(pip[1]);
5707 result->fd = pip[0];
5708 result->jp = jp;
5709 }
5710 herefd = saveherefd;
5711 out:
5712 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5713 result->fd, result->buf, result->nleft, result->jp));
5714}
5715
5716/*
5717 * Expand stuff in backwards quotes.
5718 */
5719static void
5720expbackq(union node *cmd, int quoted, int quotes)
5721{
5722 struct backcmd in;
5723 int i;
5724 char buf[128];
5725 char *p;
5726 char *dest;
5727 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005728 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005729 struct stackmark smark;
5730
5731 INT_OFF;
5732 setstackmark(&smark);
5733 dest = expdest;
5734 startloc = dest - (char *)stackblock();
5735 grabstackstr(dest);
5736 evalbackcmd(cmd, &in);
5737 popstackmark(&smark);
5738
5739 p = in.buf;
5740 i = in.nleft;
5741 if (i == 0)
5742 goto read;
5743 for (;;) {
5744 memtodest(p, i, syntax, quotes);
5745 read:
5746 if (in.fd < 0)
5747 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005748 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005749 TRACE(("expbackq: read returns %d\n", i));
5750 if (i <= 0)
5751 break;
5752 p = buf;
5753 }
5754
Denis Vlasenko60818682007-09-28 22:07:23 +00005755 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005756 if (in.fd >= 0) {
5757 close(in.fd);
5758 back_exitstatus = waitforjob(in.jp);
5759 }
5760 INT_ON;
5761
5762 /* Eat all trailing newlines */
5763 dest = expdest;
5764 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5765 STUNPUTC(dest);
5766 expdest = dest;
5767
5768 if (quoted == 0)
5769 recordregion(startloc, dest - (char *)stackblock(), 0);
5770 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5771 (dest - (char *)stackblock()) - startloc,
5772 (dest - (char *)stackblock()) - startloc,
5773 stackblock() + startloc));
5774}
5775
Mike Frysinger98c52642009-04-02 10:02:37 +00005776#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005777/*
5778 * Expand arithmetic expression. Backup to start of expression,
5779 * evaluate, place result in (backed up) result, adjust string position.
5780 */
5781static void
5782expari(int quotes)
5783{
5784 char *p, *start;
5785 int begoff;
5786 int flag;
5787 int len;
5788
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005789 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005790
5791 /*
5792 * This routine is slightly over-complicated for
5793 * efficiency. Next we scan backwards looking for the
5794 * start of arithmetic.
5795 */
5796 start = stackblock();
5797 p = expdest - 1;
5798 *p = '\0';
5799 p--;
5800 do {
5801 int esc;
5802
5803 while (*p != CTLARI) {
5804 p--;
5805#if DEBUG
5806 if (p < start) {
5807 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5808 }
5809#endif
5810 }
5811
5812 esc = esclen(start, p);
5813 if (!(esc % 2)) {
5814 break;
5815 }
5816
5817 p -= esc + 1;
5818 } while (1);
5819
5820 begoff = p - start;
5821
5822 removerecordregions(begoff);
5823
5824 flag = p[1];
5825
5826 expdest = p;
5827
5828 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005829 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005831 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005832
5833 if (flag != '"')
5834 recordregion(begoff, begoff + len, 0);
5835}
5836#endif
5837
5838/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005839static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005840
5841/*
5842 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5843 * characters to allow for further processing. Otherwise treat
5844 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005845 *
5846 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5847 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5848 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849 */
5850static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005851argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005852{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005853 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 '=',
5855 ':',
5856 CTLQUOTEMARK,
5857 CTLENDVAR,
5858 CTLESC,
5859 CTLVAR,
5860 CTLBACKQ,
5861 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005862#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 CTLENDARI,
5864#endif
5865 0
5866 };
5867 const char *reject = spclchars;
5868 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005869 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5870 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005871 int inquotes;
5872 size_t length;
5873 int startloc;
5874
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005875 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005877 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 reject++;
5879 }
5880 inquotes = 0;
5881 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 char *q;
5884
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005886 tilde:
5887 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005888 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005889 q++;
5890 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005891 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005892 }
5893 start:
5894 startloc = expdest - (char *)stackblock();
5895 for (;;) {
5896 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 c = (unsigned char) p[length];
5898 if (c) {
5899 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005900#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005901 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005902#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005903 ) {
5904 /* c == '=' || c == ':' || c == CTLENDARI */
5905 length++;
5906 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005907 }
5908 if (length > 0) {
5909 int newloc;
5910 expdest = stack_nputstr(p, length, expdest);
5911 newloc = expdest - (char *)stackblock();
5912 if (breakall && !inquotes && newloc > startloc) {
5913 recordregion(startloc, newloc, 0);
5914 }
5915 startloc = newloc;
5916 }
5917 p += length + 1;
5918 length = 0;
5919
5920 switch (c) {
5921 case '\0':
5922 goto breakloop;
5923 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005924 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005925 p--;
5926 continue;
5927 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005928 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 reject++;
5930 /* fall through */
5931 case ':':
5932 /*
5933 * sort of a hack - expand tildes in variable
5934 * assignments (after the first '=' and after ':'s).
5935 */
5936 if (*--p == '~') {
5937 goto tilde;
5938 }
5939 continue;
5940 }
5941
5942 switch (c) {
5943 case CTLENDVAR: /* ??? */
5944 goto breakloop;
5945 case CTLQUOTEMARK:
5946 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005947 if (!inquotes
5948 && memcmp(p, dolatstr, 4) == 0
5949 && ( p[4] == CTLQUOTEMARK
5950 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5951 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005952 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005953 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005954 goto start;
5955 }
5956 inquotes = !inquotes;
5957 addquote:
5958 if (quotes) {
5959 p--;
5960 length++;
5961 startloc++;
5962 }
5963 break;
5964 case CTLESC:
5965 startloc++;
5966 length++;
5967 goto addquote;
5968 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005969 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005970 goto start;
5971 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005972 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 case CTLBACKQ|CTLQUOTE:
5974 expbackq(argbackq->n, c, quotes);
5975 argbackq = argbackq->next;
5976 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005977#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005978 case CTLENDARI:
5979 p--;
5980 expari(quotes);
5981 goto start;
5982#endif
5983 }
5984 }
5985 breakloop:
5986 ;
5987}
5988
5989static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005990scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005991 int zero)
5992{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005993// This commented out code was added by James Simmons <jsimmons@infradead.org>
5994// as part of a larger change when he added support for ${var/a/b}.
5995// However, it broke # and % operators:
5996//
5997//var=ababcdcd
5998// ok bad
5999//echo ${var#ab} abcdcd abcdcd
6000//echo ${var##ab} abcdcd abcdcd
6001//echo ${var#a*b} abcdcd ababcdcd (!)
6002//echo ${var##a*b} cdcd cdcd
6003//echo ${var#?} babcdcd ababcdcd (!)
6004//echo ${var##?} babcdcd babcdcd
6005//echo ${var#*} ababcdcd babcdcd (!)
6006//echo ${var##*}
6007//echo ${var%cd} ababcd ababcd
6008//echo ${var%%cd} ababcd abab (!)
6009//echo ${var%c*d} ababcd ababcd
6010//echo ${var%%c*d} abab ababcdcd (!)
6011//echo ${var%?} ababcdc ababcdc
6012//echo ${var%%?} ababcdc ababcdcd (!)
6013//echo ${var%*} ababcdcd ababcdcd
6014//echo ${var%%*}
6015//
6016// Commenting it back out helped. Remove it completely if it really
6017// is not needed.
6018
6019 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006020 char c;
6021
6022 loc = startp;
6023 loc2 = rmesc;
6024 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006025 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006026 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006027
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006028 c = *loc2;
6029 if (zero) {
6030 *loc2 = '\0';
6031 s = rmesc;
6032 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006033 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006034
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006035// // chop off end if its '*'
6036// full = strrchr(str, '*');
6037// if (full && full != str)
6038// match--;
6039//
6040// // If str starts with '*' replace with s.
6041// if ((*str == '*') && strlen(s) >= match) {
6042// full = xstrdup(s);
6043// strncpy(full+strlen(s)-match+1, str+1, match-1);
6044// } else
6045// full = xstrndup(str, match);
6046// match = strncmp(s, full, strlen(full));
6047// free(full);
6048//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006049 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006050 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006051 return loc;
6052 if (quotes && *loc == CTLESC)
6053 loc++;
6054 loc++;
6055 loc2++;
6056 } while (c);
6057 return 0;
6058}
6059
6060static char *
6061scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6062 int zero)
6063{
6064 int esc = 0;
6065 char *loc;
6066 char *loc2;
6067
6068 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6069 int match;
6070 char c = *loc2;
6071 const char *s = loc2;
6072 if (zero) {
6073 *loc2 = '\0';
6074 s = rmesc;
6075 }
6076 match = pmatch(str, s);
6077 *loc2 = c;
6078 if (match)
6079 return loc;
6080 loc--;
6081 if (quotes) {
6082 if (--esc < 0) {
6083 esc = esclen(startp, loc);
6084 }
6085 if (esc % 2) {
6086 esc--;
6087 loc--;
6088 }
6089 }
6090 }
6091 return 0;
6092}
6093
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006094static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006095static void
6096varunset(const char *end, const char *var, const char *umsg, int varflags)
6097{
6098 const char *msg;
6099 const char *tail;
6100
6101 tail = nullstr;
6102 msg = "parameter not set";
6103 if (umsg) {
6104 if (*end == CTLENDVAR) {
6105 if (varflags & VSNUL)
6106 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006107 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006108 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006109 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006110 }
6111 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6112}
6113
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006114#if ENABLE_ASH_BASH_COMPAT
6115static char *
6116parse_sub_pattern(char *arg, int inquotes)
6117{
6118 char *idx, *repl = NULL;
6119 unsigned char c;
6120
Denis Vlasenko2659c632008-06-14 06:04:59 +00006121 idx = arg;
6122 while (1) {
6123 c = *arg;
6124 if (!c)
6125 break;
6126 if (c == '/') {
6127 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006128 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006129 repl = idx + 1;
6130 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006131 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006132 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006133 *idx++ = c;
6134 if (!inquotes && c == '\\' && arg[1] == '\\')
6135 arg++; /* skip both \\, not just first one */
6136 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006138 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006139
6140 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006141}
6142#endif /* ENABLE_ASH_BASH_COMPAT */
6143
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006144static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006145subevalvar(char *p, char *str, int strloc, int subtype,
6146 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006147{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006148 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149 char *startp;
6150 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006152 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6153 IF_ASH_BASH_COMPAT(char null = '\0';)
6154 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006155 int saveherefd = herefd;
6156 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006157 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006158 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006159
6160 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006161 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6162 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006163 STPUTC('\0', expdest);
6164 herefd = saveherefd;
6165 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006166 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006167
6168 switch (subtype) {
6169 case VSASSIGN:
6170 setvar(str, startp, 0);
6171 amount = startp - expdest;
6172 STADJUST(amount, expdest);
6173 return startp;
6174
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175#if ENABLE_ASH_BASH_COMPAT
6176 case VSSUBSTR:
6177 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006178 /* Read POS in ${var:POS:LEN} */
6179 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 len = str - startp - 1;
6181
6182 /* *loc != '\0', guaranteed by parser */
6183 if (quotes) {
6184 char *ptr;
6185
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006186 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006187 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006188 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006189 len--;
6190 ptr++;
6191 }
6192 }
6193 }
6194 orig_len = len;
6195
6196 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006197 /* ${var::LEN} */
6198 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006199 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006200 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006201 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006202 while (*loc && *loc != ':') {
6203 /* TODO?
6204 * bash complains on: var=qwe; echo ${var:1a:123}
6205 if (!isdigit(*loc))
6206 ash_msg_and_raise_error(msg_illnum, str);
6207 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006209 }
6210 if (*loc++ == ':') {
6211 len = number(loc);
6212 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006213 }
6214 if (pos >= orig_len) {
6215 pos = 0;
6216 len = 0;
6217 }
6218 if (len > (orig_len - pos))
6219 len = orig_len - pos;
6220
6221 for (str = startp; pos; str++, pos--) {
6222 if (quotes && *str == CTLESC)
6223 str++;
6224 }
6225 for (loc = startp; len; len--) {
6226 if (quotes && *str == CTLESC)
6227 *loc++ = *str++;
6228 *loc++ = *str++;
6229 }
6230 *loc = '\0';
6231 amount = loc - expdest;
6232 STADJUST(amount, expdest);
6233 return loc;
6234#endif
6235
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006236 case VSQUESTION:
6237 varunset(p, str, startp, varflags);
6238 /* NOTREACHED */
6239 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006240 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006241
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006242 /* We'll comeback here if we grow the stack while handling
6243 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6244 * stack will need rebasing, and we'll need to remove our work
6245 * areas each time
6246 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006247 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006248
6249 amount = expdest - ((char *)stackblock() + resetloc);
6250 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006251 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006252
6253 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006254 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006255 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006256 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006257 if (rmesc != startp) {
6258 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006259 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006260 }
6261 }
6262 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006263 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006265 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006266
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006267#if ENABLE_ASH_BASH_COMPAT
6268 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6269 char *idx, *end, *restart_detect;
6270
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006271 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6273 if (!repl)
6274 repl = &null;
6275 }
6276
6277 /* If there's no pattern to match, return the expansion unmolested */
6278 if (*str == '\0')
6279 return 0;
6280
6281 len = 0;
6282 idx = startp;
6283 end = str - 1;
6284 while (idx < end) {
6285 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6286 if (!loc) {
6287 /* No match, advance */
6288 restart_detect = stackblock();
6289 STPUTC(*idx, expdest);
6290 if (quotes && *idx == CTLESC) {
6291 idx++;
6292 len++;
6293 STPUTC(*idx, expdest);
6294 }
6295 if (stackblock() != restart_detect)
6296 goto restart;
6297 idx++;
6298 len++;
6299 rmesc++;
6300 continue;
6301 }
6302
6303 if (subtype == VSREPLACEALL) {
6304 while (idx < loc) {
6305 if (quotes && *idx == CTLESC)
6306 idx++;
6307 idx++;
6308 rmesc++;
6309 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006310 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006311 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006312 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006313
6314 for (loc = repl; *loc; loc++) {
6315 restart_detect = stackblock();
6316 STPUTC(*loc, expdest);
6317 if (stackblock() != restart_detect)
6318 goto restart;
6319 len++;
6320 }
6321
6322 if (subtype == VSREPLACE) {
6323 while (*idx) {
6324 restart_detect = stackblock();
6325 STPUTC(*idx, expdest);
6326 if (stackblock() != restart_detect)
6327 goto restart;
6328 len++;
6329 idx++;
6330 }
6331 break;
6332 }
6333 }
6334
6335 /* We've put the replaced text into a buffer at workloc, now
6336 * move it to the right place and adjust the stack.
6337 */
6338 startp = stackblock() + startloc;
6339 STPUTC('\0', expdest);
6340 memmove(startp, stackblock() + workloc, len);
6341 startp[len++] = '\0';
6342 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6343 STADJUST(-amount, expdest);
6344 return startp;
6345 }
6346#endif /* ENABLE_ASH_BASH_COMPAT */
6347
6348 subtype -= VSTRIMRIGHT;
6349#if DEBUG
6350 if (subtype < 0 || subtype > 7)
6351 abort();
6352#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006353 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6354 zero = subtype >> 1;
6355 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6356 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6357
6358 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6359 if (loc) {
6360 if (zero) {
6361 memmove(startp, loc, str - loc);
6362 loc = startp + (str - loc) - 1;
6363 }
6364 *loc = '\0';
6365 amount = loc - expdest;
6366 STADJUST(amount, expdest);
6367 }
6368 return loc;
6369}
6370
6371/*
6372 * Add the value of a specialized variable to the stack string.
6373 */
6374static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006375varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006376{
6377 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006378 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006379 int i;
6380 int sep = 0;
6381 int sepq = 0;
6382 ssize_t len = 0;
6383 char **ap;
6384 int syntax;
6385 int quoted = varflags & VSQUOTE;
6386 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006387 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006388
6389 if (quoted && (flags & EXP_FULL))
6390 sep = 1 << CHAR_BIT;
6391
6392 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6393 switch (*name) {
6394 case '$':
6395 num = rootpid;
6396 goto numvar;
6397 case '?':
6398 num = exitstatus;
6399 goto numvar;
6400 case '#':
6401 num = shellparam.nparam;
6402 goto numvar;
6403 case '!':
6404 num = backgndpid;
6405 if (num == 0)
6406 return -1;
6407 numvar:
6408 len = cvtnum(num);
6409 break;
6410 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006411 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006412 for (i = NOPTS - 1; i >= 0; i--) {
6413 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006414 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415 len++;
6416 }
6417 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006418 break;
6419 case '@':
6420 if (sep)
6421 goto param;
6422 /* fall through */
6423 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006424 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6426 sepq = 1;
6427 param:
6428 ap = shellparam.p;
6429 if (!ap)
6430 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006431 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006432 size_t partlen;
6433
6434 partlen = strlen(p);
6435 len += partlen;
6436
6437 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6438 memtodest(p, partlen, syntax, quotes);
6439
6440 if (*ap && sep) {
6441 char *q;
6442
6443 len++;
6444 if (subtype == VSPLUS || subtype == VSLENGTH) {
6445 continue;
6446 }
6447 q = expdest;
6448 if (sepq)
6449 STPUTC(CTLESC, q);
6450 STPUTC(sep, q);
6451 expdest = q;
6452 }
6453 }
6454 return len;
6455 case '0':
6456 case '1':
6457 case '2':
6458 case '3':
6459 case '4':
6460 case '5':
6461 case '6':
6462 case '7':
6463 case '8':
6464 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006465 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006466 if (num < 0 || num > shellparam.nparam)
6467 return -1;
6468 p = num ? shellparam.p[num - 1] : arg0;
6469 goto value;
6470 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006471 /* NB: name has form "VAR=..." */
6472
6473 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6474 * which should be considered before we check variables. */
6475 if (var_str_list) {
6476 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6477 p = NULL;
6478 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006479 char *str, *eq;
6480 str = var_str_list->text;
6481 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006482 if (!eq) /* stop at first non-assignment */
6483 break;
6484 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006485 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006486 && strncmp(str, name, name_len) == 0) {
6487 p = eq;
6488 /* goto value; - WRONG! */
6489 /* think "A=1 A=2 B=$A" */
6490 }
6491 var_str_list = var_str_list->next;
6492 } while (var_str_list);
6493 if (p)
6494 goto value;
6495 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006496 p = lookupvar(name);
6497 value:
6498 if (!p)
6499 return -1;
6500
6501 len = strlen(p);
6502 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6503 memtodest(p, len, syntax, quotes);
6504 return len;
6505 }
6506
6507 if (subtype == VSPLUS || subtype == VSLENGTH)
6508 STADJUST(-len, expdest);
6509 return len;
6510}
6511
6512/*
6513 * Expand a variable, and return a pointer to the next character in the
6514 * input string.
6515 */
6516static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006517evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006518{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006519 char varflags;
6520 char subtype;
6521 char quoted;
6522 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 char *var;
6524 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006525 int startloc;
6526 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006527
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006528 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529 subtype = varflags & VSTYPE;
6530 quoted = varflags & VSQUOTE;
6531 var = p;
6532 easy = (!quoted || (*var == '@' && shellparam.nparam));
6533 startloc = expdest - (char *)stackblock();
6534 p = strchr(p, '=') + 1;
6535
6536 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006537 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006538 if (varflags & VSNUL)
6539 varlen--;
6540
6541 if (subtype == VSPLUS) {
6542 varlen = -1 - varlen;
6543 goto vsplus;
6544 }
6545
6546 if (subtype == VSMINUS) {
6547 vsplus:
6548 if (varlen < 0) {
6549 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006550 p, flags | EXP_TILDE |
6551 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006552 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006553 );
6554 goto end;
6555 }
6556 if (easy)
6557 goto record;
6558 goto end;
6559 }
6560
6561 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6562 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006563 if (subevalvar(p, var, /* strloc: */ 0,
6564 subtype, startloc, varflags,
6565 /* quotes: */ 0,
6566 var_str_list)
6567 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006568 varflags &= ~VSNUL;
6569 /*
6570 * Remove any recorded regions beyond
6571 * start of variable
6572 */
6573 removerecordregions(startloc);
6574 goto again;
6575 }
6576 goto end;
6577 }
6578 if (easy)
6579 goto record;
6580 goto end;
6581 }
6582
6583 if (varlen < 0 && uflag)
6584 varunset(p, var, 0, 0);
6585
6586 if (subtype == VSLENGTH) {
6587 cvtnum(varlen > 0 ? varlen : 0);
6588 goto record;
6589 }
6590
6591 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006592 if (easy)
6593 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594 goto end;
6595 }
6596
6597#if DEBUG
6598 switch (subtype) {
6599 case VSTRIMLEFT:
6600 case VSTRIMLEFTMAX:
6601 case VSTRIMRIGHT:
6602 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006603#if ENABLE_ASH_BASH_COMPAT
6604 case VSSUBSTR:
6605 case VSREPLACE:
6606 case VSREPLACEALL:
6607#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006608 break;
6609 default:
6610 abort();
6611 }
6612#endif
6613
6614 if (varlen >= 0) {
6615 /*
6616 * Terminate the string and start recording the pattern
6617 * right after it
6618 */
6619 STPUTC('\0', expdest);
6620 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006621 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6622 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006623//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006624 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006625 var_str_list)
6626 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006627 int amount = expdest - (
6628 (char *)stackblock() + patloc - 1
6629 );
6630 STADJUST(-amount, expdest);
6631 }
6632 /* Remove any recorded regions beyond start of variable */
6633 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006634 record:
6635 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006636 }
6637
6638 end:
6639 if (subtype != VSNORMAL) { /* skip to end of alternative */
6640 int nesting = 1;
6641 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006642 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 if (c == CTLESC)
6644 p++;
6645 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6646 if (varlen >= 0)
6647 argbackq = argbackq->next;
6648 } else if (c == CTLVAR) {
6649 if ((*p++ & VSTYPE) != VSNORMAL)
6650 nesting++;
6651 } else if (c == CTLENDVAR) {
6652 if (--nesting == 0)
6653 break;
6654 }
6655 }
6656 }
6657 return p;
6658}
6659
6660/*
6661 * Break the argument string into pieces based upon IFS and add the
6662 * strings to the argument list. The regions of the string to be
6663 * searched for IFS characters have been stored by recordregion.
6664 */
6665static void
6666ifsbreakup(char *string, struct arglist *arglist)
6667{
6668 struct ifsregion *ifsp;
6669 struct strlist *sp;
6670 char *start;
6671 char *p;
6672 char *q;
6673 const char *ifs, *realifs;
6674 int ifsspc;
6675 int nulonly;
6676
6677 start = string;
6678 if (ifslastp != NULL) {
6679 ifsspc = 0;
6680 nulonly = 0;
6681 realifs = ifsset() ? ifsval() : defifs;
6682 ifsp = &ifsfirst;
6683 do {
6684 p = string + ifsp->begoff;
6685 nulonly = ifsp->nulonly;
6686 ifs = nulonly ? nullstr : realifs;
6687 ifsspc = 0;
6688 while (p < string + ifsp->endoff) {
6689 q = p;
6690 if (*p == CTLESC)
6691 p++;
6692 if (!strchr(ifs, *p)) {
6693 p++;
6694 continue;
6695 }
6696 if (!nulonly)
6697 ifsspc = (strchr(defifs, *p) != NULL);
6698 /* Ignore IFS whitespace at start */
6699 if (q == start && ifsspc) {
6700 p++;
6701 start = p;
6702 continue;
6703 }
6704 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006705 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006706 sp->text = start;
6707 *arglist->lastp = sp;
6708 arglist->lastp = &sp->next;
6709 p++;
6710 if (!nulonly) {
6711 for (;;) {
6712 if (p >= string + ifsp->endoff) {
6713 break;
6714 }
6715 q = p;
6716 if (*p == CTLESC)
6717 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006718 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006719 p = q;
6720 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006721 }
6722 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006723 if (ifsspc) {
6724 p++;
6725 ifsspc = 0;
6726 } else {
6727 p = q;
6728 break;
6729 }
6730 } else
6731 p++;
6732 }
6733 }
6734 start = p;
6735 } /* while */
6736 ifsp = ifsp->next;
6737 } while (ifsp != NULL);
6738 if (nulonly)
6739 goto add;
6740 }
6741
6742 if (!*start)
6743 return;
6744
6745 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006746 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006747 sp->text = start;
6748 *arglist->lastp = sp;
6749 arglist->lastp = &sp->next;
6750}
6751
6752static void
6753ifsfree(void)
6754{
6755 struct ifsregion *p;
6756
6757 INT_OFF;
6758 p = ifsfirst.next;
6759 do {
6760 struct ifsregion *ifsp;
6761 ifsp = p->next;
6762 free(p);
6763 p = ifsp;
6764 } while (p);
6765 ifslastp = NULL;
6766 ifsfirst.next = NULL;
6767 INT_ON;
6768}
6769
6770/*
6771 * Add a file name to the list.
6772 */
6773static void
6774addfname(const char *name)
6775{
6776 struct strlist *sp;
6777
Denis Vlasenko597906c2008-02-20 16:38:54 +00006778 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006779 sp->text = ststrdup(name);
6780 *exparg.lastp = sp;
6781 exparg.lastp = &sp->next;
6782}
6783
6784static char *expdir;
6785
6786/*
6787 * Do metacharacter (i.e. *, ?, [...]) expansion.
6788 */
6789static void
6790expmeta(char *enddir, char *name)
6791{
6792 char *p;
6793 const char *cp;
6794 char *start;
6795 char *endname;
6796 int metaflag;
6797 struct stat statb;
6798 DIR *dirp;
6799 struct dirent *dp;
6800 int atend;
6801 int matchdot;
6802
6803 metaflag = 0;
6804 start = name;
6805 for (p = name; *p; p++) {
6806 if (*p == '*' || *p == '?')
6807 metaflag = 1;
6808 else if (*p == '[') {
6809 char *q = p + 1;
6810 if (*q == '!')
6811 q++;
6812 for (;;) {
6813 if (*q == '\\')
6814 q++;
6815 if (*q == '/' || *q == '\0')
6816 break;
6817 if (*++q == ']') {
6818 metaflag = 1;
6819 break;
6820 }
6821 }
6822 } else if (*p == '\\')
6823 p++;
6824 else if (*p == '/') {
6825 if (metaflag)
6826 goto out;
6827 start = p + 1;
6828 }
6829 }
6830 out:
6831 if (metaflag == 0) { /* we've reached the end of the file name */
6832 if (enddir != expdir)
6833 metaflag++;
6834 p = name;
6835 do {
6836 if (*p == '\\')
6837 p++;
6838 *enddir++ = *p;
6839 } while (*p++);
6840 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6841 addfname(expdir);
6842 return;
6843 }
6844 endname = p;
6845 if (name < start) {
6846 p = name;
6847 do {
6848 if (*p == '\\')
6849 p++;
6850 *enddir++ = *p++;
6851 } while (p < start);
6852 }
6853 if (enddir == expdir) {
6854 cp = ".";
6855 } else if (enddir == expdir + 1 && *expdir == '/') {
6856 cp = "/";
6857 } else {
6858 cp = expdir;
6859 enddir[-1] = '\0';
6860 }
6861 dirp = opendir(cp);
6862 if (dirp == NULL)
6863 return;
6864 if (enddir != expdir)
6865 enddir[-1] = '/';
6866 if (*endname == 0) {
6867 atend = 1;
6868 } else {
6869 atend = 0;
6870 *endname++ = '\0';
6871 }
6872 matchdot = 0;
6873 p = start;
6874 if (*p == '\\')
6875 p++;
6876 if (*p == '.')
6877 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006878 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006879 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006880 continue;
6881 if (pmatch(start, dp->d_name)) {
6882 if (atend) {
6883 strcpy(enddir, dp->d_name);
6884 addfname(expdir);
6885 } else {
6886 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6887 continue;
6888 p[-1] = '/';
6889 expmeta(p, endname);
6890 }
6891 }
6892 }
6893 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006894 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006895 endname[-1] = '/';
6896}
6897
6898static struct strlist *
6899msort(struct strlist *list, int len)
6900{
6901 struct strlist *p, *q = NULL;
6902 struct strlist **lpp;
6903 int half;
6904 int n;
6905
6906 if (len <= 1)
6907 return list;
6908 half = len >> 1;
6909 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006910 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006911 q = p;
6912 p = p->next;
6913 }
6914 q->next = NULL; /* terminate first half of list */
6915 q = msort(list, half); /* sort first half of list */
6916 p = msort(p, len - half); /* sort second half */
6917 lpp = &list;
6918 for (;;) {
6919#if ENABLE_LOCALE_SUPPORT
6920 if (strcoll(p->text, q->text) < 0)
6921#else
6922 if (strcmp(p->text, q->text) < 0)
6923#endif
6924 {
6925 *lpp = p;
6926 lpp = &p->next;
6927 p = *lpp;
6928 if (p == NULL) {
6929 *lpp = q;
6930 break;
6931 }
6932 } else {
6933 *lpp = q;
6934 lpp = &q->next;
6935 q = *lpp;
6936 if (q == NULL) {
6937 *lpp = p;
6938 break;
6939 }
6940 }
6941 }
6942 return list;
6943}
6944
6945/*
6946 * Sort the results of file name expansion. It calculates the number of
6947 * strings to sort and then calls msort (short for merge sort) to do the
6948 * work.
6949 */
6950static struct strlist *
6951expsort(struct strlist *str)
6952{
6953 int len;
6954 struct strlist *sp;
6955
6956 len = 0;
6957 for (sp = str; sp; sp = sp->next)
6958 len++;
6959 return msort(str, len);
6960}
6961
6962static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006963expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006964{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006965 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006966 '*', '?', '[', 0
6967 };
6968 /* TODO - EXP_REDIR */
6969
6970 while (str) {
6971 struct strlist **savelastp;
6972 struct strlist *sp;
6973 char *p;
6974
6975 if (fflag)
6976 goto nometa;
6977 if (!strpbrk(str->text, metachars))
6978 goto nometa;
6979 savelastp = exparg.lastp;
6980
6981 INT_OFF;
6982 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6983 {
6984 int i = strlen(str->text);
6985 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6986 }
6987
6988 expmeta(expdir, p);
6989 free(expdir);
6990 if (p != str->text)
6991 free(p);
6992 INT_ON;
6993 if (exparg.lastp == savelastp) {
6994 /*
6995 * no matches
6996 */
6997 nometa:
6998 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006999 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007000 exparg.lastp = &str->next;
7001 } else {
7002 *exparg.lastp = NULL;
7003 *savelastp = sp = expsort(*savelastp);
7004 while (sp->next != NULL)
7005 sp = sp->next;
7006 exparg.lastp = &sp->next;
7007 }
7008 str = str->next;
7009 }
7010}
7011
7012/*
7013 * Perform variable substitution and command substitution on an argument,
7014 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7015 * perform splitting and file name expansion. When arglist is NULL, perform
7016 * here document expansion.
7017 */
7018static void
7019expandarg(union node *arg, struct arglist *arglist, int flag)
7020{
7021 struct strlist *sp;
7022 char *p;
7023
7024 argbackq = arg->narg.backquote;
7025 STARTSTACKSTR(expdest);
7026 ifsfirst.next = NULL;
7027 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007028 argstr(arg->narg.text, flag,
7029 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007030 p = _STPUTC('\0', expdest);
7031 expdest = p - 1;
7032 if (arglist == NULL) {
7033 return; /* here document expanded */
7034 }
7035 p = grabstackstr(p);
7036 exparg.lastp = &exparg.list;
7037 /*
7038 * TODO - EXP_REDIR
7039 */
7040 if (flag & EXP_FULL) {
7041 ifsbreakup(p, &exparg);
7042 *exparg.lastp = NULL;
7043 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007044 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007045 } else {
7046 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007047 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007048 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007049 sp->text = p;
7050 *exparg.lastp = sp;
7051 exparg.lastp = &sp->next;
7052 }
7053 if (ifsfirst.next)
7054 ifsfree();
7055 *exparg.lastp = NULL;
7056 if (exparg.list) {
7057 *arglist->lastp = exparg.list;
7058 arglist->lastp = exparg.lastp;
7059 }
7060}
7061
7062/*
7063 * Expand shell variables and backquotes inside a here document.
7064 */
7065static void
7066expandhere(union node *arg, int fd)
7067{
7068 herefd = fd;
7069 expandarg(arg, (struct arglist *)NULL, 0);
7070 full_write(fd, stackblock(), expdest - (char *)stackblock());
7071}
7072
7073/*
7074 * Returns true if the pattern matches the string.
7075 */
7076static int
7077patmatch(char *pattern, const char *string)
7078{
7079 return pmatch(preglob(pattern, 0, 0), string);
7080}
7081
7082/*
7083 * See if a pattern matches in a case statement.
7084 */
7085static int
7086casematch(union node *pattern, char *val)
7087{
7088 struct stackmark smark;
7089 int result;
7090
7091 setstackmark(&smark);
7092 argbackq = pattern->narg.backquote;
7093 STARTSTACKSTR(expdest);
7094 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007095 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7096 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007097 STACKSTRNUL(expdest);
7098 result = patmatch(stackblock(), val);
7099 popstackmark(&smark);
7100 return result;
7101}
7102
7103
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007104/* ============ find_command */
7105
7106struct builtincmd {
7107 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007108 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007109 /* unsigned flags; */
7110};
7111#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007112/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007113 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007114#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007115#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007116
7117struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007118 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007119 union param {
7120 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007121 /* index >= 0 for commands without path (slashes) */
7122 /* (TODO: what exactly does the value mean? PATH position?) */
7123 /* index == -1 for commands with slashes */
7124 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125 const struct builtincmd *cmd;
7126 struct funcnode *func;
7127 } u;
7128};
7129/* values of cmdtype */
7130#define CMDUNKNOWN -1 /* no entry in table for command */
7131#define CMDNORMAL 0 /* command is an executable program */
7132#define CMDFUNCTION 1 /* command is a shell function */
7133#define CMDBUILTIN 2 /* command is a shell builtin */
7134
7135/* action to find_command() */
7136#define DO_ERR 0x01 /* prints errors */
7137#define DO_ABS 0x02 /* checks absolute paths */
7138#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7139#define DO_ALTPATH 0x08 /* using alternate path */
7140#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7141
7142static void find_command(char *, struct cmdentry *, int, const char *);
7143
7144
7145/* ============ Hashing commands */
7146
7147/*
7148 * When commands are first encountered, they are entered in a hash table.
7149 * This ensures that a full path search will not have to be done for them
7150 * on each invocation.
7151 *
7152 * We should investigate converting to a linear search, even though that
7153 * would make the command name "hash" a misnomer.
7154 */
7155
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007156struct tblentry {
7157 struct tblentry *next; /* next entry in hash chain */
7158 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007159 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007160 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007161 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162};
7163
Denis Vlasenko01631112007-12-16 17:20:38 +00007164static struct tblentry **cmdtable;
7165#define INIT_G_cmdtable() do { \
7166 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7167} while (0)
7168
7169static int builtinloc = -1; /* index in path of %builtin, or -1 */
7170
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171
7172static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007173tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174{
7175 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007177#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007178 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007179 if (APPLET_IS_NOEXEC(applet_no)) {
7180 while (*envp)
7181 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007182 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007183 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007184 /* re-exec ourselves with the new arguments */
7185 execve(bb_busybox_exec_path, argv, envp);
7186 /* If they called chroot or otherwise made the binary no longer
7187 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007188 }
7189#endif
7190
7191 repeat:
7192#ifdef SYSV
7193 do {
7194 execve(cmd, argv, envp);
7195 } while (errno == EINTR);
7196#else
7197 execve(cmd, argv, envp);
7198#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007199 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007200 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007201 return;
7202 }
7203 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007204 char **ap;
7205 char **new;
7206
7207 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007208 continue;
7209 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007210 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007211 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007212 ap += 2;
7213 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007214 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007215 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007216 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007217 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007218 goto repeat;
7219 }
7220}
7221
7222/*
7223 * Exec a program. Never returns. If you change this routine, you may
7224 * have to change the find_command routine as well.
7225 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007226static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007227static void
7228shellexec(char **argv, const char *path, int idx)
7229{
7230 char *cmdname;
7231 int e;
7232 char **envp;
7233 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007234#if ENABLE_FEATURE_SH_STANDALONE
7235 int applet_no = -1;
7236#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007238 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007239 envp = listvars(VEXPORT, VUNSET, 0);
7240 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007241#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007242 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243#endif
7244 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007245 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246 e = errno;
7247 } else {
7248 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007249 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007250 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007251 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007252 if (errno != ENOENT && errno != ENOTDIR)
7253 e = errno;
7254 }
7255 stunalloc(cmdname);
7256 }
7257 }
7258
7259 /* Map to POSIX errors */
7260 switch (e) {
7261 case EACCES:
7262 exerrno = 126;
7263 break;
7264 case ENOENT:
7265 exerrno = 127;
7266 break;
7267 default:
7268 exerrno = 2;
7269 break;
7270 }
7271 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007272 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7273 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007274 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7275 /* NOTREACHED */
7276}
7277
7278static void
7279printentry(struct tblentry *cmdp)
7280{
7281 int idx;
7282 const char *path;
7283 char *name;
7284
7285 idx = cmdp->param.index;
7286 path = pathval();
7287 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007288 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007289 stunalloc(name);
7290 } while (--idx >= 0);
7291 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7292}
7293
7294/*
7295 * Clear out command entries. The argument specifies the first entry in
7296 * PATH which has changed.
7297 */
7298static void
7299clearcmdentry(int firstchange)
7300{
7301 struct tblentry **tblp;
7302 struct tblentry **pp;
7303 struct tblentry *cmdp;
7304
7305 INT_OFF;
7306 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7307 pp = tblp;
7308 while ((cmdp = *pp) != NULL) {
7309 if ((cmdp->cmdtype == CMDNORMAL &&
7310 cmdp->param.index >= firstchange)
7311 || (cmdp->cmdtype == CMDBUILTIN &&
7312 builtinloc >= firstchange)
7313 ) {
7314 *pp = cmdp->next;
7315 free(cmdp);
7316 } else {
7317 pp = &cmdp->next;
7318 }
7319 }
7320 }
7321 INT_ON;
7322}
7323
7324/*
7325 * Locate a command in the command hash table. If "add" is nonzero,
7326 * add the command to the table if it is not already present. The
7327 * variable "lastcmdentry" is set to point to the address of the link
7328 * pointing to the entry, so that delete_cmd_entry can delete the
7329 * entry.
7330 *
7331 * Interrupts must be off if called with add != 0.
7332 */
7333static struct tblentry **lastcmdentry;
7334
7335static struct tblentry *
7336cmdlookup(const char *name, int add)
7337{
7338 unsigned int hashval;
7339 const char *p;
7340 struct tblentry *cmdp;
7341 struct tblentry **pp;
7342
7343 p = name;
7344 hashval = (unsigned char)*p << 4;
7345 while (*p)
7346 hashval += (unsigned char)*p++;
7347 hashval &= 0x7FFF;
7348 pp = &cmdtable[hashval % CMDTABLESIZE];
7349 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7350 if (strcmp(cmdp->cmdname, name) == 0)
7351 break;
7352 pp = &cmdp->next;
7353 }
7354 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007355 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7356 + strlen(name)
7357 /* + 1 - already done because
7358 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007359 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007360 cmdp->cmdtype = CMDUNKNOWN;
7361 strcpy(cmdp->cmdname, name);
7362 }
7363 lastcmdentry = pp;
7364 return cmdp;
7365}
7366
7367/*
7368 * Delete the command entry returned on the last lookup.
7369 */
7370static void
7371delete_cmd_entry(void)
7372{
7373 struct tblentry *cmdp;
7374
7375 INT_OFF;
7376 cmdp = *lastcmdentry;
7377 *lastcmdentry = cmdp->next;
7378 if (cmdp->cmdtype == CMDFUNCTION)
7379 freefunc(cmdp->param.func);
7380 free(cmdp);
7381 INT_ON;
7382}
7383
7384/*
7385 * Add a new command entry, replacing any existing command entry for
7386 * the same name - except special builtins.
7387 */
7388static void
7389addcmdentry(char *name, struct cmdentry *entry)
7390{
7391 struct tblentry *cmdp;
7392
7393 cmdp = cmdlookup(name, 1);
7394 if (cmdp->cmdtype == CMDFUNCTION) {
7395 freefunc(cmdp->param.func);
7396 }
7397 cmdp->cmdtype = entry->cmdtype;
7398 cmdp->param = entry->u;
7399 cmdp->rehash = 0;
7400}
7401
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007402static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007403hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007404{
7405 struct tblentry **pp;
7406 struct tblentry *cmdp;
7407 int c;
7408 struct cmdentry entry;
7409 char *name;
7410
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007411 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007412 clearcmdentry(0);
7413 return 0;
7414 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007415
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007416 if (*argptr == NULL) {
7417 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7418 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7419 if (cmdp->cmdtype == CMDNORMAL)
7420 printentry(cmdp);
7421 }
7422 }
7423 return 0;
7424 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007425
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007426 c = 0;
7427 while ((name = *argptr) != NULL) {
7428 cmdp = cmdlookup(name, 0);
7429 if (cmdp != NULL
7430 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007431 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7432 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007433 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007434 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007435 find_command(name, &entry, DO_ERR, pathval());
7436 if (entry.cmdtype == CMDUNKNOWN)
7437 c = 1;
7438 argptr++;
7439 }
7440 return c;
7441}
7442
7443/*
7444 * Called when a cd is done. Marks all commands so the next time they
7445 * are executed they will be rehashed.
7446 */
7447static void
7448hashcd(void)
7449{
7450 struct tblentry **pp;
7451 struct tblentry *cmdp;
7452
7453 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7454 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007455 if (cmdp->cmdtype == CMDNORMAL
7456 || (cmdp->cmdtype == CMDBUILTIN
7457 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7458 && builtinloc > 0)
7459 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007460 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007461 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007462 }
7463 }
7464}
7465
7466/*
7467 * Fix command hash table when PATH changed.
7468 * Called before PATH is changed. The argument is the new value of PATH;
7469 * pathval() still returns the old value at this point.
7470 * Called with interrupts off.
7471 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007472static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007473changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007474{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007475 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007476 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007477 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007478 int idx_bltin;
7479
7480 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007481 firstchange = 9999; /* assume no change */
7482 idx = 0;
7483 idx_bltin = -1;
7484 for (;;) {
7485 if (*old != *new) {
7486 firstchange = idx;
7487 if ((*old == '\0' && *new == ':')
7488 || (*old == ':' && *new == '\0'))
7489 firstchange++;
7490 old = new; /* ignore subsequent differences */
7491 }
7492 if (*new == '\0')
7493 break;
7494 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7495 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007496 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007498 new++, old++;
7499 }
7500 if (builtinloc < 0 && idx_bltin >= 0)
7501 builtinloc = idx_bltin; /* zap builtins */
7502 if (builtinloc >= 0 && idx_bltin < 0)
7503 firstchange = 0;
7504 clearcmdentry(firstchange);
7505 builtinloc = idx_bltin;
7506}
7507
7508#define TEOF 0
7509#define TNL 1
7510#define TREDIR 2
7511#define TWORD 3
7512#define TSEMI 4
7513#define TBACKGND 5
7514#define TAND 6
7515#define TOR 7
7516#define TPIPE 8
7517#define TLP 9
7518#define TRP 10
7519#define TENDCASE 11
7520#define TENDBQUOTE 12
7521#define TNOT 13
7522#define TCASE 14
7523#define TDO 15
7524#define TDONE 16
7525#define TELIF 17
7526#define TELSE 18
7527#define TESAC 19
7528#define TFI 20
7529#define TFOR 21
7530#define TIF 22
7531#define TIN 23
7532#define TTHEN 24
7533#define TUNTIL 25
7534#define TWHILE 26
7535#define TBEGIN 27
7536#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007537typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007538
7539/* first char is indicating which tokens mark the end of a list */
7540static const char *const tokname_array[] = {
7541 "\1end of file",
7542 "\0newline",
7543 "\0redirection",
7544 "\0word",
7545 "\0;",
7546 "\0&",
7547 "\0&&",
7548 "\0||",
7549 "\0|",
7550 "\0(",
7551 "\1)",
7552 "\1;;",
7553 "\1`",
7554#define KWDOFFSET 13
7555 /* the following are keywords */
7556 "\0!",
7557 "\0case",
7558 "\1do",
7559 "\1done",
7560 "\1elif",
7561 "\1else",
7562 "\1esac",
7563 "\1fi",
7564 "\0for",
7565 "\0if",
7566 "\0in",
7567 "\1then",
7568 "\0until",
7569 "\0while",
7570 "\0{",
7571 "\1}",
7572};
7573
7574static const char *
7575tokname(int tok)
7576{
7577 static char buf[16];
7578
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007579//try this:
7580//if (tok < TSEMI) return tokname_array[tok] + 1;
7581//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7582//return buf;
7583
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007584 if (tok >= TSEMI)
7585 buf[0] = '"';
7586 sprintf(buf + (tok >= TSEMI), "%s%c",
7587 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7588 return buf;
7589}
7590
7591/* Wrapper around strcmp for qsort/bsearch/... */
7592static int
7593pstrcmp(const void *a, const void *b)
7594{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007595 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007596}
7597
7598static const char *const *
7599findkwd(const char *s)
7600{
7601 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007602 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7603 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007604}
7605
7606/*
7607 * Locate and print what a word is...
7608 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007609static int
7610describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007611{
7612 struct cmdentry entry;
7613 struct tblentry *cmdp;
7614#if ENABLE_ASH_ALIAS
7615 const struct alias *ap;
7616#endif
7617 const char *path = pathval();
7618
7619 if (describe_command_verbose) {
7620 out1str(command);
7621 }
7622
7623 /* First look at the keywords */
7624 if (findkwd(command)) {
7625 out1str(describe_command_verbose ? " is a shell keyword" : command);
7626 goto out;
7627 }
7628
7629#if ENABLE_ASH_ALIAS
7630 /* Then look at the aliases */
7631 ap = lookupalias(command, 0);
7632 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007633 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634 out1str("alias ");
7635 printalias(ap);
7636 return 0;
7637 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007638 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007639 goto out;
7640 }
7641#endif
7642 /* Then check if it is a tracked alias */
7643 cmdp = cmdlookup(command, 0);
7644 if (cmdp != NULL) {
7645 entry.cmdtype = cmdp->cmdtype;
7646 entry.u = cmdp->param;
7647 } else {
7648 /* Finally use brute force */
7649 find_command(command, &entry, DO_ABS, path);
7650 }
7651
7652 switch (entry.cmdtype) {
7653 case CMDNORMAL: {
7654 int j = entry.u.index;
7655 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007656 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657 p = command;
7658 } else {
7659 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007660 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007661 stunalloc(p);
7662 } while (--j >= 0);
7663 }
7664 if (describe_command_verbose) {
7665 out1fmt(" is%s %s",
7666 (cmdp ? " a tracked alias for" : nullstr), p
7667 );
7668 } else {
7669 out1str(p);
7670 }
7671 break;
7672 }
7673
7674 case CMDFUNCTION:
7675 if (describe_command_verbose) {
7676 out1str(" is a shell function");
7677 } else {
7678 out1str(command);
7679 }
7680 break;
7681
7682 case CMDBUILTIN:
7683 if (describe_command_verbose) {
7684 out1fmt(" is a %sshell builtin",
7685 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7686 "special " : nullstr
7687 );
7688 } else {
7689 out1str(command);
7690 }
7691 break;
7692
7693 default:
7694 if (describe_command_verbose) {
7695 out1str(": not found\n");
7696 }
7697 return 127;
7698 }
7699 out:
7700 outstr("\n", stdout);
7701 return 0;
7702}
7703
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007704static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007705typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007706{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007707 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007708 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007709 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007710
Denis Vlasenko46846e22007-05-20 13:08:31 +00007711 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007712 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007713 i++;
7714 verbose = 0;
7715 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007716 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007717 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007718 }
7719 return err;
7720}
7721
7722#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007723static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007724commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007725{
7726 int c;
7727 enum {
7728 VERIFY_BRIEF = 1,
7729 VERIFY_VERBOSE = 2,
7730 } verify = 0;
7731
7732 while ((c = nextopt("pvV")) != '\0')
7733 if (c == 'V')
7734 verify |= VERIFY_VERBOSE;
7735 else if (c == 'v')
7736 verify |= VERIFY_BRIEF;
7737#if DEBUG
7738 else if (c != 'p')
7739 abort();
7740#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007741 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7742 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007743 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007744 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007745
7746 return 0;
7747}
7748#endif
7749
7750
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007751/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007752
Denis Vlasenko340299a2008-11-21 10:36:36 +00007753static int funcblocksize; /* size of structures in function */
7754static int funcstringsize; /* size of strings in node */
7755static void *funcblock; /* block to allocate function from */
7756static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007757
Eric Andersencb57d552001-06-28 07:25:16 +00007758/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007759#define EV_EXIT 01 /* exit after evaluating tree */
7760#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007761#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007762
Denis Vlasenko340299a2008-11-21 10:36:36 +00007763static const short nodesize[N_NUMBER] = {
7764 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7765 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7766 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7767 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7768 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7769 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7770 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7771 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7772 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7773 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7774 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7775 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7776 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7777 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7778 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7779 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7780 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007781#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007782 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007783#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007784 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7785 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7786 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7787 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7788 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7789 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7790 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7791 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7792 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007793};
7794
7795static void calcsize(union node *n);
7796
7797static void
7798sizenodelist(struct nodelist *lp)
7799{
7800 while (lp) {
7801 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7802 calcsize(lp->n);
7803 lp = lp->next;
7804 }
7805}
7806
7807static void
7808calcsize(union node *n)
7809{
7810 if (n == NULL)
7811 return;
7812 funcblocksize += nodesize[n->type];
7813 switch (n->type) {
7814 case NCMD:
7815 calcsize(n->ncmd.redirect);
7816 calcsize(n->ncmd.args);
7817 calcsize(n->ncmd.assign);
7818 break;
7819 case NPIPE:
7820 sizenodelist(n->npipe.cmdlist);
7821 break;
7822 case NREDIR:
7823 case NBACKGND:
7824 case NSUBSHELL:
7825 calcsize(n->nredir.redirect);
7826 calcsize(n->nredir.n);
7827 break;
7828 case NAND:
7829 case NOR:
7830 case NSEMI:
7831 case NWHILE:
7832 case NUNTIL:
7833 calcsize(n->nbinary.ch2);
7834 calcsize(n->nbinary.ch1);
7835 break;
7836 case NIF:
7837 calcsize(n->nif.elsepart);
7838 calcsize(n->nif.ifpart);
7839 calcsize(n->nif.test);
7840 break;
7841 case NFOR:
7842 funcstringsize += strlen(n->nfor.var) + 1;
7843 calcsize(n->nfor.body);
7844 calcsize(n->nfor.args);
7845 break;
7846 case NCASE:
7847 calcsize(n->ncase.cases);
7848 calcsize(n->ncase.expr);
7849 break;
7850 case NCLIST:
7851 calcsize(n->nclist.body);
7852 calcsize(n->nclist.pattern);
7853 calcsize(n->nclist.next);
7854 break;
7855 case NDEFUN:
7856 case NARG:
7857 sizenodelist(n->narg.backquote);
7858 funcstringsize += strlen(n->narg.text) + 1;
7859 calcsize(n->narg.next);
7860 break;
7861 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007862#if ENABLE_ASH_BASH_COMPAT
7863 case NTO2:
7864#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007865 case NCLOBBER:
7866 case NFROM:
7867 case NFROMTO:
7868 case NAPPEND:
7869 calcsize(n->nfile.fname);
7870 calcsize(n->nfile.next);
7871 break;
7872 case NTOFD:
7873 case NFROMFD:
7874 calcsize(n->ndup.vname);
7875 calcsize(n->ndup.next);
7876 break;
7877 case NHERE:
7878 case NXHERE:
7879 calcsize(n->nhere.doc);
7880 calcsize(n->nhere.next);
7881 break;
7882 case NNOT:
7883 calcsize(n->nnot.com);
7884 break;
7885 };
7886}
7887
7888static char *
7889nodeckstrdup(char *s)
7890{
7891 char *rtn = funcstring;
7892
7893 strcpy(funcstring, s);
7894 funcstring += strlen(s) + 1;
7895 return rtn;
7896}
7897
7898static union node *copynode(union node *);
7899
7900static struct nodelist *
7901copynodelist(struct nodelist *lp)
7902{
7903 struct nodelist *start;
7904 struct nodelist **lpp;
7905
7906 lpp = &start;
7907 while (lp) {
7908 *lpp = funcblock;
7909 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7910 (*lpp)->n = copynode(lp->n);
7911 lp = lp->next;
7912 lpp = &(*lpp)->next;
7913 }
7914 *lpp = NULL;
7915 return start;
7916}
7917
7918static union node *
7919copynode(union node *n)
7920{
7921 union node *new;
7922
7923 if (n == NULL)
7924 return NULL;
7925 new = funcblock;
7926 funcblock = (char *) funcblock + nodesize[n->type];
7927
7928 switch (n->type) {
7929 case NCMD:
7930 new->ncmd.redirect = copynode(n->ncmd.redirect);
7931 new->ncmd.args = copynode(n->ncmd.args);
7932 new->ncmd.assign = copynode(n->ncmd.assign);
7933 break;
7934 case NPIPE:
7935 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007936 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007937 break;
7938 case NREDIR:
7939 case NBACKGND:
7940 case NSUBSHELL:
7941 new->nredir.redirect = copynode(n->nredir.redirect);
7942 new->nredir.n = copynode(n->nredir.n);
7943 break;
7944 case NAND:
7945 case NOR:
7946 case NSEMI:
7947 case NWHILE:
7948 case NUNTIL:
7949 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7950 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7951 break;
7952 case NIF:
7953 new->nif.elsepart = copynode(n->nif.elsepart);
7954 new->nif.ifpart = copynode(n->nif.ifpart);
7955 new->nif.test = copynode(n->nif.test);
7956 break;
7957 case NFOR:
7958 new->nfor.var = nodeckstrdup(n->nfor.var);
7959 new->nfor.body = copynode(n->nfor.body);
7960 new->nfor.args = copynode(n->nfor.args);
7961 break;
7962 case NCASE:
7963 new->ncase.cases = copynode(n->ncase.cases);
7964 new->ncase.expr = copynode(n->ncase.expr);
7965 break;
7966 case NCLIST:
7967 new->nclist.body = copynode(n->nclist.body);
7968 new->nclist.pattern = copynode(n->nclist.pattern);
7969 new->nclist.next = copynode(n->nclist.next);
7970 break;
7971 case NDEFUN:
7972 case NARG:
7973 new->narg.backquote = copynodelist(n->narg.backquote);
7974 new->narg.text = nodeckstrdup(n->narg.text);
7975 new->narg.next = copynode(n->narg.next);
7976 break;
7977 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007978#if ENABLE_ASH_BASH_COMPAT
7979 case NTO2:
7980#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007981 case NCLOBBER:
7982 case NFROM:
7983 case NFROMTO:
7984 case NAPPEND:
7985 new->nfile.fname = copynode(n->nfile.fname);
7986 new->nfile.fd = n->nfile.fd;
7987 new->nfile.next = copynode(n->nfile.next);
7988 break;
7989 case NTOFD:
7990 case NFROMFD:
7991 new->ndup.vname = copynode(n->ndup.vname);
7992 new->ndup.dupfd = n->ndup.dupfd;
7993 new->ndup.fd = n->ndup.fd;
7994 new->ndup.next = copynode(n->ndup.next);
7995 break;
7996 case NHERE:
7997 case NXHERE:
7998 new->nhere.doc = copynode(n->nhere.doc);
7999 new->nhere.fd = n->nhere.fd;
8000 new->nhere.next = copynode(n->nhere.next);
8001 break;
8002 case NNOT:
8003 new->nnot.com = copynode(n->nnot.com);
8004 break;
8005 };
8006 new->type = n->type;
8007 return new;
8008}
8009
8010/*
8011 * Make a copy of a parse tree.
8012 */
8013static struct funcnode *
8014copyfunc(union node *n)
8015{
8016 struct funcnode *f;
8017 size_t blocksize;
8018
8019 funcblocksize = offsetof(struct funcnode, n);
8020 funcstringsize = 0;
8021 calcsize(n);
8022 blocksize = funcblocksize;
8023 f = ckmalloc(blocksize + funcstringsize);
8024 funcblock = (char *) f + offsetof(struct funcnode, n);
8025 funcstring = (char *) f + blocksize;
8026 copynode(n);
8027 f->count = 0;
8028 return f;
8029}
8030
8031/*
8032 * Define a shell function.
8033 */
8034static void
8035defun(char *name, union node *func)
8036{
8037 struct cmdentry entry;
8038
8039 INT_OFF;
8040 entry.cmdtype = CMDFUNCTION;
8041 entry.u.func = copyfunc(func);
8042 addcmdentry(name, &entry);
8043 INT_ON;
8044}
8045
Denis Vlasenko4b875702009-03-19 13:30:04 +00008046/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008047#define SKIPBREAK (1 << 0)
8048#define SKIPCONT (1 << 1)
8049#define SKIPFUNC (1 << 2)
8050#define SKIPFILE (1 << 3)
8051#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008052static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008053static int skipcount; /* number of levels to skip */
8054static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008055static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008056
Denis Vlasenko4b875702009-03-19 13:30:04 +00008057/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008058static int evalstring(char *s, int mask);
8059
Denis Vlasenko4b875702009-03-19 13:30:04 +00008060/* Called to execute a trap.
8061 * Single callsite - at the end of evaltree().
8062 * If we return non-zero, exaltree raises EXEXIT exception.
8063 *
8064 * Perhaps we should avoid entering new trap handlers
8065 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008066 */
8067static int
8068dotrap(void)
8069{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008070 uint8_t *g;
8071 int sig;
8072 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008073
8074 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008075 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008076 xbarrier();
8077
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008078 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008079 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8080 int want_exexit;
8081 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008082
Denis Vlasenko4b875702009-03-19 13:30:04 +00008083 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008084 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008085 t = trap[sig];
8086 /* non-trapped SIGINT is handled separately by raise_interrupt,
8087 * don't upset it by resetting gotsig[SIGINT-1] */
8088 if (sig == SIGINT && !t)
8089 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008090
8091 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008092 *g = 0;
8093 if (!t)
8094 continue;
8095 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008096 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008097 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008098 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008099 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008100 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008101 }
8102
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008103 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008104 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008105}
8106
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008107/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008108static void evalloop(union node *, int);
8109static void evalfor(union node *, int);
8110static void evalcase(union node *, int);
8111static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008112static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008113static void evalpipe(union node *, int);
8114static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008115static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008116static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008117
Eric Andersen62483552001-07-10 06:09:16 +00008118/*
Eric Andersenc470f442003-07-28 09:56:35 +00008119 * Evaluate a parse tree. The value is left in the global variable
8120 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008121 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008122static void
Eric Andersenc470f442003-07-28 09:56:35 +00008123evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008124{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008125 struct jmploc *volatile savehandler = exception_handler;
8126 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008127 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008128 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008129 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008130 int int_level;
8131
8132 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008133
Eric Andersenc470f442003-07-28 09:56:35 +00008134 if (n == NULL) {
8135 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008137 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008138 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008139
8140 exception_handler = &jmploc;
8141 {
8142 int err = setjmp(jmploc.loc);
8143 if (err) {
8144 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008145 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008146 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8147 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008148 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008149 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008150 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008151 TRACE(("exception %d in evaltree, propagating err=%d\n",
8152 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008153 exception_handler = savehandler;
8154 longjmp(exception_handler->loc, err);
8155 }
8156 }
8157
Eric Andersenc470f442003-07-28 09:56:35 +00008158 switch (n->type) {
8159 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008160#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008161 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008162 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008163 break;
8164#endif
8165 case NNOT:
8166 evaltree(n->nnot.com, EV_TESTED);
8167 status = !exitstatus;
8168 goto setstatus;
8169 case NREDIR:
8170 expredir(n->nredir.redirect);
8171 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8172 if (!status) {
8173 evaltree(n->nredir.n, flags & EV_TESTED);
8174 status = exitstatus;
8175 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008176 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008177 goto setstatus;
8178 case NCMD:
8179 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008180 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008181 if (eflag && !(flags & EV_TESTED))
8182 checkexit = ~0;
8183 goto calleval;
8184 case NFOR:
8185 evalfn = evalfor;
8186 goto calleval;
8187 case NWHILE:
8188 case NUNTIL:
8189 evalfn = evalloop;
8190 goto calleval;
8191 case NSUBSHELL:
8192 case NBACKGND:
8193 evalfn = evalsubshell;
8194 goto calleval;
8195 case NPIPE:
8196 evalfn = evalpipe;
8197 goto checkexit;
8198 case NCASE:
8199 evalfn = evalcase;
8200 goto calleval;
8201 case NAND:
8202 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008203 case NSEMI: {
8204
Eric Andersenc470f442003-07-28 09:56:35 +00008205#if NAND + 1 != NOR
8206#error NAND + 1 != NOR
8207#endif
8208#if NOR + 1 != NSEMI
8209#error NOR + 1 != NSEMI
8210#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008211 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008212 evaltree(
8213 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008214 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008215 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008216 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008217 break;
8218 if (!evalskip) {
8219 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008220 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008221 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008222 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008223 evalfn(n, flags);
8224 break;
8225 }
8226 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008227 }
Eric Andersenc470f442003-07-28 09:56:35 +00008228 case NIF:
8229 evaltree(n->nif.test, EV_TESTED);
8230 if (evalskip)
8231 break;
8232 if (exitstatus == 0) {
8233 n = n->nif.ifpart;
8234 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008235 }
8236 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008237 n = n->nif.elsepart;
8238 goto evaln;
8239 }
8240 goto success;
8241 case NDEFUN:
8242 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008243 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008244 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008245 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008246 exitstatus = status;
8247 break;
8248 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008249
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008250 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008251 exception_handler = savehandler;
8252 out1:
8253 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008254 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008255 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008256 goto exexit;
8257
8258 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008259 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008260 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008261 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008262
8263 RESTORE_INT(int_level);
8264 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008265}
8266
Eric Andersenc470f442003-07-28 09:56:35 +00008267#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8268static
8269#endif
8270void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8271
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008272static void
Eric Andersenc470f442003-07-28 09:56:35 +00008273evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008274{
8275 int status;
8276
8277 loopnest++;
8278 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008279 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008280 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008281 int i;
8282
Eric Andersencb57d552001-06-28 07:25:16 +00008283 evaltree(n->nbinary.ch1, EV_TESTED);
8284 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008285 skipping:
8286 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008287 evalskip = 0;
8288 continue;
8289 }
8290 if (evalskip == SKIPBREAK && --skipcount <= 0)
8291 evalskip = 0;
8292 break;
8293 }
Eric Andersenc470f442003-07-28 09:56:35 +00008294 i = exitstatus;
8295 if (n->type != NWHILE)
8296 i = !i;
8297 if (i != 0)
8298 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008299 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008300 status = exitstatus;
8301 if (evalskip)
8302 goto skipping;
8303 }
8304 loopnest--;
8305 exitstatus = status;
8306}
8307
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008308static void
Eric Andersenc470f442003-07-28 09:56:35 +00008309evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008310{
8311 struct arglist arglist;
8312 union node *argp;
8313 struct strlist *sp;
8314 struct stackmark smark;
8315
8316 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008317 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008318 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008319 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008320 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008321 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008322 if (evalskip)
8323 goto out;
8324 }
8325 *arglist.lastp = NULL;
8326
8327 exitstatus = 0;
8328 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008329 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008330 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008331 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008332 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008333 if (evalskip) {
8334 if (evalskip == SKIPCONT && --skipcount <= 0) {
8335 evalskip = 0;
8336 continue;
8337 }
8338 if (evalskip == SKIPBREAK && --skipcount <= 0)
8339 evalskip = 0;
8340 break;
8341 }
8342 }
8343 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008344 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008345 popstackmark(&smark);
8346}
8347
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008348static void
Eric Andersenc470f442003-07-28 09:56:35 +00008349evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008350{
8351 union node *cp;
8352 union node *patp;
8353 struct arglist arglist;
8354 struct stackmark smark;
8355
8356 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008357 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008358 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008359 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008360 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008361 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8362 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008363 if (casematch(patp, arglist.list->text)) {
8364 if (evalskip == 0) {
8365 evaltree(cp->nclist.body, flags);
8366 }
8367 goto out;
8368 }
8369 }
8370 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008371 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008372 popstackmark(&smark);
8373}
8374
Eric Andersenc470f442003-07-28 09:56:35 +00008375/*
8376 * Kick off a subshell to evaluate a tree.
8377 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008378static void
Eric Andersenc470f442003-07-28 09:56:35 +00008379evalsubshell(union node *n, int flags)
8380{
8381 struct job *jp;
8382 int backgnd = (n->type == NBACKGND);
8383 int status;
8384
8385 expredir(n->nredir.redirect);
8386 if (!backgnd && flags & EV_EXIT && !trap[0])
8387 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008388 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008389 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008390 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008391 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008392 flags |= EV_EXIT;
8393 if (backgnd)
8394 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008395 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008396 redirect(n->nredir.redirect, 0);
8397 evaltreenr(n->nredir.n, flags);
8398 /* never returns */
8399 }
8400 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008401 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008402 status = waitforjob(jp);
8403 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008404 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008405}
8406
Eric Andersenc470f442003-07-28 09:56:35 +00008407/*
8408 * Compute the names of the files in a redirection list.
8409 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008410static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008411static void
8412expredir(union node *n)
8413{
8414 union node *redir;
8415
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008416 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008417 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008418
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008419 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008420 fn.lastp = &fn.list;
8421 switch (redir->type) {
8422 case NFROMTO:
8423 case NFROM:
8424 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008425#if ENABLE_ASH_BASH_COMPAT
8426 case NTO2:
8427#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008428 case NCLOBBER:
8429 case NAPPEND:
8430 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008431#if ENABLE_ASH_BASH_COMPAT
8432 store_expfname:
8433#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008434 redir->nfile.expfname = fn.list->text;
8435 break;
8436 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008437 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008438 if (redir->ndup.vname) {
8439 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008440 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008441 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008442#if ENABLE_ASH_BASH_COMPAT
8443//FIXME: we used expandarg with different args!
8444 if (!isdigit_str9(fn.list->text)) {
8445 /* >&file, not >&fd */
8446 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8447 ash_msg_and_raise_error("redir error");
8448 redir->type = NTO2;
8449 goto store_expfname;
8450 }
8451#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008452 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008453 }
8454 break;
8455 }
8456 }
8457}
8458
Eric Andersencb57d552001-06-28 07:25:16 +00008459/*
Eric Andersencb57d552001-06-28 07:25:16 +00008460 * Evaluate a pipeline. All the processes in the pipeline are children
8461 * of the process creating the pipeline. (This differs from some versions
8462 * of the shell, which make the last process in a pipeline the parent
8463 * of all the rest.)
8464 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008465static void
Eric Andersenc470f442003-07-28 09:56:35 +00008466evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008467{
8468 struct job *jp;
8469 struct nodelist *lp;
8470 int pipelen;
8471 int prevfd;
8472 int pip[2];
8473
Eric Andersenc470f442003-07-28 09:56:35 +00008474 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008475 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008476 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008477 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008478 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008479 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008480 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008481 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008482 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008483 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008484 pip[1] = -1;
8485 if (lp->next) {
8486 if (pipe(pip) < 0) {
8487 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008488 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008489 }
8490 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008491 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008492 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008493 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008494 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008495 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008496 if (prevfd > 0) {
8497 dup2(prevfd, 0);
8498 close(prevfd);
8499 }
8500 if (pip[1] > 1) {
8501 dup2(pip[1], 1);
8502 close(pip[1]);
8503 }
Eric Andersenc470f442003-07-28 09:56:35 +00008504 evaltreenr(lp->n, flags);
8505 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008506 }
8507 if (prevfd >= 0)
8508 close(prevfd);
8509 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008510 /* Don't want to trigger debugging */
8511 if (pip[1] != -1)
8512 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008513 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008514 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008515 exitstatus = waitforjob(jp);
8516 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008517 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008518 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008519}
8520
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008521/*
8522 * Controls whether the shell is interactive or not.
8523 */
8524static void
8525setinteractive(int on)
8526{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008527 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008528
8529 if (++on == is_interactive)
8530 return;
8531 is_interactive = on;
8532 setsignal(SIGINT);
8533 setsignal(SIGQUIT);
8534 setsignal(SIGTERM);
8535#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8536 if (is_interactive > 1) {
8537 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008538 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008539
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008540 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008541 out1fmt(
8542 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008543 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008544 "Enter 'help' for a list of built-in commands."
8545 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008546 bb_banner);
8547 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008548 }
8549 }
8550#endif
8551}
8552
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008553static void
8554optschanged(void)
8555{
8556#if DEBUG
8557 opentrace();
8558#endif
8559 setinteractive(iflag);
8560 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008561#if ENABLE_FEATURE_EDITING_VI
8562 if (viflag)
8563 line_input_state->flags |= VI_MODE;
8564 else
8565 line_input_state->flags &= ~VI_MODE;
8566#else
8567 viflag = 0; /* forcibly keep the option off */
8568#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008569}
8570
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008571static struct localvar *localvars;
8572
8573/*
8574 * Called after a function returns.
8575 * Interrupts must be off.
8576 */
8577static void
8578poplocalvars(void)
8579{
8580 struct localvar *lvp;
8581 struct var *vp;
8582
8583 while ((lvp = localvars) != NULL) {
8584 localvars = lvp->next;
8585 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008586 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008587 if (vp == NULL) { /* $- saved */
8588 memcpy(optlist, lvp->text, sizeof(optlist));
8589 free((char*)lvp->text);
8590 optschanged();
8591 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8592 unsetvar(vp->text);
8593 } else {
8594 if (vp->func)
8595 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8596 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8597 free((char*)vp->text);
8598 vp->flags = lvp->flags;
8599 vp->text = lvp->text;
8600 }
8601 free(lvp);
8602 }
8603}
8604
8605static int
8606evalfun(struct funcnode *func, int argc, char **argv, int flags)
8607{
8608 volatile struct shparam saveparam;
8609 struct localvar *volatile savelocalvars;
8610 struct jmploc *volatile savehandler;
8611 struct jmploc jmploc;
8612 int e;
8613
8614 saveparam = shellparam;
8615 savelocalvars = localvars;
8616 e = setjmp(jmploc.loc);
8617 if (e) {
8618 goto funcdone;
8619 }
8620 INT_OFF;
8621 savehandler = exception_handler;
8622 exception_handler = &jmploc;
8623 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008624 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008625 func->count++;
8626 funcnest++;
8627 INT_ON;
8628 shellparam.nparam = argc - 1;
8629 shellparam.p = argv + 1;
8630#if ENABLE_ASH_GETOPTS
8631 shellparam.optind = 1;
8632 shellparam.optoff = -1;
8633#endif
8634 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008635 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008636 INT_OFF;
8637 funcnest--;
8638 freefunc(func);
8639 poplocalvars();
8640 localvars = savelocalvars;
8641 freeparam(&shellparam);
8642 shellparam = saveparam;
8643 exception_handler = savehandler;
8644 INT_ON;
8645 evalskip &= ~SKIPFUNC;
8646 return e;
8647}
8648
Denis Vlasenko131ae172007-02-18 13:00:19 +00008649#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008650static char **
8651parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008652{
8653 char *cp, c;
8654
8655 for (;;) {
8656 cp = *++argv;
8657 if (!cp)
8658 return 0;
8659 if (*cp++ != '-')
8660 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008661 c = *cp++;
8662 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008663 break;
8664 if (c == '-' && !*cp) {
8665 argv++;
8666 break;
8667 }
8668 do {
8669 switch (c) {
8670 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008671 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008672 break;
8673 default:
8674 /* run 'typecmd' for other options */
8675 return 0;
8676 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008677 c = *cp++;
8678 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008679 }
8680 return argv;
8681}
8682#endif
8683
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008684/*
8685 * Make a variable a local variable. When a variable is made local, it's
8686 * value and flags are saved in a localvar structure. The saved values
8687 * will be restored when the shell function returns. We handle the name
8688 * "-" as a special case.
8689 */
8690static void
8691mklocal(char *name)
8692{
8693 struct localvar *lvp;
8694 struct var **vpp;
8695 struct var *vp;
8696
8697 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008698 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008699 if (LONE_DASH(name)) {
8700 char *p;
8701 p = ckmalloc(sizeof(optlist));
8702 lvp->text = memcpy(p, optlist, sizeof(optlist));
8703 vp = NULL;
8704 } else {
8705 char *eq;
8706
8707 vpp = hashvar(name);
8708 vp = *findvar(vpp, name);
8709 eq = strchr(name, '=');
8710 if (vp == NULL) {
8711 if (eq)
8712 setvareq(name, VSTRFIXED);
8713 else
8714 setvar(name, NULL, VSTRFIXED);
8715 vp = *vpp; /* the new variable */
8716 lvp->flags = VUNSET;
8717 } else {
8718 lvp->text = vp->text;
8719 lvp->flags = vp->flags;
8720 vp->flags |= VSTRFIXED|VTEXTFIXED;
8721 if (eq)
8722 setvareq(name, 0);
8723 }
8724 }
8725 lvp->vp = vp;
8726 lvp->next = localvars;
8727 localvars = lvp;
8728 INT_ON;
8729}
8730
8731/*
8732 * The "local" command.
8733 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008734static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008735localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008736{
8737 char *name;
8738
8739 argv = argptr;
8740 while ((name = *argv++) != NULL) {
8741 mklocal(name);
8742 }
8743 return 0;
8744}
8745
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008746static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008747falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008748{
8749 return 1;
8750}
8751
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008752static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008753truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008754{
8755 return 0;
8756}
8757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008759execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008760{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008761 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008762 iflag = 0; /* exit on error */
8763 mflag = 0;
8764 optschanged();
8765 shellexec(argv + 1, pathval(), 0);
8766 }
8767 return 0;
8768}
8769
8770/*
8771 * The return command.
8772 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008773static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008774returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008775{
8776 /*
8777 * If called outside a function, do what ksh does;
8778 * skip the rest of the file.
8779 */
8780 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8781 return argv[1] ? number(argv[1]) : exitstatus;
8782}
8783
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008784/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int breakcmd(int, char **) FAST_FUNC;
8786static int dotcmd(int, char **) FAST_FUNC;
8787static int evalcmd(int, char **) FAST_FUNC;
8788static int exitcmd(int, char **) FAST_FUNC;
8789static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008790#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008791static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008792#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008793#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008794static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008795#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008796#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008798#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008799static int readcmd(int, char **) FAST_FUNC;
8800static int setcmd(int, char **) FAST_FUNC;
8801static int shiftcmd(int, char **) FAST_FUNC;
8802static int timescmd(int, char **) FAST_FUNC;
8803static int trapcmd(int, char **) FAST_FUNC;
8804static int umaskcmd(int, char **) FAST_FUNC;
8805static int unsetcmd(int, char **) FAST_FUNC;
8806static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008807
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008808#define BUILTIN_NOSPEC "0"
8809#define BUILTIN_SPECIAL "1"
8810#define BUILTIN_REGULAR "2"
8811#define BUILTIN_SPEC_REG "3"
8812#define BUILTIN_ASSIGN "4"
8813#define BUILTIN_SPEC_ASSG "5"
8814#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008815#define BUILTIN_SPEC_REG_ASSG "7"
8816
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008817/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008818#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008819static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008820#endif
8821#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008822static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008823#endif
8824#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008825static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008826#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008827
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008828/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008829static const struct builtincmd builtintab[] = {
8830 { BUILTIN_SPEC_REG ".", dotcmd },
8831 { BUILTIN_SPEC_REG ":", truecmd },
8832#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008833 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008834#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008835 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008836#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008837#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008838#if ENABLE_ASH_ALIAS
8839 { BUILTIN_REG_ASSG "alias", aliascmd },
8840#endif
8841#if JOBS
8842 { BUILTIN_REGULAR "bg", fg_bgcmd },
8843#endif
8844 { BUILTIN_SPEC_REG "break", breakcmd },
8845 { BUILTIN_REGULAR "cd", cdcmd },
8846 { BUILTIN_NOSPEC "chdir", cdcmd },
8847#if ENABLE_ASH_CMDCMD
8848 { BUILTIN_REGULAR "command", commandcmd },
8849#endif
8850 { BUILTIN_SPEC_REG "continue", breakcmd },
8851#if ENABLE_ASH_BUILTIN_ECHO
8852 { BUILTIN_REGULAR "echo", echocmd },
8853#endif
8854 { BUILTIN_SPEC_REG "eval", evalcmd },
8855 { BUILTIN_SPEC_REG "exec", execcmd },
8856 { BUILTIN_SPEC_REG "exit", exitcmd },
8857 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8858 { BUILTIN_REGULAR "false", falsecmd },
8859#if JOBS
8860 { BUILTIN_REGULAR "fg", fg_bgcmd },
8861#endif
8862#if ENABLE_ASH_GETOPTS
8863 { BUILTIN_REGULAR "getopts", getoptscmd },
8864#endif
8865 { BUILTIN_NOSPEC "hash", hashcmd },
8866#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8867 { BUILTIN_NOSPEC "help", helpcmd },
8868#endif
8869#if JOBS
8870 { BUILTIN_REGULAR "jobs", jobscmd },
8871 { BUILTIN_REGULAR "kill", killcmd },
8872#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008873#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008874 { BUILTIN_NOSPEC "let", letcmd },
8875#endif
8876 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008877#if ENABLE_ASH_BUILTIN_PRINTF
8878 { BUILTIN_REGULAR "printf", printfcmd },
8879#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008880 { BUILTIN_NOSPEC "pwd", pwdcmd },
8881 { BUILTIN_REGULAR "read", readcmd },
8882 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8883 { BUILTIN_SPEC_REG "return", returncmd },
8884 { BUILTIN_SPEC_REG "set", setcmd },
8885 { BUILTIN_SPEC_REG "shift", shiftcmd },
8886 { BUILTIN_SPEC_REG "source", dotcmd },
8887#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008888 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008889#endif
8890 { BUILTIN_SPEC_REG "times", timescmd },
8891 { BUILTIN_SPEC_REG "trap", trapcmd },
8892 { BUILTIN_REGULAR "true", truecmd },
8893 { BUILTIN_NOSPEC "type", typecmd },
8894 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8895 { BUILTIN_REGULAR "umask", umaskcmd },
8896#if ENABLE_ASH_ALIAS
8897 { BUILTIN_REGULAR "unalias", unaliascmd },
8898#endif
8899 { BUILTIN_SPEC_REG "unset", unsetcmd },
8900 { BUILTIN_REGULAR "wait", waitcmd },
8901};
8902
Denis Vlasenko80591b02008-03-25 07:49:43 +00008903/* Should match the above table! */
8904#define COMMANDCMD (builtintab + \
8905 2 + \
8906 1 * ENABLE_ASH_BUILTIN_TEST + \
8907 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8908 1 * ENABLE_ASH_ALIAS + \
8909 1 * ENABLE_ASH_JOB_CONTROL + \
8910 3)
8911#define EXECCMD (builtintab + \
8912 2 + \
8913 1 * ENABLE_ASH_BUILTIN_TEST + \
8914 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8915 1 * ENABLE_ASH_ALIAS + \
8916 1 * ENABLE_ASH_JOB_CONTROL + \
8917 3 + \
8918 1 * ENABLE_ASH_CMDCMD + \
8919 1 + \
8920 ENABLE_ASH_BUILTIN_ECHO + \
8921 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008922
8923/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008924 * Search the table of builtin commands.
8925 */
8926static struct builtincmd *
8927find_builtin(const char *name)
8928{
8929 struct builtincmd *bp;
8930
8931 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008932 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008933 pstrcmp
8934 );
8935 return bp;
8936}
8937
8938/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008939 * Execute a simple command.
8940 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008941static int
8942isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008943{
8944 const char *q = endofname(p);
8945 if (p == q)
8946 return 0;
8947 return *q == '=';
8948}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008949static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008950bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008951{
8952 /* Preserve exitstatus of a previous possible redirection
8953 * as POSIX mandates */
8954 return back_exitstatus;
8955}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008956static void
Eric Andersenc470f442003-07-28 09:56:35 +00008957evalcommand(union node *cmd, int flags)
8958{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008959 static const struct builtincmd null_bltin = {
8960 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008961 };
Eric Andersenc470f442003-07-28 09:56:35 +00008962 struct stackmark smark;
8963 union node *argp;
8964 struct arglist arglist;
8965 struct arglist varlist;
8966 char **argv;
8967 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008968 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008969 struct cmdentry cmdentry;
8970 struct job *jp;
8971 char *lastarg;
8972 const char *path;
8973 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008974 int status;
8975 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008976 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008977 smallint cmd_is_exec;
8978 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008979
8980 /* First expand the arguments. */
8981 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8982 setstackmark(&smark);
8983 back_exitstatus = 0;
8984
8985 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008986 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008987 varlist.lastp = &varlist.list;
8988 *varlist.lastp = NULL;
8989 arglist.lastp = &arglist.list;
8990 *arglist.lastp = NULL;
8991
8992 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008993 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008994 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8995 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8996 }
8997
Eric Andersenc470f442003-07-28 09:56:35 +00008998 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8999 struct strlist **spp;
9000
9001 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009002 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009003 expandarg(argp, &arglist, EXP_VARTILDE);
9004 else
9005 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9006
Eric Andersenc470f442003-07-28 09:56:35 +00009007 for (sp = *spp; sp; sp = sp->next)
9008 argc++;
9009 }
9010
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009011 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009012 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009013 TRACE(("evalcommand arg: %s\n", sp->text));
9014 *nargv++ = sp->text;
9015 }
9016 *nargv = NULL;
9017
9018 lastarg = NULL;
9019 if (iflag && funcnest == 0 && argc > 0)
9020 lastarg = nargv[-1];
9021
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009022 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009023 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009024 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009025
9026 path = vpath.text;
9027 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9028 struct strlist **spp;
9029 char *p;
9030
9031 spp = varlist.lastp;
9032 expandarg(argp, &varlist, EXP_VARTILDE);
9033
9034 /*
9035 * Modify the command lookup path, if a PATH= assignment
9036 * is present
9037 */
9038 p = (*spp)->text;
9039 if (varequal(p, path))
9040 path = p;
9041 }
9042
9043 /* Print the command if xflag is set. */
9044 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009045 int n;
9046 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009047
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009048 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009049 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009050
9051 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009052 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009053 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009054 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009055 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009056 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009057 p--;
9058 }
9059 }
9060 sp = arglist.list;
9061 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009062 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009063 }
9064
9065 cmd_is_exec = 0;
9066 spclbltin = -1;
9067
9068 /* Now locate the command. */
9069 if (argc) {
9070 const char *oldpath;
9071 int cmd_flag = DO_ERR;
9072
9073 path += 5;
9074 oldpath = path;
9075 for (;;) {
9076 find_command(argv[0], &cmdentry, cmd_flag, path);
9077 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009078 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009079 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009080 goto bail;
9081 }
9082
9083 /* implement bltin and command here */
9084 if (cmdentry.cmdtype != CMDBUILTIN)
9085 break;
9086 if (spclbltin < 0)
9087 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9088 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009089 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009090#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009091 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009092 path = oldpath;
9093 nargv = parse_command_args(argv, &path);
9094 if (!nargv)
9095 break;
9096 argc -= nargv - argv;
9097 argv = nargv;
9098 cmd_flag |= DO_NOFUNC;
9099 } else
9100#endif
9101 break;
9102 }
9103 }
9104
9105 if (status) {
9106 /* We have a redirection error. */
9107 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009108 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009109 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009110 exitstatus = status;
9111 goto out;
9112 }
9113
9114 /* Execute the command. */
9115 switch (cmdentry.cmdtype) {
9116 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009117
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009118#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009119/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9120 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009121 {
9122 /* find_command() encodes applet_no as (-2 - applet_no) */
9123 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009124 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009125 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009126 /* run <applet>_main() */
9127 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009128 break;
9129 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009130 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009131#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009132 /* Fork off a child process if necessary. */
9133 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009134 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009135 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009136 if (forkshell(jp, cmd, FORK_FG) != 0) {
9137 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009138 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009139 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009140 break;
9141 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009142 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009143 }
9144 listsetvar(varlist.list, VEXPORT|VSTACK);
9145 shellexec(argv, path, cmdentry.u.index);
9146 /* NOTREACHED */
9147
9148 case CMDBUILTIN:
9149 cmdenviron = varlist.list;
9150 if (cmdenviron) {
9151 struct strlist *list = cmdenviron;
9152 int i = VNOSET;
9153 if (spclbltin > 0 || argc == 0) {
9154 i = 0;
9155 if (cmd_is_exec && argc > 1)
9156 i = VEXPORT;
9157 }
9158 listsetvar(list, i);
9159 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009160 /* Tight loop with builtins only:
9161 * "while kill -0 $child; do true; done"
9162 * will never exit even if $child died, unless we do this
9163 * to reap the zombie and make kill detect that it's gone: */
9164 dowait(DOWAIT_NONBLOCK, NULL);
9165
Eric Andersenc470f442003-07-28 09:56:35 +00009166 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9167 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009168 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009169 if (i == EXEXIT)
9170 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009171 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009172 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009173 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009174 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009175 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009176 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009177 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009178 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009179 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009180 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009181 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009182 }
9183 break;
9184
9185 case CMDFUNCTION:
9186 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009187 /* See above for the rationale */
9188 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009189 if (evalfun(cmdentry.u.func, argc, argv, flags))
9190 goto raise;
9191 break;
9192 }
9193
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009194 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009195 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009196 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009197 /* dsl: I think this is intended to be used to support
9198 * '_' in 'vi' command mode during line editing...
9199 * However I implemented that within libedit itself.
9200 */
9201 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009202 }
Eric Andersenc470f442003-07-28 09:56:35 +00009203 popstackmark(&smark);
9204}
9205
9206static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009207evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9208{
Eric Andersenc470f442003-07-28 09:56:35 +00009209 char *volatile savecmdname;
9210 struct jmploc *volatile savehandler;
9211 struct jmploc jmploc;
9212 int i;
9213
9214 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009215 i = setjmp(jmploc.loc);
9216 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009217 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009218 savehandler = exception_handler;
9219 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009220 commandname = argv[0];
9221 argptr = argv + 1;
9222 optptr = NULL; /* initialize nextopt */
9223 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009224 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009225 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009226 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009227 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009228 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009229 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009230
9231 return i;
9232}
9233
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009234static int
9235goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009236{
9237 return !*endofname(p);
9238}
9239
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009240
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009241/*
9242 * Search for a command. This is called before we fork so that the
9243 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009244 * the child. The check for "goodname" is an overly conservative
9245 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009246 */
Eric Andersenc470f442003-07-28 09:56:35 +00009247static void
9248prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009249{
9250 struct cmdentry entry;
9251
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009252 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9253 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009254}
9255
Eric Andersencb57d552001-06-28 07:25:16 +00009256
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009257/* ============ Builtin commands
9258 *
9259 * Builtin commands whose functions are closely tied to evaluation
9260 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009261 */
9262
9263/*
Eric Andersencb57d552001-06-28 07:25:16 +00009264 * Handle break and continue commands. Break, continue, and return are
9265 * all handled by setting the evalskip flag. The evaluation routines
9266 * above all check this flag, and if it is set they start skipping
9267 * commands rather than executing them. The variable skipcount is
9268 * the number of loops to break/continue, or the number of function
9269 * levels to return. (The latter is always 1.) It should probably
9270 * be an error to break out of more loops than exist, but it isn't
9271 * in the standard shell so we don't make it one here.
9272 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009273static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009274breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009275{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009276 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009277
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009278 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009279 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009280 if (n > loopnest)
9281 n = loopnest;
9282 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009283 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009284 skipcount = n;
9285 }
9286 return 0;
9287}
9288
Eric Andersenc470f442003-07-28 09:56:35 +00009289
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009290/* ============ input.c
9291 *
Eric Andersen90898442003-08-06 11:20:52 +00009292 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009293 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009294
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009295enum {
9296 INPUT_PUSH_FILE = 1,
9297 INPUT_NOFILE_OK = 2,
9298};
Eric Andersencb57d552001-06-28 07:25:16 +00009299
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009300static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009301/* values of checkkwd variable */
9302#define CHKALIAS 0x1
9303#define CHKKWD 0x2
9304#define CHKNL 0x4
9305
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009306/*
9307 * Push a string back onto the input at this current parsefile level.
9308 * We handle aliases this way.
9309 */
9310#if !ENABLE_ASH_ALIAS
9311#define pushstring(s, ap) pushstring(s)
9312#endif
9313static void
9314pushstring(char *s, struct alias *ap)
9315{
9316 struct strpush *sp;
9317 int len;
9318
9319 len = strlen(s);
9320 INT_OFF;
9321 if (g_parsefile->strpush) {
9322 sp = ckzalloc(sizeof(*sp));
9323 sp->prev = g_parsefile->strpush;
9324 } else {
9325 sp = &(g_parsefile->basestrpush);
9326 }
9327 g_parsefile->strpush = sp;
9328 sp->prev_string = g_parsefile->next_to_pgetc;
9329 sp->prev_left_in_line = g_parsefile->left_in_line;
9330#if ENABLE_ASH_ALIAS
9331 sp->ap = ap;
9332 if (ap) {
9333 ap->flag |= ALIASINUSE;
9334 sp->string = s;
9335 }
9336#endif
9337 g_parsefile->next_to_pgetc = s;
9338 g_parsefile->left_in_line = len;
9339 INT_ON;
9340}
9341
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009342static void
9343popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009344{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009345 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009346
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009347 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009348#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009349 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009350 if (g_parsefile->next_to_pgetc[-1] == ' '
9351 || g_parsefile->next_to_pgetc[-1] == '\t'
9352 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009353 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009354 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009355 if (sp->string != sp->ap->val) {
9356 free(sp->string);
9357 }
9358 sp->ap->flag &= ~ALIASINUSE;
9359 if (sp->ap->flag & ALIASDEAD) {
9360 unalias(sp->ap->name);
9361 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009362 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009363#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009364 g_parsefile->next_to_pgetc = sp->prev_string;
9365 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009366 g_parsefile->strpush = sp->prev;
9367 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009368 free(sp);
9369 INT_ON;
9370}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009371
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009372//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9373//it peeks whether it is &>, and then pushes back both chars.
9374//This function needs to save last *next_to_pgetc to buf[0]
9375//to make two pungetc() reliable. Currently,
9376// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009377static int
9378preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009379{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009380 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009381 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009382
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009383 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009384#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009385 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009386 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009387 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009388 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009389#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009390 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009391#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009392 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9393 if (nr == 0) {
9394 /* Ctrl+C pressed */
9395 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009396 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009397 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009398 raise(SIGINT);
9399 return 1;
9400 }
Eric Andersenc470f442003-07-28 09:56:35 +00009401 goto retry;
9402 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009403 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009404 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009405 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009406 }
Eric Andersencb57d552001-06-28 07:25:16 +00009407 }
9408#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009409 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009410#endif
9411
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009412#if 0
9413/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009414 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009415 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009416 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009417 if (flags >= 0 && (flags & O_NONBLOCK)) {
9418 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009419 if (fcntl(0, F_SETFL, flags) >= 0) {
9420 out2str("sh: turning off NDELAY mode\n");
9421 goto retry;
9422 }
9423 }
9424 }
9425 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009426#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009427 return nr;
9428}
9429
9430/*
9431 * Refill the input buffer and return the next input character:
9432 *
9433 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009434 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9435 * or we are reading from a string so we can't refill the buffer,
9436 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009437 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009438 * 4) Process input up to the next newline, deleting nul characters.
9439 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009440//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9441#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009442/*
9443 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9444 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9445 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9446 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9447 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009448static int
Eric Andersenc470f442003-07-28 09:56:35 +00009449preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009450{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009451 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009452 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009453
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009454 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009455#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009456 if (g_parsefile->left_in_line == -1
9457 && g_parsefile->strpush->ap
9458 && g_parsefile->next_to_pgetc[-1] != ' '
9459 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009460 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009461 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009462 return PEOA;
9463 }
Eric Andersen2870d962001-07-02 17:27:21 +00009464#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009465 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009466 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009467 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9468 g_parsefile->left_in_line,
9469 g_parsefile->next_to_pgetc,
9470 g_parsefile->next_to_pgetc);
9471 if (--g_parsefile->left_in_line >= 0)
9472 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009473 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009474 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009475 * "pgetc" needs refilling.
9476 */
9477
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009478 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009479 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009480 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009481 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009482 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009483 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009484 /* even in failure keep left_in_line and next_to_pgetc
9485 * in lock step, for correct multi-layer pungetc.
9486 * left_in_line was decremented before preadbuffer(),
9487 * must inc next_to_pgetc: */
9488 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009489 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009490 }
Eric Andersencb57d552001-06-28 07:25:16 +00009491
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009492 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009493 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009494 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009495 again:
9496 more = preadfd();
9497 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009498 /* don't try reading again */
9499 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009500 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009502 return PEOF;
9503 }
9504 }
9505
Denis Vlasenko727752d2008-11-28 03:41:47 +00009506 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009507 * Set g_parsefile->left_in_line
9508 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009509 * NUL chars are deleted.
9510 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009511 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009512 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009513 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009514
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009515 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009516
Denis Vlasenko727752d2008-11-28 03:41:47 +00009517 c = *q;
9518 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009519 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009520 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009521 q++;
9522 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009523 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009524 break;
9525 }
Eric Andersencb57d552001-06-28 07:25:16 +00009526 }
9527
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009528 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009529 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9530 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009531 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009532 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009533 }
9534 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009536
Eric Andersencb57d552001-06-28 07:25:16 +00009537 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009538 char save = *q;
9539 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009540 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009541 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009542 }
9543
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009544 pgetc_debug("preadbuffer at %d:%p'%s'",
9545 g_parsefile->left_in_line,
9546 g_parsefile->next_to_pgetc,
9547 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009548 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009549}
9550
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009551#define pgetc_as_macro() \
9552 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009553 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009554 : preadbuffer() \
9555 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009556
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009557static int
9558pgetc(void)
9559{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009560 pgetc_debug("pgetc_fast at %d:%p'%s'",
9561 g_parsefile->left_in_line,
9562 g_parsefile->next_to_pgetc,
9563 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009564 return pgetc_as_macro();
9565}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009566
9567#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009568#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009569#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009570#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009571#endif
9572
9573/*
9574 * Same as pgetc(), but ignores PEOA.
9575 */
9576#if ENABLE_ASH_ALIAS
9577static int
9578pgetc2(void)
9579{
9580 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009582 pgetc_debug("pgetc_fast at %d:%p'%s'",
9583 g_parsefile->left_in_line,
9584 g_parsefile->next_to_pgetc,
9585 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009586 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009587 } while (c == PEOA);
9588 return c;
9589}
9590#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009591#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009592#endif
9593
9594/*
9595 * Read a line from the script.
9596 */
9597static char *
9598pfgets(char *line, int len)
9599{
9600 char *p = line;
9601 int nleft = len;
9602 int c;
9603
9604 while (--nleft > 0) {
9605 c = pgetc2();
9606 if (c == PEOF) {
9607 if (p == line)
9608 return NULL;
9609 break;
9610 }
9611 *p++ = c;
9612 if (c == '\n')
9613 break;
9614 }
9615 *p = '\0';
9616 return line;
9617}
9618
Eric Andersenc470f442003-07-28 09:56:35 +00009619/*
9620 * Undo the last call to pgetc. Only one character may be pushed back.
9621 * PEOF may be pushed back.
9622 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009623static void
Eric Andersenc470f442003-07-28 09:56:35 +00009624pungetc(void)
9625{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009626 g_parsefile->left_in_line++;
9627 g_parsefile->next_to_pgetc--;
9628 pgetc_debug("pushed back to %d:%p'%s'",
9629 g_parsefile->left_in_line,
9630 g_parsefile->next_to_pgetc,
9631 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009632}
9633
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009634/*
9635 * To handle the "." command, a stack of input files is used. Pushfile
9636 * adds a new entry to the stack and popfile restores the previous level.
9637 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009638static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009640{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641 struct parsefile *pf;
9642
Denis Vlasenko597906c2008-02-20 16:38:54 +00009643 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009644 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009645 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009646 /*pf->strpush = NULL; - ckzalloc did it */
9647 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009648 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009649}
9650
9651static void
9652popfile(void)
9653{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009654 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009655
Denis Vlasenkob012b102007-02-19 22:43:01 +00009656 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009657 if (pf->fd >= 0)
9658 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009659 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009660 while (pf->strpush)
9661 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009662 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009663 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009664 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009665}
9666
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009667/*
9668 * Return to top level.
9669 */
9670static void
9671popallfiles(void)
9672{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009673 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009674 popfile();
9675}
9676
9677/*
9678 * Close the file(s) that the shell is reading commands from. Called
9679 * after a fork is done.
9680 */
9681static void
9682closescript(void)
9683{
9684 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009685 if (g_parsefile->fd > 0) {
9686 close(g_parsefile->fd);
9687 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009688 }
9689}
9690
9691/*
9692 * Like setinputfile, but takes an open file descriptor. Call this with
9693 * interrupts off.
9694 */
9695static void
9696setinputfd(int fd, int push)
9697{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009698 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699 if (push) {
9700 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009701 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009702 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009703 g_parsefile->fd = fd;
9704 if (g_parsefile->buf == NULL)
9705 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009706 g_parsefile->left_in_buffer = 0;
9707 g_parsefile->left_in_line = 0;
9708 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009709}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009710
Eric Andersenc470f442003-07-28 09:56:35 +00009711/*
9712 * Set the input to take input from a file. If push is set, push the
9713 * old input onto the stack first.
9714 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009715static int
9716setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009717{
9718 int fd;
9719 int fd2;
9720
Denis Vlasenkob012b102007-02-19 22:43:01 +00009721 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009722 fd = open(fname, O_RDONLY);
9723 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009724 if (flags & INPUT_NOFILE_OK)
9725 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009726 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009727 }
Eric Andersenc470f442003-07-28 09:56:35 +00009728 if (fd < 10) {
9729 fd2 = copyfd(fd, 10);
9730 close(fd);
9731 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009732 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009733 fd = fd2;
9734 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009735 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009736 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009737 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009738 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009739}
9740
Eric Andersencb57d552001-06-28 07:25:16 +00009741/*
9742 * Like setinputfile, but takes input from a string.
9743 */
Eric Andersenc470f442003-07-28 09:56:35 +00009744static void
9745setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009746{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009747 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009748 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009749 g_parsefile->next_to_pgetc = string;
9750 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009751 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009752 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009753 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009754}
9755
9756
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009757/* ============ mail.c
9758 *
9759 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009760 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009761
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009762#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009763
Eric Andersencb57d552001-06-28 07:25:16 +00009764#define MAXMBOXES 10
9765
Eric Andersenc470f442003-07-28 09:56:35 +00009766/* times of mailboxes */
9767static time_t mailtime[MAXMBOXES];
9768/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009769static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009770
Eric Andersencb57d552001-06-28 07:25:16 +00009771/*
Eric Andersenc470f442003-07-28 09:56:35 +00009772 * Print appropriate message(s) if mail has arrived.
9773 * If mail_var_path_changed is set,
9774 * then the value of MAIL has mail_var_path_changed,
9775 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009776 */
Eric Andersenc470f442003-07-28 09:56:35 +00009777static void
9778chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009779{
Eric Andersencb57d552001-06-28 07:25:16 +00009780 const char *mpath;
9781 char *p;
9782 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009783 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009784 struct stackmark smark;
9785 struct stat statb;
9786
Eric Andersencb57d552001-06-28 07:25:16 +00009787 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009788 mpath = mpathset() ? mpathval() : mailval();
9789 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009790 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009791 if (p == NULL)
9792 break;
9793 if (*p == '\0')
9794 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009795 for (q = p; *q; q++)
9796 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009797#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009798 if (q[-1] != '/')
9799 abort();
9800#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009801 q[-1] = '\0'; /* delete trailing '/' */
9802 if (stat(p, &statb) < 0) {
9803 *mtp = 0;
9804 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009805 }
Eric Andersenc470f442003-07-28 09:56:35 +00009806 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9807 fprintf(
9808 stderr, snlfmt,
9809 pathopt ? pathopt : "you have mail"
9810 );
9811 }
9812 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009813 }
Eric Andersenc470f442003-07-28 09:56:35 +00009814 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009815 popstackmark(&smark);
9816}
Eric Andersencb57d552001-06-28 07:25:16 +00009817
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009818static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009819changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009820{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009821 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009822}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009823
Denis Vlasenko131ae172007-02-18 13:00:19 +00009824#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009825
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009826
9827/* ============ ??? */
9828
Eric Andersencb57d552001-06-28 07:25:16 +00009829/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009830 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009831 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009832static void
9833setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009834{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009835 char **newparam;
9836 char **ap;
9837 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009838
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009839 for (nparam = 0; argv[nparam]; nparam++)
9840 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009841 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9842 while (*argv) {
9843 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009844 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009845 *ap = NULL;
9846 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009847 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009848 shellparam.nparam = nparam;
9849 shellparam.p = newparam;
9850#if ENABLE_ASH_GETOPTS
9851 shellparam.optind = 1;
9852 shellparam.optoff = -1;
9853#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009854}
9855
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009856/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009857 * Process shell options. The global variable argptr contains a pointer
9858 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009859 *
9860 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9861 * For a non-interactive shell, an error condition encountered
9862 * by a special built-in ... shall cause the shell to write a diagnostic message
9863 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009864 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009865 * ...
9866 * Utility syntax error (option or operand error) Shall exit
9867 * ...
9868 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9869 * we see that bash does not do that (set "finishes" with error code 1 instead,
9870 * and shell continues), and people rely on this behavior!
9871 * Testcase:
9872 * set -o barfoo 2>/dev/null
9873 * echo $?
9874 *
9875 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009876 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009877static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009878plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009879{
9880 int i;
9881
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009882 if (name) {
9883 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009884 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009885 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009886 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009887 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009888 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009889 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009890 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009891 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009892 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009893 if (val) {
9894 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9895 } else {
9896 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9897 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009898 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009899 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009900}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009901static void
9902setoption(int flag, int val)
9903{
9904 int i;
9905
9906 for (i = 0; i < NOPTS; i++) {
9907 if (optletters(i) == flag) {
9908 optlist[i] = val;
9909 return;
9910 }
9911 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009912 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009913 /* NOTREACHED */
9914}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009915static int
Eric Andersenc470f442003-07-28 09:56:35 +00009916options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009917{
9918 char *p;
9919 int val;
9920 int c;
9921
9922 if (cmdline)
9923 minusc = NULL;
9924 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009925 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009926 if (c != '-' && c != '+')
9927 break;
9928 argptr++;
9929 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009930 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009931 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009932 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009933 if (!cmdline) {
9934 /* "-" means turn off -x and -v */
9935 if (p[0] == '\0')
9936 xflag = vflag = 0;
9937 /* "--" means reset params */
9938 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009939 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009940 }
Eric Andersenc470f442003-07-28 09:56:35 +00009941 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009942 }
Eric Andersencb57d552001-06-28 07:25:16 +00009943 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009944 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009945 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009946 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009947 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009948 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009949 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009950 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009951 /* it already printed err message */
9952 return 1; /* error */
9953 }
Eric Andersencb57d552001-06-28 07:25:16 +00009954 if (*argptr)
9955 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009956 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9957 isloginsh = 1;
9958 /* bash does not accept +-login, we also won't */
9959 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009960 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009961 isloginsh = 1;
9962 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009963 } else {
9964 setoption(c, val);
9965 }
9966 }
9967 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009968 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009969}
9970
Eric Andersencb57d552001-06-28 07:25:16 +00009971/*
Eric Andersencb57d552001-06-28 07:25:16 +00009972 * The shift builtin command.
9973 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009974static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009975shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009976{
9977 int n;
9978 char **ap1, **ap2;
9979
9980 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009981 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009982 n = number(argv[1]);
9983 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009984 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009985 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009986 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009987 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009988 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009989 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009990 }
9991 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009992 while ((*ap2++ = *ap1++) != NULL)
9993 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009994#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009995 shellparam.optind = 1;
9996 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009997#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009998 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009999 return 0;
10000}
10001
Eric Andersencb57d552001-06-28 07:25:16 +000010002/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010003 * POSIX requires that 'set' (but not export or readonly) output the
10004 * variables in lexicographic order - by the locale's collating order (sigh).
10005 * Maybe we could keep them in an ordered balanced binary tree
10006 * instead of hashed lists.
10007 * For now just roll 'em through qsort for printing...
10008 */
10009static int
10010showvars(const char *sep_prefix, int on, int off)
10011{
10012 const char *sep;
10013 char **ep, **epend;
10014
10015 ep = listvars(on, off, &epend);
10016 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10017
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010018 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010019
10020 for (; ep < epend; ep++) {
10021 const char *p;
10022 const char *q;
10023
10024 p = strchrnul(*ep, '=');
10025 q = nullstr;
10026 if (*p)
10027 q = single_quote(++p);
10028 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10029 }
10030 return 0;
10031}
10032
10033/*
Eric Andersencb57d552001-06-28 07:25:16 +000010034 * The set command builtin.
10035 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010036static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010037setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010038{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010039 int retval;
10040
Denis Vlasenko68404f12008-03-17 09:00:54 +000010041 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010042 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010043 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010044 retval = 1;
10045 if (!options(0)) { /* if no parse error... */
10046 retval = 0;
10047 optschanged();
10048 if (*argptr != NULL) {
10049 setparam(argptr);
10050 }
Eric Andersencb57d552001-06-28 07:25:16 +000010051 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010052 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010053 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010054}
10055
Denis Vlasenko131ae172007-02-18 13:00:19 +000010056#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010057static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010058change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010059{
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010060 /* Galois LFSR parameter */
10061 /* Taps at 32 31 29 1: */
10062 enum { MASK = 0x8000000b };
10063 /* Another example - taps at 32 31 30 10: */
10064 /* MASK = 0x00400007 */
10065
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010066 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010067 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010068 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010069
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010070 /* LCG has period of 2^32 and alternating lowest bit */
10071 random_LCG = 1664525 * random_LCG + 1013904223;
10072 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10073 t = (random_galois_LFSR << 1);
10074 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10075 t ^= MASK;
10076 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010077 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010078 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010079 * for $RANDOM range. Combining with subtraction is
10080 * just for fun. + and ^ would work equally well. */
10081 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010082 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010083 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010084 vrandom.flags &= ~VNOFUNC;
10085 } else {
10086 /* set/reset */
Denys Vlasenko1f27ab02009-09-23 17:17:53 +020010087 random_galois_LFSR = random_LCG = strtoul(value, NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010088 }
Eric Andersenef02f822004-03-11 13:34:24 +000010089}
Eric Andersen16767e22004-03-16 05:14:10 +000010090#endif
10091
Denis Vlasenko131ae172007-02-18 13:00:19 +000010092#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010093static int
Eric Andersenc470f442003-07-28 09:56:35 +000010094getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010095{
10096 char *p, *q;
10097 char c = '?';
10098 int done = 0;
10099 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010100 char s[12];
10101 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010102
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010103 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010104 return 1;
10105 optnext = optfirst + *param_optind - 1;
10106
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010107 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010108 p = NULL;
10109 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010110 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010111 if (p == NULL || *p == '\0') {
10112 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010113 p = *optnext;
10114 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010115 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010116 p = NULL;
10117 done = 1;
10118 goto out;
10119 }
10120 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010121 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010122 goto atend;
10123 }
10124
10125 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010126 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010127 if (*q == '\0') {
10128 if (optstr[0] == ':') {
10129 s[0] = c;
10130 s[1] = '\0';
10131 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010132 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010133 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010134 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010135 }
10136 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010137 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010138 }
10139 if (*++q == ':')
10140 q++;
10141 }
10142
10143 if (*++q == ':') {
10144 if (*p == '\0' && (p = *optnext) == NULL) {
10145 if (optstr[0] == ':') {
10146 s[0] = c;
10147 s[1] = '\0';
10148 err |= setvarsafe("OPTARG", s, 0);
10149 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010150 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010151 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010152 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010153 c = '?';
10154 }
Eric Andersenc470f442003-07-28 09:56:35 +000010155 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010156 }
10157
10158 if (p == *optnext)
10159 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010160 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010161 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010162 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010163 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010164 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010165 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010166 *param_optind = optnext - optfirst + 1;
10167 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010168 err |= setvarsafe("OPTIND", s, VNOFUNC);
10169 s[0] = c;
10170 s[1] = '\0';
10171 err |= setvarsafe(optvar, s, 0);
10172 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010173 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010174 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010175 flush_stdout_stderr();
10176 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010177 }
10178 return done;
10179}
Eric Andersenc470f442003-07-28 09:56:35 +000010180
10181/*
10182 * The getopts builtin. Shellparam.optnext points to the next argument
10183 * to be processed. Shellparam.optptr points to the next character to
10184 * be processed in the current argument. If shellparam.optnext is NULL,
10185 * then it's the first time getopts has been called.
10186 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010187static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010188getoptscmd(int argc, char **argv)
10189{
10190 char **optbase;
10191
10192 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010193 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010194 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010195 optbase = shellparam.p;
10196 if (shellparam.optind > shellparam.nparam + 1) {
10197 shellparam.optind = 1;
10198 shellparam.optoff = -1;
10199 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010200 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010201 optbase = &argv[3];
10202 if (shellparam.optind > argc - 2) {
10203 shellparam.optind = 1;
10204 shellparam.optoff = -1;
10205 }
10206 }
10207
10208 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010209 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010210}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010211#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010212
Eric Andersencb57d552001-06-28 07:25:16 +000010213
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010214/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010215
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010216struct heredoc {
10217 struct heredoc *next; /* next here document in list */
10218 union node *here; /* redirection node */
10219 char *eofmark; /* string indicating end of input */
10220 smallint striptabs; /* if set, strip leading tabs */
10221};
10222
10223static smallint tokpushback; /* last token pushed back */
10224static smallint parsebackquote; /* nonzero if we are inside backquotes */
10225static smallint quoteflag; /* set if (part of) last token was quoted */
10226static token_id_t lasttoken; /* last token read (integer id Txxx) */
10227static struct heredoc *heredoclist; /* list of here documents to read */
10228static char *wordtext; /* text of last word returned by readtoken */
10229static struct nodelist *backquotelist;
10230static union node *redirnode;
10231static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010232
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010233/*
10234 * Called when an unexpected token is read during the parse. The argument
10235 * is the token that is expected, or -1 if more than one type of token can
10236 * occur at this point.
10237 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010238static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010239static void
10240raise_error_unexpected_syntax(int token)
10241{
10242 char msg[64];
10243 int l;
10244
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010245 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010246 if (token >= 0)
10247 sprintf(msg + l, " (expecting %s)", tokname(token));
10248 raise_error_syntax(msg);
10249 /* NOTREACHED */
10250}
Eric Andersencb57d552001-06-28 07:25:16 +000010251
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010252#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010253
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010254/* parsing is heavily cross-recursive, need these forward decls */
10255static union node *andor(void);
10256static union node *pipeline(void);
10257static union node *parse_command(void);
10258static void parseheredoc(void);
10259static char peektoken(void);
10260static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010261
Eric Andersenc470f442003-07-28 09:56:35 +000010262static union node *
10263list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010264{
10265 union node *n1, *n2, *n3;
10266 int tok;
10267
Eric Andersenc470f442003-07-28 09:56:35 +000010268 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10269 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010270 return NULL;
10271 n1 = NULL;
10272 for (;;) {
10273 n2 = andor();
10274 tok = readtoken();
10275 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010276 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010277 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010278 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010279 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010280 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010281 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010282 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010283 n2 = n3;
10284 }
10285 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010286 }
10287 }
10288 if (n1 == NULL) {
10289 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010290 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010291 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010292 n3->type = NSEMI;
10293 n3->nbinary.ch1 = n1;
10294 n3->nbinary.ch2 = n2;
10295 n1 = n3;
10296 }
10297 switch (tok) {
10298 case TBACKGND:
10299 case TSEMI:
10300 tok = readtoken();
10301 /* fall through */
10302 case TNL:
10303 if (tok == TNL) {
10304 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010305 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010306 return n1;
10307 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010308 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010309 }
Eric Andersenc470f442003-07-28 09:56:35 +000010310 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010311 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010312 return n1;
10313 break;
10314 case TEOF:
10315 if (heredoclist)
10316 parseheredoc();
10317 else
Eric Andersenc470f442003-07-28 09:56:35 +000010318 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010319 return n1;
10320 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010321 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010322 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010323 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010324 return n1;
10325 }
10326 }
10327}
10328
Eric Andersenc470f442003-07-28 09:56:35 +000010329static union node *
10330andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010331{
Eric Andersencb57d552001-06-28 07:25:16 +000010332 union node *n1, *n2, *n3;
10333 int t;
10334
Eric Andersencb57d552001-06-28 07:25:16 +000010335 n1 = pipeline();
10336 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010337 t = readtoken();
10338 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010339 t = NAND;
10340 } else if (t == TOR) {
10341 t = NOR;
10342 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010343 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010344 return n1;
10345 }
Eric Andersenc470f442003-07-28 09:56:35 +000010346 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010347 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010348 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010349 n3->type = t;
10350 n3->nbinary.ch1 = n1;
10351 n3->nbinary.ch2 = n2;
10352 n1 = n3;
10353 }
10354}
10355
Eric Andersenc470f442003-07-28 09:56:35 +000010356static union node *
10357pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010358{
Eric Andersencb57d552001-06-28 07:25:16 +000010359 union node *n1, *n2, *pipenode;
10360 struct nodelist *lp, *prev;
10361 int negate;
10362
10363 negate = 0;
10364 TRACE(("pipeline: entered\n"));
10365 if (readtoken() == TNOT) {
10366 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010367 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010368 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010369 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010370 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010371 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010372 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010373 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010374 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010375 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010376 pipenode->npipe.cmdlist = lp;
10377 lp->n = n1;
10378 do {
10379 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010380 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010381 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010382 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010383 prev->next = lp;
10384 } while (readtoken() == TPIPE);
10385 lp->next = NULL;
10386 n1 = pipenode;
10387 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010388 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010389 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010390 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010391 n2->type = NNOT;
10392 n2->nnot.com = n1;
10393 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010394 }
10395 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010396}
10397
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010398static union node *
10399makename(void)
10400{
10401 union node *n;
10402
Denis Vlasenko597906c2008-02-20 16:38:54 +000010403 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010404 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010405 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010406 n->narg.text = wordtext;
10407 n->narg.backquote = backquotelist;
10408 return n;
10409}
10410
10411static void
10412fixredir(union node *n, const char *text, int err)
10413{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010414 int fd;
10415
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416 TRACE(("Fix redir %s %d\n", text, err));
10417 if (!err)
10418 n->ndup.vname = NULL;
10419
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010420 fd = bb_strtou(text, NULL, 10);
10421 if (!errno && fd >= 0)
10422 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010423 else if (LONE_DASH(text))
10424 n->ndup.dupfd = -1;
10425 else {
10426 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010427 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010428 n->ndup.vname = makename();
10429 }
10430}
10431
10432/*
10433 * Returns true if the text contains nothing to expand (no dollar signs
10434 * or backquotes).
10435 */
10436static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010437noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010438{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010439 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010440 char c;
10441
10442 p = text;
10443 while ((c = *p++) != '\0') {
10444 if (c == CTLQUOTEMARK)
10445 continue;
10446 if (c == CTLESC)
10447 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010448 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010449 return 0;
10450 }
10451 return 1;
10452}
10453
10454static void
10455parsefname(void)
10456{
10457 union node *n = redirnode;
10458
10459 if (readtoken() != TWORD)
10460 raise_error_unexpected_syntax(-1);
10461 if (n->type == NHERE) {
10462 struct heredoc *here = heredoc;
10463 struct heredoc *p;
10464 int i;
10465
10466 if (quoteflag == 0)
10467 n->type = NXHERE;
10468 TRACE(("Here document %d\n", n->type));
10469 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010470 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010471 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010472 here->eofmark = wordtext;
10473 here->next = NULL;
10474 if (heredoclist == NULL)
10475 heredoclist = here;
10476 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010477 for (p = heredoclist; p->next; p = p->next)
10478 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010479 p->next = here;
10480 }
10481 } else if (n->type == NTOFD || n->type == NFROMFD) {
10482 fixredir(n, wordtext, 0);
10483 } else {
10484 n->nfile.fname = makename();
10485 }
10486}
Eric Andersencb57d552001-06-28 07:25:16 +000010487
Eric Andersenc470f442003-07-28 09:56:35 +000010488static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010489simplecmd(void)
10490{
10491 union node *args, **app;
10492 union node *n = NULL;
10493 union node *vars, **vpp;
10494 union node **rpp, *redir;
10495 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010496#if ENABLE_ASH_BASH_COMPAT
10497 smallint double_brackets_flag = 0;
10498#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499
10500 args = NULL;
10501 app = &args;
10502 vars = NULL;
10503 vpp = &vars;
10504 redir = NULL;
10505 rpp = &redir;
10506
10507 savecheckkwd = CHKALIAS;
10508 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010509 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010510 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010511 t = readtoken();
10512 switch (t) {
10513#if ENABLE_ASH_BASH_COMPAT
10514 case TAND: /* "&&" */
10515 case TOR: /* "||" */
10516 if (!double_brackets_flag) {
10517 tokpushback = 1;
10518 goto out;
10519 }
10520 wordtext = (char *) (t == TAND ? "-a" : "-o");
10521#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010522 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010523 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010524 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010525 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010526 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010527#if ENABLE_ASH_BASH_COMPAT
10528 if (strcmp("[[", wordtext) == 0)
10529 double_brackets_flag = 1;
10530 else if (strcmp("]]", wordtext) == 0)
10531 double_brackets_flag = 0;
10532#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010533 n->narg.backquote = backquotelist;
10534 if (savecheckkwd && isassignment(wordtext)) {
10535 *vpp = n;
10536 vpp = &n->narg.next;
10537 } else {
10538 *app = n;
10539 app = &n->narg.next;
10540 savecheckkwd = 0;
10541 }
10542 break;
10543 case TREDIR:
10544 *rpp = n = redirnode;
10545 rpp = &n->nfile.next;
10546 parsefname(); /* read name of redirection file */
10547 break;
10548 case TLP:
10549 if (args && app == &args->narg.next
10550 && !vars && !redir
10551 ) {
10552 struct builtincmd *bcmd;
10553 const char *name;
10554
10555 /* We have a function */
10556 if (readtoken() != TRP)
10557 raise_error_unexpected_syntax(TRP);
10558 name = n->narg.text;
10559 if (!goodname(name)
10560 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10561 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010562 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010563 }
10564 n->type = NDEFUN;
10565 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10566 n->narg.next = parse_command();
10567 return n;
10568 }
10569 /* fall through */
10570 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010571 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010572 goto out;
10573 }
10574 }
10575 out:
10576 *app = NULL;
10577 *vpp = NULL;
10578 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010579 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010580 n->type = NCMD;
10581 n->ncmd.args = args;
10582 n->ncmd.assign = vars;
10583 n->ncmd.redirect = redir;
10584 return n;
10585}
10586
10587static union node *
10588parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010589{
Eric Andersencb57d552001-06-28 07:25:16 +000010590 union node *n1, *n2;
10591 union node *ap, **app;
10592 union node *cp, **cpp;
10593 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010594 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010595 int t;
10596
10597 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010598 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010599
Eric Andersencb57d552001-06-28 07:25:16 +000010600 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010601 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010602 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010603 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010604 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010605 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010606 n1->type = NIF;
10607 n1->nif.test = list(0);
10608 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010609 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010610 n1->nif.ifpart = list(0);
10611 n2 = n1;
10612 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010613 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010614 n2 = n2->nif.elsepart;
10615 n2->type = NIF;
10616 n2->nif.test = list(0);
10617 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010618 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010619 n2->nif.ifpart = list(0);
10620 }
10621 if (lasttoken == TELSE)
10622 n2->nif.elsepart = list(0);
10623 else {
10624 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010625 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010626 }
Eric Andersenc470f442003-07-28 09:56:35 +000010627 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010628 break;
10629 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010630 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010631 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010632 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010633 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010634 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010635 got = readtoken();
10636 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010637 TRACE(("expecting DO got %s %s\n", tokname(got),
10638 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010639 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010640 }
10641 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010642 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010643 break;
10644 }
10645 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010646 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010647 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010648 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010649 n1->type = NFOR;
10650 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010651 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010652 if (readtoken() == TIN) {
10653 app = &ap;
10654 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010655 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010656 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010657 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010658 n2->narg.text = wordtext;
10659 n2->narg.backquote = backquotelist;
10660 *app = n2;
10661 app = &n2->narg.next;
10662 }
10663 *app = NULL;
10664 n1->nfor.args = ap;
10665 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010666 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010667 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010668 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010669 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010670 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010671 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010672 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010673 n1->nfor.args = n2;
10674 /*
10675 * Newline or semicolon here is optional (but note
10676 * that the original Bourne shell only allowed NL).
10677 */
10678 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010679 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010680 }
Eric Andersenc470f442003-07-28 09:56:35 +000010681 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010682 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010683 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010684 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010685 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010686 break;
10687 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010688 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010689 n1->type = NCASE;
10690 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010691 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010692 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010693 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010694 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010695 n2->narg.text = wordtext;
10696 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010697 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010698 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010699 } while (readtoken() == TNL);
10700 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010701 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010702 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010703 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010704 checkkwd = CHKNL | CHKKWD;
10705 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010706 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010707 if (lasttoken == TLP)
10708 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010709 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010710 cp->type = NCLIST;
10711 app = &cp->nclist.pattern;
10712 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010713 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010714 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010715 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010716 ap->narg.text = wordtext;
10717 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010718 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010719 break;
10720 app = &ap->narg.next;
10721 readtoken();
10722 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010723 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010724 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010725 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010726 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010727
Eric Andersenc470f442003-07-28 09:56:35 +000010728 cpp = &cp->nclist.next;
10729
10730 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010731 t = readtoken();
10732 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010733 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010734 raise_error_unexpected_syntax(TENDCASE);
10735 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010736 }
Eric Andersenc470f442003-07-28 09:56:35 +000010737 }
Eric Andersencb57d552001-06-28 07:25:16 +000010738 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010739 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010740 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010741 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010742 n1->type = NSUBSHELL;
10743 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010744 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010745 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010746 break;
10747 case TBEGIN:
10748 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010749 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010750 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010751 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010752 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010753 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010754 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010755 }
10756
Eric Andersenc470f442003-07-28 09:56:35 +000010757 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010758 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010759
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010760 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010761 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010762 checkkwd = CHKKWD | CHKALIAS;
10763 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010764 while (readtoken() == TREDIR) {
10765 *rpp = n2 = redirnode;
10766 rpp = &n2->nfile.next;
10767 parsefname();
10768 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010769 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010770 *rpp = NULL;
10771 if (redir) {
10772 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010773 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010774 n2->type = NREDIR;
10775 n2->nredir.n = n1;
10776 n1 = n2;
10777 }
10778 n1->nredir.redirect = redir;
10779 }
Eric Andersencb57d552001-06-28 07:25:16 +000010780 return n1;
10781}
10782
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010783#if ENABLE_ASH_BASH_COMPAT
10784static int decode_dollar_squote(void)
10785{
10786 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10787 int c, cnt;
10788 char *p;
10789 char buf[4];
10790
10791 c = pgetc();
10792 p = strchr(C_escapes, c);
10793 if (p) {
10794 buf[0] = c;
10795 p = buf;
10796 cnt = 3;
10797 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10798 do {
10799 c = pgetc();
10800 *++p = c;
10801 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10802 pungetc();
10803 } else if (c == 'x') { /* \xHH */
10804 do {
10805 c = pgetc();
10806 *++p = c;
10807 } while (isxdigit(c) && --cnt);
10808 pungetc();
10809 if (cnt == 3) { /* \x but next char is "bad" */
10810 c = 'x';
10811 goto unrecognized;
10812 }
10813 } else { /* simple seq like \\ or \t */
10814 p++;
10815 }
10816 *p = '\0';
10817 p = buf;
10818 c = bb_process_escape_sequence((void*)&p);
10819 } else { /* unrecognized "\z": print both chars unless ' or " */
10820 if (c != '\'' && c != '"') {
10821 unrecognized:
10822 c |= 0x100; /* "please encode \, then me" */
10823 }
10824 }
10825 return c;
10826}
10827#endif
10828
Eric Andersencb57d552001-06-28 07:25:16 +000010829/*
10830 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10831 * is not NULL, read a here document. In the latter case, eofmark is the
10832 * word which marks the end of the document and striptabs is true if
10833 * leading tabs should be stripped from the document. The argument firstc
10834 * is the first character of the input token or document.
10835 *
10836 * Because C does not have internal subroutines, I have simulated them
10837 * using goto's to implement the subroutine linkage. The following macros
10838 * will run code that appears at the end of readtoken1.
10839 */
Eric Andersen2870d962001-07-02 17:27:21 +000010840#define CHECKEND() {goto checkend; checkend_return:;}
10841#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10842#define PARSESUB() {goto parsesub; parsesub_return:;}
10843#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10844#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10845#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010846static int
Eric Andersenc470f442003-07-28 09:56:35 +000010847readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010848{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010849 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010850 int c = firstc;
10851 char *out;
10852 int len;
10853 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010854 struct nodelist *bqlist;
10855 smallint quotef;
10856 smallint dblquote;
10857 smallint oldstyle;
10858 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010859#if ENABLE_ASH_EXPAND_PRMT
10860 smallint pssyntax; /* we are expanding a prompt string */
10861#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010862 int varnest; /* levels of variables expansion */
10863 int arinest; /* levels of arithmetic expansion */
10864 int parenlevel; /* levels of parens in arithmetic */
10865 int dqvarnest; /* levels of variables expansion within double quotes */
10866
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010867 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010868
Eric Andersencb57d552001-06-28 07:25:16 +000010869#if __GNUC__
10870 /* Avoid longjmp clobbering */
10871 (void) &out;
10872 (void) &quotef;
10873 (void) &dblquote;
10874 (void) &varnest;
10875 (void) &arinest;
10876 (void) &parenlevel;
10877 (void) &dqvarnest;
10878 (void) &oldstyle;
10879 (void) &prevsyntax;
10880 (void) &syntax;
10881#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010882 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010883 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010884 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010885 oldstyle = 0;
10886 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010887#if ENABLE_ASH_EXPAND_PRMT
10888 pssyntax = (syntax == PSSYNTAX);
10889 if (pssyntax)
10890 syntax = DQSYNTAX;
10891#endif
10892 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010893 varnest = 0;
10894 arinest = 0;
10895 parenlevel = 0;
10896 dqvarnest = 0;
10897
10898 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010899 loop:
10900 /* For each line, until end of word */
10901 {
Eric Andersenc470f442003-07-28 09:56:35 +000010902 CHECKEND(); /* set c to PEOF if at end of here document */
10903 for (;;) { /* until end of line or end of word */
10904 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010905 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010906 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010907 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010908 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010909 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010910 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010911 if (doprompt)
10912 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010913 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010914 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010915 case CWORD:
10916 USTPUTC(c, out);
10917 break;
10918 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010919 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010920 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010921#if ENABLE_ASH_BASH_COMPAT
10922 if (c == '\\' && bash_dollar_squote) {
10923 c = decode_dollar_squote();
10924 if (c & 0x100) {
10925 USTPUTC('\\', out);
10926 c = (unsigned char)c;
10927 }
10928 }
10929#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010930 USTPUTC(c, out);
10931 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010932 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010933 c = pgetc2();
10934 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010935 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010936 USTPUTC('\\', out);
10937 pungetc();
10938 } else if (c == '\n') {
10939 if (doprompt)
10940 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010941 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010942#if ENABLE_ASH_EXPAND_PRMT
10943 if (c == '$' && pssyntax) {
10944 USTPUTC(CTLESC, out);
10945 USTPUTC('\\', out);
10946 }
10947#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010948 if (dblquote && c != '\\'
10949 && c != '`' && c != '$'
10950 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010951 ) {
10952 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010953 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010954 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010955 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010956 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010957 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010958 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010959 }
10960 break;
10961 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010962 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010963 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010964 if (eofmark == NULL) {
10965 USTPUTC(CTLQUOTEMARK, out);
10966 }
Eric Andersencb57d552001-06-28 07:25:16 +000010967 break;
10968 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010969 syntax = DQSYNTAX;
10970 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010971 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010972 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010973 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010974 if (eofmark != NULL && arinest == 0
10975 && varnest == 0
10976 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010977 USTPUTC(c, out);
10978 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010979 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010980 syntax = BASESYNTAX;
10981 dblquote = 0;
10982 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010983 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010984 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010985 }
10986 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010987 case CVAR: /* '$' */
10988 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010989 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010990 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010991 if (varnest > 0) {
10992 varnest--;
10993 if (dqvarnest > 0) {
10994 dqvarnest--;
10995 }
10996 USTPUTC(CTLENDVAR, out);
10997 } else {
10998 USTPUTC(c, out);
10999 }
11000 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011001#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011002 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011003 parenlevel++;
11004 USTPUTC(c, out);
11005 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011006 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011007 if (parenlevel > 0) {
11008 USTPUTC(c, out);
11009 --parenlevel;
11010 } else {
11011 if (pgetc() == ')') {
11012 if (--arinest == 0) {
11013 USTPUTC(CTLENDARI, out);
11014 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011015 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011016 } else
11017 USTPUTC(')', out);
11018 } else {
11019 /*
11020 * unbalanced parens
11021 * (don't 2nd guess - no error)
11022 */
11023 pungetc();
11024 USTPUTC(')', out);
11025 }
11026 }
11027 break;
11028#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011029 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011030 PARSEBACKQOLD();
11031 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011032 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011033 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011034 case CIGN:
11035 break;
11036 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011037 if (varnest == 0) {
11038#if ENABLE_ASH_BASH_COMPAT
11039 if (c == '&') {
11040 if (pgetc() == '>')
11041 c = 0x100 + '>'; /* flag &> */
11042 pungetc();
11043 }
11044#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011045 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011046 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011047#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011048 if (c != PEOA)
11049#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011050 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011051
Eric Andersencb57d552001-06-28 07:25:16 +000011052 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011053 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011054 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011055 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011056 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011057#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011058 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011059 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011060#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011061 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011062 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011063 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011064 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011065 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011066 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011067 }
11068 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011069 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011070 out = stackblock();
11071 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011072 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011073 && quotef == 0
11074 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011075 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011076 PARSEREDIR(); /* passed as params: out, c */
11077 lasttoken = TREDIR;
11078 return lasttoken;
11079 }
11080 /* else: non-number X seen, interpret it
11081 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011082 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011083 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011084 }
11085 quoteflag = quotef;
11086 backquotelist = bqlist;
11087 grabstackblock(len);
11088 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011089 lasttoken = TWORD;
11090 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011091/* end of readtoken routine */
11092
Eric Andersencb57d552001-06-28 07:25:16 +000011093/*
11094 * Check to see whether we are at the end of the here document. When this
11095 * is called, c is set to the first character of the next input line. If
11096 * we are at the end of the here document, this routine sets the c to PEOF.
11097 */
Eric Andersenc470f442003-07-28 09:56:35 +000011098checkend: {
11099 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011100#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011101 if (c == PEOA) {
11102 c = pgetc2();
11103 }
11104#endif
11105 if (striptabs) {
11106 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011107 c = pgetc2();
11108 }
Eric Andersenc470f442003-07-28 09:56:35 +000011109 }
11110 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011111 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011112 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011113
Eric Andersenc470f442003-07-28 09:56:35 +000011114 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011115 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11116 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011117 if (*p == '\n' && *q == '\0') {
11118 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011119 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011120 needprompt = doprompt;
11121 } else {
11122 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011123 }
11124 }
11125 }
11126 }
Eric Andersenc470f442003-07-28 09:56:35 +000011127 goto checkend_return;
11128}
Eric Andersencb57d552001-06-28 07:25:16 +000011129
Eric Andersencb57d552001-06-28 07:25:16 +000011130/*
11131 * Parse a redirection operator. The variable "out" points to a string
11132 * specifying the fd to be redirected. The variable "c" contains the
11133 * first character of the redirection operator.
11134 */
Eric Andersenc470f442003-07-28 09:56:35 +000011135parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011136 /* out is already checked to be a valid number or "" */
11137 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011138 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011139
Denis Vlasenko597906c2008-02-20 16:38:54 +000011140 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011141 if (c == '>') {
11142 np->nfile.fd = 1;
11143 c = pgetc();
11144 if (c == '>')
11145 np->type = NAPPEND;
11146 else if (c == '|')
11147 np->type = NCLOBBER;
11148 else if (c == '&')
11149 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011150 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011151 else {
11152 np->type = NTO;
11153 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011154 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011155 }
11156#if ENABLE_ASH_BASH_COMPAT
11157 else if (c == 0x100 + '>') { /* this flags &> redirection */
11158 np->nfile.fd = 1;
11159 pgetc(); /* this is '>', no need to check */
11160 np->type = NTO2;
11161 }
11162#endif
11163 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011164 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011165 c = pgetc();
11166 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011167 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011168 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011169 np = stzalloc(sizeof(struct nhere));
11170 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011171 }
11172 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011173 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011174 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011175 c = pgetc();
11176 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011177 heredoc->striptabs = 1;
11178 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011179 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011180 pungetc();
11181 }
11182 break;
11183
11184 case '&':
11185 np->type = NFROMFD;
11186 break;
11187
11188 case '>':
11189 np->type = NFROMTO;
11190 break;
11191
11192 default:
11193 np->type = NFROM;
11194 pungetc();
11195 break;
11196 }
Eric Andersencb57d552001-06-28 07:25:16 +000011197 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011198 if (fd >= 0)
11199 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011200 redirnode = np;
11201 goto parseredir_return;
11202}
Eric Andersencb57d552001-06-28 07:25:16 +000011203
Eric Andersencb57d552001-06-28 07:25:16 +000011204/*
11205 * Parse a substitution. At this point, we have read the dollar sign
11206 * and nothing else.
11207 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011208
11209/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11210 * (assuming ascii char codes, as the original implementation did) */
11211#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011212 (((unsigned)(c) - 33 < 32) \
11213 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011214parsesub: {
11215 int subtype;
11216 int typeloc;
11217 int flags;
11218 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011219 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011220
Eric Andersenc470f442003-07-28 09:56:35 +000011221 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011222 if (c <= PEOA_OR_PEOF
11223 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011224 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011225#if ENABLE_ASH_BASH_COMPAT
11226 if (c == '\'')
11227 bash_dollar_squote = 1;
11228 else
11229#endif
11230 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011231 pungetc();
11232 } else if (c == '(') { /* $(command) or $((arith)) */
11233 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011234#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011235 PARSEARITH();
11236#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011237 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011238#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011239 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011240 pungetc();
11241 PARSEBACKQNEW();
11242 }
11243 } else {
11244 USTPUTC(CTLVAR, out);
11245 typeloc = out - (char *)stackblock();
11246 USTPUTC(VSNORMAL, out);
11247 subtype = VSNORMAL;
11248 if (c == '{') {
11249 c = pgetc();
11250 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011251 c = pgetc();
11252 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011253 c = '#';
11254 else
11255 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011256 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011257 subtype = 0;
11258 }
11259 if (c > PEOA_OR_PEOF && is_name(c)) {
11260 do {
11261 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011262 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011263 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011264 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011265 do {
11266 STPUTC(c, out);
11267 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011268 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011269 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011270 USTPUTC(c, out);
11271 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011272 } else {
11273 badsub:
11274 raise_error_syntax("bad substitution");
11275 }
Eric Andersencb57d552001-06-28 07:25:16 +000011276
Eric Andersenc470f442003-07-28 09:56:35 +000011277 STPUTC('=', out);
11278 flags = 0;
11279 if (subtype == 0) {
11280 switch (c) {
11281 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011282 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011283#if ENABLE_ASH_BASH_COMPAT
11284 if (c == ':' || c == '$' || isdigit(c)) {
11285 pungetc();
11286 subtype = VSSUBSTR;
11287 break;
11288 }
11289#endif
11290 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011291 /*FALLTHROUGH*/
11292 default:
11293 p = strchr(types, c);
11294 if (p == NULL)
11295 goto badsub;
11296 subtype = p - types + VSNORMAL;
11297 break;
11298 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011299 case '#': {
11300 int cc = c;
11301 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11302 c = pgetc();
11303 if (c == cc)
11304 subtype++;
11305 else
11306 pungetc();
11307 break;
11308 }
11309#if ENABLE_ASH_BASH_COMPAT
11310 case '/':
11311 subtype = VSREPLACE;
11312 c = pgetc();
11313 if (c == '/')
11314 subtype++; /* VSREPLACEALL */
11315 else
11316 pungetc();
11317 break;
11318#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011319 }
Eric Andersenc470f442003-07-28 09:56:35 +000011320 } else {
11321 pungetc();
11322 }
11323 if (dblquote || arinest)
11324 flags |= VSQUOTE;
11325 *((char *)stackblock() + typeloc) = subtype | flags;
11326 if (subtype != VSNORMAL) {
11327 varnest++;
11328 if (dblquote || arinest) {
11329 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011330 }
11331 }
11332 }
Eric Andersenc470f442003-07-28 09:56:35 +000011333 goto parsesub_return;
11334}
Eric Andersencb57d552001-06-28 07:25:16 +000011335
Eric Andersencb57d552001-06-28 07:25:16 +000011336/*
11337 * Called to parse command substitutions. Newstyle is set if the command
11338 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11339 * list of commands (passed by reference), and savelen is the number of
11340 * characters on the top of the stack which must be preserved.
11341 */
Eric Andersenc470f442003-07-28 09:56:35 +000011342parsebackq: {
11343 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011344 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011345 union node *n;
11346 char *volatile str;
11347 struct jmploc jmploc;
11348 struct jmploc *volatile savehandler;
11349 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011350 smallint saveprompt = 0;
11351
Eric Andersencb57d552001-06-28 07:25:16 +000011352#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011353 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011354#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011355 savepbq = parsebackquote;
11356 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011357 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011358 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011359 exception_handler = savehandler;
11360 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011361 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011362 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011363 str = NULL;
11364 savelen = out - (char *)stackblock();
11365 if (savelen > 0) {
11366 str = ckmalloc(savelen);
11367 memcpy(str, stackblock(), savelen);
11368 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011369 savehandler = exception_handler;
11370 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011371 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011372 if (oldstyle) {
11373 /* We must read until the closing backquote, giving special
11374 treatment to some slashes, and then push the string and
11375 reread it as input, interpreting it normally. */
11376 char *pout;
11377 int pc;
11378 size_t psavelen;
11379 char *pstr;
11380
11381
11382 STARTSTACKSTR(pout);
11383 for (;;) {
11384 if (needprompt) {
11385 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011386 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011387 pc = pgetc();
11388 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011389 case '`':
11390 goto done;
11391
11392 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011393 pc = pgetc();
11394 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011395 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011396 if (doprompt)
11397 setprompt(2);
11398 /*
11399 * If eating a newline, avoid putting
11400 * the newline into the new character
11401 * stream (via the STPUTC after the
11402 * switch).
11403 */
11404 continue;
11405 }
11406 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011407 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011408 STPUTC('\\', pout);
11409 if (pc > PEOA_OR_PEOF) {
11410 break;
11411 }
11412 /* fall through */
11413
11414 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011415#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011416 case PEOA:
11417#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011418 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011419 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011420
11421 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011422 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011423 needprompt = doprompt;
11424 break;
11425
11426 default:
11427 break;
11428 }
11429 STPUTC(pc, pout);
11430 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011431 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011432 STPUTC('\0', pout);
11433 psavelen = pout - (char *)stackblock();
11434 if (psavelen > 0) {
11435 pstr = grabstackstr(pout);
11436 setinputstring(pstr);
11437 }
11438 }
11439 nlpp = &bqlist;
11440 while (*nlpp)
11441 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011442 *nlpp = stzalloc(sizeof(**nlpp));
11443 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011444 parsebackquote = oldstyle;
11445
11446 if (oldstyle) {
11447 saveprompt = doprompt;
11448 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011449 }
11450
Eric Andersenc470f442003-07-28 09:56:35 +000011451 n = list(2);
11452
11453 if (oldstyle)
11454 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011455 else if (readtoken() != TRP)
11456 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011457
11458 (*nlpp)->n = n;
11459 if (oldstyle) {
11460 /*
11461 * Start reading from old file again, ignoring any pushed back
11462 * tokens left from the backquote parsing
11463 */
11464 popfile();
11465 tokpushback = 0;
11466 }
11467 while (stackblocksize() <= savelen)
11468 growstackblock();
11469 STARTSTACKSTR(out);
11470 if (str) {
11471 memcpy(out, str, savelen);
11472 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011473 INT_OFF;
11474 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011475 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011476 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011477 }
11478 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011479 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011480 if (arinest || dblquote)
11481 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11482 else
11483 USTPUTC(CTLBACKQ, out);
11484 if (oldstyle)
11485 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011486 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011487}
11488
Mike Frysinger98c52642009-04-02 10:02:37 +000011489#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011490/*
11491 * Parse an arithmetic expansion (indicate start of one and set state)
11492 */
Eric Andersenc470f442003-07-28 09:56:35 +000011493parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011494 if (++arinest == 1) {
11495 prevsyntax = syntax;
11496 syntax = ARISYNTAX;
11497 USTPUTC(CTLARI, out);
11498 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011499 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011500 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011501 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011502 } else {
11503 /*
11504 * we collapse embedded arithmetic expansion to
11505 * parenthesis, which should be equivalent
11506 */
11507 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011508 }
Eric Andersenc470f442003-07-28 09:56:35 +000011509 goto parsearith_return;
11510}
11511#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011512
Eric Andersenc470f442003-07-28 09:56:35 +000011513} /* end of readtoken */
11514
Eric Andersencb57d552001-06-28 07:25:16 +000011515/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011516 * Read the next input token.
11517 * If the token is a word, we set backquotelist to the list of cmds in
11518 * backquotes. We set quoteflag to true if any part of the word was
11519 * quoted.
11520 * If the token is TREDIR, then we set redirnode to a structure containing
11521 * the redirection.
11522 * In all cases, the variable startlinno is set to the number of the line
11523 * on which the token starts.
11524 *
11525 * [Change comment: here documents and internal procedures]
11526 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11527 * word parsing code into a separate routine. In this case, readtoken
11528 * doesn't need to have any internal procedures, but parseword does.
11529 * We could also make parseoperator in essence the main routine, and
11530 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011531 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011532#define NEW_xxreadtoken
11533#ifdef NEW_xxreadtoken
11534/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011535static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011536 '\n', '(', ')', /* singles */
11537 '&', '|', ';', /* doubles */
11538 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011539};
Eric Andersencb57d552001-06-28 07:25:16 +000011540
Denis Vlasenko834dee72008-10-07 09:18:30 +000011541#define xxreadtoken_singles 3
11542#define xxreadtoken_doubles 3
11543
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011544static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011545 TNL, TLP, TRP, /* only single occurrence allowed */
11546 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11547 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011548 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011549};
11550
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011551static int
11552xxreadtoken(void)
11553{
11554 int c;
11555
11556 if (tokpushback) {
11557 tokpushback = 0;
11558 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011559 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011560 if (needprompt) {
11561 setprompt(2);
11562 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011563 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011564 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011565 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011566 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011567 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011568
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011569 if (c == '#') {
11570 while ((c = pgetc()) != '\n' && c != PEOF)
11571 continue;
11572 pungetc();
11573 } else if (c == '\\') {
11574 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011575 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011576 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011577 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011578 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011579 if (doprompt)
11580 setprompt(2);
11581 } else {
11582 const char *p;
11583
11584 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11585 if (c != PEOF) {
11586 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011587 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011588 needprompt = doprompt;
11589 }
11590
11591 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011592 if (p == NULL)
11593 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011594
Denis Vlasenko834dee72008-10-07 09:18:30 +000011595 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11596 int cc = pgetc();
11597 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011598 p += xxreadtoken_doubles + 1;
11599 } else {
11600 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011601#if ENABLE_ASH_BASH_COMPAT
11602 if (c == '&' && cc == '>') /* &> */
11603 break; /* return readtoken1(...) */
11604#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011605 }
11606 }
11607 }
11608 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11609 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011610 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011611 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011612
11613 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011614}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011615#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011616#define RETURN(token) return lasttoken = token
11617static int
11618xxreadtoken(void)
11619{
11620 int c;
11621
11622 if (tokpushback) {
11623 tokpushback = 0;
11624 return lasttoken;
11625 }
11626 if (needprompt) {
11627 setprompt(2);
11628 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011629 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011630 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011631 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011632 switch (c) {
11633 case ' ': case '\t':
11634#if ENABLE_ASH_ALIAS
11635 case PEOA:
11636#endif
11637 continue;
11638 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011639 while ((c = pgetc()) != '\n' && c != PEOF)
11640 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011641 pungetc();
11642 continue;
11643 case '\\':
11644 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011645 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011646 if (doprompt)
11647 setprompt(2);
11648 continue;
11649 }
11650 pungetc();
11651 goto breakloop;
11652 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011653 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011654 needprompt = doprompt;
11655 RETURN(TNL);
11656 case PEOF:
11657 RETURN(TEOF);
11658 case '&':
11659 if (pgetc() == '&')
11660 RETURN(TAND);
11661 pungetc();
11662 RETURN(TBACKGND);
11663 case '|':
11664 if (pgetc() == '|')
11665 RETURN(TOR);
11666 pungetc();
11667 RETURN(TPIPE);
11668 case ';':
11669 if (pgetc() == ';')
11670 RETURN(TENDCASE);
11671 pungetc();
11672 RETURN(TSEMI);
11673 case '(':
11674 RETURN(TLP);
11675 case ')':
11676 RETURN(TRP);
11677 default:
11678 goto breakloop;
11679 }
11680 }
11681 breakloop:
11682 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11683#undef RETURN
11684}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011685#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011686
11687static int
11688readtoken(void)
11689{
11690 int t;
11691#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011692 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011693#endif
11694
11695#if ENABLE_ASH_ALIAS
11696 top:
11697#endif
11698
11699 t = xxreadtoken();
11700
11701 /*
11702 * eat newlines
11703 */
11704 if (checkkwd & CHKNL) {
11705 while (t == TNL) {
11706 parseheredoc();
11707 t = xxreadtoken();
11708 }
11709 }
11710
11711 if (t != TWORD || quoteflag) {
11712 goto out;
11713 }
11714
11715 /*
11716 * check for keywords
11717 */
11718 if (checkkwd & CHKKWD) {
11719 const char *const *pp;
11720
11721 pp = findkwd(wordtext);
11722 if (pp) {
11723 lasttoken = t = pp - tokname_array;
11724 TRACE(("keyword %s recognized\n", tokname(t)));
11725 goto out;
11726 }
11727 }
11728
11729 if (checkkwd & CHKALIAS) {
11730#if ENABLE_ASH_ALIAS
11731 struct alias *ap;
11732 ap = lookupalias(wordtext, 1);
11733 if (ap != NULL) {
11734 if (*ap->val) {
11735 pushstring(ap->val, ap);
11736 }
11737 goto top;
11738 }
11739#endif
11740 }
11741 out:
11742 checkkwd = 0;
11743#if DEBUG
11744 if (!alreadyseen)
11745 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11746 else
11747 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11748#endif
11749 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011750}
11751
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011752static char
11753peektoken(void)
11754{
11755 int t;
11756
11757 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011758 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011759 return tokname_array[t][0];
11760}
Eric Andersencb57d552001-06-28 07:25:16 +000011761
11762/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011763 * Read and parse a command. Returns NODE_EOF on end of file.
11764 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011765 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011766static union node *
11767parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011768{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011769 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011770
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011771 tokpushback = 0;
11772 doprompt = interact;
11773 if (doprompt)
11774 setprompt(doprompt);
11775 needprompt = 0;
11776 t = readtoken();
11777 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011778 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011779 if (t == TNL)
11780 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011781 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011782 return list(1);
11783}
11784
11785/*
11786 * Input any here documents.
11787 */
11788static void
11789parseheredoc(void)
11790{
11791 struct heredoc *here;
11792 union node *n;
11793
11794 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011795 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011796
11797 while (here) {
11798 if (needprompt) {
11799 setprompt(2);
11800 }
11801 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11802 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011803 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011804 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011805 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011806 n->narg.text = wordtext;
11807 n->narg.backquote = backquotelist;
11808 here->here->nhere.doc = n;
11809 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011810 }
Eric Andersencb57d552001-06-28 07:25:16 +000011811}
11812
11813
11814/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011815 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011816 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011817#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011818static const char *
11819expandstr(const char *ps)
11820{
11821 union node n;
11822
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011823 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11824 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011825 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011826 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011827 popfile();
11828
11829 n.narg.type = NARG;
11830 n.narg.next = NULL;
11831 n.narg.text = wordtext;
11832 n.narg.backquote = backquotelist;
11833
11834 expandarg(&n, NULL, 0);
11835 return stackblock();
11836}
11837#endif
11838
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011839/*
11840 * Execute a command or commands contained in a string.
11841 */
11842static int
11843evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011844{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011845 union node *n;
11846 struct stackmark smark;
11847 int skip;
11848
11849 setinputstring(s);
11850 setstackmark(&smark);
11851
11852 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011853 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011854 evaltree(n, 0);
11855 popstackmark(&smark);
11856 skip = evalskip;
11857 if (skip)
11858 break;
11859 }
11860 popfile();
11861
11862 skip &= mask;
11863 evalskip = skip;
11864 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011865}
11866
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011867/*
11868 * The eval command.
11869 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011870static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011871evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011872{
11873 char *p;
11874 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011875
Denis Vlasenko68404f12008-03-17 09:00:54 +000011876 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011877 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011878 argv += 2;
11879 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011880 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011881 for (;;) {
11882 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011883 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011884 if (p == NULL)
11885 break;
11886 STPUTC(' ', concat);
11887 }
11888 STPUTC('\0', concat);
11889 p = grabstackstr(concat);
11890 }
11891 evalstring(p, ~SKIPEVAL);
11892
11893 }
11894 return exitstatus;
11895}
11896
11897/*
11898 * Read and execute commands. "Top" is nonzero for the top level command
11899 * loop; it turns on prompting if the shell is interactive.
11900 */
11901static int
11902cmdloop(int top)
11903{
11904 union node *n;
11905 struct stackmark smark;
11906 int inter;
11907 int numeof = 0;
11908
11909 TRACE(("cmdloop(%d) called\n", top));
11910 for (;;) {
11911 int skip;
11912
11913 setstackmark(&smark);
11914#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011915 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011916 showjobs(stderr, SHOW_CHANGED);
11917#endif
11918 inter = 0;
11919 if (iflag && top) {
11920 inter++;
11921#if ENABLE_ASH_MAIL
11922 chkmail();
11923#endif
11924 }
11925 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011926#if DEBUG
11927 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011928 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011929#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011930 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011931 if (!top || numeof >= 50)
11932 break;
11933 if (!stoppedjobs()) {
11934 if (!Iflag)
11935 break;
11936 out2str("\nUse \"exit\" to leave shell.\n");
11937 }
11938 numeof++;
11939 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011940 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11941 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011942 numeof = 0;
11943 evaltree(n, 0);
11944 }
11945 popstackmark(&smark);
11946 skip = evalskip;
11947
11948 if (skip) {
11949 evalskip = 0;
11950 return skip & SKIPEVAL;
11951 }
11952 }
11953 return 0;
11954}
11955
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011956/*
11957 * Take commands from a file. To be compatible we should do a path
11958 * search for the file, which is necessary to find sub-commands.
11959 */
11960static char *
11961find_dot_file(char *name)
11962{
11963 char *fullname;
11964 const char *path = pathval();
11965 struct stat statb;
11966
11967 /* don't try this for absolute or relative paths */
11968 if (strchr(name, '/'))
11969 return name;
11970
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011971 /* IIRC standards do not say whether . is to be searched.
11972 * And it is even smaller this way, making it unconditional for now:
11973 */
11974 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11975 fullname = name;
11976 goto try_cur_dir;
11977 }
11978
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011979 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011980 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011981 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11982 /*
11983 * Don't bother freeing here, since it will
11984 * be freed by the caller.
11985 */
11986 return fullname;
11987 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011988 if (fullname != name)
11989 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011990 }
11991
11992 /* not found in the PATH */
11993 ash_msg_and_raise_error("%s: not found", name);
11994 /* NOTREACHED */
11995}
11996
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011997static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011998dotcmd(int argc, char **argv)
11999{
12000 struct strlist *sp;
12001 volatile struct shparam saveparam;
12002 int status = 0;
12003
12004 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012005 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012006
Denis Vlasenko68404f12008-03-17 09:00:54 +000012007 if (argv[1]) { /* That's what SVR2 does */
12008 char *fullname = find_dot_file(argv[1]);
12009 argv += 2;
12010 argc -= 2;
12011 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012012 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012013 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012014 shellparam.nparam = argc;
12015 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012016 };
12017
12018 setinputfile(fullname, INPUT_PUSH_FILE);
12019 commandname = fullname;
12020 cmdloop(0);
12021 popfile();
12022
Denis Vlasenko68404f12008-03-17 09:00:54 +000012023 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012024 freeparam(&shellparam);
12025 shellparam = saveparam;
12026 };
12027 status = exitstatus;
12028 }
12029 return status;
12030}
12031
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012032static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012033exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012034{
12035 if (stoppedjobs())
12036 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012037 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038 exitstatus = number(argv[1]);
12039 raise_exception(EXEXIT);
12040 /* NOTREACHED */
12041}
12042
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012043/*
12044 * Read a file containing shell functions.
12045 */
12046static void
12047readcmdfile(char *name)
12048{
12049 setinputfile(name, INPUT_PUSH_FILE);
12050 cmdloop(0);
12051 popfile();
12052}
12053
12054
Denis Vlasenkocc571512007-02-23 21:10:35 +000012055/* ============ find_command inplementation */
12056
12057/*
12058 * Resolve a command name. If you change this routine, you may have to
12059 * change the shellexec routine as well.
12060 */
12061static void
12062find_command(char *name, struct cmdentry *entry, int act, const char *path)
12063{
12064 struct tblentry *cmdp;
12065 int idx;
12066 int prev;
12067 char *fullname;
12068 struct stat statb;
12069 int e;
12070 int updatetbl;
12071 struct builtincmd *bcmd;
12072
12073 /* If name contains a slash, don't use PATH or hash table */
12074 if (strchr(name, '/') != NULL) {
12075 entry->u.index = -1;
12076 if (act & DO_ABS) {
12077 while (stat(name, &statb) < 0) {
12078#ifdef SYSV
12079 if (errno == EINTR)
12080 continue;
12081#endif
12082 entry->cmdtype = CMDUNKNOWN;
12083 return;
12084 }
12085 }
12086 entry->cmdtype = CMDNORMAL;
12087 return;
12088 }
12089
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012090/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012091
12092 updatetbl = (path == pathval());
12093 if (!updatetbl) {
12094 act |= DO_ALTPATH;
12095 if (strstr(path, "%builtin") != NULL)
12096 act |= DO_ALTBLTIN;
12097 }
12098
12099 /* If name is in the table, check answer will be ok */
12100 cmdp = cmdlookup(name, 0);
12101 if (cmdp != NULL) {
12102 int bit;
12103
12104 switch (cmdp->cmdtype) {
12105 default:
12106#if DEBUG
12107 abort();
12108#endif
12109 case CMDNORMAL:
12110 bit = DO_ALTPATH;
12111 break;
12112 case CMDFUNCTION:
12113 bit = DO_NOFUNC;
12114 break;
12115 case CMDBUILTIN:
12116 bit = DO_ALTBLTIN;
12117 break;
12118 }
12119 if (act & bit) {
12120 updatetbl = 0;
12121 cmdp = NULL;
12122 } else if (cmdp->rehash == 0)
12123 /* if not invalidated by cd, we're done */
12124 goto success;
12125 }
12126
12127 /* If %builtin not in path, check for builtin next */
12128 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012129 if (bcmd) {
12130 if (IS_BUILTIN_REGULAR(bcmd))
12131 goto builtin_success;
12132 if (act & DO_ALTPATH) {
12133 if (!(act & DO_ALTBLTIN))
12134 goto builtin_success;
12135 } else if (builtinloc <= 0) {
12136 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012137 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012138 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012139
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012140#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012141 {
12142 int applet_no = find_applet_by_name(name);
12143 if (applet_no >= 0) {
12144 entry->cmdtype = CMDNORMAL;
12145 entry->u.index = -2 - applet_no;
12146 return;
12147 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012148 }
12149#endif
12150
Denis Vlasenkocc571512007-02-23 21:10:35 +000012151 /* We have to search path. */
12152 prev = -1; /* where to start */
12153 if (cmdp && cmdp->rehash) { /* doing a rehash */
12154 if (cmdp->cmdtype == CMDBUILTIN)
12155 prev = builtinloc;
12156 else
12157 prev = cmdp->param.index;
12158 }
12159
12160 e = ENOENT;
12161 idx = -1;
12162 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012163 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012164 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012165 /* NB: code below will still use fullname
12166 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012167 idx++;
12168 if (pathopt) {
12169 if (prefix(pathopt, "builtin")) {
12170 if (bcmd)
12171 goto builtin_success;
12172 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012173 }
12174 if ((act & DO_NOFUNC)
12175 || !prefix(pathopt, "func")
12176 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012177 continue;
12178 }
12179 }
12180 /* if rehash, don't redo absolute path names */
12181 if (fullname[0] == '/' && idx <= prev) {
12182 if (idx < prev)
12183 continue;
12184 TRACE(("searchexec \"%s\": no change\n", name));
12185 goto success;
12186 }
12187 while (stat(fullname, &statb) < 0) {
12188#ifdef SYSV
12189 if (errno == EINTR)
12190 continue;
12191#endif
12192 if (errno != ENOENT && errno != ENOTDIR)
12193 e = errno;
12194 goto loop;
12195 }
12196 e = EACCES; /* if we fail, this will be the error */
12197 if (!S_ISREG(statb.st_mode))
12198 continue;
12199 if (pathopt) { /* this is a %func directory */
12200 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012201 /* NB: stalloc will return space pointed by fullname
12202 * (because we don't have any intervening allocations
12203 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012204 readcmdfile(fullname);
12205 cmdp = cmdlookup(name, 0);
12206 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12207 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12208 stunalloc(fullname);
12209 goto success;
12210 }
12211 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12212 if (!updatetbl) {
12213 entry->cmdtype = CMDNORMAL;
12214 entry->u.index = idx;
12215 return;
12216 }
12217 INT_OFF;
12218 cmdp = cmdlookup(name, 1);
12219 cmdp->cmdtype = CMDNORMAL;
12220 cmdp->param.index = idx;
12221 INT_ON;
12222 goto success;
12223 }
12224
12225 /* We failed. If there was an entry for this command, delete it */
12226 if (cmdp && updatetbl)
12227 delete_cmd_entry();
12228 if (act & DO_ERR)
12229 ash_msg("%s: %s", name, errmsg(e, "not found"));
12230 entry->cmdtype = CMDUNKNOWN;
12231 return;
12232
12233 builtin_success:
12234 if (!updatetbl) {
12235 entry->cmdtype = CMDBUILTIN;
12236 entry->u.cmd = bcmd;
12237 return;
12238 }
12239 INT_OFF;
12240 cmdp = cmdlookup(name, 1);
12241 cmdp->cmdtype = CMDBUILTIN;
12242 cmdp->param.cmd = bcmd;
12243 INT_ON;
12244 success:
12245 cmdp->rehash = 0;
12246 entry->cmdtype = cmdp->cmdtype;
12247 entry->u = cmdp->param;
12248}
12249
12250
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012251/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012252
Eric Andersencb57d552001-06-28 07:25:16 +000012253/*
Eric Andersencb57d552001-06-28 07:25:16 +000012254 * The trap builtin.
12255 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012256static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012257trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012258{
12259 char *action;
12260 char **ap;
12261 int signo;
12262
Eric Andersenc470f442003-07-28 09:56:35 +000012263 nextopt(nullstr);
12264 ap = argptr;
12265 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012266 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012267 char *tr = trap_ptr[signo];
12268 if (tr) {
Denys Vlasenko2f7894b2009-09-24 01:43:21 +020012269 out1fmt("trap -- %s %s%s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012270 single_quote(tr),
Denys Vlasenko2f7894b2009-09-24 01:43:21 +020012271 (signo == 0 ? "" : "SIG"),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012272 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012273 /* trap_ptr != trap only if we are in special-cased `trap` code.
12274 * In this case, we will exit very soon, no need to free(). */
12275 /* if (trap_ptr != trap) */
12276 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012277 }
12278 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012279 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012280 if (trap_ptr != trap) {
12281 free(trap_ptr);
12282 trap_ptr = trap;
12283 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012284 */
Eric Andersencb57d552001-06-28 07:25:16 +000012285 return 0;
12286 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012287
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012288 action = NULL;
12289 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012290 action = *ap++;
12291 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012292 signo = get_signum(*ap);
12293 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012294 ash_msg_and_raise_error("%s: bad trap", *ap);
12295 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012296 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012297 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012298 action = NULL;
12299 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012300 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012301 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012302 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012303 trap[signo] = action;
12304 if (signo != 0)
12305 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012306 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012307 ap++;
12308 }
12309 return 0;
12310}
12311
Eric Andersenc470f442003-07-28 09:56:35 +000012312
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012313/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012314
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012315#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012316/*
12317 * Lists available builtins
12318 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012319static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012320helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012321{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012322 unsigned col;
12323 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012324
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012325 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012326 "Built-in commands:\n"
12327 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012328 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012329 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012330 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012331 if (col > 60) {
12332 out1fmt("\n");
12333 col = 0;
12334 }
12335 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012336#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012337 {
12338 const char *a = applet_names;
12339 while (*a) {
12340 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12341 if (col > 60) {
12342 out1fmt("\n");
12343 col = 0;
12344 }
12345 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012346 }
12347 }
12348#endif
12349 out1fmt("\n\n");
12350 return EXIT_SUCCESS;
12351}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012352#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012353
Eric Andersencb57d552001-06-28 07:25:16 +000012354/*
Eric Andersencb57d552001-06-28 07:25:16 +000012355 * The export and readonly commands.
12356 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012357static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012358exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012359{
12360 struct var *vp;
12361 char *name;
12362 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012363 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012364 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012365
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012366 if (nextopt("p") != 'p') {
12367 aptr = argptr;
12368 name = *aptr;
12369 if (name) {
12370 do {
12371 p = strchr(name, '=');
12372 if (p != NULL) {
12373 p++;
12374 } else {
12375 vp = *findvar(hashvar(name), name);
12376 if (vp) {
12377 vp->flags |= flag;
12378 continue;
12379 }
Eric Andersencb57d552001-06-28 07:25:16 +000012380 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012381 setvar(name, p, flag);
12382 } while ((name = *++aptr) != NULL);
12383 return 0;
12384 }
Eric Andersencb57d552001-06-28 07:25:16 +000012385 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012386 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012387 return 0;
12388}
12389
Eric Andersencb57d552001-06-28 07:25:16 +000012390/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012391 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012392 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012393static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012394unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012395{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012396 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012397
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012398 cmdp = cmdlookup(name, 0);
12399 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12400 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012401}
12402
Eric Andersencb57d552001-06-28 07:25:16 +000012403/*
Eric Andersencb57d552001-06-28 07:25:16 +000012404 * The unset builtin command. We unset the function before we unset the
12405 * variable to allow a function to be unset when there is a readonly variable
12406 * with the same name.
12407 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012408static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012409unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012410{
12411 char **ap;
12412 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012413 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012414 int ret = 0;
12415
12416 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012417 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012418 }
Eric Andersencb57d552001-06-28 07:25:16 +000012419
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012420 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012421 if (flag != 'f') {
12422 i = unsetvar(*ap);
12423 ret |= i;
12424 if (!(i & 2))
12425 continue;
12426 }
12427 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012428 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012429 }
Eric Andersenc470f442003-07-28 09:56:35 +000012430 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012431}
12432
12433
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012434/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012435
Eric Andersenc470f442003-07-28 09:56:35 +000012436#include <sys/times.h>
12437
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012438static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012439 ' ', offsetof(struct tms, tms_utime),
12440 '\n', offsetof(struct tms, tms_stime),
12441 ' ', offsetof(struct tms, tms_cutime),
12442 '\n', offsetof(struct tms, tms_cstime),
12443 0
12444};
Eric Andersencb57d552001-06-28 07:25:16 +000012445
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012446static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012447timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012448{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012449 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012450 const unsigned char *p;
12451 struct tms buf;
12452
12453 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012454 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012455
12456 p = timescmd_str;
12457 do {
12458 t = *(clock_t *)(((char *) &buf) + p[1]);
12459 s = t / clk_tck;
12460 out1fmt("%ldm%ld.%.3lds%c",
12461 s/60, s%60,
12462 ((t - s * clk_tck) * 1000) / clk_tck,
12463 p[0]);
12464 } while (*(p += 2));
12465
Eric Andersencb57d552001-06-28 07:25:16 +000012466 return 0;
12467}
12468
Mike Frysinger98c52642009-04-02 10:02:37 +000012469#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012470/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012471 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12472 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012473 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012474 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012475 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012476static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012477letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012478{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012479 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012480
Denis Vlasenko68404f12008-03-17 09:00:54 +000012481 argv++;
12482 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012483 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012484 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012485 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012486 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012487
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012488 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012489}
Mike Frysinger98c52642009-04-02 10:02:37 +000012490#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012491
Eric Andersenc470f442003-07-28 09:56:35 +000012492
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012493/* ============ miscbltin.c
12494 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012495 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012496 */
12497
12498#undef rflag
12499
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012500#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012501typedef enum __rlimit_resource rlim_t;
12502#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012503
Eric Andersenc470f442003-07-28 09:56:35 +000012504/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012505 * The read builtin. Options:
12506 * -r Do not interpret '\' specially
12507 * -s Turn off echo (tty only)
12508 * -n NCHARS Read NCHARS max
12509 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12510 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12511 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012512 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012513 * TODO: bash also has:
12514 * -a ARRAY Read into array[0],[1],etc
12515 * -d DELIM End on DELIM char, not newline
12516 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012517 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012518static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012519readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012520{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012521 static const char *const arg_REPLY[] = { "REPLY", NULL };
12522
Eric Andersenc470f442003-07-28 09:56:35 +000012523 char **ap;
12524 int backslash;
12525 char c;
12526 int rflag;
12527 char *prompt;
12528 const char *ifs;
12529 char *p;
12530 int startword;
12531 int status;
12532 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012533 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012534#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012535 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012536 int silent = 0;
12537 struct termios tty, old_tty;
12538#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012539#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012540 unsigned end_ms = 0;
12541 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012542#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012543
12544 rflag = 0;
12545 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012546 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012547 IF_ASH_READ_TIMEOUT("t:")
12548 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012549 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012550 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012551 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012552 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012553 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012554#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012555 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012556 nchars = bb_strtou(optionarg, NULL, 10);
12557 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012558 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012559 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012560 break;
12561 case 's':
12562 silent = 1;
12563 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012564#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012565#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012566 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012567 timeout = bb_strtou(optionarg, NULL, 10);
12568 if (errno || timeout > UINT_MAX / 2048)
12569 ash_msg_and_raise_error("invalid timeout");
12570 timeout *= 1000;
12571#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012572 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012573 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012574 /* EINVAL means number is ok, but not terminated by NUL */
12575 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012576 char *p2;
12577 if (*++p) {
12578 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012579 ts.tv_usec = bb_strtou(p, &p2, 10);
12580 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012581 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012582 scale = p2 - p;
12583 /* normalize to usec */
12584 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012585 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012586 while (scale++ < 6)
12587 ts.tv_usec *= 10;
12588 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012589 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012590 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012591 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012592 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012593 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012594 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012595#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012596 break;
12597#endif
12598 case 'r':
12599 rflag = 1;
12600 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012601 case 'u':
12602 fd = bb_strtou(optionarg, NULL, 10);
12603 if (fd < 0 || errno)
12604 ash_msg_and_raise_error("invalid file descriptor");
12605 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012606 default:
12607 break;
12608 }
Eric Andersenc470f442003-07-28 09:56:35 +000012609 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012610 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012611 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012612 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012613 ap = argptr;
12614 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012615 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012616 ifs = bltinlookup("IFS");
12617 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012618 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012619#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012620 tcgetattr(fd, &tty);
12621 old_tty = tty;
12622 if (nchars || silent) {
12623 if (nchars) {
12624 tty.c_lflag &= ~ICANON;
12625 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012626 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012627 if (silent) {
12628 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12629 }
12630 /* if tcgetattr failed, tcsetattr will fail too.
12631 * Ignoring, it's harmless. */
12632 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012633 }
12634#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012635
Eric Andersenc470f442003-07-28 09:56:35 +000012636 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012637 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012638 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012639#if ENABLE_ASH_READ_TIMEOUT
12640 if (timeout) /* NB: ensuring end_ms is nonzero */
12641 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12642#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012643 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012644 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012645 const char *is_ifs;
12646
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012647#if ENABLE_ASH_READ_TIMEOUT
12648 if (end_ms) {
12649 struct pollfd pfd[1];
12650 pfd[0].fd = fd;
12651 pfd[0].events = POLLIN;
12652 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12653 if ((int)timeout <= 0 /* already late? */
12654 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12655 ) { /* timed out! */
12656#if ENABLE_ASH_READ_NCHARS
12657 tcsetattr(fd, TCSANOW, &old_tty);
12658#endif
12659 return 1;
12660 }
12661 }
12662#endif
12663 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012664 status = 1;
12665 break;
12666 }
12667 if (c == '\0')
12668 continue;
12669 if (backslash) {
12670 backslash = 0;
12671 if (c != '\n')
12672 goto put;
12673 continue;
12674 }
12675 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012676 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012677 continue;
12678 }
12679 if (c == '\n')
12680 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012681 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012682/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012683 is_ifs = strchr(ifs, c);
12684 if (startword && is_ifs) {
12685 if (isspace(c))
12686 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012687 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012688 startword--;
12689 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012690 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012691 }
12692 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012693 if (ap[1] != NULL && is_ifs) {
12694 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012695 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012696 beg = stackblock();
12697 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012698 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012699 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012700 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012701 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012702 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012703 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012704 put:
12705 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012706 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012707/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012708#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012709 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012710#else
12711 while (1);
12712#endif
12713
12714#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012715 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012716#endif
12717
Eric Andersenc470f442003-07-28 09:56:35 +000012718 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012719 /* Remove trailing space ifs chars */
12720 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012721 *p = '\0';
12722 setvar(*ap, stackblock(), 0);
12723 while (*++ap != NULL)
12724 setvar(*ap, nullstr, 0);
12725 return status;
12726}
12727
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012728static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012729umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012730{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012731 static const char permuser[3] ALIGN1 = "ugo";
12732 static const char permmode[3] ALIGN1 = "rwx";
12733 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012734 S_IRUSR, S_IWUSR, S_IXUSR,
12735 S_IRGRP, S_IWGRP, S_IXGRP,
12736 S_IROTH, S_IWOTH, S_IXOTH
12737 };
12738
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012739 /* TODO: use bb_parse_mode() instead */
12740
Eric Andersenc470f442003-07-28 09:56:35 +000012741 char *ap;
12742 mode_t mask;
12743 int i;
12744 int symbolic_mode = 0;
12745
12746 while (nextopt("S") != '\0') {
12747 symbolic_mode = 1;
12748 }
12749
Denis Vlasenkob012b102007-02-19 22:43:01 +000012750 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012751 mask = umask(0);
12752 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012753 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012754
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012755 ap = *argptr;
12756 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012757 if (symbolic_mode) {
12758 char buf[18];
12759 char *p = buf;
12760
12761 for (i = 0; i < 3; i++) {
12762 int j;
12763
12764 *p++ = permuser[i];
12765 *p++ = '=';
12766 for (j = 0; j < 3; j++) {
12767 if ((mask & permmask[3 * i + j]) == 0) {
12768 *p++ = permmode[j];
12769 }
12770 }
12771 *p++ = ',';
12772 }
12773 *--p = 0;
12774 puts(buf);
12775 } else {
12776 out1fmt("%.4o\n", mask);
12777 }
12778 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012779 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012780 mask = 0;
12781 do {
12782 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012783 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012784 mask = (mask << 3) + (*ap - '0');
12785 } while (*++ap != '\0');
12786 umask(mask);
12787 } else {
12788 mask = ~mask & 0777;
12789 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012790 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012791 }
12792 umask(~mask & 0777);
12793 }
12794 }
12795 return 0;
12796}
12797
12798/*
12799 * ulimit builtin
12800 *
12801 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12802 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12803 * ash by J.T. Conklin.
12804 *
12805 * Public domain.
12806 */
Eric Andersenc470f442003-07-28 09:56:35 +000012807struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012808 uint8_t cmd; /* RLIMIT_xxx fit into it */
12809 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012810 char option;
12811};
12812
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012813static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012814#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012815 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012816#endif
12817#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012818 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012819#endif
12820#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012821 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012822#endif
12823#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012824 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012825#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012826#ifdef RLIMIT_CORE
12827 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012828#endif
12829#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012831#endif
12832#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012833 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012834#endif
12835#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012836 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012837#endif
12838#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012839 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012840#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012841#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012842 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012843#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012844#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012845 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012846#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012847};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012848static const char limits_name[] =
12849#ifdef RLIMIT_CPU
12850 "time(seconds)" "\0"
12851#endif
12852#ifdef RLIMIT_FSIZE
12853 "file(blocks)" "\0"
12854#endif
12855#ifdef RLIMIT_DATA
12856 "data(kb)" "\0"
12857#endif
12858#ifdef RLIMIT_STACK
12859 "stack(kb)" "\0"
12860#endif
12861#ifdef RLIMIT_CORE
12862 "coredump(blocks)" "\0"
12863#endif
12864#ifdef RLIMIT_RSS
12865 "memory(kb)" "\0"
12866#endif
12867#ifdef RLIMIT_MEMLOCK
12868 "locked memory(kb)" "\0"
12869#endif
12870#ifdef RLIMIT_NPROC
12871 "process" "\0"
12872#endif
12873#ifdef RLIMIT_NOFILE
12874 "nofiles" "\0"
12875#endif
12876#ifdef RLIMIT_AS
12877 "vmemory(kb)" "\0"
12878#endif
12879#ifdef RLIMIT_LOCKS
12880 "locks" "\0"
12881#endif
12882;
Eric Andersenc470f442003-07-28 09:56:35 +000012883
Glenn L McGrath76620622004-01-13 10:19:37 +000012884enum limtype { SOFT = 0x1, HARD = 0x2 };
12885
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012886static void
12887printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012888 const struct limits *l)
12889{
12890 rlim_t val;
12891
12892 val = limit->rlim_max;
12893 if (how & SOFT)
12894 val = limit->rlim_cur;
12895
12896 if (val == RLIM_INFINITY)
12897 out1fmt("unlimited\n");
12898 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012899 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012900 out1fmt("%lld\n", (long long) val);
12901 }
12902}
12903
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012904static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012905ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012906{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012907 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012908 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012909 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012910 const struct limits *l;
12911 int set, all = 0;
12912 int optc, what;
12913 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012914
12915 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012916 while ((optc = nextopt("HSa"
12917#ifdef RLIMIT_CPU
12918 "t"
12919#endif
12920#ifdef RLIMIT_FSIZE
12921 "f"
12922#endif
12923#ifdef RLIMIT_DATA
12924 "d"
12925#endif
12926#ifdef RLIMIT_STACK
12927 "s"
12928#endif
12929#ifdef RLIMIT_CORE
12930 "c"
12931#endif
12932#ifdef RLIMIT_RSS
12933 "m"
12934#endif
12935#ifdef RLIMIT_MEMLOCK
12936 "l"
12937#endif
12938#ifdef RLIMIT_NPROC
12939 "p"
12940#endif
12941#ifdef RLIMIT_NOFILE
12942 "n"
12943#endif
12944#ifdef RLIMIT_AS
12945 "v"
12946#endif
12947#ifdef RLIMIT_LOCKS
12948 "w"
12949#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012950 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012951 switch (optc) {
12952 case 'H':
12953 how = HARD;
12954 break;
12955 case 'S':
12956 how = SOFT;
12957 break;
12958 case 'a':
12959 all = 1;
12960 break;
12961 default:
12962 what = optc;
12963 }
12964
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012965 for (l = limits_tbl; l->option != what; l++)
12966 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012967
12968 set = *argptr ? 1 : 0;
12969 if (set) {
12970 char *p = *argptr;
12971
12972 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012973 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012974 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012975 val = RLIM_INFINITY;
12976 else {
12977 val = (rlim_t) 0;
12978
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012979 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012980 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012981 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012982 if (val < (rlim_t) 0)
12983 break;
12984 }
12985 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012986 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012987 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012988 }
12989 }
12990 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012991 const char *lname = limits_name;
12992 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012993 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012994 out1fmt("%-20s ", lname);
12995 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012996 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012997 }
12998 return 0;
12999 }
13000
13001 getrlimit(l->cmd, &limit);
13002 if (set) {
13003 if (how & HARD)
13004 limit.rlim_max = val;
13005 if (how & SOFT)
13006 limit.rlim_cur = val;
13007 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013008 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013009 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013010 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013011 }
13012 return 0;
13013}
13014
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013015/* ============ main() and helpers */
13016
13017/*
13018 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013019 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013020static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013021static void
13022exitshell(void)
13023{
13024 struct jmploc loc;
13025 char *p;
13026 int status;
13027
13028 status = exitstatus;
13029 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13030 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013031 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013032/* dash bug: it just does _exit(exitstatus) here
13033 * but we have to do setjobctl(0) first!
13034 * (bug is still not fixed in dash-0.5.3 - if you run dash
13035 * under Midnight Commander, on exit from dash MC is backgrounded) */
13036 status = exitstatus;
13037 goto out;
13038 }
13039 exception_handler = &loc;
13040 p = trap[0];
13041 if (p) {
13042 trap[0] = NULL;
13043 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013044 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013045 }
13046 flush_stdout_stderr();
13047 out:
13048 setjobctl(0);
13049 _exit(status);
13050 /* NOTREACHED */
13051}
13052
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013053static void
13054init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013055{
13056 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013057 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013058
13059 /* from trap.c: */
13060 signal(SIGCHLD, SIG_DFL);
13061
13062 /* from var.c: */
13063 {
13064 char **envp;
Denys Vlasenko6db47842009-09-05 20:15:17 +020013065 char ppid[sizeof(int)*3 + 2];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013066 const char *p;
13067 struct stat st1, st2;
13068
13069 initvar();
13070 for (envp = environ; envp && *envp; envp++) {
13071 if (strchr(*envp, '=')) {
13072 setvareq(*envp, VEXPORT|VTEXTFIXED);
13073 }
13074 }
13075
Denys Vlasenko6db47842009-09-05 20:15:17 +020013076 sprintf(ppid, "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013077 setvar("PPID", ppid, 0);
13078
13079 p = lookupvar("PWD");
13080 if (p)
13081 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13082 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13083 p = '\0';
13084 setpwd(p, 0);
13085 }
13086}
13087
13088/*
13089 * Process the shell command line arguments.
13090 */
13091static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013092procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013093{
13094 int i;
13095 const char *xminusc;
13096 char **xargv;
13097
13098 xargv = argv;
13099 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013100 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013101 xargv++;
13102 for (i = 0; i < NOPTS; i++)
13103 optlist[i] = 2;
13104 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013105 if (options(1)) {
13106 /* it already printed err message */
13107 raise_exception(EXERROR);
13108 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013109 xargv = argptr;
13110 xminusc = minusc;
13111 if (*xargv == NULL) {
13112 if (xminusc)
13113 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13114 sflag = 1;
13115 }
13116 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13117 iflag = 1;
13118 if (mflag == 2)
13119 mflag = iflag;
13120 for (i = 0; i < NOPTS; i++)
13121 if (optlist[i] == 2)
13122 optlist[i] = 0;
13123#if DEBUG == 2
13124 debug = 1;
13125#endif
13126 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13127 if (xminusc) {
13128 minusc = *xargv++;
13129 if (*xargv)
13130 goto setarg0;
13131 } else if (!sflag) {
13132 setinputfile(*xargv, 0);
13133 setarg0:
13134 arg0 = *xargv++;
13135 commandname = arg0;
13136 }
13137
13138 shellparam.p = xargv;
13139#if ENABLE_ASH_GETOPTS
13140 shellparam.optind = 1;
13141 shellparam.optoff = -1;
13142#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013143 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013144 while (*xargv) {
13145 shellparam.nparam++;
13146 xargv++;
13147 }
13148 optschanged();
13149}
13150
13151/*
13152 * Read /etc/profile or .profile.
13153 */
13154static void
13155read_profile(const char *name)
13156{
13157 int skip;
13158
13159 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13160 return;
13161 skip = cmdloop(0);
13162 popfile();
13163 if (skip)
13164 exitshell();
13165}
13166
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013167/*
13168 * This routine is called when an error or an interrupt occurs in an
13169 * interactive shell and control is returned to the main command loop.
13170 */
13171static void
13172reset(void)
13173{
13174 /* from eval.c: */
13175 evalskip = 0;
13176 loopnest = 0;
13177 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013178 g_parsefile->left_in_buffer = 0;
13179 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013180 popallfiles();
13181 /* from parser.c: */
13182 tokpushback = 0;
13183 checkkwd = 0;
13184 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013185 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013186}
13187
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013188#if PROFILE
13189static short profile_buf[16384];
13190extern int etext();
13191#endif
13192
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013193/*
13194 * Main routine. We initialize things, parse the arguments, execute
13195 * profiles if we're a login shell, and then call cmdloop to execute
13196 * commands. The setjmp call sets up the location to jump to when an
13197 * exception occurs. When an exception occurs the variable "state"
13198 * is used to figure out how far we had gotten.
13199 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013200int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013201int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013202{
Mike Frysinger98c52642009-04-02 10:02:37 +000013203 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013204 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013205 struct jmploc jmploc;
13206 struct stackmark smark;
13207
Denis Vlasenko01631112007-12-16 17:20:38 +000013208 /* Initialize global data */
13209 INIT_G_misc();
13210 INIT_G_memstack();
13211 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013212#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013213 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013214#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013215 INIT_G_cmdtable();
13216
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013217#if PROFILE
13218 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13219#endif
13220
13221#if ENABLE_FEATURE_EDITING
13222 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13223#endif
13224 state = 0;
13225 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013226 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013227 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013228
13229 reset();
13230
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013231 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013232 if (e == EXERROR)
13233 exitstatus = 2;
13234 s = state;
13235 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13236 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013237 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013238 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013239
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013240 popstackmark(&smark);
13241 FORCE_INT_ON; /* enable interrupts */
13242 if (s == 1)
13243 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013244 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013245 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013246 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013247 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013248 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013249 }
13250 exception_handler = &jmploc;
13251#if DEBUG
13252 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013253 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013254 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013255#endif
13256 rootpid = getpid();
13257
13258#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013259 /* Can use monotonic_ns() for better randomness but for now it is
13260 * not used anywhere else in busybox... so avoid bloat */
13261 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013262#endif
13263 init();
13264 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013265 procargs(argv);
13266
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013267#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13268 if (iflag) {
13269 const char *hp = lookupvar("HISTFILE");
13270
13271 if (hp == NULL) {
13272 hp = lookupvar("HOME");
13273 if (hp != NULL) {
13274 char *defhp = concat_path_file(hp, ".ash_history");
13275 setvar("HISTFILE", defhp, 0);
13276 free(defhp);
13277 }
13278 }
13279 }
13280#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013281 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013282 isloginsh = 1;
13283 if (isloginsh) {
13284 state = 1;
13285 read_profile("/etc/profile");
13286 state1:
13287 state = 2;
13288 read_profile(".profile");
13289 }
13290 state2:
13291 state = 3;
13292 if (
13293#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013294 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013295#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013296 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013297 ) {
13298 shinit = lookupvar("ENV");
13299 if (shinit != NULL && *shinit != '\0') {
13300 read_profile(shinit);
13301 }
13302 }
13303 state3:
13304 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013305 if (minusc) {
13306 /* evalstring pushes parsefile stack.
13307 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013308 * is one of stacked source fds.
13309 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013310 if (!sflag)
13311 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013312 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013313 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013314
13315 if (sflag || minusc == NULL) {
13316#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013317 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013318 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013319 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013320 line_input_state->hist_file = hp;
13321 }
13322#endif
13323 state4: /* XXX ??? - why isn't this before the "if" statement */
13324 cmdloop(1);
13325 }
13326#if PROFILE
13327 monitor(0);
13328#endif
13329#ifdef GPROF
13330 {
13331 extern void _mcleanup(void);
13332 _mcleanup();
13333 }
13334#endif
13335 exitshell();
13336 /* NOTREACHED */
13337}
13338
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013339
Eric Andersendf82f612001-06-28 07:46:40 +000013340/*-
13341 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013342 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013343 *
13344 * This code is derived from software contributed to Berkeley by
13345 * Kenneth Almquist.
13346 *
13347 * Redistribution and use in source and binary forms, with or without
13348 * modification, are permitted provided that the following conditions
13349 * are met:
13350 * 1. Redistributions of source code must retain the above copyright
13351 * notice, this list of conditions and the following disclaimer.
13352 * 2. Redistributions in binary form must reproduce the above copyright
13353 * notice, this list of conditions and the following disclaimer in the
13354 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013355 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013356 * may be used to endorse or promote products derived from this software
13357 * without specific prior written permission.
13358 *
13359 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13360 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13361 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13362 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13363 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13364 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13365 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13366 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13367 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13368 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13369 * SUCH DAMAGE.
13370 */