blob: f2d372f4afab7e16f3c3957ca4c97dbabd786344 [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 Vlasenkoa8915072007-02-23 21:10:06 +00003275static int forkshell(struct job *, union node *, int);
3276static int waitforjob(struct job *);
3277
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003278#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003279enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003280#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003281#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003282static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003283static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003284#endif
3285
3286/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 * Ignore a signal.
3288 */
3289static void
3290ignoresig(int signo)
3291{
3292 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294 /* No, need to do it */
3295 signal(signo, SIG_IGN);
3296 }
3297 sigmode[signo - 1] = S_HARD_IGN;
3298}
3299
3300/*
3301 * Signal handler. Only one usage site - in setsignal()
3302 */
3303static void
3304onsig(int signo)
3305{
3306 gotsig[signo - 1] = 1;
3307
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003308 if (signo == SIGINT && !trap[SIGINT]) {
3309 if (!suppress_int) {
3310 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003311 raise_interrupt(); /* does not return */
3312 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003313 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003314 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003315 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003316 }
3317}
3318
3319/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003320 * Set the signal handler for the specified signal. The routine figures
3321 * out what it should be set to.
3322 */
3323static void
3324setsignal(int signo)
3325{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003326 char *t;
3327 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003328 struct sigaction act;
3329
3330 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003331 new_act = S_DFL;
3332 if (t != NULL) { /* trap for this sig is set */
3333 new_act = S_CATCH;
3334 if (t[0] == '\0') /* trap is "": ignore this sig */
3335 new_act = S_IGN;
3336 }
3337
3338 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 switch (signo) {
3340 case SIGINT:
3341 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003342 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343 break;
3344 case SIGQUIT:
3345#if DEBUG
3346 if (debug)
3347 break;
3348#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003349 /* man bash:
3350 * "In all cases, bash ignores SIGQUIT. Non-builtin
3351 * commands run by bash have signal handlers
3352 * set to the values inherited by the shell
3353 * from its parent". */
3354 new_act = S_IGN;
3355 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003356 case SIGTERM:
3357 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003358 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 break;
3360#if JOBS
3361 case SIGTSTP:
3362 case SIGTTOU:
3363 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 break;
3366#endif
3367 }
3368 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003369//TODO: if !rootshell, we reset SIGQUIT to DFL,
3370//whereas we have to restore it to what shell got on entry
3371//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003372
3373 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374 cur_act = *t;
3375 if (cur_act == 0) {
3376 /* current setting is not yet known */
3377 if (sigaction(signo, NULL, &act)) {
3378 /* pretend it worked; maybe we should give a warning,
3379 * but other shells don't. We don't alter sigmode,
3380 * so we retry every time.
3381 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382 return;
3383 }
3384 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003385 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003386 if (mflag
3387 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3388 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003389 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003390 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391 }
3392 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003393 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003395
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003396 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003397 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398 case S_CATCH:
3399 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003400 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402 break;
3403 case S_IGN:
3404 act.sa_handler = SIG_IGN;
3405 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003407 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003408
3409 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003410}
3411
3412/* mode flags for set_curjob */
3413#define CUR_DELETE 2
3414#define CUR_RUNNING 1
3415#define CUR_STOPPED 0
3416
3417/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003418#define DOWAIT_NONBLOCK WNOHANG
3419#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003420
3421#if JOBS
3422/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003423static int initialpgrp; //references:2
3424static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003425#endif
3426/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003427static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003429static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003431static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003432/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003433static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003434
3435static void
3436set_curjob(struct job *jp, unsigned mode)
3437{
3438 struct job *jp1;
3439 struct job **jpp, **curp;
3440
3441 /* first remove from list */
3442 jpp = curp = &curjob;
3443 do {
3444 jp1 = *jpp;
3445 if (jp1 == jp)
3446 break;
3447 jpp = &jp1->prev_job;
3448 } while (1);
3449 *jpp = jp1->prev_job;
3450
3451 /* Then re-insert in correct position */
3452 jpp = curp;
3453 switch (mode) {
3454 default:
3455#if DEBUG
3456 abort();
3457#endif
3458 case CUR_DELETE:
3459 /* job being deleted */
3460 break;
3461 case CUR_RUNNING:
3462 /* newly created job or backgrounded job,
3463 put after all stopped jobs. */
3464 do {
3465 jp1 = *jpp;
3466#if JOBS
3467 if (!jp1 || jp1->state != JOBSTOPPED)
3468#endif
3469 break;
3470 jpp = &jp1->prev_job;
3471 } while (1);
3472 /* FALLTHROUGH */
3473#if JOBS
3474 case CUR_STOPPED:
3475#endif
3476 /* newly stopped job - becomes curjob */
3477 jp->prev_job = *jpp;
3478 *jpp = jp;
3479 break;
3480 }
3481}
3482
3483#if JOBS || DEBUG
3484static int
3485jobno(const struct job *jp)
3486{
3487 return jp - jobtab + 1;
3488}
3489#endif
3490
3491/*
3492 * Convert a job name to a job structure.
3493 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003494#if !JOBS
3495#define getjob(name, getctl) getjob(name)
3496#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003497static struct job *
3498getjob(const char *name, int getctl)
3499{
3500 struct job *jp;
3501 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003502 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003503 unsigned num;
3504 int c;
3505 const char *p;
3506 char *(*match)(const char *, const char *);
3507
3508 jp = curjob;
3509 p = name;
3510 if (!p)
3511 goto currentjob;
3512
3513 if (*p != '%')
3514 goto err;
3515
3516 c = *++p;
3517 if (!c)
3518 goto currentjob;
3519
3520 if (!p[1]) {
3521 if (c == '+' || c == '%') {
3522 currentjob:
3523 err_msg = "No current job";
3524 goto check;
3525 }
3526 if (c == '-') {
3527 if (jp)
3528 jp = jp->prev_job;
3529 err_msg = "No previous job";
3530 check:
3531 if (!jp)
3532 goto err;
3533 goto gotit;
3534 }
3535 }
3536
3537 if (is_number(p)) {
3538 num = atoi(p);
3539 if (num < njobs) {
3540 jp = jobtab + num - 1;
3541 if (jp->used)
3542 goto gotit;
3543 goto err;
3544 }
3545 }
3546
3547 match = prefix;
3548 if (*p == '?') {
3549 match = strstr;
3550 p++;
3551 }
3552
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003553 found = NULL;
3554 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003555 if (match(jp->ps[0].cmd, p)) {
3556 if (found)
3557 goto err;
3558 found = jp;
3559 err_msg = "%s: ambiguous";
3560 }
3561 jp = jp->prev_job;
3562 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003563 if (!found)
3564 goto err;
3565 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003566
3567 gotit:
3568#if JOBS
3569 err_msg = "job %s not created under job control";
3570 if (getctl && jp->jobctl == 0)
3571 goto err;
3572#endif
3573 return jp;
3574 err:
3575 ash_msg_and_raise_error(err_msg, name);
3576}
3577
3578/*
3579 * Mark a job structure as unused.
3580 */
3581static void
3582freejob(struct job *jp)
3583{
3584 struct procstat *ps;
3585 int i;
3586
3587 INT_OFF;
3588 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589 if (ps->cmd != nullstr)
3590 free(ps->cmd);
3591 }
3592 if (jp->ps != &jp->ps0)
3593 free(jp->ps);
3594 jp->used = 0;
3595 set_curjob(jp, CUR_DELETE);
3596 INT_ON;
3597}
3598
3599#if JOBS
3600static void
3601xtcsetpgrp(int fd, pid_t pgrp)
3602{
3603 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003604 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003605}
3606
3607/*
3608 * Turn job control on and off.
3609 *
3610 * Note: This code assumes that the third arg to ioctl is a character
3611 * pointer, which is true on Berkeley systems but not System V. Since
3612 * System V doesn't have job control yet, this isn't a problem now.
3613 *
3614 * Called with interrupts off.
3615 */
3616static void
3617setjobctl(int on)
3618{
3619 int fd;
3620 int pgrp;
3621
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003622 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003623 return;
3624 if (on) {
3625 int ofd;
3626 ofd = fd = open(_PATH_TTY, O_RDWR);
3627 if (fd < 0) {
3628 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629 * That sometimes helps to acquire controlling tty.
3630 * Obviously, a workaround for bugs when someone
3631 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003632 fd = 2;
3633 while (!isatty(fd))
3634 if (--fd < 0)
3635 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003636 }
3637 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003638 if (ofd >= 0)
3639 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003640 if (fd < 0)
3641 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003642 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003643 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003644 do { /* while we are in the background */
3645 pgrp = tcgetpgrp(fd);
3646 if (pgrp < 0) {
3647 out:
3648 ash_msg("can't access tty; job control turned off");
3649 mflag = on = 0;
3650 goto close;
3651 }
3652 if (pgrp == getpgrp())
3653 break;
3654 killpg(0, SIGTTIN);
3655 } while (1);
3656 initialpgrp = pgrp;
3657
3658 setsignal(SIGTSTP);
3659 setsignal(SIGTTOU);
3660 setsignal(SIGTTIN);
3661 pgrp = rootpid;
3662 setpgid(0, pgrp);
3663 xtcsetpgrp(fd, pgrp);
3664 } else {
3665 /* turning job control off */
3666 fd = ttyfd;
3667 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003668 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003669 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003670 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003671 setpgid(0, pgrp);
3672 setsignal(SIGTSTP);
3673 setsignal(SIGTTOU);
3674 setsignal(SIGTTIN);
3675 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003676 if (fd >= 0)
3677 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678 fd = -1;
3679 }
3680 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003681 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003682}
3683
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003684static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003685killcmd(int argc, char **argv)
3686{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003687 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003688 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003689 do {
3690 if (argv[i][0] == '%') {
3691 struct job *jp = getjob(argv[i], 0);
3692 unsigned pid = jp->ps[0].pid;
3693 /* Enough space for ' -NNN<nul>' */
3694 argv[i] = alloca(sizeof(int)*3 + 3);
3695 /* kill_main has matching code to expect
3696 * leading space. Needed to not confuse
3697 * negative pids with "kill -SIGNAL_NO" syntax */
3698 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003699 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003700 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003701 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003702 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703}
3704
3705static void
3706showpipe(struct job *jp, FILE *out)
3707{
3708 struct procstat *sp;
3709 struct procstat *spend;
3710
3711 spend = jp->ps + jp->nprocs;
3712 for (sp = jp->ps + 1; sp < spend; sp++)
3713 fprintf(out, " | %s", sp->cmd);
3714 outcslow('\n', out);
3715 flush_stdout_stderr();
3716}
3717
3718
3719static int
3720restartjob(struct job *jp, int mode)
3721{
3722 struct procstat *ps;
3723 int i;
3724 int status;
3725 pid_t pgid;
3726
3727 INT_OFF;
3728 if (jp->state == JOBDONE)
3729 goto out;
3730 jp->state = JOBRUNNING;
3731 pgid = jp->ps->pid;
3732 if (mode == FORK_FG)
3733 xtcsetpgrp(ttyfd, pgid);
3734 killpg(pgid, SIGCONT);
3735 ps = jp->ps;
3736 i = jp->nprocs;
3737 do {
3738 if (WIFSTOPPED(ps->status)) {
3739 ps->status = -1;
3740 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003741 ps++;
3742 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003743 out:
3744 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3745 INT_ON;
3746 return status;
3747}
3748
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003749static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003750fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003751{
3752 struct job *jp;
3753 FILE *out;
3754 int mode;
3755 int retval;
3756
3757 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3758 nextopt(nullstr);
3759 argv = argptr;
3760 out = stdout;
3761 do {
3762 jp = getjob(*argv, 1);
3763 if (mode == FORK_BG) {
3764 set_curjob(jp, CUR_RUNNING);
3765 fprintf(out, "[%d] ", jobno(jp));
3766 }
3767 outstr(jp->ps->cmd, out);
3768 showpipe(jp, out);
3769 retval = restartjob(jp, mode);
3770 } while (*argv && *++argv);
3771 return retval;
3772}
3773#endif
3774
3775static int
3776sprint_status(char *s, int status, int sigonly)
3777{
3778 int col;
3779 int st;
3780
3781 col = 0;
3782 if (!WIFEXITED(status)) {
3783#if JOBS
3784 if (WIFSTOPPED(status))
3785 st = WSTOPSIG(status);
3786 else
3787#endif
3788 st = WTERMSIG(status);
3789 if (sigonly) {
3790 if (st == SIGINT || st == SIGPIPE)
3791 goto out;
3792#if JOBS
3793 if (WIFSTOPPED(status))
3794 goto out;
3795#endif
3796 }
3797 st &= 0x7f;
3798 col = fmtstr(s, 32, strsignal(st));
3799 if (WCOREDUMP(status)) {
3800 col += fmtstr(s + col, 16, " (core dumped)");
3801 }
3802 } else if (!sigonly) {
3803 st = WEXITSTATUS(status);
3804 if (st)
3805 col = fmtstr(s, 16, "Done(%d)", st);
3806 else
3807 col = fmtstr(s, 16, "Done");
3808 }
3809 out:
3810 return col;
3811}
3812
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003813static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003814dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815{
3816 int pid;
3817 int status;
3818 struct job *jp;
3819 struct job *thisjob;
3820 int state;
3821
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003822 TRACE(("dowait(0x%x) called\n", wait_flags));
3823
3824 /* Do a wait system call. If job control is compiled in, we accept
3825 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826 * NB: _not_ safe_waitpid, we need to detect EINTR */
3827 pid = waitpid(-1, &status,
3828 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003829 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003831 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003832 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003833
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003834 INT_OFF;
3835 thisjob = NULL;
3836 for (jp = curjob; jp; jp = jp->prev_job) {
3837 struct procstat *sp;
3838 struct procstat *spend;
3839 if (jp->state == JOBDONE)
3840 continue;
3841 state = JOBDONE;
3842 spend = jp->ps + jp->nprocs;
3843 sp = jp->ps;
3844 do {
3845 if (sp->pid == pid) {
3846 TRACE(("Job %d: changing status of proc %d "
3847 "from 0x%x to 0x%x\n",
3848 jobno(jp), pid, sp->status, status));
3849 sp->status = status;
3850 thisjob = jp;
3851 }
3852 if (sp->status == -1)
3853 state = JOBRUNNING;
3854#if JOBS
3855 if (state == JOBRUNNING)
3856 continue;
3857 if (WIFSTOPPED(sp->status)) {
3858 jp->stopstatus = sp->status;
3859 state = JOBSTOPPED;
3860 }
3861#endif
3862 } while (++sp < spend);
3863 if (thisjob)
3864 goto gotjob;
3865 }
3866#if JOBS
3867 if (!WIFSTOPPED(status))
3868#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 jobless--;
3870 goto out;
3871
3872 gotjob:
3873 if (state != JOBRUNNING) {
3874 thisjob->changed = 1;
3875
3876 if (thisjob->state != state) {
3877 TRACE(("Job %d: changing state from %d to %d\n",
3878 jobno(thisjob), thisjob->state, state));
3879 thisjob->state = state;
3880#if JOBS
3881 if (state == JOBSTOPPED) {
3882 set_curjob(thisjob, CUR_STOPPED);
3883 }
3884#endif
3885 }
3886 }
3887
3888 out:
3889 INT_ON;
3890
3891 if (thisjob && thisjob == job) {
3892 char s[48 + 1];
3893 int len;
3894
3895 len = sprint_status(s, status, 1);
3896 if (len) {
3897 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003898 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 out2str(s);
3900 }
3901 }
3902 return pid;
3903}
3904
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003905static int
3906blocking_wait_with_raise_on_sig(struct job *job)
3907{
3908 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003909 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003910 raise_exception(EXSIG);
3911 return pid;
3912}
3913
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003914#if JOBS
3915static void
3916showjob(FILE *out, struct job *jp, int mode)
3917{
3918 struct procstat *ps;
3919 struct procstat *psend;
3920 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003921 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003922 char s[80];
3923
3924 ps = jp->ps;
3925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003927 /* just output process (group) id of pipeline */
3928 fprintf(out, "%d\n", ps->pid);
3929 return;
3930 }
3931
3932 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003933 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934
3935 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003936 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003938 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003939
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003940 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 col += fmtstr(s + col, 16, "%d ", ps->pid);
3942
3943 psend = ps + jp->nprocs;
3944
3945 if (jp->state == JOBRUNNING) {
3946 strcpy(s + col, "Running");
3947 col += sizeof("Running") - 1;
3948 } else {
3949 int status = psend[-1].status;
3950 if (jp->state == JOBSTOPPED)
3951 status = jp->stopstatus;
3952 col += sprint_status(s + col, status, 0);
3953 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003954 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003955
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003956 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957 * or prints several "PID | <cmdN>" lines,
3958 * depending on SHOW_PIDS bit.
3959 * We do not print status of individual processes
3960 * between PID and <cmdN>. bash does it, but not very well:
3961 * first line shows overall job status, not process status,
3962 * making it impossible to know 1st process status.
3963 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003964 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003965 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003966 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003967 s[0] = '\0';
3968 col = 33;
3969 if (mode & SHOW_PIDS)
3970 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003972 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3973 if (ps != jp->ps)
3974 fprintf(out, "| ");
3975 fprintf(out, "%s", ps->cmd);
3976 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003977 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003978 }
3979 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003980
3981 jp->changed = 0;
3982
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3985 freejob(jp);
3986 }
3987}
3988
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003989/*
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3992 */
3993static void
3994showjobs(FILE *out, int mode)
3995{
3996 struct job *jp;
3997
Denys Vlasenko883cea42009-07-11 15:31:59 +02003998 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003999
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004000 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002 continue;
4003
4004 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004005 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004007 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008 }
4009}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004010
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004011static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004012jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004013{
4014 int mode, m;
4015
4016 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004017 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004018 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004019 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004020 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004021 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004022 }
4023
4024 argv = argptr;
4025 if (*argv) {
4026 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004027 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004028 while (*++argv);
4029 } else
4030 showjobs(stdout, mode);
4031
4032 return 0;
4033}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004034#endif /* JOBS */
4035
4036static int
4037getstatus(struct job *job)
4038{
4039 int status;
4040 int retval;
4041
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4045#if JOBS
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4048#endif
4049 {
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4052#if JOBS
4053 if (retval == SIGINT)
4054 job->sigint = 1;
4055#endif
4056 }
4057 retval += 128;
4058 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004059 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004060 jobno(job), job->nprocs, status, retval));
4061 return retval;
4062}
4063
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004064static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004065waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066{
4067 struct job *job;
4068 int retval;
4069 struct job *jp;
4070
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004071 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004072 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004073
4074 nextopt(nullstr);
4075 retval = 0;
4076
4077 argv = argptr;
4078 if (!*argv) {
4079 /* wait for all jobs */
4080 for (;;) {
4081 jp = curjob;
4082 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004083 if (!jp) /* no running procs */
4084 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004085 if (jp->state == JOBRUNNING)
4086 break;
4087 jp->waited = 1;
4088 jp = jp->prev_job;
4089 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004090 /* man bash:
4091 * "When bash is waiting for an asynchronous command via
4092 * the wait builtin, the reception of a signal for which a trap
4093 * has been set will cause the wait builtin to return immediately
4094 * with an exit status greater than 128, immediately after which
4095 * the trap is executed."
4096 * Do we do it that way? */
4097 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 }
4099 }
4100
4101 retval = 127;
4102 do {
4103 if (**argv != '%') {
4104 pid_t pid = number(*argv);
4105 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004106 while (1) {
4107 if (!job)
4108 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004109 if (job->ps[job->nprocs - 1].pid == pid)
4110 break;
4111 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004112 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004113 } else
4114 job = getjob(*argv, 0);
4115 /* loop until process terminated or stopped */
4116 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004117 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004118 job->waited = 1;
4119 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004120 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121 } while (*++argv);
4122
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004123 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124 return retval;
4125}
4126
4127static struct job *
4128growjobtab(void)
4129{
4130 size_t len;
4131 ptrdiff_t offset;
4132 struct job *jp, *jq;
4133
4134 len = njobs * sizeof(*jp);
4135 jq = jobtab;
4136 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4137
4138 offset = (char *)jp - (char *)jq;
4139 if (offset) {
4140 /* Relocate pointers */
4141 size_t l = len;
4142
4143 jq = (struct job *)((char *)jq + l);
4144 while (l) {
4145 l -= sizeof(*jp);
4146 jq--;
4147#define joff(p) ((struct job *)((char *)(p) + l))
4148#define jmove(p) (p) = (void *)((char *)(p) + offset)
4149 if (joff(jp)->ps == &jq->ps0)
4150 jmove(joff(jp)->ps);
4151 if (joff(jp)->prev_job)
4152 jmove(joff(jp)->prev_job);
4153 }
4154 if (curjob)
4155 jmove(curjob);
4156#undef joff
4157#undef jmove
4158 }
4159
4160 njobs += 4;
4161 jobtab = jp;
4162 jp = (struct job *)((char *)jp + len);
4163 jq = jp + 3;
4164 do {
4165 jq->used = 0;
4166 } while (--jq >= jp);
4167 return jp;
4168}
4169
4170/*
4171 * Return a new job structure.
4172 * Called with interrupts off.
4173 */
4174static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004175makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004176{
4177 int i;
4178 struct job *jp;
4179
4180 for (i = njobs, jp = jobtab; ; jp++) {
4181 if (--i < 0) {
4182 jp = growjobtab();
4183 break;
4184 }
4185 if (jp->used == 0)
4186 break;
4187 if (jp->state != JOBDONE || !jp->waited)
4188 continue;
4189#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004190 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004191 continue;
4192#endif
4193 freejob(jp);
4194 break;
4195 }
4196 memset(jp, 0, sizeof(*jp));
4197#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004198 /* jp->jobctl is a bitfield.
4199 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004200 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004201 jp->jobctl = 1;
4202#endif
4203 jp->prev_job = curjob;
4204 curjob = jp;
4205 jp->used = 1;
4206 jp->ps = &jp->ps0;
4207 if (nprocs > 1) {
4208 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4209 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004210 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004211 jobno(jp)));
4212 return jp;
4213}
4214
4215#if JOBS
4216/*
4217 * Return a string identifying a command (to be printed by the
4218 * jobs command).
4219 */
4220static char *cmdnextc;
4221
4222static void
4223cmdputs(const char *s)
4224{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004225 static const char vstype[VSTYPE + 1][3] = {
4226 "", "}", "-", "+", "?", "=",
4227 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004228 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004229 };
4230
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004231 const char *p, *str;
4232 char c, cc[2] = " ";
4233 char *nextc;
4234 int subtype = 0;
4235 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004236
4237 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4238 p = s;
4239 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004240 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004241 switch (c) {
4242 case CTLESC:
4243 c = *p++;
4244 break;
4245 case CTLVAR:
4246 subtype = *p++;
4247 if ((subtype & VSTYPE) == VSLENGTH)
4248 str = "${#";
4249 else
4250 str = "${";
4251 if (!(subtype & VSQUOTE) == !(quoted & 1))
4252 goto dostr;
4253 quoted ^= 1;
4254 c = '"';
4255 break;
4256 case CTLENDVAR:
4257 str = "\"}" + !(quoted & 1);
4258 quoted >>= 1;
4259 subtype = 0;
4260 goto dostr;
4261 case CTLBACKQ:
4262 str = "$(...)";
4263 goto dostr;
4264 case CTLBACKQ+CTLQUOTE:
4265 str = "\"$(...)\"";
4266 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004267#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004268 case CTLARI:
4269 str = "$((";
4270 goto dostr;
4271 case CTLENDARI:
4272 str = "))";
4273 goto dostr;
4274#endif
4275 case CTLQUOTEMARK:
4276 quoted ^= 1;
4277 c = '"';
4278 break;
4279 case '=':
4280 if (subtype == 0)
4281 break;
4282 if ((subtype & VSTYPE) != VSNORMAL)
4283 quoted <<= 1;
4284 str = vstype[subtype & VSTYPE];
4285 if (subtype & VSNUL)
4286 c = ':';
4287 else
4288 goto checkstr;
4289 break;
4290 case '\'':
4291 case '\\':
4292 case '"':
4293 case '$':
4294 /* These can only happen inside quotes */
4295 cc[0] = c;
4296 str = cc;
4297 c = '\\';
4298 break;
4299 default:
4300 break;
4301 }
4302 USTPUTC(c, nextc);
4303 checkstr:
4304 if (!str)
4305 continue;
4306 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004307 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004308 USTPUTC(c, nextc);
4309 }
4310 }
4311 if (quoted & 1) {
4312 USTPUTC('"', nextc);
4313 }
4314 *nextc = 0;
4315 cmdnextc = nextc;
4316}
4317
4318/* cmdtxt() and cmdlist() call each other */
4319static void cmdtxt(union node *n);
4320
4321static void
4322cmdlist(union node *np, int sep)
4323{
4324 for (; np; np = np->narg.next) {
4325 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004326 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004327 cmdtxt(np);
4328 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004329 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330 }
4331}
4332
4333static void
4334cmdtxt(union node *n)
4335{
4336 union node *np;
4337 struct nodelist *lp;
4338 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004339
4340 if (!n)
4341 return;
4342 switch (n->type) {
4343 default:
4344#if DEBUG
4345 abort();
4346#endif
4347 case NPIPE:
4348 lp = n->npipe.cmdlist;
4349 for (;;) {
4350 cmdtxt(lp->n);
4351 lp = lp->next;
4352 if (!lp)
4353 break;
4354 cmdputs(" | ");
4355 }
4356 break;
4357 case NSEMI:
4358 p = "; ";
4359 goto binop;
4360 case NAND:
4361 p = " && ";
4362 goto binop;
4363 case NOR:
4364 p = " || ";
4365 binop:
4366 cmdtxt(n->nbinary.ch1);
4367 cmdputs(p);
4368 n = n->nbinary.ch2;
4369 goto donode;
4370 case NREDIR:
4371 case NBACKGND:
4372 n = n->nredir.n;
4373 goto donode;
4374 case NNOT:
4375 cmdputs("!");
4376 n = n->nnot.com;
4377 donode:
4378 cmdtxt(n);
4379 break;
4380 case NIF:
4381 cmdputs("if ");
4382 cmdtxt(n->nif.test);
4383 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004384 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004385 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004386 cmdputs("; else ");
4387 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004388 } else {
4389 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004390 }
4391 p = "; fi";
4392 goto dotail;
4393 case NSUBSHELL:
4394 cmdputs("(");
4395 n = n->nredir.n;
4396 p = ")";
4397 goto dotail;
4398 case NWHILE:
4399 p = "while ";
4400 goto until;
4401 case NUNTIL:
4402 p = "until ";
4403 until:
4404 cmdputs(p);
4405 cmdtxt(n->nbinary.ch1);
4406 n = n->nbinary.ch2;
4407 p = "; done";
4408 dodo:
4409 cmdputs("; do ");
4410 dotail:
4411 cmdtxt(n);
4412 goto dotail2;
4413 case NFOR:
4414 cmdputs("for ");
4415 cmdputs(n->nfor.var);
4416 cmdputs(" in ");
4417 cmdlist(n->nfor.args, 1);
4418 n = n->nfor.body;
4419 p = "; done";
4420 goto dodo;
4421 case NDEFUN:
4422 cmdputs(n->narg.text);
4423 p = "() { ... }";
4424 goto dotail2;
4425 case NCMD:
4426 cmdlist(n->ncmd.args, 1);
4427 cmdlist(n->ncmd.redirect, 0);
4428 break;
4429 case NARG:
4430 p = n->narg.text;
4431 dotail2:
4432 cmdputs(p);
4433 break;
4434 case NHERE:
4435 case NXHERE:
4436 p = "<<...";
4437 goto dotail2;
4438 case NCASE:
4439 cmdputs("case ");
4440 cmdputs(n->ncase.expr->narg.text);
4441 cmdputs(" in ");
4442 for (np = n->ncase.cases; np; np = np->nclist.next) {
4443 cmdtxt(np->nclist.pattern);
4444 cmdputs(") ");
4445 cmdtxt(np->nclist.body);
4446 cmdputs(";; ");
4447 }
4448 p = "esac";
4449 goto dotail2;
4450 case NTO:
4451 p = ">";
4452 goto redir;
4453 case NCLOBBER:
4454 p = ">|";
4455 goto redir;
4456 case NAPPEND:
4457 p = ">>";
4458 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004459#if ENABLE_ASH_BASH_COMPAT
4460 case NTO2:
4461#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004462 case NTOFD:
4463 p = ">&";
4464 goto redir;
4465 case NFROM:
4466 p = "<";
4467 goto redir;
4468 case NFROMFD:
4469 p = "<&";
4470 goto redir;
4471 case NFROMTO:
4472 p = "<>";
4473 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004474 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004475 cmdputs(p);
4476 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004477 cmdputs(utoa(n->ndup.dupfd));
4478 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004479 }
4480 n = n->nfile.fname;
4481 goto donode;
4482 }
4483}
4484
4485static char *
4486commandtext(union node *n)
4487{
4488 char *name;
4489
4490 STARTSTACKSTR(cmdnextc);
4491 cmdtxt(n);
4492 name = stackblock();
4493 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4494 name, cmdnextc, cmdnextc));
4495 return ckstrdup(name);
4496}
4497#endif /* JOBS */
4498
4499/*
4500 * Fork off a subshell. If we are doing job control, give the subshell its
4501 * own process group. Jp is a job structure that the job is to be added to.
4502 * N is the command that will be evaluated by the child. Both jp and n may
4503 * be NULL. The mode parameter can be one of the following:
4504 * FORK_FG - Fork off a foreground process.
4505 * FORK_BG - Fork off a background process.
4506 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4507 * process group even if job control is on.
4508 *
4509 * When job control is turned off, background processes have their standard
4510 * input redirected to /dev/null (except for the second and later processes
4511 * in a pipeline).
4512 *
4513 * Called with interrupts off.
4514 */
4515/*
4516 * Clear traps on a fork.
4517 */
4518static void
4519clear_traps(void)
4520{
4521 char **tp;
4522
4523 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004524 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004525 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004526 if (trap_ptr == trap)
4527 free(*tp);
4528 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004529 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004530 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004531 setsignal(tp - trap);
4532 INT_ON;
4533 }
4534 }
4535}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004536
4537/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004538static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004539
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004540/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004541static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004542forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004543{
4544 int oldlvl;
4545
4546 TRACE(("Child shell %d\n", getpid()));
4547 oldlvl = shlvl;
4548 shlvl++;
4549
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004550 /* man bash: "Non-builtin commands run by bash have signal handlers
4551 * set to the values inherited by the shell from its parent".
4552 * Do we do it correctly? */
4553
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004554 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004555
4556 if (mode == FORK_NOJOB /* is it `xxx` ? */
4557 && n && n->type == NCMD /* is it single cmd? */
4558 /* && n->ncmd.args->type == NARG - always true? */
4559 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4560 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4561 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4562 ) {
4563 TRACE(("Trap hack\n"));
4564 /* Awful hack for `trap` or $(trap).
4565 *
4566 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4567 * contains an example where "trap" is executed in a subshell:
4568 *
4569 * save_traps=$(trap)
4570 * ...
4571 * eval "$save_traps"
4572 *
4573 * Standard does not say that "trap" in subshell shall print
4574 * parent shell's traps. It only says that its output
4575 * must have suitable form, but then, in the above example
4576 * (which is not supposed to be normative), it implies that.
4577 *
4578 * bash (and probably other shell) does implement it
4579 * (traps are reset to defaults, but "trap" still shows them),
4580 * but as a result, "trap" logic is hopelessly messed up:
4581 *
4582 * # trap
4583 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4584 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4585 * # true | trap <--- trap is in subshell - no output (ditto)
4586 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4587 * trap -- 'echo Ho' SIGWINCH
4588 * # echo `(trap)` <--- in subshell in subshell - output
4589 * trap -- 'echo Ho' SIGWINCH
4590 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4591 * trap -- 'echo Ho' SIGWINCH
4592 *
4593 * The rules when to forget and when to not forget traps
4594 * get really complex and nonsensical.
4595 *
4596 * Our solution: ONLY bare $(trap) or `trap` is special.
4597 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004598 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004599 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004600 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004601 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004602 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004603#if JOBS
4604 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004605 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004606 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4607 pid_t pgrp;
4608
4609 if (jp->nprocs == 0)
4610 pgrp = getpid();
4611 else
4612 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004613 /* this can fail because we are doing it in the parent also */
4614 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615 if (mode == FORK_FG)
4616 xtcsetpgrp(ttyfd, pgrp);
4617 setsignal(SIGTSTP);
4618 setsignal(SIGTTOU);
4619 } else
4620#endif
4621 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004622 /* man bash: "When job control is not in effect,
4623 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004624 ignoresig(SIGINT);
4625 ignoresig(SIGQUIT);
4626 if (jp->nprocs == 0) {
4627 close(0);
4628 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004629 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004630 }
4631 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004632 if (!oldlvl) {
4633 if (iflag) { /* why if iflag only? */
4634 setsignal(SIGINT);
4635 setsignal(SIGTERM);
4636 }
4637 /* man bash:
4638 * "In all cases, bash ignores SIGQUIT. Non-builtin
4639 * commands run by bash have signal handlers
4640 * set to the values inherited by the shell
4641 * from its parent".
4642 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004643 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004644 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004645#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004646 if (n && n->type == NCMD
4647 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4648 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004649 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004650 /* "jobs": we do not want to clear job list for it,
4651 * instead we remove only _its_ own_ job from job list.
4652 * This makes "jobs .... | cat" more useful.
4653 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004654 freejob(curjob);
4655 return;
4656 }
4657#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004658 for (jp = curjob; jp; jp = jp->prev_job)
4659 freejob(jp);
4660 jobless = 0;
4661}
4662
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004663/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004664#if !JOBS
4665#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4666#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004667static void
4668forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4669{
4670 TRACE(("In parent shell: child = %d\n", pid));
4671 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004672 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4673 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004674 jobless++;
4675 return;
4676 }
4677#if JOBS
4678 if (mode != FORK_NOJOB && jp->jobctl) {
4679 int pgrp;
4680
4681 if (jp->nprocs == 0)
4682 pgrp = pid;
4683 else
4684 pgrp = jp->ps[0].pid;
4685 /* This can fail because we are doing it in the child also */
4686 setpgid(pid, pgrp);
4687 }
4688#endif
4689 if (mode == FORK_BG) {
4690 backgndpid = pid; /* set $! */
4691 set_curjob(jp, CUR_RUNNING);
4692 }
4693 if (jp) {
4694 struct procstat *ps = &jp->ps[jp->nprocs++];
4695 ps->pid = pid;
4696 ps->status = -1;
4697 ps->cmd = nullstr;
4698#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004699 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004700 ps->cmd = commandtext(n);
4701#endif
4702 }
4703}
4704
4705static int
4706forkshell(struct job *jp, union node *n, int mode)
4707{
4708 int pid;
4709
4710 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4711 pid = fork();
4712 if (pid < 0) {
4713 TRACE(("Fork failed, errno=%d", errno));
4714 if (jp)
4715 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004716 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004717 }
4718 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004719 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004720 else
4721 forkparent(jp, n, mode, pid);
4722 return pid;
4723}
4724
4725/*
4726 * Wait for job to finish.
4727 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004728 * Under job control we have the problem that while a child process
4729 * is running interrupts generated by the user are sent to the child
4730 * but not to the shell. This means that an infinite loop started by
4731 * an interactive user may be hard to kill. With job control turned off,
4732 * an interactive user may place an interactive program inside a loop.
4733 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004734 * these interrupts to also abort the loop. The approach we take here
4735 * is to have the shell ignore interrupt signals while waiting for a
4736 * foreground process to terminate, and then send itself an interrupt
4737 * signal if the child process was terminated by an interrupt signal.
4738 * Unfortunately, some programs want to do a bit of cleanup and then
4739 * exit on interrupt; unless these processes terminate themselves by
4740 * sending a signal to themselves (instead of calling exit) they will
4741 * confuse this approach.
4742 *
4743 * Called with interrupts off.
4744 */
4745static int
4746waitforjob(struct job *jp)
4747{
4748 int st;
4749
4750 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004751
4752 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004753 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004754 /* In non-interactive shells, we _can_ get
4755 * a keyboard signal here and be EINTRed,
4756 * but we just loop back, waiting for command to complete.
4757 *
4758 * man bash:
4759 * "If bash is waiting for a command to complete and receives
4760 * a signal for which a trap has been set, the trap
4761 * will not be executed until the command completes."
4762 *
4763 * Reality is that even if trap is not set, bash
4764 * will not act on the signal until command completes.
4765 * Try this. sleep5intoff.c:
4766 * #include <signal.h>
4767 * #include <unistd.h>
4768 * int main() {
4769 * sigset_t set;
4770 * sigemptyset(&set);
4771 * sigaddset(&set, SIGINT);
4772 * sigaddset(&set, SIGQUIT);
4773 * sigprocmask(SIG_BLOCK, &set, NULL);
4774 * sleep(5);
4775 * return 0;
4776 * }
4777 * $ bash -c './sleep5intoff; echo hi'
4778 * ^C^C^C^C <--- pressing ^C once a second
4779 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004780 * $ bash -c './sleep5intoff; echo hi'
4781 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4782 * $ _
4783 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004784 dowait(DOWAIT_BLOCK, jp);
4785 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004786 INT_ON;
4787
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004788 st = getstatus(jp);
4789#if JOBS
4790 if (jp->jobctl) {
4791 xtcsetpgrp(ttyfd, rootpid);
4792 /*
4793 * This is truly gross.
4794 * If we're doing job control, then we did a TIOCSPGRP which
4795 * caused us (the shell) to no longer be in the controlling
4796 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4797 * intuit from the subprocess exit status whether a SIGINT
4798 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4799 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004800 if (jp->sigint) /* TODO: do the same with all signals */
4801 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004802 }
4803 if (jp->state == JOBDONE)
4804#endif
4805 freejob(jp);
4806 return st;
4807}
4808
4809/*
4810 * return 1 if there are stopped jobs, otherwise 0
4811 */
4812static int
4813stoppedjobs(void)
4814{
4815 struct job *jp;
4816 int retval;
4817
4818 retval = 0;
4819 if (job_warning)
4820 goto out;
4821 jp = curjob;
4822 if (jp && jp->state == JOBSTOPPED) {
4823 out2str("You have stopped jobs.\n");
4824 job_warning = 2;
4825 retval++;
4826 }
4827 out:
4828 return retval;
4829}
4830
4831
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004832/* ============ redir.c
4833 *
4834 * Code for dealing with input/output redirection.
4835 */
4836
4837#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004838#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004839
4840/*
4841 * Open a file in noclobber mode.
4842 * The code was copied from bash.
4843 */
4844static int
4845noclobberopen(const char *fname)
4846{
4847 int r, fd;
4848 struct stat finfo, finfo2;
4849
4850 /*
4851 * If the file exists and is a regular file, return an error
4852 * immediately.
4853 */
4854 r = stat(fname, &finfo);
4855 if (r == 0 && S_ISREG(finfo.st_mode)) {
4856 errno = EEXIST;
4857 return -1;
4858 }
4859
4860 /*
4861 * If the file was not present (r != 0), make sure we open it
4862 * exclusively so that if it is created before we open it, our open
4863 * will fail. Make sure that we do not truncate an existing file.
4864 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4865 * file was not a regular file, we leave O_EXCL off.
4866 */
4867 if (r != 0)
4868 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4869 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4870
4871 /* If the open failed, return the file descriptor right away. */
4872 if (fd < 0)
4873 return fd;
4874
4875 /*
4876 * OK, the open succeeded, but the file may have been changed from a
4877 * non-regular file to a regular file between the stat and the open.
4878 * We are assuming that the O_EXCL open handles the case where FILENAME
4879 * did not exist and is symlinked to an existing file between the stat
4880 * and open.
4881 */
4882
4883 /*
4884 * If we can open it and fstat the file descriptor, and neither check
4885 * revealed that it was a regular file, and the file has not been
4886 * replaced, return the file descriptor.
4887 */
4888 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4889 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4890 return fd;
4891
4892 /* The file has been replaced. badness. */
4893 close(fd);
4894 errno = EEXIST;
4895 return -1;
4896}
4897
4898/*
4899 * Handle here documents. Normally we fork off a process to write the
4900 * data to a pipe. If the document is short, we can stuff the data in
4901 * the pipe without forking.
4902 */
4903/* openhere needs this forward reference */
4904static void expandhere(union node *arg, int fd);
4905static int
4906openhere(union node *redir)
4907{
4908 int pip[2];
4909 size_t len = 0;
4910
4911 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004912 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004913 if (redir->type == NHERE) {
4914 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004915 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004916 full_write(pip[1], redir->nhere.doc->narg.text, len);
4917 goto out;
4918 }
4919 }
4920 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004921 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004922 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004923 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4924 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4925 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4926 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004927 signal(SIGPIPE, SIG_DFL);
4928 if (redir->type == NHERE)
4929 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004930 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004931 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004932 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004933 }
4934 out:
4935 close(pip[1]);
4936 return pip[0];
4937}
4938
4939static int
4940openredirect(union node *redir)
4941{
4942 char *fname;
4943 int f;
4944
4945 switch (redir->nfile.type) {
4946 case NFROM:
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_RDONLY);
4949 if (f < 0)
4950 goto eopen;
4951 break;
4952 case NFROMTO:
4953 fname = redir->nfile.expfname;
4954 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4955 if (f < 0)
4956 goto ecreate;
4957 break;
4958 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004959#if ENABLE_ASH_BASH_COMPAT
4960 case NTO2:
4961#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004962 /* Take care of noclobber mode. */
4963 if (Cflag) {
4964 fname = redir->nfile.expfname;
4965 f = noclobberopen(fname);
4966 if (f < 0)
4967 goto ecreate;
4968 break;
4969 }
4970 /* FALLTHROUGH */
4971 case NCLOBBER:
4972 fname = redir->nfile.expfname;
4973 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4974 if (f < 0)
4975 goto ecreate;
4976 break;
4977 case NAPPEND:
4978 fname = redir->nfile.expfname;
4979 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4980 if (f < 0)
4981 goto ecreate;
4982 break;
4983 default:
4984#if DEBUG
4985 abort();
4986#endif
4987 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004988/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004989// case NTOFD:
4990// case NFROMFD:
4991// f = -1;
4992// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004993 case NHERE:
4994 case NXHERE:
4995 f = openhere(redir);
4996 break;
4997 }
4998
4999 return f;
5000 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005001 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005002 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005003 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005004}
5005
5006/*
5007 * Copy a file descriptor to be >= to. Returns -1
5008 * if the source file descriptor is closed, EMPTY if there are no unused
5009 * file descriptors left.
5010 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005011/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5012 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005013enum {
5014 COPYFD_EXACT = (int)~(INT_MAX),
5015 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5016};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005017static int
5018copyfd(int from, int to)
5019{
5020 int newfd;
5021
Denis Vlasenko5a867312008-07-24 19:46:38 +00005022 if (to & COPYFD_EXACT) {
5023 to &= ~COPYFD_EXACT;
5024 /*if (from != to)*/
5025 newfd = dup2(from, to);
5026 } else {
5027 newfd = fcntl(from, F_DUPFD, to);
5028 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005029 if (newfd < 0) {
5030 if (errno == EMFILE)
5031 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005032 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005033 ash_msg_and_raise_error("%d: %m", from);
5034 }
5035 return newfd;
5036}
5037
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005038/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005039struct two_fd_t {
5040 int orig, copy;
5041};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005042struct redirtab {
5043 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005044 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005045 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005046 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005047};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005048#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005049
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005050static int need_to_remember(struct redirtab *rp, int fd)
5051{
5052 int i;
5053
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005054 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005055 return 0;
5056
5057 for (i = 0; i < rp->pair_count; i++) {
5058 if (rp->two_fd[i].orig == fd) {
5059 /* already remembered */
5060 return 0;
5061 }
5062 }
5063 return 1;
5064}
5065
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005066/* "hidden" fd is a fd used to read scripts, or a copy of such */
5067static int is_hidden_fd(struct redirtab *rp, int fd)
5068{
5069 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005070 struct parsefile *pf;
5071
5072 if (fd == -1)
5073 return 0;
5074 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005075 while (pf) {
5076 if (fd == pf->fd) {
5077 return 1;
5078 }
5079 pf = pf->prev;
5080 }
5081 if (!rp)
5082 return 0;
5083 fd |= COPYFD_RESTORE;
5084 for (i = 0; i < rp->pair_count; i++) {
5085 if (rp->two_fd[i].copy == fd) {
5086 return 1;
5087 }
5088 }
5089 return 0;
5090}
5091
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005092/*
5093 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5094 * old file descriptors are stashed away so that the redirection can be
5095 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5096 * standard output, and the standard error if it becomes a duplicate of
5097 * stdout, is saved in memory.
5098 */
5099/* flags passed to redirect */
5100#define REDIR_PUSH 01 /* save previous values of file descriptors */
5101#define REDIR_SAVEFD2 03 /* set preverrout */
5102static void
5103redirect(union node *redir, int flags)
5104{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005105 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005106 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 int i;
5108 int fd;
5109 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005111
Denis Vlasenko01631112007-12-16 17:20:38 +00005112 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005113 if (!redir) {
5114 return;
5115 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005116
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005117 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 INT_OFF;
5120 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005121 union node *tmp = redir;
5122 do {
5123 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005124#if ENABLE_ASH_BASH_COMPAT
5125 if (redir->nfile.type == NTO2)
5126 sv_pos++;
5127#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128 tmp = tmp->nfile.next;
5129 } while (tmp);
5130 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005131 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005132 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005133 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005134 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005135 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005136 while (sv_pos > 0) {
5137 sv_pos--;
5138 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5139 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005140 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005141
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005142 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005143 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005144 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005145 int right_fd = redir->ndup.dupfd;
5146 /* redirect from/to same file descriptor? */
5147 if (right_fd == fd)
5148 continue;
5149 /* echo >&10 and 10 is a fd opened to the sh script? */
5150 if (is_hidden_fd(sv, right_fd)) {
5151 errno = EBADF; /* as if it is closed */
5152 ash_msg_and_raise_error("%d: %m", right_fd);
5153 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005154 newfd = -1;
5155 } else {
5156 newfd = openredirect(redir); /* always >= 0 */
5157 if (fd == newfd) {
5158 /* Descriptor wasn't open before redirect.
5159 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005160 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005161 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005162 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005163 continue;
5164 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005165 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005166#if ENABLE_ASH_BASH_COMPAT
5167 redirect_more:
5168#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005169 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005170 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005171 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005172/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5173 * are closed in popredir() in the child, preventing them from leaking
5174 * into child. (popredir() also cleans up the mess in case of failures)
5175 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176 if (i == -1) {
5177 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005178 if (i != EBADF) {
5179 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005180 if (newfd >= 0)
5181 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005182 errno = i;
5183 ash_msg_and_raise_error("%d: %m", fd);
5184 /* NOTREACHED */
5185 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005186 /* EBADF: it is not open - good, remember to close it */
5187 remember_to_close:
5188 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005189 } else { /* fd is open, save its copy */
5190 /* "exec fd>&-" should not close fds
5191 * which point to script file(s).
5192 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005193 if (is_hidden_fd(sv, fd))
5194 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005195 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005196 if (fd == 2)
5197 copied_fd2 = i;
5198 sv->two_fd[sv_pos].orig = fd;
5199 sv->two_fd[sv_pos].copy = i;
5200 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005201 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005202 if (newfd < 0) {
5203 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005204 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005205 /* Don't want to trigger debugging */
5206 if (fd != -1)
5207 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005208 } else {
5209 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005210 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005211 } else if (fd != newfd) { /* move newfd to fd */
5212 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005213#if ENABLE_ASH_BASH_COMPAT
5214 if (!(redir->nfile.type == NTO2 && fd == 2))
5215#endif
5216 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005217 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005218#if ENABLE_ASH_BASH_COMPAT
5219 if (redir->nfile.type == NTO2 && fd == 1) {
5220 /* We already redirected it to fd 1, now copy it to 2 */
5221 newfd = 1;
5222 fd = 2;
5223 goto redirect_more;
5224 }
5225#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005226 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005227
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005228 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005229 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5230 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005231}
5232
5233/*
5234 * Undo the effects of the last redirection.
5235 */
5236static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005237popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005238{
5239 struct redirtab *rp;
5240 int i;
5241
Denis Vlasenko01631112007-12-16 17:20:38 +00005242 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005243 return;
5244 INT_OFF;
5245 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005246 for (i = 0; i < rp->pair_count; i++) {
5247 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005248 int copy = rp->two_fd[i].copy;
5249 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005250 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005251 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005252 continue;
5253 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005254 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005255 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005256 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005257 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005258 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005259 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005260 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005261 }
5262 }
5263 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005264 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005265 free(rp);
5266 INT_ON;
5267}
5268
5269/*
5270 * Undo all redirections. Called on error or interrupt.
5271 */
5272
5273/*
5274 * Discard all saved file descriptors.
5275 */
5276static void
5277clearredir(int drop)
5278{
5279 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005280 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005281 if (!redirlist)
5282 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005283 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005284 }
5285}
5286
5287static int
5288redirectsafe(union node *redir, int flags)
5289{
5290 int err;
5291 volatile int saveint;
5292 struct jmploc *volatile savehandler = exception_handler;
5293 struct jmploc jmploc;
5294
5295 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005296 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5297 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005298 if (!err) {
5299 exception_handler = &jmploc;
5300 redirect(redir, flags);
5301 }
5302 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005303 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005304 longjmp(exception_handler->loc, 1);
5305 RESTORE_INT(saveint);
5306 return err;
5307}
5308
5309
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005310/* ============ Routines to expand arguments to commands
5311 *
5312 * We have to deal with backquotes, shell variables, and file metacharacters.
5313 */
5314
Mike Frysinger98c52642009-04-02 10:02:37 +00005315#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005316static arith_t
5317ash_arith(const char *s)
5318{
5319 arith_eval_hooks_t math_hooks;
5320 arith_t result;
5321 int errcode = 0;
5322
5323 math_hooks.lookupvar = lookupvar;
5324 math_hooks.setvar = setvar;
5325 math_hooks.endofname = endofname;
5326
5327 INT_OFF;
5328 result = arith(s, &errcode, &math_hooks);
5329 if (errcode < 0) {
5330 if (errcode == -3)
5331 ash_msg_and_raise_error("exponent less than 0");
5332 if (errcode == -2)
5333 ash_msg_and_raise_error("divide by zero");
5334 if (errcode == -5)
5335 ash_msg_and_raise_error("expression recursion loop detected");
5336 raise_error_syntax(s);
5337 }
5338 INT_ON;
5339
5340 return result;
5341}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005342#endif
5343
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005344/*
5345 * expandarg flags
5346 */
5347#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5348#define EXP_TILDE 0x2 /* do normal tilde expansion */
5349#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5350#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5351#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5352#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5353#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5354#define EXP_WORD 0x80 /* expand word in parameter expansion */
5355#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5356/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005357 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005358 */
5359#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5360#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5361#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5362#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5363#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5364
5365/*
5366 * Structure specifying which parts of the string should be searched
5367 * for IFS characters.
5368 */
5369struct ifsregion {
5370 struct ifsregion *next; /* next region in list */
5371 int begoff; /* offset of start of region */
5372 int endoff; /* offset of end of region */
5373 int nulonly; /* search for nul bytes only */
5374};
5375
5376struct arglist {
5377 struct strlist *list;
5378 struct strlist **lastp;
5379};
5380
5381/* output of current string */
5382static char *expdest;
5383/* list of back quote expressions */
5384static struct nodelist *argbackq;
5385/* first struct in list of ifs regions */
5386static struct ifsregion ifsfirst;
5387/* last struct in list */
5388static struct ifsregion *ifslastp;
5389/* holds expanded arg list */
5390static struct arglist exparg;
5391
5392/*
5393 * Our own itoa().
5394 */
5395static int
5396cvtnum(arith_t num)
5397{
5398 int len;
5399
5400 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005401 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005402 STADJUST(len, expdest);
5403 return len;
5404}
5405
5406static size_t
5407esclen(const char *start, const char *p)
5408{
5409 size_t esc = 0;
5410
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005411 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005412 esc++;
5413 }
5414 return esc;
5415}
5416
5417/*
5418 * Remove any CTLESC characters from a string.
5419 */
5420static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005421rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005422{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005423 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005424
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005425 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005426 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005427 unsigned protect_against_glob;
5428 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005429
5430 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005431 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005432 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005433
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434 q = p;
5435 r = str;
5436 if (flag & RMESCAPE_ALLOC) {
5437 size_t len = p - str;
5438 size_t fulllen = len + strlen(p) + 1;
5439
5440 if (flag & RMESCAPE_GROW) {
5441 r = makestrspace(fulllen, expdest);
5442 } else if (flag & RMESCAPE_HEAP) {
5443 r = ckmalloc(fulllen);
5444 } else {
5445 r = stalloc(fulllen);
5446 }
5447 q = r;
5448 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005449 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005450 }
5451 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005452
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005453 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5454 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005455 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005456 while (*p) {
5457 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005458// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5459// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5460// Note: both inquotes and protect_against_glob only affect whether
5461// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005462 inquotes = ~inquotes;
5463 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005464 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005465 continue;
5466 }
5467 if (*p == '\\') {
5468 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470 goto copy;
5471 }
5472 if (*p == CTLESC) {
5473 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 *q++ = '\\';
5476 }
5477 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005478 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005479 copy:
5480 *q++ = *p++;
5481 }
5482 *q = '\0';
5483 if (flag & RMESCAPE_GROW) {
5484 expdest = r;
5485 STADJUST(q - r + 1, expdest);
5486 }
5487 return r;
5488}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005489#define pmatch(a, b) !fnmatch((a), (b), 0)
5490
5491/*
5492 * Prepare a pattern for a expmeta (internal glob(3)) call.
5493 *
5494 * Returns an stalloced string.
5495 */
5496static char *
5497preglob(const char *pattern, int quoted, int flag)
5498{
5499 flag |= RMESCAPE_GLOB;
5500 if (quoted) {
5501 flag |= RMESCAPE_QUOTED;
5502 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005503 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005504}
5505
5506/*
5507 * Put a string on the stack.
5508 */
5509static void
5510memtodest(const char *p, size_t len, int syntax, int quotes)
5511{
5512 char *q = expdest;
5513
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005514 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005515
5516 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005517 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005518 if (!c)
5519 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005520 if (quotes) {
5521 int n = SIT(c, syntax);
5522 if (n == CCTL || n == CBACK)
5523 USTPUTC(CTLESC, q);
5524 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005525 USTPUTC(c, q);
5526 }
5527
5528 expdest = q;
5529}
5530
5531static void
5532strtodest(const char *p, int syntax, int quotes)
5533{
5534 memtodest(p, strlen(p), syntax, quotes);
5535}
5536
5537/*
5538 * Record the fact that we have to scan this region of the
5539 * string for IFS characters.
5540 */
5541static void
5542recordregion(int start, int end, int nulonly)
5543{
5544 struct ifsregion *ifsp;
5545
5546 if (ifslastp == NULL) {
5547 ifsp = &ifsfirst;
5548 } else {
5549 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005550 ifsp = ckzalloc(sizeof(*ifsp));
5551 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005552 ifslastp->next = ifsp;
5553 INT_ON;
5554 }
5555 ifslastp = ifsp;
5556 ifslastp->begoff = start;
5557 ifslastp->endoff = end;
5558 ifslastp->nulonly = nulonly;
5559}
5560
5561static void
5562removerecordregions(int endoff)
5563{
5564 if (ifslastp == NULL)
5565 return;
5566
5567 if (ifsfirst.endoff > endoff) {
5568 while (ifsfirst.next != NULL) {
5569 struct ifsregion *ifsp;
5570 INT_OFF;
5571 ifsp = ifsfirst.next->next;
5572 free(ifsfirst.next);
5573 ifsfirst.next = ifsp;
5574 INT_ON;
5575 }
5576 if (ifsfirst.begoff > endoff)
5577 ifslastp = NULL;
5578 else {
5579 ifslastp = &ifsfirst;
5580 ifsfirst.endoff = endoff;
5581 }
5582 return;
5583 }
5584
5585 ifslastp = &ifsfirst;
5586 while (ifslastp->next && ifslastp->next->begoff < endoff)
5587 ifslastp=ifslastp->next;
5588 while (ifslastp->next != NULL) {
5589 struct ifsregion *ifsp;
5590 INT_OFF;
5591 ifsp = ifslastp->next->next;
5592 free(ifslastp->next);
5593 ifslastp->next = ifsp;
5594 INT_ON;
5595 }
5596 if (ifslastp->endoff > endoff)
5597 ifslastp->endoff = endoff;
5598}
5599
5600static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005601exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005602{
5603 char c;
5604 char *name;
5605 struct passwd *pw;
5606 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005607 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005608 int startloc;
5609
5610 name = p + 1;
5611
5612 while ((c = *++p) != '\0') {
5613 switch (c) {
5614 case CTLESC:
5615 return startp;
5616 case CTLQUOTEMARK:
5617 return startp;
5618 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005619 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005620 goto done;
5621 break;
5622 case '/':
5623 case CTLENDVAR:
5624 goto done;
5625 }
5626 }
5627 done:
5628 *p = '\0';
5629 if (*name == '\0') {
5630 home = lookupvar(homestr);
5631 } else {
5632 pw = getpwnam(name);
5633 if (pw == NULL)
5634 goto lose;
5635 home = pw->pw_dir;
5636 }
5637 if (!home || !*home)
5638 goto lose;
5639 *p = c;
5640 startloc = expdest - (char *)stackblock();
5641 strtodest(home, SQSYNTAX, quotes);
5642 recordregion(startloc, expdest - (char *)stackblock(), 0);
5643 return p;
5644 lose:
5645 *p = c;
5646 return startp;
5647}
5648
5649/*
5650 * Execute a command inside back quotes. If it's a builtin command, we
5651 * want to save its output in a block obtained from malloc. Otherwise
5652 * we fork off a subprocess and get the output of the command via a pipe.
5653 * Should be called with interrupts off.
5654 */
5655struct backcmd { /* result of evalbackcmd */
5656 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005657 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005658 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005659 struct job *jp; /* job structure for command */
5660};
5661
5662/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005663static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005665static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005666
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005667static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005668evalbackcmd(union node *n, struct backcmd *result)
5669{
5670 int saveherefd;
5671
5672 result->fd = -1;
5673 result->buf = NULL;
5674 result->nleft = 0;
5675 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005676 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005677 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678
5679 saveherefd = herefd;
5680 herefd = -1;
5681
5682 {
5683 int pip[2];
5684 struct job *jp;
5685
5686 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005687 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005688 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005689 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5690 FORCE_INT_ON;
5691 close(pip[0]);
5692 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005693 /*close(1);*/
5694 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005695 close(pip[1]);
5696 }
5697 eflag = 0;
5698 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5699 /* NOTREACHED */
5700 }
5701 close(pip[1]);
5702 result->fd = pip[0];
5703 result->jp = jp;
5704 }
5705 herefd = saveherefd;
5706 out:
5707 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5708 result->fd, result->buf, result->nleft, result->jp));
5709}
5710
5711/*
5712 * Expand stuff in backwards quotes.
5713 */
5714static void
5715expbackq(union node *cmd, int quoted, int quotes)
5716{
5717 struct backcmd in;
5718 int i;
5719 char buf[128];
5720 char *p;
5721 char *dest;
5722 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005723 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005724 struct stackmark smark;
5725
5726 INT_OFF;
5727 setstackmark(&smark);
5728 dest = expdest;
5729 startloc = dest - (char *)stackblock();
5730 grabstackstr(dest);
5731 evalbackcmd(cmd, &in);
5732 popstackmark(&smark);
5733
5734 p = in.buf;
5735 i = in.nleft;
5736 if (i == 0)
5737 goto read;
5738 for (;;) {
5739 memtodest(p, i, syntax, quotes);
5740 read:
5741 if (in.fd < 0)
5742 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005743 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005744 TRACE(("expbackq: read returns %d\n", i));
5745 if (i <= 0)
5746 break;
5747 p = buf;
5748 }
5749
Denis Vlasenko60818682007-09-28 22:07:23 +00005750 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005751 if (in.fd >= 0) {
5752 close(in.fd);
5753 back_exitstatus = waitforjob(in.jp);
5754 }
5755 INT_ON;
5756
5757 /* Eat all trailing newlines */
5758 dest = expdest;
5759 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5760 STUNPUTC(dest);
5761 expdest = dest;
5762
5763 if (quoted == 0)
5764 recordregion(startloc, dest - (char *)stackblock(), 0);
5765 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5766 (dest - (char *)stackblock()) - startloc,
5767 (dest - (char *)stackblock()) - startloc,
5768 stackblock() + startloc));
5769}
5770
Mike Frysinger98c52642009-04-02 10:02:37 +00005771#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005772/*
5773 * Expand arithmetic expression. Backup to start of expression,
5774 * evaluate, place result in (backed up) result, adjust string position.
5775 */
5776static void
5777expari(int quotes)
5778{
5779 char *p, *start;
5780 int begoff;
5781 int flag;
5782 int len;
5783
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005784 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005785
5786 /*
5787 * This routine is slightly over-complicated for
5788 * efficiency. Next we scan backwards looking for the
5789 * start of arithmetic.
5790 */
5791 start = stackblock();
5792 p = expdest - 1;
5793 *p = '\0';
5794 p--;
5795 do {
5796 int esc;
5797
5798 while (*p != CTLARI) {
5799 p--;
5800#if DEBUG
5801 if (p < start) {
5802 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5803 }
5804#endif
5805 }
5806
5807 esc = esclen(start, p);
5808 if (!(esc % 2)) {
5809 break;
5810 }
5811
5812 p -= esc + 1;
5813 } while (1);
5814
5815 begoff = p - start;
5816
5817 removerecordregions(begoff);
5818
5819 flag = p[1];
5820
5821 expdest = p;
5822
5823 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005824 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005825
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005826 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005827
5828 if (flag != '"')
5829 recordregion(begoff, begoff + len, 0);
5830}
5831#endif
5832
5833/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005834static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005835
5836/*
5837 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5838 * characters to allow for further processing. Otherwise treat
5839 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005840 *
5841 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5842 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5843 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005844 */
5845static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005846argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005848 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849 '=',
5850 ':',
5851 CTLQUOTEMARK,
5852 CTLENDVAR,
5853 CTLESC,
5854 CTLVAR,
5855 CTLBACKQ,
5856 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005857#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858 CTLENDARI,
5859#endif
5860 0
5861 };
5862 const char *reject = spclchars;
5863 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005864 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5865 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 int inquotes;
5867 size_t length;
5868 int startloc;
5869
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005870 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005871 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005872 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005873 reject++;
5874 }
5875 inquotes = 0;
5876 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005877 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 char *q;
5879
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 tilde:
5882 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005883 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005884 q++;
5885 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005886 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005887 }
5888 start:
5889 startloc = expdest - (char *)stackblock();
5890 for (;;) {
5891 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005892 c = (unsigned char) p[length];
5893 if (c) {
5894 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005895#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005896 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005898 ) {
5899 /* c == '=' || c == ':' || c == CTLENDARI */
5900 length++;
5901 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005902 }
5903 if (length > 0) {
5904 int newloc;
5905 expdest = stack_nputstr(p, length, expdest);
5906 newloc = expdest - (char *)stackblock();
5907 if (breakall && !inquotes && newloc > startloc) {
5908 recordregion(startloc, newloc, 0);
5909 }
5910 startloc = newloc;
5911 }
5912 p += length + 1;
5913 length = 0;
5914
5915 switch (c) {
5916 case '\0':
5917 goto breakloop;
5918 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005919 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005920 p--;
5921 continue;
5922 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005923 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005924 reject++;
5925 /* fall through */
5926 case ':':
5927 /*
5928 * sort of a hack - expand tildes in variable
5929 * assignments (after the first '=' and after ':'s).
5930 */
5931 if (*--p == '~') {
5932 goto tilde;
5933 }
5934 continue;
5935 }
5936
5937 switch (c) {
5938 case CTLENDVAR: /* ??? */
5939 goto breakloop;
5940 case CTLQUOTEMARK:
5941 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005942 if (!inquotes
5943 && memcmp(p, dolatstr, 4) == 0
5944 && ( p[4] == CTLQUOTEMARK
5945 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5946 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005947 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005948 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005949 goto start;
5950 }
5951 inquotes = !inquotes;
5952 addquote:
5953 if (quotes) {
5954 p--;
5955 length++;
5956 startloc++;
5957 }
5958 break;
5959 case CTLESC:
5960 startloc++;
5961 length++;
5962 goto addquote;
5963 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005964 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005965 goto start;
5966 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005967 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005968 case CTLBACKQ|CTLQUOTE:
5969 expbackq(argbackq->n, c, quotes);
5970 argbackq = argbackq->next;
5971 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005972#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 case CTLENDARI:
5974 p--;
5975 expari(quotes);
5976 goto start;
5977#endif
5978 }
5979 }
5980 breakloop:
5981 ;
5982}
5983
5984static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005985scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005986 int zero)
5987{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005988// This commented out code was added by James Simmons <jsimmons@infradead.org>
5989// as part of a larger change when he added support for ${var/a/b}.
5990// However, it broke # and % operators:
5991//
5992//var=ababcdcd
5993// ok bad
5994//echo ${var#ab} abcdcd abcdcd
5995//echo ${var##ab} abcdcd abcdcd
5996//echo ${var#a*b} abcdcd ababcdcd (!)
5997//echo ${var##a*b} cdcd cdcd
5998//echo ${var#?} babcdcd ababcdcd (!)
5999//echo ${var##?} babcdcd babcdcd
6000//echo ${var#*} ababcdcd babcdcd (!)
6001//echo ${var##*}
6002//echo ${var%cd} ababcd ababcd
6003//echo ${var%%cd} ababcd abab (!)
6004//echo ${var%c*d} ababcd ababcd
6005//echo ${var%%c*d} abab ababcdcd (!)
6006//echo ${var%?} ababcdc ababcdc
6007//echo ${var%%?} ababcdc ababcdcd (!)
6008//echo ${var%*} ababcdcd ababcdcd
6009//echo ${var%%*}
6010//
6011// Commenting it back out helped. Remove it completely if it really
6012// is not needed.
6013
6014 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006015 char c;
6016
6017 loc = startp;
6018 loc2 = rmesc;
6019 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006020 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006021 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006022
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006023 c = *loc2;
6024 if (zero) {
6025 *loc2 = '\0';
6026 s = rmesc;
6027 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006028 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006029
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006030// // chop off end if its '*'
6031// full = strrchr(str, '*');
6032// if (full && full != str)
6033// match--;
6034//
6035// // If str starts with '*' replace with s.
6036// if ((*str == '*') && strlen(s) >= match) {
6037// full = xstrdup(s);
6038// strncpy(full+strlen(s)-match+1, str+1, match-1);
6039// } else
6040// full = xstrndup(str, match);
6041// match = strncmp(s, full, strlen(full));
6042// free(full);
6043//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006044 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006045 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006046 return loc;
6047 if (quotes && *loc == CTLESC)
6048 loc++;
6049 loc++;
6050 loc2++;
6051 } while (c);
6052 return 0;
6053}
6054
6055static char *
6056scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6057 int zero)
6058{
6059 int esc = 0;
6060 char *loc;
6061 char *loc2;
6062
6063 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6064 int match;
6065 char c = *loc2;
6066 const char *s = loc2;
6067 if (zero) {
6068 *loc2 = '\0';
6069 s = rmesc;
6070 }
6071 match = pmatch(str, s);
6072 *loc2 = c;
6073 if (match)
6074 return loc;
6075 loc--;
6076 if (quotes) {
6077 if (--esc < 0) {
6078 esc = esclen(startp, loc);
6079 }
6080 if (esc % 2) {
6081 esc--;
6082 loc--;
6083 }
6084 }
6085 }
6086 return 0;
6087}
6088
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006089static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006090static void
6091varunset(const char *end, const char *var, const char *umsg, int varflags)
6092{
6093 const char *msg;
6094 const char *tail;
6095
6096 tail = nullstr;
6097 msg = "parameter not set";
6098 if (umsg) {
6099 if (*end == CTLENDVAR) {
6100 if (varflags & VSNUL)
6101 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006102 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006103 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006104 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006105 }
6106 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6107}
6108
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006109#if ENABLE_ASH_BASH_COMPAT
6110static char *
6111parse_sub_pattern(char *arg, int inquotes)
6112{
6113 char *idx, *repl = NULL;
6114 unsigned char c;
6115
Denis Vlasenko2659c632008-06-14 06:04:59 +00006116 idx = arg;
6117 while (1) {
6118 c = *arg;
6119 if (!c)
6120 break;
6121 if (c == '/') {
6122 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006123 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006124 repl = idx + 1;
6125 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006126 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006127 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006128 *idx++ = c;
6129 if (!inquotes && c == '\\' && arg[1] == '\\')
6130 arg++; /* skip both \\, not just first one */
6131 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006132 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006133 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006134
6135 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006136}
6137#endif /* ENABLE_ASH_BASH_COMPAT */
6138
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006139static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006140subevalvar(char *p, char *str, int strloc, int subtype,
6141 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006142{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006143 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006144 char *startp;
6145 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006146 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006147 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6148 IF_ASH_BASH_COMPAT(char null = '\0';)
6149 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006150 int saveherefd = herefd;
6151 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006152 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006153 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006154
6155 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006156 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6157 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006158 STPUTC('\0', expdest);
6159 herefd = saveherefd;
6160 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006161 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006162
6163 switch (subtype) {
6164 case VSASSIGN:
6165 setvar(str, startp, 0);
6166 amount = startp - expdest;
6167 STADJUST(amount, expdest);
6168 return startp;
6169
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006170#if ENABLE_ASH_BASH_COMPAT
6171 case VSSUBSTR:
6172 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006173 /* Read POS in ${var:POS:LEN} */
6174 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175 len = str - startp - 1;
6176
6177 /* *loc != '\0', guaranteed by parser */
6178 if (quotes) {
6179 char *ptr;
6180
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006181 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006182 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006183 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184 len--;
6185 ptr++;
6186 }
6187 }
6188 }
6189 orig_len = len;
6190
6191 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006192 /* ${var::LEN} */
6193 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006194 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006195 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006196 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006197 while (*loc && *loc != ':') {
6198 /* TODO?
6199 * bash complains on: var=qwe; echo ${var:1a:123}
6200 if (!isdigit(*loc))
6201 ash_msg_and_raise_error(msg_illnum, str);
6202 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006203 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006204 }
6205 if (*loc++ == ':') {
6206 len = number(loc);
6207 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 }
6209 if (pos >= orig_len) {
6210 pos = 0;
6211 len = 0;
6212 }
6213 if (len > (orig_len - pos))
6214 len = orig_len - pos;
6215
6216 for (str = startp; pos; str++, pos--) {
6217 if (quotes && *str == CTLESC)
6218 str++;
6219 }
6220 for (loc = startp; len; len--) {
6221 if (quotes && *str == CTLESC)
6222 *loc++ = *str++;
6223 *loc++ = *str++;
6224 }
6225 *loc = '\0';
6226 amount = loc - expdest;
6227 STADJUST(amount, expdest);
6228 return loc;
6229#endif
6230
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006231 case VSQUESTION:
6232 varunset(p, str, startp, varflags);
6233 /* NOTREACHED */
6234 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006235 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006236
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006237 /* We'll comeback here if we grow the stack while handling
6238 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6239 * stack will need rebasing, and we'll need to remove our work
6240 * areas each time
6241 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006242 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006243
6244 amount = expdest - ((char *)stackblock() + resetloc);
6245 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006246 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006247
6248 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006249 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006250 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006251 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006252 if (rmesc != startp) {
6253 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006254 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006255 }
6256 }
6257 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006258 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006259 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006260 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006261
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006262#if ENABLE_ASH_BASH_COMPAT
6263 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6264 char *idx, *end, *restart_detect;
6265
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006266 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006267 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6268 if (!repl)
6269 repl = &null;
6270 }
6271
6272 /* If there's no pattern to match, return the expansion unmolested */
6273 if (*str == '\0')
6274 return 0;
6275
6276 len = 0;
6277 idx = startp;
6278 end = str - 1;
6279 while (idx < end) {
6280 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6281 if (!loc) {
6282 /* No match, advance */
6283 restart_detect = stackblock();
6284 STPUTC(*idx, expdest);
6285 if (quotes && *idx == CTLESC) {
6286 idx++;
6287 len++;
6288 STPUTC(*idx, expdest);
6289 }
6290 if (stackblock() != restart_detect)
6291 goto restart;
6292 idx++;
6293 len++;
6294 rmesc++;
6295 continue;
6296 }
6297
6298 if (subtype == VSREPLACEALL) {
6299 while (idx < loc) {
6300 if (quotes && *idx == CTLESC)
6301 idx++;
6302 idx++;
6303 rmesc++;
6304 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006305 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006306 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006307 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006308
6309 for (loc = repl; *loc; loc++) {
6310 restart_detect = stackblock();
6311 STPUTC(*loc, expdest);
6312 if (stackblock() != restart_detect)
6313 goto restart;
6314 len++;
6315 }
6316
6317 if (subtype == VSREPLACE) {
6318 while (*idx) {
6319 restart_detect = stackblock();
6320 STPUTC(*idx, expdest);
6321 if (stackblock() != restart_detect)
6322 goto restart;
6323 len++;
6324 idx++;
6325 }
6326 break;
6327 }
6328 }
6329
6330 /* We've put the replaced text into a buffer at workloc, now
6331 * move it to the right place and adjust the stack.
6332 */
6333 startp = stackblock() + startloc;
6334 STPUTC('\0', expdest);
6335 memmove(startp, stackblock() + workloc, len);
6336 startp[len++] = '\0';
6337 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6338 STADJUST(-amount, expdest);
6339 return startp;
6340 }
6341#endif /* ENABLE_ASH_BASH_COMPAT */
6342
6343 subtype -= VSTRIMRIGHT;
6344#if DEBUG
6345 if (subtype < 0 || subtype > 7)
6346 abort();
6347#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006348 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6349 zero = subtype >> 1;
6350 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6351 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6352
6353 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6354 if (loc) {
6355 if (zero) {
6356 memmove(startp, loc, str - loc);
6357 loc = startp + (str - loc) - 1;
6358 }
6359 *loc = '\0';
6360 amount = loc - expdest;
6361 STADJUST(amount, expdest);
6362 }
6363 return loc;
6364}
6365
6366/*
6367 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006368 * name parameter (examples):
6369 * ash -c 'echo $1' name:'1='
6370 * ash -c 'echo $qwe' name:'qwe='
6371 * ash -c 'echo $$' name:'$='
6372 * ash -c 'echo ${$}' name:'$='
6373 * ash -c 'echo ${$##q}' name:'$=q'
6374 * ash -c 'echo ${#$}' name:'$='
6375 * note: examples with bad shell syntax:
6376 * ash -c 'echo ${#$1}' name:'$=1'
6377 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006378 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006379static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006380varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006381{
6382 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006383 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006384 int i;
6385 int sep = 0;
6386 int sepq = 0;
6387 ssize_t len = 0;
6388 char **ap;
6389 int syntax;
6390 int quoted = varflags & VSQUOTE;
6391 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006392 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393
6394 if (quoted && (flags & EXP_FULL))
6395 sep = 1 << CHAR_BIT;
6396
6397 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6398 switch (*name) {
6399 case '$':
6400 num = rootpid;
6401 goto numvar;
6402 case '?':
6403 num = exitstatus;
6404 goto numvar;
6405 case '#':
6406 num = shellparam.nparam;
6407 goto numvar;
6408 case '!':
6409 num = backgndpid;
6410 if (num == 0)
6411 return -1;
6412 numvar:
6413 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006414 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006416 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006417 for (i = NOPTS - 1; i >= 0; i--) {
6418 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006419 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006420 len++;
6421 }
6422 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006423 check_1char_name:
6424#if 0
6425 /* handles cases similar to ${#$1} */
6426 if (name[2] != '\0')
6427 raise_error_syntax("bad substitution");
6428#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006429 break;
6430 case '@':
6431 if (sep)
6432 goto param;
6433 /* fall through */
6434 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006435 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006436 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6437 sepq = 1;
6438 param:
6439 ap = shellparam.p;
6440 if (!ap)
6441 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006442 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 size_t partlen;
6444
6445 partlen = strlen(p);
6446 len += partlen;
6447
6448 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6449 memtodest(p, partlen, syntax, quotes);
6450
6451 if (*ap && sep) {
6452 char *q;
6453
6454 len++;
6455 if (subtype == VSPLUS || subtype == VSLENGTH) {
6456 continue;
6457 }
6458 q = expdest;
6459 if (sepq)
6460 STPUTC(CTLESC, q);
6461 STPUTC(sep, q);
6462 expdest = q;
6463 }
6464 }
6465 return len;
6466 case '0':
6467 case '1':
6468 case '2':
6469 case '3':
6470 case '4':
6471 case '5':
6472 case '6':
6473 case '7':
6474 case '8':
6475 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006476 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006477 if (num < 0 || num > shellparam.nparam)
6478 return -1;
6479 p = num ? shellparam.p[num - 1] : arg0;
6480 goto value;
6481 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006482 /* NB: name has form "VAR=..." */
6483
6484 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6485 * which should be considered before we check variables. */
6486 if (var_str_list) {
6487 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6488 p = NULL;
6489 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006490 char *str, *eq;
6491 str = var_str_list->text;
6492 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006493 if (!eq) /* stop at first non-assignment */
6494 break;
6495 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006496 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006497 && strncmp(str, name, name_len) == 0) {
6498 p = eq;
6499 /* goto value; - WRONG! */
6500 /* think "A=1 A=2 B=$A" */
6501 }
6502 var_str_list = var_str_list->next;
6503 } while (var_str_list);
6504 if (p)
6505 goto value;
6506 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006507 p = lookupvar(name);
6508 value:
6509 if (!p)
6510 return -1;
6511
6512 len = strlen(p);
6513 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6514 memtodest(p, len, syntax, quotes);
6515 return len;
6516 }
6517
6518 if (subtype == VSPLUS || subtype == VSLENGTH)
6519 STADJUST(-len, expdest);
6520 return len;
6521}
6522
6523/*
6524 * Expand a variable, and return a pointer to the next character in the
6525 * input string.
6526 */
6527static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006528evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006530 char varflags;
6531 char subtype;
6532 char quoted;
6533 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006534 char *var;
6535 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006536 int startloc;
6537 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006538
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006539 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006540 subtype = varflags & VSTYPE;
6541 quoted = varflags & VSQUOTE;
6542 var = p;
6543 easy = (!quoted || (*var == '@' && shellparam.nparam));
6544 startloc = expdest - (char *)stackblock();
6545 p = strchr(p, '=') + 1;
6546
6547 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006548 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006549 if (varflags & VSNUL)
6550 varlen--;
6551
6552 if (subtype == VSPLUS) {
6553 varlen = -1 - varlen;
6554 goto vsplus;
6555 }
6556
6557 if (subtype == VSMINUS) {
6558 vsplus:
6559 if (varlen < 0) {
6560 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006561 p, flags | EXP_TILDE |
6562 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006563 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006564 );
6565 goto end;
6566 }
6567 if (easy)
6568 goto record;
6569 goto end;
6570 }
6571
6572 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6573 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006574 if (subevalvar(p, var, /* strloc: */ 0,
6575 subtype, startloc, varflags,
6576 /* quotes: */ 0,
6577 var_str_list)
6578 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006579 varflags &= ~VSNUL;
6580 /*
6581 * Remove any recorded regions beyond
6582 * start of variable
6583 */
6584 removerecordregions(startloc);
6585 goto again;
6586 }
6587 goto end;
6588 }
6589 if (easy)
6590 goto record;
6591 goto end;
6592 }
6593
6594 if (varlen < 0 && uflag)
6595 varunset(p, var, 0, 0);
6596
6597 if (subtype == VSLENGTH) {
6598 cvtnum(varlen > 0 ? varlen : 0);
6599 goto record;
6600 }
6601
6602 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006603 if (easy)
6604 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006605 goto end;
6606 }
6607
6608#if DEBUG
6609 switch (subtype) {
6610 case VSTRIMLEFT:
6611 case VSTRIMLEFTMAX:
6612 case VSTRIMRIGHT:
6613 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006614#if ENABLE_ASH_BASH_COMPAT
6615 case VSSUBSTR:
6616 case VSREPLACE:
6617 case VSREPLACEALL:
6618#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006619 break;
6620 default:
6621 abort();
6622 }
6623#endif
6624
6625 if (varlen >= 0) {
6626 /*
6627 * Terminate the string and start recording the pattern
6628 * right after it
6629 */
6630 STPUTC('\0', expdest);
6631 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006632 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6633 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006634//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006635 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006636 var_str_list)
6637 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006638 int amount = expdest - (
6639 (char *)stackblock() + patloc - 1
6640 );
6641 STADJUST(-amount, expdest);
6642 }
6643 /* Remove any recorded regions beyond start of variable */
6644 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006645 record:
6646 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006647 }
6648
6649 end:
6650 if (subtype != VSNORMAL) { /* skip to end of alternative */
6651 int nesting = 1;
6652 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006653 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006654 if (c == CTLESC)
6655 p++;
6656 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6657 if (varlen >= 0)
6658 argbackq = argbackq->next;
6659 } else if (c == CTLVAR) {
6660 if ((*p++ & VSTYPE) != VSNORMAL)
6661 nesting++;
6662 } else if (c == CTLENDVAR) {
6663 if (--nesting == 0)
6664 break;
6665 }
6666 }
6667 }
6668 return p;
6669}
6670
6671/*
6672 * Break the argument string into pieces based upon IFS and add the
6673 * strings to the argument list. The regions of the string to be
6674 * searched for IFS characters have been stored by recordregion.
6675 */
6676static void
6677ifsbreakup(char *string, struct arglist *arglist)
6678{
6679 struct ifsregion *ifsp;
6680 struct strlist *sp;
6681 char *start;
6682 char *p;
6683 char *q;
6684 const char *ifs, *realifs;
6685 int ifsspc;
6686 int nulonly;
6687
6688 start = string;
6689 if (ifslastp != NULL) {
6690 ifsspc = 0;
6691 nulonly = 0;
6692 realifs = ifsset() ? ifsval() : defifs;
6693 ifsp = &ifsfirst;
6694 do {
6695 p = string + ifsp->begoff;
6696 nulonly = ifsp->nulonly;
6697 ifs = nulonly ? nullstr : realifs;
6698 ifsspc = 0;
6699 while (p < string + ifsp->endoff) {
6700 q = p;
6701 if (*p == CTLESC)
6702 p++;
6703 if (!strchr(ifs, *p)) {
6704 p++;
6705 continue;
6706 }
6707 if (!nulonly)
6708 ifsspc = (strchr(defifs, *p) != NULL);
6709 /* Ignore IFS whitespace at start */
6710 if (q == start && ifsspc) {
6711 p++;
6712 start = p;
6713 continue;
6714 }
6715 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006716 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006717 sp->text = start;
6718 *arglist->lastp = sp;
6719 arglist->lastp = &sp->next;
6720 p++;
6721 if (!nulonly) {
6722 for (;;) {
6723 if (p >= string + ifsp->endoff) {
6724 break;
6725 }
6726 q = p;
6727 if (*p == CTLESC)
6728 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006729 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006730 p = q;
6731 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006732 }
6733 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006734 if (ifsspc) {
6735 p++;
6736 ifsspc = 0;
6737 } else {
6738 p = q;
6739 break;
6740 }
6741 } else
6742 p++;
6743 }
6744 }
6745 start = p;
6746 } /* while */
6747 ifsp = ifsp->next;
6748 } while (ifsp != NULL);
6749 if (nulonly)
6750 goto add;
6751 }
6752
6753 if (!*start)
6754 return;
6755
6756 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006757 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006758 sp->text = start;
6759 *arglist->lastp = sp;
6760 arglist->lastp = &sp->next;
6761}
6762
6763static void
6764ifsfree(void)
6765{
6766 struct ifsregion *p;
6767
6768 INT_OFF;
6769 p = ifsfirst.next;
6770 do {
6771 struct ifsregion *ifsp;
6772 ifsp = p->next;
6773 free(p);
6774 p = ifsp;
6775 } while (p);
6776 ifslastp = NULL;
6777 ifsfirst.next = NULL;
6778 INT_ON;
6779}
6780
6781/*
6782 * Add a file name to the list.
6783 */
6784static void
6785addfname(const char *name)
6786{
6787 struct strlist *sp;
6788
Denis Vlasenko597906c2008-02-20 16:38:54 +00006789 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006790 sp->text = ststrdup(name);
6791 *exparg.lastp = sp;
6792 exparg.lastp = &sp->next;
6793}
6794
6795static char *expdir;
6796
6797/*
6798 * Do metacharacter (i.e. *, ?, [...]) expansion.
6799 */
6800static void
6801expmeta(char *enddir, char *name)
6802{
6803 char *p;
6804 const char *cp;
6805 char *start;
6806 char *endname;
6807 int metaflag;
6808 struct stat statb;
6809 DIR *dirp;
6810 struct dirent *dp;
6811 int atend;
6812 int matchdot;
6813
6814 metaflag = 0;
6815 start = name;
6816 for (p = name; *p; p++) {
6817 if (*p == '*' || *p == '?')
6818 metaflag = 1;
6819 else if (*p == '[') {
6820 char *q = p + 1;
6821 if (*q == '!')
6822 q++;
6823 for (;;) {
6824 if (*q == '\\')
6825 q++;
6826 if (*q == '/' || *q == '\0')
6827 break;
6828 if (*++q == ']') {
6829 metaflag = 1;
6830 break;
6831 }
6832 }
6833 } else if (*p == '\\')
6834 p++;
6835 else if (*p == '/') {
6836 if (metaflag)
6837 goto out;
6838 start = p + 1;
6839 }
6840 }
6841 out:
6842 if (metaflag == 0) { /* we've reached the end of the file name */
6843 if (enddir != expdir)
6844 metaflag++;
6845 p = name;
6846 do {
6847 if (*p == '\\')
6848 p++;
6849 *enddir++ = *p;
6850 } while (*p++);
6851 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6852 addfname(expdir);
6853 return;
6854 }
6855 endname = p;
6856 if (name < start) {
6857 p = name;
6858 do {
6859 if (*p == '\\')
6860 p++;
6861 *enddir++ = *p++;
6862 } while (p < start);
6863 }
6864 if (enddir == expdir) {
6865 cp = ".";
6866 } else if (enddir == expdir + 1 && *expdir == '/') {
6867 cp = "/";
6868 } else {
6869 cp = expdir;
6870 enddir[-1] = '\0';
6871 }
6872 dirp = opendir(cp);
6873 if (dirp == NULL)
6874 return;
6875 if (enddir != expdir)
6876 enddir[-1] = '/';
6877 if (*endname == 0) {
6878 atend = 1;
6879 } else {
6880 atend = 0;
6881 *endname++ = '\0';
6882 }
6883 matchdot = 0;
6884 p = start;
6885 if (*p == '\\')
6886 p++;
6887 if (*p == '.')
6888 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006889 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006890 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006891 continue;
6892 if (pmatch(start, dp->d_name)) {
6893 if (atend) {
6894 strcpy(enddir, dp->d_name);
6895 addfname(expdir);
6896 } else {
6897 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6898 continue;
6899 p[-1] = '/';
6900 expmeta(p, endname);
6901 }
6902 }
6903 }
6904 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006905 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006906 endname[-1] = '/';
6907}
6908
6909static struct strlist *
6910msort(struct strlist *list, int len)
6911{
6912 struct strlist *p, *q = NULL;
6913 struct strlist **lpp;
6914 int half;
6915 int n;
6916
6917 if (len <= 1)
6918 return list;
6919 half = len >> 1;
6920 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006921 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006922 q = p;
6923 p = p->next;
6924 }
6925 q->next = NULL; /* terminate first half of list */
6926 q = msort(list, half); /* sort first half of list */
6927 p = msort(p, len - half); /* sort second half */
6928 lpp = &list;
6929 for (;;) {
6930#if ENABLE_LOCALE_SUPPORT
6931 if (strcoll(p->text, q->text) < 0)
6932#else
6933 if (strcmp(p->text, q->text) < 0)
6934#endif
6935 {
6936 *lpp = p;
6937 lpp = &p->next;
6938 p = *lpp;
6939 if (p == NULL) {
6940 *lpp = q;
6941 break;
6942 }
6943 } else {
6944 *lpp = q;
6945 lpp = &q->next;
6946 q = *lpp;
6947 if (q == NULL) {
6948 *lpp = p;
6949 break;
6950 }
6951 }
6952 }
6953 return list;
6954}
6955
6956/*
6957 * Sort the results of file name expansion. It calculates the number of
6958 * strings to sort and then calls msort (short for merge sort) to do the
6959 * work.
6960 */
6961static struct strlist *
6962expsort(struct strlist *str)
6963{
6964 int len;
6965 struct strlist *sp;
6966
6967 len = 0;
6968 for (sp = str; sp; sp = sp->next)
6969 len++;
6970 return msort(str, len);
6971}
6972
6973static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006974expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006975{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006976 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006977 '*', '?', '[', 0
6978 };
6979 /* TODO - EXP_REDIR */
6980
6981 while (str) {
6982 struct strlist **savelastp;
6983 struct strlist *sp;
6984 char *p;
6985
6986 if (fflag)
6987 goto nometa;
6988 if (!strpbrk(str->text, metachars))
6989 goto nometa;
6990 savelastp = exparg.lastp;
6991
6992 INT_OFF;
6993 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6994 {
6995 int i = strlen(str->text);
6996 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6997 }
6998
6999 expmeta(expdir, p);
7000 free(expdir);
7001 if (p != str->text)
7002 free(p);
7003 INT_ON;
7004 if (exparg.lastp == savelastp) {
7005 /*
7006 * no matches
7007 */
7008 nometa:
7009 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007010 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007011 exparg.lastp = &str->next;
7012 } else {
7013 *exparg.lastp = NULL;
7014 *savelastp = sp = expsort(*savelastp);
7015 while (sp->next != NULL)
7016 sp = sp->next;
7017 exparg.lastp = &sp->next;
7018 }
7019 str = str->next;
7020 }
7021}
7022
7023/*
7024 * Perform variable substitution and command substitution on an argument,
7025 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7026 * perform splitting and file name expansion. When arglist is NULL, perform
7027 * here document expansion.
7028 */
7029static void
7030expandarg(union node *arg, struct arglist *arglist, int flag)
7031{
7032 struct strlist *sp;
7033 char *p;
7034
7035 argbackq = arg->narg.backquote;
7036 STARTSTACKSTR(expdest);
7037 ifsfirst.next = NULL;
7038 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007039 argstr(arg->narg.text, flag,
7040 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007041 p = _STPUTC('\0', expdest);
7042 expdest = p - 1;
7043 if (arglist == NULL) {
7044 return; /* here document expanded */
7045 }
7046 p = grabstackstr(p);
7047 exparg.lastp = &exparg.list;
7048 /*
7049 * TODO - EXP_REDIR
7050 */
7051 if (flag & EXP_FULL) {
7052 ifsbreakup(p, &exparg);
7053 *exparg.lastp = NULL;
7054 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007055 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007056 } else {
7057 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007058 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007059 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007060 sp->text = p;
7061 *exparg.lastp = sp;
7062 exparg.lastp = &sp->next;
7063 }
7064 if (ifsfirst.next)
7065 ifsfree();
7066 *exparg.lastp = NULL;
7067 if (exparg.list) {
7068 *arglist->lastp = exparg.list;
7069 arglist->lastp = exparg.lastp;
7070 }
7071}
7072
7073/*
7074 * Expand shell variables and backquotes inside a here document.
7075 */
7076static void
7077expandhere(union node *arg, int fd)
7078{
7079 herefd = fd;
7080 expandarg(arg, (struct arglist *)NULL, 0);
7081 full_write(fd, stackblock(), expdest - (char *)stackblock());
7082}
7083
7084/*
7085 * Returns true if the pattern matches the string.
7086 */
7087static int
7088patmatch(char *pattern, const char *string)
7089{
7090 return pmatch(preglob(pattern, 0, 0), string);
7091}
7092
7093/*
7094 * See if a pattern matches in a case statement.
7095 */
7096static int
7097casematch(union node *pattern, char *val)
7098{
7099 struct stackmark smark;
7100 int result;
7101
7102 setstackmark(&smark);
7103 argbackq = pattern->narg.backquote;
7104 STARTSTACKSTR(expdest);
7105 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007106 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7107 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007108 STACKSTRNUL(expdest);
7109 result = patmatch(stackblock(), val);
7110 popstackmark(&smark);
7111 return result;
7112}
7113
7114
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007115/* ============ find_command */
7116
7117struct builtincmd {
7118 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007119 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007120 /* unsigned flags; */
7121};
7122#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007123/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007124 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007126#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007127
7128struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007129 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007130 union param {
7131 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007132 /* index >= 0 for commands without path (slashes) */
7133 /* (TODO: what exactly does the value mean? PATH position?) */
7134 /* index == -1 for commands with slashes */
7135 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007136 const struct builtincmd *cmd;
7137 struct funcnode *func;
7138 } u;
7139};
7140/* values of cmdtype */
7141#define CMDUNKNOWN -1 /* no entry in table for command */
7142#define CMDNORMAL 0 /* command is an executable program */
7143#define CMDFUNCTION 1 /* command is a shell function */
7144#define CMDBUILTIN 2 /* command is a shell builtin */
7145
7146/* action to find_command() */
7147#define DO_ERR 0x01 /* prints errors */
7148#define DO_ABS 0x02 /* checks absolute paths */
7149#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7150#define DO_ALTPATH 0x08 /* using alternate path */
7151#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7152
7153static void find_command(char *, struct cmdentry *, int, const char *);
7154
7155
7156/* ============ Hashing commands */
7157
7158/*
7159 * When commands are first encountered, they are entered in a hash table.
7160 * This ensures that a full path search will not have to be done for them
7161 * on each invocation.
7162 *
7163 * We should investigate converting to a linear search, even though that
7164 * would make the command name "hash" a misnomer.
7165 */
7166
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007167struct tblentry {
7168 struct tblentry *next; /* next entry in hash chain */
7169 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007170 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007172 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007173};
7174
Denis Vlasenko01631112007-12-16 17:20:38 +00007175static struct tblentry **cmdtable;
7176#define INIT_G_cmdtable() do { \
7177 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7178} while (0)
7179
7180static int builtinloc = -1; /* index in path of %builtin, or -1 */
7181
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007182
7183static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007184tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185{
7186 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007188#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007189 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007190 if (APPLET_IS_NOEXEC(applet_no)) {
7191 while (*envp)
7192 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007193 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007194 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007195 /* re-exec ourselves with the new arguments */
7196 execve(bb_busybox_exec_path, argv, envp);
7197 /* If they called chroot or otherwise made the binary no longer
7198 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007199 }
7200#endif
7201
7202 repeat:
7203#ifdef SYSV
7204 do {
7205 execve(cmd, argv, envp);
7206 } while (errno == EINTR);
7207#else
7208 execve(cmd, argv, envp);
7209#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007210 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007211 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007212 return;
7213 }
7214 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007215 char **ap;
7216 char **new;
7217
7218 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007219 continue;
7220 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007221 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007222 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007223 ap += 2;
7224 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007225 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007226 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007227 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007228 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007229 goto repeat;
7230 }
7231}
7232
7233/*
7234 * Exec a program. Never returns. If you change this routine, you may
7235 * have to change the find_command routine as well.
7236 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007237static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007238static void
7239shellexec(char **argv, const char *path, int idx)
7240{
7241 char *cmdname;
7242 int e;
7243 char **envp;
7244 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007245#if ENABLE_FEATURE_SH_STANDALONE
7246 int applet_no = -1;
7247#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007248
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007249 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007250 envp = listvars(VEXPORT, VUNSET, 0);
7251 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007252#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007253 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007254#endif
7255 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007256 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007257 e = errno;
7258 } else {
7259 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007260 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007261 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007262 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007263 if (errno != ENOENT && errno != ENOTDIR)
7264 e = errno;
7265 }
7266 stunalloc(cmdname);
7267 }
7268 }
7269
7270 /* Map to POSIX errors */
7271 switch (e) {
7272 case EACCES:
7273 exerrno = 126;
7274 break;
7275 case ENOENT:
7276 exerrno = 127;
7277 break;
7278 default:
7279 exerrno = 2;
7280 break;
7281 }
7282 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007283 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7284 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007285 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7286 /* NOTREACHED */
7287}
7288
7289static void
7290printentry(struct tblentry *cmdp)
7291{
7292 int idx;
7293 const char *path;
7294 char *name;
7295
7296 idx = cmdp->param.index;
7297 path = pathval();
7298 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007299 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007300 stunalloc(name);
7301 } while (--idx >= 0);
7302 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7303}
7304
7305/*
7306 * Clear out command entries. The argument specifies the first entry in
7307 * PATH which has changed.
7308 */
7309static void
7310clearcmdentry(int firstchange)
7311{
7312 struct tblentry **tblp;
7313 struct tblentry **pp;
7314 struct tblentry *cmdp;
7315
7316 INT_OFF;
7317 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7318 pp = tblp;
7319 while ((cmdp = *pp) != NULL) {
7320 if ((cmdp->cmdtype == CMDNORMAL &&
7321 cmdp->param.index >= firstchange)
7322 || (cmdp->cmdtype == CMDBUILTIN &&
7323 builtinloc >= firstchange)
7324 ) {
7325 *pp = cmdp->next;
7326 free(cmdp);
7327 } else {
7328 pp = &cmdp->next;
7329 }
7330 }
7331 }
7332 INT_ON;
7333}
7334
7335/*
7336 * Locate a command in the command hash table. If "add" is nonzero,
7337 * add the command to the table if it is not already present. The
7338 * variable "lastcmdentry" is set to point to the address of the link
7339 * pointing to the entry, so that delete_cmd_entry can delete the
7340 * entry.
7341 *
7342 * Interrupts must be off if called with add != 0.
7343 */
7344static struct tblentry **lastcmdentry;
7345
7346static struct tblentry *
7347cmdlookup(const char *name, int add)
7348{
7349 unsigned int hashval;
7350 const char *p;
7351 struct tblentry *cmdp;
7352 struct tblentry **pp;
7353
7354 p = name;
7355 hashval = (unsigned char)*p << 4;
7356 while (*p)
7357 hashval += (unsigned char)*p++;
7358 hashval &= 0x7FFF;
7359 pp = &cmdtable[hashval % CMDTABLESIZE];
7360 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7361 if (strcmp(cmdp->cmdname, name) == 0)
7362 break;
7363 pp = &cmdp->next;
7364 }
7365 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007366 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7367 + strlen(name)
7368 /* + 1 - already done because
7369 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007370 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007371 cmdp->cmdtype = CMDUNKNOWN;
7372 strcpy(cmdp->cmdname, name);
7373 }
7374 lastcmdentry = pp;
7375 return cmdp;
7376}
7377
7378/*
7379 * Delete the command entry returned on the last lookup.
7380 */
7381static void
7382delete_cmd_entry(void)
7383{
7384 struct tblentry *cmdp;
7385
7386 INT_OFF;
7387 cmdp = *lastcmdentry;
7388 *lastcmdentry = cmdp->next;
7389 if (cmdp->cmdtype == CMDFUNCTION)
7390 freefunc(cmdp->param.func);
7391 free(cmdp);
7392 INT_ON;
7393}
7394
7395/*
7396 * Add a new command entry, replacing any existing command entry for
7397 * the same name - except special builtins.
7398 */
7399static void
7400addcmdentry(char *name, struct cmdentry *entry)
7401{
7402 struct tblentry *cmdp;
7403
7404 cmdp = cmdlookup(name, 1);
7405 if (cmdp->cmdtype == CMDFUNCTION) {
7406 freefunc(cmdp->param.func);
7407 }
7408 cmdp->cmdtype = entry->cmdtype;
7409 cmdp->param = entry->u;
7410 cmdp->rehash = 0;
7411}
7412
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007413static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007414hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007415{
7416 struct tblentry **pp;
7417 struct tblentry *cmdp;
7418 int c;
7419 struct cmdentry entry;
7420 char *name;
7421
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007422 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007423 clearcmdentry(0);
7424 return 0;
7425 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007426
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007427 if (*argptr == NULL) {
7428 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7429 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7430 if (cmdp->cmdtype == CMDNORMAL)
7431 printentry(cmdp);
7432 }
7433 }
7434 return 0;
7435 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007436
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007437 c = 0;
7438 while ((name = *argptr) != NULL) {
7439 cmdp = cmdlookup(name, 0);
7440 if (cmdp != NULL
7441 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007442 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7443 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007444 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007445 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007446 find_command(name, &entry, DO_ERR, pathval());
7447 if (entry.cmdtype == CMDUNKNOWN)
7448 c = 1;
7449 argptr++;
7450 }
7451 return c;
7452}
7453
7454/*
7455 * Called when a cd is done. Marks all commands so the next time they
7456 * are executed they will be rehashed.
7457 */
7458static void
7459hashcd(void)
7460{
7461 struct tblentry **pp;
7462 struct tblentry *cmdp;
7463
7464 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7465 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007466 if (cmdp->cmdtype == CMDNORMAL
7467 || (cmdp->cmdtype == CMDBUILTIN
7468 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7469 && builtinloc > 0)
7470 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007471 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007472 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007473 }
7474 }
7475}
7476
7477/*
7478 * Fix command hash table when PATH changed.
7479 * Called before PATH is changed. The argument is the new value of PATH;
7480 * pathval() still returns the old value at this point.
7481 * Called with interrupts off.
7482 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007483static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007484changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007485{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007486 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007487 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007488 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007489 int idx_bltin;
7490
7491 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007492 firstchange = 9999; /* assume no change */
7493 idx = 0;
7494 idx_bltin = -1;
7495 for (;;) {
7496 if (*old != *new) {
7497 firstchange = idx;
7498 if ((*old == '\0' && *new == ':')
7499 || (*old == ':' && *new == '\0'))
7500 firstchange++;
7501 old = new; /* ignore subsequent differences */
7502 }
7503 if (*new == '\0')
7504 break;
7505 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7506 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007507 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007508 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007509 new++, old++;
7510 }
7511 if (builtinloc < 0 && idx_bltin >= 0)
7512 builtinloc = idx_bltin; /* zap builtins */
7513 if (builtinloc >= 0 && idx_bltin < 0)
7514 firstchange = 0;
7515 clearcmdentry(firstchange);
7516 builtinloc = idx_bltin;
7517}
7518
7519#define TEOF 0
7520#define TNL 1
7521#define TREDIR 2
7522#define TWORD 3
7523#define TSEMI 4
7524#define TBACKGND 5
7525#define TAND 6
7526#define TOR 7
7527#define TPIPE 8
7528#define TLP 9
7529#define TRP 10
7530#define TENDCASE 11
7531#define TENDBQUOTE 12
7532#define TNOT 13
7533#define TCASE 14
7534#define TDO 15
7535#define TDONE 16
7536#define TELIF 17
7537#define TELSE 18
7538#define TESAC 19
7539#define TFI 20
7540#define TFOR 21
7541#define TIF 22
7542#define TIN 23
7543#define TTHEN 24
7544#define TUNTIL 25
7545#define TWHILE 26
7546#define TBEGIN 27
7547#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007548typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007549
7550/* first char is indicating which tokens mark the end of a list */
7551static const char *const tokname_array[] = {
7552 "\1end of file",
7553 "\0newline",
7554 "\0redirection",
7555 "\0word",
7556 "\0;",
7557 "\0&",
7558 "\0&&",
7559 "\0||",
7560 "\0|",
7561 "\0(",
7562 "\1)",
7563 "\1;;",
7564 "\1`",
7565#define KWDOFFSET 13
7566 /* the following are keywords */
7567 "\0!",
7568 "\0case",
7569 "\1do",
7570 "\1done",
7571 "\1elif",
7572 "\1else",
7573 "\1esac",
7574 "\1fi",
7575 "\0for",
7576 "\0if",
7577 "\0in",
7578 "\1then",
7579 "\0until",
7580 "\0while",
7581 "\0{",
7582 "\1}",
7583};
7584
7585static const char *
7586tokname(int tok)
7587{
7588 static char buf[16];
7589
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007590//try this:
7591//if (tok < TSEMI) return tokname_array[tok] + 1;
7592//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7593//return buf;
7594
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007595 if (tok >= TSEMI)
7596 buf[0] = '"';
7597 sprintf(buf + (tok >= TSEMI), "%s%c",
7598 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7599 return buf;
7600}
7601
7602/* Wrapper around strcmp for qsort/bsearch/... */
7603static int
7604pstrcmp(const void *a, const void *b)
7605{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007606 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007607}
7608
7609static const char *const *
7610findkwd(const char *s)
7611{
7612 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007613 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7614 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007615}
7616
7617/*
7618 * Locate and print what a word is...
7619 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007620static int
7621describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007622{
7623 struct cmdentry entry;
7624 struct tblentry *cmdp;
7625#if ENABLE_ASH_ALIAS
7626 const struct alias *ap;
7627#endif
7628 const char *path = pathval();
7629
7630 if (describe_command_verbose) {
7631 out1str(command);
7632 }
7633
7634 /* First look at the keywords */
7635 if (findkwd(command)) {
7636 out1str(describe_command_verbose ? " is a shell keyword" : command);
7637 goto out;
7638 }
7639
7640#if ENABLE_ASH_ALIAS
7641 /* Then look at the aliases */
7642 ap = lookupalias(command, 0);
7643 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007644 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007645 out1str("alias ");
7646 printalias(ap);
7647 return 0;
7648 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007649 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650 goto out;
7651 }
7652#endif
7653 /* Then check if it is a tracked alias */
7654 cmdp = cmdlookup(command, 0);
7655 if (cmdp != NULL) {
7656 entry.cmdtype = cmdp->cmdtype;
7657 entry.u = cmdp->param;
7658 } else {
7659 /* Finally use brute force */
7660 find_command(command, &entry, DO_ABS, path);
7661 }
7662
7663 switch (entry.cmdtype) {
7664 case CMDNORMAL: {
7665 int j = entry.u.index;
7666 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007667 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007668 p = command;
7669 } else {
7670 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007671 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007672 stunalloc(p);
7673 } while (--j >= 0);
7674 }
7675 if (describe_command_verbose) {
7676 out1fmt(" is%s %s",
7677 (cmdp ? " a tracked alias for" : nullstr), p
7678 );
7679 } else {
7680 out1str(p);
7681 }
7682 break;
7683 }
7684
7685 case CMDFUNCTION:
7686 if (describe_command_verbose) {
7687 out1str(" is a shell function");
7688 } else {
7689 out1str(command);
7690 }
7691 break;
7692
7693 case CMDBUILTIN:
7694 if (describe_command_verbose) {
7695 out1fmt(" is a %sshell builtin",
7696 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7697 "special " : nullstr
7698 );
7699 } else {
7700 out1str(command);
7701 }
7702 break;
7703
7704 default:
7705 if (describe_command_verbose) {
7706 out1str(": not found\n");
7707 }
7708 return 127;
7709 }
7710 out:
7711 outstr("\n", stdout);
7712 return 0;
7713}
7714
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007715static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007716typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007717{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007718 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007719 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007720 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007721
Denis Vlasenko46846e22007-05-20 13:08:31 +00007722 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007723 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007724 i++;
7725 verbose = 0;
7726 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007727 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007728 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007729 }
7730 return err;
7731}
7732
7733#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007734static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007735commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007736{
7737 int c;
7738 enum {
7739 VERIFY_BRIEF = 1,
7740 VERIFY_VERBOSE = 2,
7741 } verify = 0;
7742
7743 while ((c = nextopt("pvV")) != '\0')
7744 if (c == 'V')
7745 verify |= VERIFY_VERBOSE;
7746 else if (c == 'v')
7747 verify |= VERIFY_BRIEF;
7748#if DEBUG
7749 else if (c != 'p')
7750 abort();
7751#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007752 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7753 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007754 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007755 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007756
7757 return 0;
7758}
7759#endif
7760
7761
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007762/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007763
Denis Vlasenko340299a2008-11-21 10:36:36 +00007764static int funcblocksize; /* size of structures in function */
7765static int funcstringsize; /* size of strings in node */
7766static void *funcblock; /* block to allocate function from */
7767static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007768
Eric Andersencb57d552001-06-28 07:25:16 +00007769/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007770#define EV_EXIT 01 /* exit after evaluating tree */
7771#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007772#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007773
Denis Vlasenko340299a2008-11-21 10:36:36 +00007774static const short nodesize[N_NUMBER] = {
7775 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7776 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7777 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7778 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7779 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7780 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7781 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7782 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7783 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7784 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7785 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7786 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7787 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7788 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7789 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7790 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7791 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007792#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007793 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007794#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007795 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7796 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7797 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7798 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7799 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7800 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7801 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7802 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7803 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007804};
7805
7806static void calcsize(union node *n);
7807
7808static void
7809sizenodelist(struct nodelist *lp)
7810{
7811 while (lp) {
7812 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7813 calcsize(lp->n);
7814 lp = lp->next;
7815 }
7816}
7817
7818static void
7819calcsize(union node *n)
7820{
7821 if (n == NULL)
7822 return;
7823 funcblocksize += nodesize[n->type];
7824 switch (n->type) {
7825 case NCMD:
7826 calcsize(n->ncmd.redirect);
7827 calcsize(n->ncmd.args);
7828 calcsize(n->ncmd.assign);
7829 break;
7830 case NPIPE:
7831 sizenodelist(n->npipe.cmdlist);
7832 break;
7833 case NREDIR:
7834 case NBACKGND:
7835 case NSUBSHELL:
7836 calcsize(n->nredir.redirect);
7837 calcsize(n->nredir.n);
7838 break;
7839 case NAND:
7840 case NOR:
7841 case NSEMI:
7842 case NWHILE:
7843 case NUNTIL:
7844 calcsize(n->nbinary.ch2);
7845 calcsize(n->nbinary.ch1);
7846 break;
7847 case NIF:
7848 calcsize(n->nif.elsepart);
7849 calcsize(n->nif.ifpart);
7850 calcsize(n->nif.test);
7851 break;
7852 case NFOR:
7853 funcstringsize += strlen(n->nfor.var) + 1;
7854 calcsize(n->nfor.body);
7855 calcsize(n->nfor.args);
7856 break;
7857 case NCASE:
7858 calcsize(n->ncase.cases);
7859 calcsize(n->ncase.expr);
7860 break;
7861 case NCLIST:
7862 calcsize(n->nclist.body);
7863 calcsize(n->nclist.pattern);
7864 calcsize(n->nclist.next);
7865 break;
7866 case NDEFUN:
7867 case NARG:
7868 sizenodelist(n->narg.backquote);
7869 funcstringsize += strlen(n->narg.text) + 1;
7870 calcsize(n->narg.next);
7871 break;
7872 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007873#if ENABLE_ASH_BASH_COMPAT
7874 case NTO2:
7875#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007876 case NCLOBBER:
7877 case NFROM:
7878 case NFROMTO:
7879 case NAPPEND:
7880 calcsize(n->nfile.fname);
7881 calcsize(n->nfile.next);
7882 break;
7883 case NTOFD:
7884 case NFROMFD:
7885 calcsize(n->ndup.vname);
7886 calcsize(n->ndup.next);
7887 break;
7888 case NHERE:
7889 case NXHERE:
7890 calcsize(n->nhere.doc);
7891 calcsize(n->nhere.next);
7892 break;
7893 case NNOT:
7894 calcsize(n->nnot.com);
7895 break;
7896 };
7897}
7898
7899static char *
7900nodeckstrdup(char *s)
7901{
7902 char *rtn = funcstring;
7903
7904 strcpy(funcstring, s);
7905 funcstring += strlen(s) + 1;
7906 return rtn;
7907}
7908
7909static union node *copynode(union node *);
7910
7911static struct nodelist *
7912copynodelist(struct nodelist *lp)
7913{
7914 struct nodelist *start;
7915 struct nodelist **lpp;
7916
7917 lpp = &start;
7918 while (lp) {
7919 *lpp = funcblock;
7920 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7921 (*lpp)->n = copynode(lp->n);
7922 lp = lp->next;
7923 lpp = &(*lpp)->next;
7924 }
7925 *lpp = NULL;
7926 return start;
7927}
7928
7929static union node *
7930copynode(union node *n)
7931{
7932 union node *new;
7933
7934 if (n == NULL)
7935 return NULL;
7936 new = funcblock;
7937 funcblock = (char *) funcblock + nodesize[n->type];
7938
7939 switch (n->type) {
7940 case NCMD:
7941 new->ncmd.redirect = copynode(n->ncmd.redirect);
7942 new->ncmd.args = copynode(n->ncmd.args);
7943 new->ncmd.assign = copynode(n->ncmd.assign);
7944 break;
7945 case NPIPE:
7946 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007947 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007948 break;
7949 case NREDIR:
7950 case NBACKGND:
7951 case NSUBSHELL:
7952 new->nredir.redirect = copynode(n->nredir.redirect);
7953 new->nredir.n = copynode(n->nredir.n);
7954 break;
7955 case NAND:
7956 case NOR:
7957 case NSEMI:
7958 case NWHILE:
7959 case NUNTIL:
7960 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7961 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7962 break;
7963 case NIF:
7964 new->nif.elsepart = copynode(n->nif.elsepart);
7965 new->nif.ifpart = copynode(n->nif.ifpart);
7966 new->nif.test = copynode(n->nif.test);
7967 break;
7968 case NFOR:
7969 new->nfor.var = nodeckstrdup(n->nfor.var);
7970 new->nfor.body = copynode(n->nfor.body);
7971 new->nfor.args = copynode(n->nfor.args);
7972 break;
7973 case NCASE:
7974 new->ncase.cases = copynode(n->ncase.cases);
7975 new->ncase.expr = copynode(n->ncase.expr);
7976 break;
7977 case NCLIST:
7978 new->nclist.body = copynode(n->nclist.body);
7979 new->nclist.pattern = copynode(n->nclist.pattern);
7980 new->nclist.next = copynode(n->nclist.next);
7981 break;
7982 case NDEFUN:
7983 case NARG:
7984 new->narg.backquote = copynodelist(n->narg.backquote);
7985 new->narg.text = nodeckstrdup(n->narg.text);
7986 new->narg.next = copynode(n->narg.next);
7987 break;
7988 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007989#if ENABLE_ASH_BASH_COMPAT
7990 case NTO2:
7991#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007992 case NCLOBBER:
7993 case NFROM:
7994 case NFROMTO:
7995 case NAPPEND:
7996 new->nfile.fname = copynode(n->nfile.fname);
7997 new->nfile.fd = n->nfile.fd;
7998 new->nfile.next = copynode(n->nfile.next);
7999 break;
8000 case NTOFD:
8001 case NFROMFD:
8002 new->ndup.vname = copynode(n->ndup.vname);
8003 new->ndup.dupfd = n->ndup.dupfd;
8004 new->ndup.fd = n->ndup.fd;
8005 new->ndup.next = copynode(n->ndup.next);
8006 break;
8007 case NHERE:
8008 case NXHERE:
8009 new->nhere.doc = copynode(n->nhere.doc);
8010 new->nhere.fd = n->nhere.fd;
8011 new->nhere.next = copynode(n->nhere.next);
8012 break;
8013 case NNOT:
8014 new->nnot.com = copynode(n->nnot.com);
8015 break;
8016 };
8017 new->type = n->type;
8018 return new;
8019}
8020
8021/*
8022 * Make a copy of a parse tree.
8023 */
8024static struct funcnode *
8025copyfunc(union node *n)
8026{
8027 struct funcnode *f;
8028 size_t blocksize;
8029
8030 funcblocksize = offsetof(struct funcnode, n);
8031 funcstringsize = 0;
8032 calcsize(n);
8033 blocksize = funcblocksize;
8034 f = ckmalloc(blocksize + funcstringsize);
8035 funcblock = (char *) f + offsetof(struct funcnode, n);
8036 funcstring = (char *) f + blocksize;
8037 copynode(n);
8038 f->count = 0;
8039 return f;
8040}
8041
8042/*
8043 * Define a shell function.
8044 */
8045static void
8046defun(char *name, union node *func)
8047{
8048 struct cmdentry entry;
8049
8050 INT_OFF;
8051 entry.cmdtype = CMDFUNCTION;
8052 entry.u.func = copyfunc(func);
8053 addcmdentry(name, &entry);
8054 INT_ON;
8055}
8056
Denis Vlasenko4b875702009-03-19 13:30:04 +00008057/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008058#define SKIPBREAK (1 << 0)
8059#define SKIPCONT (1 << 1)
8060#define SKIPFUNC (1 << 2)
8061#define SKIPFILE (1 << 3)
8062#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008063static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008064static int skipcount; /* number of levels to skip */
8065static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008066static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008067
Denis Vlasenko4b875702009-03-19 13:30:04 +00008068/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008069static int evalstring(char *s, int mask);
8070
Denis Vlasenko4b875702009-03-19 13:30:04 +00008071/* Called to execute a trap.
8072 * Single callsite - at the end of evaltree().
8073 * If we return non-zero, exaltree raises EXEXIT exception.
8074 *
8075 * Perhaps we should avoid entering new trap handlers
8076 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008077 */
8078static int
8079dotrap(void)
8080{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008081 uint8_t *g;
8082 int sig;
8083 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008084
8085 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008086 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008087 xbarrier();
8088
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008089 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008090 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8091 int want_exexit;
8092 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008093
Denis Vlasenko4b875702009-03-19 13:30:04 +00008094 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008095 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008096 t = trap[sig];
8097 /* non-trapped SIGINT is handled separately by raise_interrupt,
8098 * don't upset it by resetting gotsig[SIGINT-1] */
8099 if (sig == SIGINT && !t)
8100 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008101
8102 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008103 *g = 0;
8104 if (!t)
8105 continue;
8106 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008107 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008108 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008109 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008110 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008111 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008112 }
8113
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008114 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008115 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008116}
8117
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008118/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008119static void evalloop(union node *, int);
8120static void evalfor(union node *, int);
8121static void evalcase(union node *, int);
8122static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008123static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008124static void evalpipe(union node *, int);
8125static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008126static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008127static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008128
Eric Andersen62483552001-07-10 06:09:16 +00008129/*
Eric Andersenc470f442003-07-28 09:56:35 +00008130 * Evaluate a parse tree. The value is left in the global variable
8131 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008132 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008133static void
Eric Andersenc470f442003-07-28 09:56:35 +00008134evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008135{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136 struct jmploc *volatile savehandler = exception_handler;
8137 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008138 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008139 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008140 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008141 int int_level;
8142
8143 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008144
Eric Andersenc470f442003-07-28 09:56:35 +00008145 if (n == NULL) {
8146 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008147 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008148 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008149 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008150
8151 exception_handler = &jmploc;
8152 {
8153 int err = setjmp(jmploc.loc);
8154 if (err) {
8155 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008156 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008157 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8158 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008159 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008160 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008161 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008162 TRACE(("exception %d in evaltree, propagating err=%d\n",
8163 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008164 exception_handler = savehandler;
8165 longjmp(exception_handler->loc, err);
8166 }
8167 }
8168
Eric Andersenc470f442003-07-28 09:56:35 +00008169 switch (n->type) {
8170 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008171#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008172 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008173 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008174 break;
8175#endif
8176 case NNOT:
8177 evaltree(n->nnot.com, EV_TESTED);
8178 status = !exitstatus;
8179 goto setstatus;
8180 case NREDIR:
8181 expredir(n->nredir.redirect);
8182 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8183 if (!status) {
8184 evaltree(n->nredir.n, flags & EV_TESTED);
8185 status = exitstatus;
8186 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008187 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008188 goto setstatus;
8189 case NCMD:
8190 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008191 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008192 if (eflag && !(flags & EV_TESTED))
8193 checkexit = ~0;
8194 goto calleval;
8195 case NFOR:
8196 evalfn = evalfor;
8197 goto calleval;
8198 case NWHILE:
8199 case NUNTIL:
8200 evalfn = evalloop;
8201 goto calleval;
8202 case NSUBSHELL:
8203 case NBACKGND:
8204 evalfn = evalsubshell;
8205 goto calleval;
8206 case NPIPE:
8207 evalfn = evalpipe;
8208 goto checkexit;
8209 case NCASE:
8210 evalfn = evalcase;
8211 goto calleval;
8212 case NAND:
8213 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008214 case NSEMI: {
8215
Eric Andersenc470f442003-07-28 09:56:35 +00008216#if NAND + 1 != NOR
8217#error NAND + 1 != NOR
8218#endif
8219#if NOR + 1 != NSEMI
8220#error NOR + 1 != NSEMI
8221#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008222 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008223 evaltree(
8224 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008225 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008226 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008227 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008228 break;
8229 if (!evalskip) {
8230 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008231 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008232 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008233 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008234 evalfn(n, flags);
8235 break;
8236 }
8237 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008238 }
Eric Andersenc470f442003-07-28 09:56:35 +00008239 case NIF:
8240 evaltree(n->nif.test, EV_TESTED);
8241 if (evalskip)
8242 break;
8243 if (exitstatus == 0) {
8244 n = n->nif.ifpart;
8245 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008246 }
8247 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008248 n = n->nif.elsepart;
8249 goto evaln;
8250 }
8251 goto success;
8252 case NDEFUN:
8253 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008254 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008255 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008256 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008257 exitstatus = status;
8258 break;
8259 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008260
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008261 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008262 exception_handler = savehandler;
8263 out1:
8264 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008265 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008266 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008267 goto exexit;
8268
8269 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008270 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008271 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008272 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008273
8274 RESTORE_INT(int_level);
8275 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008276}
8277
Eric Andersenc470f442003-07-28 09:56:35 +00008278#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8279static
8280#endif
8281void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8282
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008283static void
Eric Andersenc470f442003-07-28 09:56:35 +00008284evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008285{
8286 int status;
8287
8288 loopnest++;
8289 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008290 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008291 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008292 int i;
8293
Eric Andersencb57d552001-06-28 07:25:16 +00008294 evaltree(n->nbinary.ch1, EV_TESTED);
8295 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008296 skipping:
8297 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008298 evalskip = 0;
8299 continue;
8300 }
8301 if (evalskip == SKIPBREAK && --skipcount <= 0)
8302 evalskip = 0;
8303 break;
8304 }
Eric Andersenc470f442003-07-28 09:56:35 +00008305 i = exitstatus;
8306 if (n->type != NWHILE)
8307 i = !i;
8308 if (i != 0)
8309 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008310 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008311 status = exitstatus;
8312 if (evalskip)
8313 goto skipping;
8314 }
8315 loopnest--;
8316 exitstatus = status;
8317}
8318
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008319static void
Eric Andersenc470f442003-07-28 09:56:35 +00008320evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008321{
8322 struct arglist arglist;
8323 union node *argp;
8324 struct strlist *sp;
8325 struct stackmark smark;
8326
8327 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008328 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008329 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008330 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008331 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008332 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008333 if (evalskip)
8334 goto out;
8335 }
8336 *arglist.lastp = NULL;
8337
8338 exitstatus = 0;
8339 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008340 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008341 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008342 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008343 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008344 if (evalskip) {
8345 if (evalskip == SKIPCONT && --skipcount <= 0) {
8346 evalskip = 0;
8347 continue;
8348 }
8349 if (evalskip == SKIPBREAK && --skipcount <= 0)
8350 evalskip = 0;
8351 break;
8352 }
8353 }
8354 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008355 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008356 popstackmark(&smark);
8357}
8358
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008359static void
Eric Andersenc470f442003-07-28 09:56:35 +00008360evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008361{
8362 union node *cp;
8363 union node *patp;
8364 struct arglist arglist;
8365 struct stackmark smark;
8366
8367 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008368 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008369 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008370 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008371 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008372 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8373 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008374 if (casematch(patp, arglist.list->text)) {
8375 if (evalskip == 0) {
8376 evaltree(cp->nclist.body, flags);
8377 }
8378 goto out;
8379 }
8380 }
8381 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008382 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008383 popstackmark(&smark);
8384}
8385
Eric Andersenc470f442003-07-28 09:56:35 +00008386/*
8387 * Kick off a subshell to evaluate a tree.
8388 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008389static void
Eric Andersenc470f442003-07-28 09:56:35 +00008390evalsubshell(union node *n, int flags)
8391{
8392 struct job *jp;
8393 int backgnd = (n->type == NBACKGND);
8394 int status;
8395
8396 expredir(n->nredir.redirect);
8397 if (!backgnd && flags & EV_EXIT && !trap[0])
8398 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008399 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008400 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008401 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008402 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008403 flags |= EV_EXIT;
8404 if (backgnd)
8405 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008406 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008407 redirect(n->nredir.redirect, 0);
8408 evaltreenr(n->nredir.n, flags);
8409 /* never returns */
8410 }
8411 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008412 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008413 status = waitforjob(jp);
8414 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008415 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008416}
8417
Eric Andersenc470f442003-07-28 09:56:35 +00008418/*
8419 * Compute the names of the files in a redirection list.
8420 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008421static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008422static void
8423expredir(union node *n)
8424{
8425 union node *redir;
8426
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008427 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008428 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008429
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008430 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008431 fn.lastp = &fn.list;
8432 switch (redir->type) {
8433 case NFROMTO:
8434 case NFROM:
8435 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008436#if ENABLE_ASH_BASH_COMPAT
8437 case NTO2:
8438#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008439 case NCLOBBER:
8440 case NAPPEND:
8441 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008442#if ENABLE_ASH_BASH_COMPAT
8443 store_expfname:
8444#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008445 redir->nfile.expfname = fn.list->text;
8446 break;
8447 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008448 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008449 if (redir->ndup.vname) {
8450 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008451 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008452 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008453#if ENABLE_ASH_BASH_COMPAT
8454//FIXME: we used expandarg with different args!
8455 if (!isdigit_str9(fn.list->text)) {
8456 /* >&file, not >&fd */
8457 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8458 ash_msg_and_raise_error("redir error");
8459 redir->type = NTO2;
8460 goto store_expfname;
8461 }
8462#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008463 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008464 }
8465 break;
8466 }
8467 }
8468}
8469
Eric Andersencb57d552001-06-28 07:25:16 +00008470/*
Eric Andersencb57d552001-06-28 07:25:16 +00008471 * Evaluate a pipeline. All the processes in the pipeline are children
8472 * of the process creating the pipeline. (This differs from some versions
8473 * of the shell, which make the last process in a pipeline the parent
8474 * of all the rest.)
8475 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008476static void
Eric Andersenc470f442003-07-28 09:56:35 +00008477evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008478{
8479 struct job *jp;
8480 struct nodelist *lp;
8481 int pipelen;
8482 int prevfd;
8483 int pip[2];
8484
Eric Andersenc470f442003-07-28 09:56:35 +00008485 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008486 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008487 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008488 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008489 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008490 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008491 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008492 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008493 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008494 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008495 pip[1] = -1;
8496 if (lp->next) {
8497 if (pipe(pip) < 0) {
8498 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008499 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008500 }
8501 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008502 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008503 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008504 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008505 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008506 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008507 if (prevfd > 0) {
8508 dup2(prevfd, 0);
8509 close(prevfd);
8510 }
8511 if (pip[1] > 1) {
8512 dup2(pip[1], 1);
8513 close(pip[1]);
8514 }
Eric Andersenc470f442003-07-28 09:56:35 +00008515 evaltreenr(lp->n, flags);
8516 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008517 }
8518 if (prevfd >= 0)
8519 close(prevfd);
8520 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008521 /* Don't want to trigger debugging */
8522 if (pip[1] != -1)
8523 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008524 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008525 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008526 exitstatus = waitforjob(jp);
8527 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008528 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008529 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008530}
8531
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008532/*
8533 * Controls whether the shell is interactive or not.
8534 */
8535static void
8536setinteractive(int on)
8537{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008538 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008539
8540 if (++on == is_interactive)
8541 return;
8542 is_interactive = on;
8543 setsignal(SIGINT);
8544 setsignal(SIGQUIT);
8545 setsignal(SIGTERM);
8546#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8547 if (is_interactive > 1) {
8548 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008549 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008550
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008551 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008552 /* note: ash and hush share this string */
8553 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008554 "Enter 'help' for a list of built-in commands."
8555 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008556 bb_banner,
8557 "built-in shell (ash)"
8558 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008559 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008560 }
8561 }
8562#endif
8563}
8564
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008565static void
8566optschanged(void)
8567{
8568#if DEBUG
8569 opentrace();
8570#endif
8571 setinteractive(iflag);
8572 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008573#if ENABLE_FEATURE_EDITING_VI
8574 if (viflag)
8575 line_input_state->flags |= VI_MODE;
8576 else
8577 line_input_state->flags &= ~VI_MODE;
8578#else
8579 viflag = 0; /* forcibly keep the option off */
8580#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008581}
8582
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008583static struct localvar *localvars;
8584
8585/*
8586 * Called after a function returns.
8587 * Interrupts must be off.
8588 */
8589static void
8590poplocalvars(void)
8591{
8592 struct localvar *lvp;
8593 struct var *vp;
8594
8595 while ((lvp = localvars) != NULL) {
8596 localvars = lvp->next;
8597 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008598 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008599 if (vp == NULL) { /* $- saved */
8600 memcpy(optlist, lvp->text, sizeof(optlist));
8601 free((char*)lvp->text);
8602 optschanged();
8603 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8604 unsetvar(vp->text);
8605 } else {
8606 if (vp->func)
8607 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8608 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8609 free((char*)vp->text);
8610 vp->flags = lvp->flags;
8611 vp->text = lvp->text;
8612 }
8613 free(lvp);
8614 }
8615}
8616
8617static int
8618evalfun(struct funcnode *func, int argc, char **argv, int flags)
8619{
8620 volatile struct shparam saveparam;
8621 struct localvar *volatile savelocalvars;
8622 struct jmploc *volatile savehandler;
8623 struct jmploc jmploc;
8624 int e;
8625
8626 saveparam = shellparam;
8627 savelocalvars = localvars;
8628 e = setjmp(jmploc.loc);
8629 if (e) {
8630 goto funcdone;
8631 }
8632 INT_OFF;
8633 savehandler = exception_handler;
8634 exception_handler = &jmploc;
8635 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008636 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008637 func->count++;
8638 funcnest++;
8639 INT_ON;
8640 shellparam.nparam = argc - 1;
8641 shellparam.p = argv + 1;
8642#if ENABLE_ASH_GETOPTS
8643 shellparam.optind = 1;
8644 shellparam.optoff = -1;
8645#endif
8646 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008647 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008648 INT_OFF;
8649 funcnest--;
8650 freefunc(func);
8651 poplocalvars();
8652 localvars = savelocalvars;
8653 freeparam(&shellparam);
8654 shellparam = saveparam;
8655 exception_handler = savehandler;
8656 INT_ON;
8657 evalskip &= ~SKIPFUNC;
8658 return e;
8659}
8660
Denis Vlasenko131ae172007-02-18 13:00:19 +00008661#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008662static char **
8663parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008664{
8665 char *cp, c;
8666
8667 for (;;) {
8668 cp = *++argv;
8669 if (!cp)
8670 return 0;
8671 if (*cp++ != '-')
8672 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008673 c = *cp++;
8674 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008675 break;
8676 if (c == '-' && !*cp) {
8677 argv++;
8678 break;
8679 }
8680 do {
8681 switch (c) {
8682 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008683 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008684 break;
8685 default:
8686 /* run 'typecmd' for other options */
8687 return 0;
8688 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008689 c = *cp++;
8690 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008691 }
8692 return argv;
8693}
8694#endif
8695
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008696/*
8697 * Make a variable a local variable. When a variable is made local, it's
8698 * value and flags are saved in a localvar structure. The saved values
8699 * will be restored when the shell function returns. We handle the name
8700 * "-" as a special case.
8701 */
8702static void
8703mklocal(char *name)
8704{
8705 struct localvar *lvp;
8706 struct var **vpp;
8707 struct var *vp;
8708
8709 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008710 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008711 if (LONE_DASH(name)) {
8712 char *p;
8713 p = ckmalloc(sizeof(optlist));
8714 lvp->text = memcpy(p, optlist, sizeof(optlist));
8715 vp = NULL;
8716 } else {
8717 char *eq;
8718
8719 vpp = hashvar(name);
8720 vp = *findvar(vpp, name);
8721 eq = strchr(name, '=');
8722 if (vp == NULL) {
8723 if (eq)
8724 setvareq(name, VSTRFIXED);
8725 else
8726 setvar(name, NULL, VSTRFIXED);
8727 vp = *vpp; /* the new variable */
8728 lvp->flags = VUNSET;
8729 } else {
8730 lvp->text = vp->text;
8731 lvp->flags = vp->flags;
8732 vp->flags |= VSTRFIXED|VTEXTFIXED;
8733 if (eq)
8734 setvareq(name, 0);
8735 }
8736 }
8737 lvp->vp = vp;
8738 lvp->next = localvars;
8739 localvars = lvp;
8740 INT_ON;
8741}
8742
8743/*
8744 * The "local" command.
8745 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008746static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008747localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008748{
8749 char *name;
8750
8751 argv = argptr;
8752 while ((name = *argv++) != NULL) {
8753 mklocal(name);
8754 }
8755 return 0;
8756}
8757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008759falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008760{
8761 return 1;
8762}
8763
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008764static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008765truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008766{
8767 return 0;
8768}
8769
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008770static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008771execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008772{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008773 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008774 iflag = 0; /* exit on error */
8775 mflag = 0;
8776 optschanged();
8777 shellexec(argv + 1, pathval(), 0);
8778 }
8779 return 0;
8780}
8781
8782/*
8783 * The return command.
8784 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008786returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008787{
8788 /*
8789 * If called outside a function, do what ksh does;
8790 * skip the rest of the file.
8791 */
8792 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8793 return argv[1] ? number(argv[1]) : exitstatus;
8794}
8795
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008796/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int breakcmd(int, char **) FAST_FUNC;
8798static int dotcmd(int, char **) FAST_FUNC;
8799static int evalcmd(int, char **) FAST_FUNC;
8800static int exitcmd(int, char **) FAST_FUNC;
8801static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008802#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008803static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008804#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008805#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008807#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008808#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008810#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008811static int readcmd(int, char **) FAST_FUNC;
8812static int setcmd(int, char **) FAST_FUNC;
8813static int shiftcmd(int, char **) FAST_FUNC;
8814static int timescmd(int, char **) FAST_FUNC;
8815static int trapcmd(int, char **) FAST_FUNC;
8816static int umaskcmd(int, char **) FAST_FUNC;
8817static int unsetcmd(int, char **) FAST_FUNC;
8818static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008819
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008820#define BUILTIN_NOSPEC "0"
8821#define BUILTIN_SPECIAL "1"
8822#define BUILTIN_REGULAR "2"
8823#define BUILTIN_SPEC_REG "3"
8824#define BUILTIN_ASSIGN "4"
8825#define BUILTIN_SPEC_ASSG "5"
8826#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008827#define BUILTIN_SPEC_REG_ASSG "7"
8828
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008830#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008831static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008832#endif
8833#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008834static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008835#endif
8836#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008837static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008838#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008839
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008840/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008841static const struct builtincmd builtintab[] = {
8842 { BUILTIN_SPEC_REG ".", dotcmd },
8843 { BUILTIN_SPEC_REG ":", truecmd },
8844#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008845 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008846#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008847 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008848#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008849#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008850#if ENABLE_ASH_ALIAS
8851 { BUILTIN_REG_ASSG "alias", aliascmd },
8852#endif
8853#if JOBS
8854 { BUILTIN_REGULAR "bg", fg_bgcmd },
8855#endif
8856 { BUILTIN_SPEC_REG "break", breakcmd },
8857 { BUILTIN_REGULAR "cd", cdcmd },
8858 { BUILTIN_NOSPEC "chdir", cdcmd },
8859#if ENABLE_ASH_CMDCMD
8860 { BUILTIN_REGULAR "command", commandcmd },
8861#endif
8862 { BUILTIN_SPEC_REG "continue", breakcmd },
8863#if ENABLE_ASH_BUILTIN_ECHO
8864 { BUILTIN_REGULAR "echo", echocmd },
8865#endif
8866 { BUILTIN_SPEC_REG "eval", evalcmd },
8867 { BUILTIN_SPEC_REG "exec", execcmd },
8868 { BUILTIN_SPEC_REG "exit", exitcmd },
8869 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8870 { BUILTIN_REGULAR "false", falsecmd },
8871#if JOBS
8872 { BUILTIN_REGULAR "fg", fg_bgcmd },
8873#endif
8874#if ENABLE_ASH_GETOPTS
8875 { BUILTIN_REGULAR "getopts", getoptscmd },
8876#endif
8877 { BUILTIN_NOSPEC "hash", hashcmd },
8878#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8879 { BUILTIN_NOSPEC "help", helpcmd },
8880#endif
8881#if JOBS
8882 { BUILTIN_REGULAR "jobs", jobscmd },
8883 { BUILTIN_REGULAR "kill", killcmd },
8884#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008885#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008886 { BUILTIN_NOSPEC "let", letcmd },
8887#endif
8888 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008889#if ENABLE_ASH_BUILTIN_PRINTF
8890 { BUILTIN_REGULAR "printf", printfcmd },
8891#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008892 { BUILTIN_NOSPEC "pwd", pwdcmd },
8893 { BUILTIN_REGULAR "read", readcmd },
8894 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8895 { BUILTIN_SPEC_REG "return", returncmd },
8896 { BUILTIN_SPEC_REG "set", setcmd },
8897 { BUILTIN_SPEC_REG "shift", shiftcmd },
8898 { BUILTIN_SPEC_REG "source", dotcmd },
8899#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008900 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008901#endif
8902 { BUILTIN_SPEC_REG "times", timescmd },
8903 { BUILTIN_SPEC_REG "trap", trapcmd },
8904 { BUILTIN_REGULAR "true", truecmd },
8905 { BUILTIN_NOSPEC "type", typecmd },
8906 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8907 { BUILTIN_REGULAR "umask", umaskcmd },
8908#if ENABLE_ASH_ALIAS
8909 { BUILTIN_REGULAR "unalias", unaliascmd },
8910#endif
8911 { BUILTIN_SPEC_REG "unset", unsetcmd },
8912 { BUILTIN_REGULAR "wait", waitcmd },
8913};
8914
Denis Vlasenko80591b02008-03-25 07:49:43 +00008915/* Should match the above table! */
8916#define COMMANDCMD (builtintab + \
8917 2 + \
8918 1 * ENABLE_ASH_BUILTIN_TEST + \
8919 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8920 1 * ENABLE_ASH_ALIAS + \
8921 1 * ENABLE_ASH_JOB_CONTROL + \
8922 3)
8923#define EXECCMD (builtintab + \
8924 2 + \
8925 1 * ENABLE_ASH_BUILTIN_TEST + \
8926 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8927 1 * ENABLE_ASH_ALIAS + \
8928 1 * ENABLE_ASH_JOB_CONTROL + \
8929 3 + \
8930 1 * ENABLE_ASH_CMDCMD + \
8931 1 + \
8932 ENABLE_ASH_BUILTIN_ECHO + \
8933 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008934
8935/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008936 * Search the table of builtin commands.
8937 */
8938static struct builtincmd *
8939find_builtin(const char *name)
8940{
8941 struct builtincmd *bp;
8942
8943 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008944 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008945 pstrcmp
8946 );
8947 return bp;
8948}
8949
8950/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008951 * Execute a simple command.
8952 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008953static int
8954isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008955{
8956 const char *q = endofname(p);
8957 if (p == q)
8958 return 0;
8959 return *q == '=';
8960}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008961static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008962bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008963{
8964 /* Preserve exitstatus of a previous possible redirection
8965 * as POSIX mandates */
8966 return back_exitstatus;
8967}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008968static void
Eric Andersenc470f442003-07-28 09:56:35 +00008969evalcommand(union node *cmd, int flags)
8970{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008971 static const struct builtincmd null_bltin = {
8972 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008973 };
Eric Andersenc470f442003-07-28 09:56:35 +00008974 struct stackmark smark;
8975 union node *argp;
8976 struct arglist arglist;
8977 struct arglist varlist;
8978 char **argv;
8979 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008980 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008981 struct cmdentry cmdentry;
8982 struct job *jp;
8983 char *lastarg;
8984 const char *path;
8985 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008986 int status;
8987 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008988 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008989 smallint cmd_is_exec;
8990 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008991
8992 /* First expand the arguments. */
8993 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8994 setstackmark(&smark);
8995 back_exitstatus = 0;
8996
8997 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008998 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008999 varlist.lastp = &varlist.list;
9000 *varlist.lastp = NULL;
9001 arglist.lastp = &arglist.list;
9002 *arglist.lastp = NULL;
9003
9004 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009005 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009006 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9007 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9008 }
9009
Eric Andersenc470f442003-07-28 09:56:35 +00009010 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9011 struct strlist **spp;
9012
9013 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009014 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009015 expandarg(argp, &arglist, EXP_VARTILDE);
9016 else
9017 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9018
Eric Andersenc470f442003-07-28 09:56:35 +00009019 for (sp = *spp; sp; sp = sp->next)
9020 argc++;
9021 }
9022
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009023 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009024 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009025 TRACE(("evalcommand arg: %s\n", sp->text));
9026 *nargv++ = sp->text;
9027 }
9028 *nargv = NULL;
9029
9030 lastarg = NULL;
9031 if (iflag && funcnest == 0 && argc > 0)
9032 lastarg = nargv[-1];
9033
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009034 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009035 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009036 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009037
9038 path = vpath.text;
9039 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9040 struct strlist **spp;
9041 char *p;
9042
9043 spp = varlist.lastp;
9044 expandarg(argp, &varlist, EXP_VARTILDE);
9045
9046 /*
9047 * Modify the command lookup path, if a PATH= assignment
9048 * is present
9049 */
9050 p = (*spp)->text;
9051 if (varequal(p, path))
9052 path = p;
9053 }
9054
9055 /* Print the command if xflag is set. */
9056 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009057 int n;
9058 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009059
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009060 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009061 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009062
9063 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009064 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009065 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009066 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009067 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009068 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009069 p--;
9070 }
9071 }
9072 sp = arglist.list;
9073 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009074 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009075 }
9076
9077 cmd_is_exec = 0;
9078 spclbltin = -1;
9079
9080 /* Now locate the command. */
9081 if (argc) {
9082 const char *oldpath;
9083 int cmd_flag = DO_ERR;
9084
9085 path += 5;
9086 oldpath = path;
9087 for (;;) {
9088 find_command(argv[0], &cmdentry, cmd_flag, path);
9089 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009090 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009091 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009092 goto bail;
9093 }
9094
9095 /* implement bltin and command here */
9096 if (cmdentry.cmdtype != CMDBUILTIN)
9097 break;
9098 if (spclbltin < 0)
9099 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9100 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009101 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009102#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009103 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009104 path = oldpath;
9105 nargv = parse_command_args(argv, &path);
9106 if (!nargv)
9107 break;
9108 argc -= nargv - argv;
9109 argv = nargv;
9110 cmd_flag |= DO_NOFUNC;
9111 } else
9112#endif
9113 break;
9114 }
9115 }
9116
9117 if (status) {
9118 /* We have a redirection error. */
9119 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009120 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009121 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009122 exitstatus = status;
9123 goto out;
9124 }
9125
9126 /* Execute the command. */
9127 switch (cmdentry.cmdtype) {
9128 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009129
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009130#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009131/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9132 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009133 {
9134 /* find_command() encodes applet_no as (-2 - applet_no) */
9135 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009136 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009137 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009138 /* run <applet>_main() */
9139 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009140 break;
9141 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009142 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009143#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009144 /* Fork off a child process if necessary. */
9145 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009146 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009147 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009148 if (forkshell(jp, cmd, FORK_FG) != 0) {
9149 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009150 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009151 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009152 break;
9153 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009154 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009155 }
9156 listsetvar(varlist.list, VEXPORT|VSTACK);
9157 shellexec(argv, path, cmdentry.u.index);
9158 /* NOTREACHED */
9159
9160 case CMDBUILTIN:
9161 cmdenviron = varlist.list;
9162 if (cmdenviron) {
9163 struct strlist *list = cmdenviron;
9164 int i = VNOSET;
9165 if (spclbltin > 0 || argc == 0) {
9166 i = 0;
9167 if (cmd_is_exec && argc > 1)
9168 i = VEXPORT;
9169 }
9170 listsetvar(list, i);
9171 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009172 /* Tight loop with builtins only:
9173 * "while kill -0 $child; do true; done"
9174 * will never exit even if $child died, unless we do this
9175 * to reap the zombie and make kill detect that it's gone: */
9176 dowait(DOWAIT_NONBLOCK, NULL);
9177
Eric Andersenc470f442003-07-28 09:56:35 +00009178 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9179 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009180 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009181 if (i == EXEXIT)
9182 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009183 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009184 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009185 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009186 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009187 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009188 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009189 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009190 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009191 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009192 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009193 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009194 }
9195 break;
9196
9197 case CMDFUNCTION:
9198 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009199 /* See above for the rationale */
9200 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009201 if (evalfun(cmdentry.u.func, argc, argv, flags))
9202 goto raise;
9203 break;
9204 }
9205
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009206 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009207 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009208 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009209 /* dsl: I think this is intended to be used to support
9210 * '_' in 'vi' command mode during line editing...
9211 * However I implemented that within libedit itself.
9212 */
9213 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009214 }
Eric Andersenc470f442003-07-28 09:56:35 +00009215 popstackmark(&smark);
9216}
9217
9218static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009219evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9220{
Eric Andersenc470f442003-07-28 09:56:35 +00009221 char *volatile savecmdname;
9222 struct jmploc *volatile savehandler;
9223 struct jmploc jmploc;
9224 int i;
9225
9226 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009227 i = setjmp(jmploc.loc);
9228 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009229 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009230 savehandler = exception_handler;
9231 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009232 commandname = argv[0];
9233 argptr = argv + 1;
9234 optptr = NULL; /* initialize nextopt */
9235 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009236 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009237 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009238 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009239 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009240 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009241 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009242
9243 return i;
9244}
9245
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009246static int
9247goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009248{
9249 return !*endofname(p);
9250}
9251
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009252
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009253/*
9254 * Search for a command. This is called before we fork so that the
9255 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009256 * the child. The check for "goodname" is an overly conservative
9257 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009258 */
Eric Andersenc470f442003-07-28 09:56:35 +00009259static void
9260prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009261{
9262 struct cmdentry entry;
9263
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009264 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9265 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009266}
9267
Eric Andersencb57d552001-06-28 07:25:16 +00009268
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009269/* ============ Builtin commands
9270 *
9271 * Builtin commands whose functions are closely tied to evaluation
9272 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009273 */
9274
9275/*
Eric Andersencb57d552001-06-28 07:25:16 +00009276 * Handle break and continue commands. Break, continue, and return are
9277 * all handled by setting the evalskip flag. The evaluation routines
9278 * above all check this flag, and if it is set they start skipping
9279 * commands rather than executing them. The variable skipcount is
9280 * the number of loops to break/continue, or the number of function
9281 * levels to return. (The latter is always 1.) It should probably
9282 * be an error to break out of more loops than exist, but it isn't
9283 * in the standard shell so we don't make it one here.
9284 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009285static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009286breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009287{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009288 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009289
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009290 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009291 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009292 if (n > loopnest)
9293 n = loopnest;
9294 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009295 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009296 skipcount = n;
9297 }
9298 return 0;
9299}
9300
Eric Andersenc470f442003-07-28 09:56:35 +00009301
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009302/* ============ input.c
9303 *
Eric Andersen90898442003-08-06 11:20:52 +00009304 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009305 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009306
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009307enum {
9308 INPUT_PUSH_FILE = 1,
9309 INPUT_NOFILE_OK = 2,
9310};
Eric Andersencb57d552001-06-28 07:25:16 +00009311
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009312static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009313/* values of checkkwd variable */
9314#define CHKALIAS 0x1
9315#define CHKKWD 0x2
9316#define CHKNL 0x4
9317
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009318/*
9319 * Push a string back onto the input at this current parsefile level.
9320 * We handle aliases this way.
9321 */
9322#if !ENABLE_ASH_ALIAS
9323#define pushstring(s, ap) pushstring(s)
9324#endif
9325static void
9326pushstring(char *s, struct alias *ap)
9327{
9328 struct strpush *sp;
9329 int len;
9330
9331 len = strlen(s);
9332 INT_OFF;
9333 if (g_parsefile->strpush) {
9334 sp = ckzalloc(sizeof(*sp));
9335 sp->prev = g_parsefile->strpush;
9336 } else {
9337 sp = &(g_parsefile->basestrpush);
9338 }
9339 g_parsefile->strpush = sp;
9340 sp->prev_string = g_parsefile->next_to_pgetc;
9341 sp->prev_left_in_line = g_parsefile->left_in_line;
9342#if ENABLE_ASH_ALIAS
9343 sp->ap = ap;
9344 if (ap) {
9345 ap->flag |= ALIASINUSE;
9346 sp->string = s;
9347 }
9348#endif
9349 g_parsefile->next_to_pgetc = s;
9350 g_parsefile->left_in_line = len;
9351 INT_ON;
9352}
9353
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009354static void
9355popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009356{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009357 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009358
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009359 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009360#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009361 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009362 if (g_parsefile->next_to_pgetc[-1] == ' '
9363 || g_parsefile->next_to_pgetc[-1] == '\t'
9364 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009365 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009366 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009367 if (sp->string != sp->ap->val) {
9368 free(sp->string);
9369 }
9370 sp->ap->flag &= ~ALIASINUSE;
9371 if (sp->ap->flag & ALIASDEAD) {
9372 unalias(sp->ap->name);
9373 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009374 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009375#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009376 g_parsefile->next_to_pgetc = sp->prev_string;
9377 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009378 g_parsefile->strpush = sp->prev;
9379 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009380 free(sp);
9381 INT_ON;
9382}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009383
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009384//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9385//it peeks whether it is &>, and then pushes back both chars.
9386//This function needs to save last *next_to_pgetc to buf[0]
9387//to make two pungetc() reliable. Currently,
9388// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009389static int
9390preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009391{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009392 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009393 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009394
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009395 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009396#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009397 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009398 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009399 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009400 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009401#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009402 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009403#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009404 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9405 if (nr == 0) {
9406 /* Ctrl+C pressed */
9407 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009408 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009409 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009410 raise(SIGINT);
9411 return 1;
9412 }
Eric Andersenc470f442003-07-28 09:56:35 +00009413 goto retry;
9414 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009415 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009416 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009417 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009418 }
Eric Andersencb57d552001-06-28 07:25:16 +00009419 }
9420#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009421 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009422#endif
9423
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009424#if 0
9425/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009426 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009427 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009428 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009429 if (flags >= 0 && (flags & O_NONBLOCK)) {
9430 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009431 if (fcntl(0, F_SETFL, flags) >= 0) {
9432 out2str("sh: turning off NDELAY mode\n");
9433 goto retry;
9434 }
9435 }
9436 }
9437 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009438#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009439 return nr;
9440}
9441
9442/*
9443 * Refill the input buffer and return the next input character:
9444 *
9445 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009446 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9447 * or we are reading from a string so we can't refill the buffer,
9448 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009449 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009450 * 4) Process input up to the next newline, deleting nul characters.
9451 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009452//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9453#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009454/*
9455 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9456 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9457 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9458 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9459 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009460static int
Eric Andersenc470f442003-07-28 09:56:35 +00009461preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009462{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009463 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009464 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009465
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009466 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009467#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009468 if (g_parsefile->left_in_line == -1
9469 && g_parsefile->strpush->ap
9470 && g_parsefile->next_to_pgetc[-1] != ' '
9471 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009472 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009473 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009474 return PEOA;
9475 }
Eric Andersen2870d962001-07-02 17:27:21 +00009476#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009477 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009478 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009479 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9480 g_parsefile->left_in_line,
9481 g_parsefile->next_to_pgetc,
9482 g_parsefile->next_to_pgetc);
9483 if (--g_parsefile->left_in_line >= 0)
9484 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009485 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009486 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009487 * "pgetc" needs refilling.
9488 */
9489
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009490 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009491 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009492 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009493 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009494 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009495 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 /* even in failure keep left_in_line and next_to_pgetc
9497 * in lock step, for correct multi-layer pungetc.
9498 * left_in_line was decremented before preadbuffer(),
9499 * must inc next_to_pgetc: */
9500 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009501 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009502 }
Eric Andersencb57d552001-06-28 07:25:16 +00009503
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009504 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009505 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009506 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009507 again:
9508 more = preadfd();
9509 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009510 /* don't try reading again */
9511 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009512 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009513 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009514 return PEOF;
9515 }
9516 }
9517
Denis Vlasenko727752d2008-11-28 03:41:47 +00009518 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009519 * Set g_parsefile->left_in_line
9520 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009521 * NUL chars are deleted.
9522 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009523 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009524 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009525 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009526
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009527 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009528
Denis Vlasenko727752d2008-11-28 03:41:47 +00009529 c = *q;
9530 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009531 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009532 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009533 q++;
9534 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009536 break;
9537 }
Eric Andersencb57d552001-06-28 07:25:16 +00009538 }
9539
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009540 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009541 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9542 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009543 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009544 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009545 }
9546 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009547 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009548
Eric Andersencb57d552001-06-28 07:25:16 +00009549 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009550 char save = *q;
9551 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009553 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009554 }
9555
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009556 pgetc_debug("preadbuffer at %d:%p'%s'",
9557 g_parsefile->left_in_line,
9558 g_parsefile->next_to_pgetc,
9559 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009560 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009561}
9562
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009563#define pgetc_as_macro() \
9564 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009565 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009566 : preadbuffer() \
9567 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009568
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009569static int
9570pgetc(void)
9571{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009572 pgetc_debug("pgetc_fast at %d:%p'%s'",
9573 g_parsefile->left_in_line,
9574 g_parsefile->next_to_pgetc,
9575 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009576 return pgetc_as_macro();
9577}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009578
9579#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009580#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009582#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009583#endif
9584
9585/*
9586 * Same as pgetc(), but ignores PEOA.
9587 */
9588#if ENABLE_ASH_ALIAS
9589static int
9590pgetc2(void)
9591{
9592 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009593 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009594 pgetc_debug("pgetc_fast at %d:%p'%s'",
9595 g_parsefile->left_in_line,
9596 g_parsefile->next_to_pgetc,
9597 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009598 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009599 } while (c == PEOA);
9600 return c;
9601}
9602#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009603#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009604#endif
9605
9606/*
9607 * Read a line from the script.
9608 */
9609static char *
9610pfgets(char *line, int len)
9611{
9612 char *p = line;
9613 int nleft = len;
9614 int c;
9615
9616 while (--nleft > 0) {
9617 c = pgetc2();
9618 if (c == PEOF) {
9619 if (p == line)
9620 return NULL;
9621 break;
9622 }
9623 *p++ = c;
9624 if (c == '\n')
9625 break;
9626 }
9627 *p = '\0';
9628 return line;
9629}
9630
Eric Andersenc470f442003-07-28 09:56:35 +00009631/*
9632 * Undo the last call to pgetc. Only one character may be pushed back.
9633 * PEOF may be pushed back.
9634 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009635static void
Eric Andersenc470f442003-07-28 09:56:35 +00009636pungetc(void)
9637{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009638 g_parsefile->left_in_line++;
9639 g_parsefile->next_to_pgetc--;
9640 pgetc_debug("pushed back to %d:%p'%s'",
9641 g_parsefile->left_in_line,
9642 g_parsefile->next_to_pgetc,
9643 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009644}
9645
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009646/*
9647 * To handle the "." command, a stack of input files is used. Pushfile
9648 * adds a new entry to the stack and popfile restores the previous level.
9649 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009650static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009651pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009652{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009653 struct parsefile *pf;
9654
Denis Vlasenko597906c2008-02-20 16:38:54 +00009655 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009656 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009657 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009658 /*pf->strpush = NULL; - ckzalloc did it */
9659 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009660 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009661}
9662
9663static void
9664popfile(void)
9665{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009666 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009667
Denis Vlasenkob012b102007-02-19 22:43:01 +00009668 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009669 if (pf->fd >= 0)
9670 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009671 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009672 while (pf->strpush)
9673 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009674 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009675 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009676 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009677}
9678
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009679/*
9680 * Return to top level.
9681 */
9682static void
9683popallfiles(void)
9684{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009685 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009686 popfile();
9687}
9688
9689/*
9690 * Close the file(s) that the shell is reading commands from. Called
9691 * after a fork is done.
9692 */
9693static void
9694closescript(void)
9695{
9696 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009697 if (g_parsefile->fd > 0) {
9698 close(g_parsefile->fd);
9699 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009700 }
9701}
9702
9703/*
9704 * Like setinputfile, but takes an open file descriptor. Call this with
9705 * interrupts off.
9706 */
9707static void
9708setinputfd(int fd, int push)
9709{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009710 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009711 if (push) {
9712 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009713 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009714 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009715 g_parsefile->fd = fd;
9716 if (g_parsefile->buf == NULL)
9717 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009718 g_parsefile->left_in_buffer = 0;
9719 g_parsefile->left_in_line = 0;
9720 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009721}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009722
Eric Andersenc470f442003-07-28 09:56:35 +00009723/*
9724 * Set the input to take input from a file. If push is set, push the
9725 * old input onto the stack first.
9726 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009727static int
9728setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009729{
9730 int fd;
9731 int fd2;
9732
Denis Vlasenkob012b102007-02-19 22:43:01 +00009733 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009734 fd = open(fname, O_RDONLY);
9735 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009736 if (flags & INPUT_NOFILE_OK)
9737 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009738 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009739 }
Eric Andersenc470f442003-07-28 09:56:35 +00009740 if (fd < 10) {
9741 fd2 = copyfd(fd, 10);
9742 close(fd);
9743 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009744 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009745 fd = fd2;
9746 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009747 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009748 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009749 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009750 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009751}
9752
Eric Andersencb57d552001-06-28 07:25:16 +00009753/*
9754 * Like setinputfile, but takes input from a string.
9755 */
Eric Andersenc470f442003-07-28 09:56:35 +00009756static void
9757setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009758{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009759 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009760 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009761 g_parsefile->next_to_pgetc = string;
9762 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009763 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009764 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009765 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009766}
9767
9768
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009769/* ============ mail.c
9770 *
9771 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009772 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009773
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009774#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009775
Eric Andersencb57d552001-06-28 07:25:16 +00009776#define MAXMBOXES 10
9777
Eric Andersenc470f442003-07-28 09:56:35 +00009778/* times of mailboxes */
9779static time_t mailtime[MAXMBOXES];
9780/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009781static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009782
Eric Andersencb57d552001-06-28 07:25:16 +00009783/*
Eric Andersenc470f442003-07-28 09:56:35 +00009784 * Print appropriate message(s) if mail has arrived.
9785 * If mail_var_path_changed is set,
9786 * then the value of MAIL has mail_var_path_changed,
9787 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009788 */
Eric Andersenc470f442003-07-28 09:56:35 +00009789static void
9790chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009791{
Eric Andersencb57d552001-06-28 07:25:16 +00009792 const char *mpath;
9793 char *p;
9794 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009795 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009796 struct stackmark smark;
9797 struct stat statb;
9798
Eric Andersencb57d552001-06-28 07:25:16 +00009799 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009800 mpath = mpathset() ? mpathval() : mailval();
9801 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009802 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009803 if (p == NULL)
9804 break;
9805 if (*p == '\0')
9806 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009807 for (q = p; *q; q++)
9808 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009809#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009810 if (q[-1] != '/')
9811 abort();
9812#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009813 q[-1] = '\0'; /* delete trailing '/' */
9814 if (stat(p, &statb) < 0) {
9815 *mtp = 0;
9816 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009817 }
Eric Andersenc470f442003-07-28 09:56:35 +00009818 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9819 fprintf(
9820 stderr, snlfmt,
9821 pathopt ? pathopt : "you have mail"
9822 );
9823 }
9824 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009825 }
Eric Andersenc470f442003-07-28 09:56:35 +00009826 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009827 popstackmark(&smark);
9828}
Eric Andersencb57d552001-06-28 07:25:16 +00009829
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009830static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009831changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009832{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009833 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009834}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009835
Denis Vlasenko131ae172007-02-18 13:00:19 +00009836#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009837
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009838
9839/* ============ ??? */
9840
Eric Andersencb57d552001-06-28 07:25:16 +00009841/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009842 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009843 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009844static void
9845setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009846{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009847 char **newparam;
9848 char **ap;
9849 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009850
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009851 for (nparam = 0; argv[nparam]; nparam++)
9852 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009853 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9854 while (*argv) {
9855 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009856 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009857 *ap = NULL;
9858 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009859 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009860 shellparam.nparam = nparam;
9861 shellparam.p = newparam;
9862#if ENABLE_ASH_GETOPTS
9863 shellparam.optind = 1;
9864 shellparam.optoff = -1;
9865#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009866}
9867
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009868/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009869 * Process shell options. The global variable argptr contains a pointer
9870 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009871 *
9872 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9873 * For a non-interactive shell, an error condition encountered
9874 * by a special built-in ... shall cause the shell to write a diagnostic message
9875 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009876 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009877 * ...
9878 * Utility syntax error (option or operand error) Shall exit
9879 * ...
9880 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9881 * we see that bash does not do that (set "finishes" with error code 1 instead,
9882 * and shell continues), and people rely on this behavior!
9883 * Testcase:
9884 * set -o barfoo 2>/dev/null
9885 * echo $?
9886 *
9887 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009888 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009889static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009890plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009891{
9892 int i;
9893
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009894 if (name) {
9895 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009896 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009897 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009898 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009899 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009900 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009901 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009902 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009903 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009904 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009905 if (val) {
9906 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9907 } else {
9908 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9909 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009910 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009911 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009912}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009913static void
9914setoption(int flag, int val)
9915{
9916 int i;
9917
9918 for (i = 0; i < NOPTS; i++) {
9919 if (optletters(i) == flag) {
9920 optlist[i] = val;
9921 return;
9922 }
9923 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009924 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009925 /* NOTREACHED */
9926}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009927static int
Eric Andersenc470f442003-07-28 09:56:35 +00009928options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009929{
9930 char *p;
9931 int val;
9932 int c;
9933
9934 if (cmdline)
9935 minusc = NULL;
9936 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009937 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009938 if (c != '-' && c != '+')
9939 break;
9940 argptr++;
9941 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009942 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009943 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009944 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009945 if (!cmdline) {
9946 /* "-" means turn off -x and -v */
9947 if (p[0] == '\0')
9948 xflag = vflag = 0;
9949 /* "--" means reset params */
9950 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009951 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009952 }
Eric Andersenc470f442003-07-28 09:56:35 +00009953 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009954 }
Eric Andersencb57d552001-06-28 07:25:16 +00009955 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009956 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009957 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009958 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009959 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009960 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009961 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009962 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009963 /* it already printed err message */
9964 return 1; /* error */
9965 }
Eric Andersencb57d552001-06-28 07:25:16 +00009966 if (*argptr)
9967 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009968 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9969 isloginsh = 1;
9970 /* bash does not accept +-login, we also won't */
9971 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009972 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009973 isloginsh = 1;
9974 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009975 } else {
9976 setoption(c, val);
9977 }
9978 }
9979 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009980 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009981}
9982
Eric Andersencb57d552001-06-28 07:25:16 +00009983/*
Eric Andersencb57d552001-06-28 07:25:16 +00009984 * The shift builtin command.
9985 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009986static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009987shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009988{
9989 int n;
9990 char **ap1, **ap2;
9991
9992 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009993 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009994 n = number(argv[1]);
9995 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009996 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009997 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009998 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009999 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010000 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010001 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010002 }
10003 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010004 while ((*ap2++ = *ap1++) != NULL)
10005 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010006#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010007 shellparam.optind = 1;
10008 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010009#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010010 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010011 return 0;
10012}
10013
Eric Andersencb57d552001-06-28 07:25:16 +000010014/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010015 * POSIX requires that 'set' (but not export or readonly) output the
10016 * variables in lexicographic order - by the locale's collating order (sigh).
10017 * Maybe we could keep them in an ordered balanced binary tree
10018 * instead of hashed lists.
10019 * For now just roll 'em through qsort for printing...
10020 */
10021static int
10022showvars(const char *sep_prefix, int on, int off)
10023{
10024 const char *sep;
10025 char **ep, **epend;
10026
10027 ep = listvars(on, off, &epend);
10028 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10029
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010030 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010031
10032 for (; ep < epend; ep++) {
10033 const char *p;
10034 const char *q;
10035
10036 p = strchrnul(*ep, '=');
10037 q = nullstr;
10038 if (*p)
10039 q = single_quote(++p);
10040 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10041 }
10042 return 0;
10043}
10044
10045/*
Eric Andersencb57d552001-06-28 07:25:16 +000010046 * The set command builtin.
10047 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010048static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010049setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010050{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010051 int retval;
10052
Denis Vlasenko68404f12008-03-17 09:00:54 +000010053 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010054 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010055 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010056 retval = 1;
10057 if (!options(0)) { /* if no parse error... */
10058 retval = 0;
10059 optschanged();
10060 if (*argptr != NULL) {
10061 setparam(argptr);
10062 }
Eric Andersencb57d552001-06-28 07:25:16 +000010063 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010064 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010065 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010066}
10067
Denis Vlasenko131ae172007-02-18 13:00:19 +000010068#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010069static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010070change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010071{
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010072 /* Galois LFSR parameter */
10073 /* Taps at 32 31 29 1: */
10074 enum { MASK = 0x8000000b };
10075 /* Another example - taps at 32 31 30 10: */
10076 /* MASK = 0x00400007 */
10077
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010078 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010079 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010080 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010081
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010082 /* LCG has period of 2^32 and alternating lowest bit */
10083 random_LCG = 1664525 * random_LCG + 1013904223;
10084 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10085 t = (random_galois_LFSR << 1);
10086 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10087 t ^= MASK;
10088 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010089 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010090 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010091 * for $RANDOM range. Combining with subtraction is
10092 * just for fun. + and ^ would work equally well. */
10093 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010094 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010095 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010096 vrandom.flags &= ~VNOFUNC;
10097 } else {
10098 /* set/reset */
Denys Vlasenko1f27ab02009-09-23 17:17:53 +020010099 random_galois_LFSR = random_LCG = strtoul(value, NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010100 }
Eric Andersenef02f822004-03-11 13:34:24 +000010101}
Eric Andersen16767e22004-03-16 05:14:10 +000010102#endif
10103
Denis Vlasenko131ae172007-02-18 13:00:19 +000010104#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010105static int
Eric Andersenc470f442003-07-28 09:56:35 +000010106getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010107{
10108 char *p, *q;
10109 char c = '?';
10110 int done = 0;
10111 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010112 char s[12];
10113 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010114
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010115 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010116 return 1;
10117 optnext = optfirst + *param_optind - 1;
10118
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010119 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010120 p = NULL;
10121 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010122 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010123 if (p == NULL || *p == '\0') {
10124 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010125 p = *optnext;
10126 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010127 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010128 p = NULL;
10129 done = 1;
10130 goto out;
10131 }
10132 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010133 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010134 goto atend;
10135 }
10136
10137 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010138 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010139 if (*q == '\0') {
10140 if (optstr[0] == ':') {
10141 s[0] = c;
10142 s[1] = '\0';
10143 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010144 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010145 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010146 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010147 }
10148 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010149 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010150 }
10151 if (*++q == ':')
10152 q++;
10153 }
10154
10155 if (*++q == ':') {
10156 if (*p == '\0' && (p = *optnext) == NULL) {
10157 if (optstr[0] == ':') {
10158 s[0] = c;
10159 s[1] = '\0';
10160 err |= setvarsafe("OPTARG", s, 0);
10161 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010162 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010163 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010164 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010165 c = '?';
10166 }
Eric Andersenc470f442003-07-28 09:56:35 +000010167 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010168 }
10169
10170 if (p == *optnext)
10171 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010172 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010173 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010174 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010175 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010176 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010177 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010178 *param_optind = optnext - optfirst + 1;
10179 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010180 err |= setvarsafe("OPTIND", s, VNOFUNC);
10181 s[0] = c;
10182 s[1] = '\0';
10183 err |= setvarsafe(optvar, s, 0);
10184 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010185 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010186 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010187 flush_stdout_stderr();
10188 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010189 }
10190 return done;
10191}
Eric Andersenc470f442003-07-28 09:56:35 +000010192
10193/*
10194 * The getopts builtin. Shellparam.optnext points to the next argument
10195 * to be processed. Shellparam.optptr points to the next character to
10196 * be processed in the current argument. If shellparam.optnext is NULL,
10197 * then it's the first time getopts has been called.
10198 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010199static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010200getoptscmd(int argc, char **argv)
10201{
10202 char **optbase;
10203
10204 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010205 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010206 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010207 optbase = shellparam.p;
10208 if (shellparam.optind > shellparam.nparam + 1) {
10209 shellparam.optind = 1;
10210 shellparam.optoff = -1;
10211 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010212 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010213 optbase = &argv[3];
10214 if (shellparam.optind > argc - 2) {
10215 shellparam.optind = 1;
10216 shellparam.optoff = -1;
10217 }
10218 }
10219
10220 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010221 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010222}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010223#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010224
Eric Andersencb57d552001-06-28 07:25:16 +000010225
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010226/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010227
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010228struct heredoc {
10229 struct heredoc *next; /* next here document in list */
10230 union node *here; /* redirection node */
10231 char *eofmark; /* string indicating end of input */
10232 smallint striptabs; /* if set, strip leading tabs */
10233};
10234
10235static smallint tokpushback; /* last token pushed back */
10236static smallint parsebackquote; /* nonzero if we are inside backquotes */
10237static smallint quoteflag; /* set if (part of) last token was quoted */
10238static token_id_t lasttoken; /* last token read (integer id Txxx) */
10239static struct heredoc *heredoclist; /* list of here documents to read */
10240static char *wordtext; /* text of last word returned by readtoken */
10241static struct nodelist *backquotelist;
10242static union node *redirnode;
10243static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010244
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010245/*
10246 * Called when an unexpected token is read during the parse. The argument
10247 * is the token that is expected, or -1 if more than one type of token can
10248 * occur at this point.
10249 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010250static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010251static void
10252raise_error_unexpected_syntax(int token)
10253{
10254 char msg[64];
10255 int l;
10256
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010257 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010258 if (token >= 0)
10259 sprintf(msg + l, " (expecting %s)", tokname(token));
10260 raise_error_syntax(msg);
10261 /* NOTREACHED */
10262}
Eric Andersencb57d552001-06-28 07:25:16 +000010263
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010264#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010265
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010266/* parsing is heavily cross-recursive, need these forward decls */
10267static union node *andor(void);
10268static union node *pipeline(void);
10269static union node *parse_command(void);
10270static void parseheredoc(void);
10271static char peektoken(void);
10272static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010273
Eric Andersenc470f442003-07-28 09:56:35 +000010274static union node *
10275list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010276{
10277 union node *n1, *n2, *n3;
10278 int tok;
10279
Eric Andersenc470f442003-07-28 09:56:35 +000010280 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10281 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010282 return NULL;
10283 n1 = NULL;
10284 for (;;) {
10285 n2 = andor();
10286 tok = readtoken();
10287 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010288 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010289 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010290 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010291 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010292 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010293 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010294 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010295 n2 = n3;
10296 }
10297 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010298 }
10299 }
10300 if (n1 == NULL) {
10301 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010302 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010303 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010304 n3->type = NSEMI;
10305 n3->nbinary.ch1 = n1;
10306 n3->nbinary.ch2 = n2;
10307 n1 = n3;
10308 }
10309 switch (tok) {
10310 case TBACKGND:
10311 case TSEMI:
10312 tok = readtoken();
10313 /* fall through */
10314 case TNL:
10315 if (tok == TNL) {
10316 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010317 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010318 return n1;
10319 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010320 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010321 }
Eric Andersenc470f442003-07-28 09:56:35 +000010322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010323 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010324 return n1;
10325 break;
10326 case TEOF:
10327 if (heredoclist)
10328 parseheredoc();
10329 else
Eric Andersenc470f442003-07-28 09:56:35 +000010330 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010331 return n1;
10332 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010333 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010334 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010335 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010336 return n1;
10337 }
10338 }
10339}
10340
Eric Andersenc470f442003-07-28 09:56:35 +000010341static union node *
10342andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010343{
Eric Andersencb57d552001-06-28 07:25:16 +000010344 union node *n1, *n2, *n3;
10345 int t;
10346
Eric Andersencb57d552001-06-28 07:25:16 +000010347 n1 = pipeline();
10348 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010349 t = readtoken();
10350 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010351 t = NAND;
10352 } else if (t == TOR) {
10353 t = NOR;
10354 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010355 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010356 return n1;
10357 }
Eric Andersenc470f442003-07-28 09:56:35 +000010358 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010359 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010360 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010361 n3->type = t;
10362 n3->nbinary.ch1 = n1;
10363 n3->nbinary.ch2 = n2;
10364 n1 = n3;
10365 }
10366}
10367
Eric Andersenc470f442003-07-28 09:56:35 +000010368static union node *
10369pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010370{
Eric Andersencb57d552001-06-28 07:25:16 +000010371 union node *n1, *n2, *pipenode;
10372 struct nodelist *lp, *prev;
10373 int negate;
10374
10375 negate = 0;
10376 TRACE(("pipeline: entered\n"));
10377 if (readtoken() == TNOT) {
10378 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010379 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010380 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010381 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010382 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010383 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010384 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010385 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010386 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010387 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010388 pipenode->npipe.cmdlist = lp;
10389 lp->n = n1;
10390 do {
10391 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010392 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010393 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010394 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010395 prev->next = lp;
10396 } while (readtoken() == TPIPE);
10397 lp->next = NULL;
10398 n1 = pipenode;
10399 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010400 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010401 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010402 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010403 n2->type = NNOT;
10404 n2->nnot.com = n1;
10405 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010406 }
10407 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010408}
10409
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010410static union node *
10411makename(void)
10412{
10413 union node *n;
10414
Denis Vlasenko597906c2008-02-20 16:38:54 +000010415 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010417 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010418 n->narg.text = wordtext;
10419 n->narg.backquote = backquotelist;
10420 return n;
10421}
10422
10423static void
10424fixredir(union node *n, const char *text, int err)
10425{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010426 int fd;
10427
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010428 TRACE(("Fix redir %s %d\n", text, err));
10429 if (!err)
10430 n->ndup.vname = NULL;
10431
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010432 fd = bb_strtou(text, NULL, 10);
10433 if (!errno && fd >= 0)
10434 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010435 else if (LONE_DASH(text))
10436 n->ndup.dupfd = -1;
10437 else {
10438 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010439 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010440 n->ndup.vname = makename();
10441 }
10442}
10443
10444/*
10445 * Returns true if the text contains nothing to expand (no dollar signs
10446 * or backquotes).
10447 */
10448static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010449noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010451 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010452 char c;
10453
10454 p = text;
10455 while ((c = *p++) != '\0') {
10456 if (c == CTLQUOTEMARK)
10457 continue;
10458 if (c == CTLESC)
10459 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010460 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010461 return 0;
10462 }
10463 return 1;
10464}
10465
10466static void
10467parsefname(void)
10468{
10469 union node *n = redirnode;
10470
10471 if (readtoken() != TWORD)
10472 raise_error_unexpected_syntax(-1);
10473 if (n->type == NHERE) {
10474 struct heredoc *here = heredoc;
10475 struct heredoc *p;
10476 int i;
10477
10478 if (quoteflag == 0)
10479 n->type = NXHERE;
10480 TRACE(("Here document %d\n", n->type));
10481 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010482 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010483 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484 here->eofmark = wordtext;
10485 here->next = NULL;
10486 if (heredoclist == NULL)
10487 heredoclist = here;
10488 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010489 for (p = heredoclist; p->next; p = p->next)
10490 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010491 p->next = here;
10492 }
10493 } else if (n->type == NTOFD || n->type == NFROMFD) {
10494 fixredir(n, wordtext, 0);
10495 } else {
10496 n->nfile.fname = makename();
10497 }
10498}
Eric Andersencb57d552001-06-28 07:25:16 +000010499
Eric Andersenc470f442003-07-28 09:56:35 +000010500static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010501simplecmd(void)
10502{
10503 union node *args, **app;
10504 union node *n = NULL;
10505 union node *vars, **vpp;
10506 union node **rpp, *redir;
10507 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010508#if ENABLE_ASH_BASH_COMPAT
10509 smallint double_brackets_flag = 0;
10510#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010511
10512 args = NULL;
10513 app = &args;
10514 vars = NULL;
10515 vpp = &vars;
10516 redir = NULL;
10517 rpp = &redir;
10518
10519 savecheckkwd = CHKALIAS;
10520 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010521 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010522 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010523 t = readtoken();
10524 switch (t) {
10525#if ENABLE_ASH_BASH_COMPAT
10526 case TAND: /* "&&" */
10527 case TOR: /* "||" */
10528 if (!double_brackets_flag) {
10529 tokpushback = 1;
10530 goto out;
10531 }
10532 wordtext = (char *) (t == TAND ? "-a" : "-o");
10533#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010535 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010536 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010537 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010538 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010539#if ENABLE_ASH_BASH_COMPAT
10540 if (strcmp("[[", wordtext) == 0)
10541 double_brackets_flag = 1;
10542 else if (strcmp("]]", wordtext) == 0)
10543 double_brackets_flag = 0;
10544#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010545 n->narg.backquote = backquotelist;
10546 if (savecheckkwd && isassignment(wordtext)) {
10547 *vpp = n;
10548 vpp = &n->narg.next;
10549 } else {
10550 *app = n;
10551 app = &n->narg.next;
10552 savecheckkwd = 0;
10553 }
10554 break;
10555 case TREDIR:
10556 *rpp = n = redirnode;
10557 rpp = &n->nfile.next;
10558 parsefname(); /* read name of redirection file */
10559 break;
10560 case TLP:
10561 if (args && app == &args->narg.next
10562 && !vars && !redir
10563 ) {
10564 struct builtincmd *bcmd;
10565 const char *name;
10566
10567 /* We have a function */
10568 if (readtoken() != TRP)
10569 raise_error_unexpected_syntax(TRP);
10570 name = n->narg.text;
10571 if (!goodname(name)
10572 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10573 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010574 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010575 }
10576 n->type = NDEFUN;
10577 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10578 n->narg.next = parse_command();
10579 return n;
10580 }
10581 /* fall through */
10582 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010583 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010584 goto out;
10585 }
10586 }
10587 out:
10588 *app = NULL;
10589 *vpp = NULL;
10590 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010591 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010592 n->type = NCMD;
10593 n->ncmd.args = args;
10594 n->ncmd.assign = vars;
10595 n->ncmd.redirect = redir;
10596 return n;
10597}
10598
10599static union node *
10600parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010601{
Eric Andersencb57d552001-06-28 07:25:16 +000010602 union node *n1, *n2;
10603 union node *ap, **app;
10604 union node *cp, **cpp;
10605 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010606 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010607 int t;
10608
10609 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010610 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010611
Eric Andersencb57d552001-06-28 07:25:16 +000010612 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010613 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010614 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010615 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010616 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010617 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n1->type = NIF;
10619 n1->nif.test = list(0);
10620 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010621 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010622 n1->nif.ifpart = list(0);
10623 n2 = n1;
10624 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010625 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010626 n2 = n2->nif.elsepart;
10627 n2->type = NIF;
10628 n2->nif.test = list(0);
10629 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010630 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010631 n2->nif.ifpart = list(0);
10632 }
10633 if (lasttoken == TELSE)
10634 n2->nif.elsepart = list(0);
10635 else {
10636 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010637 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010638 }
Eric Andersenc470f442003-07-28 09:56:35 +000010639 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010640 break;
10641 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010642 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010643 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010644 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010645 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010646 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010647 got = readtoken();
10648 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010649 TRACE(("expecting DO got %s %s\n", tokname(got),
10650 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010652 }
10653 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010654 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010655 break;
10656 }
10657 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010658 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010659 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010660 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010661 n1->type = NFOR;
10662 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010663 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010664 if (readtoken() == TIN) {
10665 app = &ap;
10666 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010667 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010668 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010669 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010670 n2->narg.text = wordtext;
10671 n2->narg.backquote = backquotelist;
10672 *app = n2;
10673 app = &n2->narg.next;
10674 }
10675 *app = NULL;
10676 n1->nfor.args = ap;
10677 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010678 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010679 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010681 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010682 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010683 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010684 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010685 n1->nfor.args = n2;
10686 /*
10687 * Newline or semicolon here is optional (but note
10688 * that the original Bourne shell only allowed NL).
10689 */
10690 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010691 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010692 }
Eric Andersenc470f442003-07-28 09:56:35 +000010693 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010694 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010695 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010696 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010697 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010698 break;
10699 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010700 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010701 n1->type = NCASE;
10702 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010703 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010704 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010705 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010706 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010707 n2->narg.text = wordtext;
10708 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010710 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010711 } while (readtoken() == TNL);
10712 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010713 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010714 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010715 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010716 checkkwd = CHKNL | CHKKWD;
10717 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010718 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010719 if (lasttoken == TLP)
10720 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010721 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010722 cp->type = NCLIST;
10723 app = &cp->nclist.pattern;
10724 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010725 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010726 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010727 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010728 ap->narg.text = wordtext;
10729 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010730 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010731 break;
10732 app = &ap->narg.next;
10733 readtoken();
10734 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010735 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010736 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010737 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010738 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010739
Eric Andersenc470f442003-07-28 09:56:35 +000010740 cpp = &cp->nclist.next;
10741
10742 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010743 t = readtoken();
10744 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010745 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010746 raise_error_unexpected_syntax(TENDCASE);
10747 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010748 }
Eric Andersenc470f442003-07-28 09:56:35 +000010749 }
Eric Andersencb57d552001-06-28 07:25:16 +000010750 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010751 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010752 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010753 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010754 n1->type = NSUBSHELL;
10755 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010756 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010757 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010758 break;
10759 case TBEGIN:
10760 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010761 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010762 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010763 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010764 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010765 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010766 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010767 }
10768
Eric Andersenc470f442003-07-28 09:56:35 +000010769 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010770 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010771
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010772 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010773 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010774 checkkwd = CHKKWD | CHKALIAS;
10775 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010776 while (readtoken() == TREDIR) {
10777 *rpp = n2 = redirnode;
10778 rpp = &n2->nfile.next;
10779 parsefname();
10780 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010781 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 *rpp = NULL;
10783 if (redir) {
10784 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010785 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010786 n2->type = NREDIR;
10787 n2->nredir.n = n1;
10788 n1 = n2;
10789 }
10790 n1->nredir.redirect = redir;
10791 }
Eric Andersencb57d552001-06-28 07:25:16 +000010792 return n1;
10793}
10794
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010795#if ENABLE_ASH_BASH_COMPAT
10796static int decode_dollar_squote(void)
10797{
10798 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10799 int c, cnt;
10800 char *p;
10801 char buf[4];
10802
10803 c = pgetc();
10804 p = strchr(C_escapes, c);
10805 if (p) {
10806 buf[0] = c;
10807 p = buf;
10808 cnt = 3;
10809 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10810 do {
10811 c = pgetc();
10812 *++p = c;
10813 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10814 pungetc();
10815 } else if (c == 'x') { /* \xHH */
10816 do {
10817 c = pgetc();
10818 *++p = c;
10819 } while (isxdigit(c) && --cnt);
10820 pungetc();
10821 if (cnt == 3) { /* \x but next char is "bad" */
10822 c = 'x';
10823 goto unrecognized;
10824 }
10825 } else { /* simple seq like \\ or \t */
10826 p++;
10827 }
10828 *p = '\0';
10829 p = buf;
10830 c = bb_process_escape_sequence((void*)&p);
10831 } else { /* unrecognized "\z": print both chars unless ' or " */
10832 if (c != '\'' && c != '"') {
10833 unrecognized:
10834 c |= 0x100; /* "please encode \, then me" */
10835 }
10836 }
10837 return c;
10838}
10839#endif
10840
Eric Andersencb57d552001-06-28 07:25:16 +000010841/*
10842 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10843 * is not NULL, read a here document. In the latter case, eofmark is the
10844 * word which marks the end of the document and striptabs is true if
10845 * leading tabs should be stripped from the document. The argument firstc
10846 * is the first character of the input token or document.
10847 *
10848 * Because C does not have internal subroutines, I have simulated them
10849 * using goto's to implement the subroutine linkage. The following macros
10850 * will run code that appears at the end of readtoken1.
10851 */
Eric Andersen2870d962001-07-02 17:27:21 +000010852#define CHECKEND() {goto checkend; checkend_return:;}
10853#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10854#define PARSESUB() {goto parsesub; parsesub_return:;}
10855#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10856#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10857#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010858static int
Eric Andersenc470f442003-07-28 09:56:35 +000010859readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010860{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010861 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010862 int c = firstc;
10863 char *out;
10864 int len;
10865 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010866 struct nodelist *bqlist;
10867 smallint quotef;
10868 smallint dblquote;
10869 smallint oldstyle;
10870 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010871#if ENABLE_ASH_EXPAND_PRMT
10872 smallint pssyntax; /* we are expanding a prompt string */
10873#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010874 int varnest; /* levels of variables expansion */
10875 int arinest; /* levels of arithmetic expansion */
10876 int parenlevel; /* levels of parens in arithmetic */
10877 int dqvarnest; /* levels of variables expansion within double quotes */
10878
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010879 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010880
Eric Andersencb57d552001-06-28 07:25:16 +000010881#if __GNUC__
10882 /* Avoid longjmp clobbering */
10883 (void) &out;
10884 (void) &quotef;
10885 (void) &dblquote;
10886 (void) &varnest;
10887 (void) &arinest;
10888 (void) &parenlevel;
10889 (void) &dqvarnest;
10890 (void) &oldstyle;
10891 (void) &prevsyntax;
10892 (void) &syntax;
10893#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010894 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010895 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010896 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010897 oldstyle = 0;
10898 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010899#if ENABLE_ASH_EXPAND_PRMT
10900 pssyntax = (syntax == PSSYNTAX);
10901 if (pssyntax)
10902 syntax = DQSYNTAX;
10903#endif
10904 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010905 varnest = 0;
10906 arinest = 0;
10907 parenlevel = 0;
10908 dqvarnest = 0;
10909
10910 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010911 loop:
10912 /* For each line, until end of word */
10913 {
Eric Andersenc470f442003-07-28 09:56:35 +000010914 CHECKEND(); /* set c to PEOF if at end of here document */
10915 for (;;) { /* until end of line or end of word */
10916 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010917 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010918 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010919 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010920 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010921 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010922 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010923 if (doprompt)
10924 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010925 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010926 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010927 case CWORD:
10928 USTPUTC(c, out);
10929 break;
10930 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010931 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010932 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010933#if ENABLE_ASH_BASH_COMPAT
10934 if (c == '\\' && bash_dollar_squote) {
10935 c = decode_dollar_squote();
10936 if (c & 0x100) {
10937 USTPUTC('\\', out);
10938 c = (unsigned char)c;
10939 }
10940 }
10941#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010942 USTPUTC(c, out);
10943 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010944 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010945 c = pgetc2();
10946 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010947 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010948 USTPUTC('\\', out);
10949 pungetc();
10950 } else if (c == '\n') {
10951 if (doprompt)
10952 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010953 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010954#if ENABLE_ASH_EXPAND_PRMT
10955 if (c == '$' && pssyntax) {
10956 USTPUTC(CTLESC, out);
10957 USTPUTC('\\', out);
10958 }
10959#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010960 if (dblquote && c != '\\'
10961 && c != '`' && c != '$'
10962 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010963 ) {
10964 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010965 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010966 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010967 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010968 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010969 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010970 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010971 }
10972 break;
10973 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010974 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010975 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010976 if (eofmark == NULL) {
10977 USTPUTC(CTLQUOTEMARK, out);
10978 }
Eric Andersencb57d552001-06-28 07:25:16 +000010979 break;
10980 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010981 syntax = DQSYNTAX;
10982 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010983 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010984 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010985 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010986 if (eofmark != NULL && arinest == 0
10987 && varnest == 0
10988 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010989 USTPUTC(c, out);
10990 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010991 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010992 syntax = BASESYNTAX;
10993 dblquote = 0;
10994 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010995 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010996 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010997 }
10998 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010999 case CVAR: /* '$' */
11000 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011001 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011002 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011003 if (varnest > 0) {
11004 varnest--;
11005 if (dqvarnest > 0) {
11006 dqvarnest--;
11007 }
11008 USTPUTC(CTLENDVAR, out);
11009 } else {
11010 USTPUTC(c, out);
11011 }
11012 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011013#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011014 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011015 parenlevel++;
11016 USTPUTC(c, out);
11017 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011018 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011019 if (parenlevel > 0) {
11020 USTPUTC(c, out);
11021 --parenlevel;
11022 } else {
11023 if (pgetc() == ')') {
11024 if (--arinest == 0) {
11025 USTPUTC(CTLENDARI, out);
11026 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011027 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011028 } else
11029 USTPUTC(')', out);
11030 } else {
11031 /*
11032 * unbalanced parens
11033 * (don't 2nd guess - no error)
11034 */
11035 pungetc();
11036 USTPUTC(')', out);
11037 }
11038 }
11039 break;
11040#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011041 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011042 PARSEBACKQOLD();
11043 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011044 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011045 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011046 case CIGN:
11047 break;
11048 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011049 if (varnest == 0) {
11050#if ENABLE_ASH_BASH_COMPAT
11051 if (c == '&') {
11052 if (pgetc() == '>')
11053 c = 0x100 + '>'; /* flag &> */
11054 pungetc();
11055 }
11056#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011057 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011058 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011059#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011060 if (c != PEOA)
11061#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011062 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011063
Eric Andersencb57d552001-06-28 07:25:16 +000011064 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011065 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011066 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011067 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011068 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011069#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011070 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011071 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011072#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011073 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011074 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011075 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011076 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011077 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011078 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011079 }
11080 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011081 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011082 out = stackblock();
11083 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011084 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011085 && quotef == 0
11086 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011087 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011088 PARSEREDIR(); /* passed as params: out, c */
11089 lasttoken = TREDIR;
11090 return lasttoken;
11091 }
11092 /* else: non-number X seen, interpret it
11093 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011094 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011095 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011096 }
11097 quoteflag = quotef;
11098 backquotelist = bqlist;
11099 grabstackblock(len);
11100 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011101 lasttoken = TWORD;
11102 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011103/* end of readtoken routine */
11104
Eric Andersencb57d552001-06-28 07:25:16 +000011105/*
11106 * Check to see whether we are at the end of the here document. When this
11107 * is called, c is set to the first character of the next input line. If
11108 * we are at the end of the here document, this routine sets the c to PEOF.
11109 */
Eric Andersenc470f442003-07-28 09:56:35 +000011110checkend: {
11111 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011112#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011113 if (c == PEOA) {
11114 c = pgetc2();
11115 }
11116#endif
11117 if (striptabs) {
11118 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011119 c = pgetc2();
11120 }
Eric Andersenc470f442003-07-28 09:56:35 +000011121 }
11122 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011123 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011124 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011125
Eric Andersenc470f442003-07-28 09:56:35 +000011126 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011127 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11128 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011129 if (*p == '\n' && *q == '\0') {
11130 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011131 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011132 needprompt = doprompt;
11133 } else {
11134 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011135 }
11136 }
11137 }
11138 }
Eric Andersenc470f442003-07-28 09:56:35 +000011139 goto checkend_return;
11140}
Eric Andersencb57d552001-06-28 07:25:16 +000011141
Eric Andersencb57d552001-06-28 07:25:16 +000011142/*
11143 * Parse a redirection operator. The variable "out" points to a string
11144 * specifying the fd to be redirected. The variable "c" contains the
11145 * first character of the redirection operator.
11146 */
Eric Andersenc470f442003-07-28 09:56:35 +000011147parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011148 /* out is already checked to be a valid number or "" */
11149 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011150 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011151
Denis Vlasenko597906c2008-02-20 16:38:54 +000011152 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011153 if (c == '>') {
11154 np->nfile.fd = 1;
11155 c = pgetc();
11156 if (c == '>')
11157 np->type = NAPPEND;
11158 else if (c == '|')
11159 np->type = NCLOBBER;
11160 else if (c == '&')
11161 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011162 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011163 else {
11164 np->type = NTO;
11165 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011166 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011167 }
11168#if ENABLE_ASH_BASH_COMPAT
11169 else if (c == 0x100 + '>') { /* this flags &> redirection */
11170 np->nfile.fd = 1;
11171 pgetc(); /* this is '>', no need to check */
11172 np->type = NTO2;
11173 }
11174#endif
11175 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011176 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011177 c = pgetc();
11178 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011179 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011180 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011181 np = stzalloc(sizeof(struct nhere));
11182 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011183 }
11184 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011185 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011186 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011187 c = pgetc();
11188 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011189 heredoc->striptabs = 1;
11190 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011191 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011192 pungetc();
11193 }
11194 break;
11195
11196 case '&':
11197 np->type = NFROMFD;
11198 break;
11199
11200 case '>':
11201 np->type = NFROMTO;
11202 break;
11203
11204 default:
11205 np->type = NFROM;
11206 pungetc();
11207 break;
11208 }
Eric Andersencb57d552001-06-28 07:25:16 +000011209 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011210 if (fd >= 0)
11211 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011212 redirnode = np;
11213 goto parseredir_return;
11214}
Eric Andersencb57d552001-06-28 07:25:16 +000011215
Eric Andersencb57d552001-06-28 07:25:16 +000011216/*
11217 * Parse a substitution. At this point, we have read the dollar sign
11218 * and nothing else.
11219 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011220
11221/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11222 * (assuming ascii char codes, as the original implementation did) */
11223#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011224 (((unsigned)(c) - 33 < 32) \
11225 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011226parsesub: {
11227 int subtype;
11228 int typeloc;
11229 int flags;
11230 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011231 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011232
Eric Andersenc470f442003-07-28 09:56:35 +000011233 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011234 if (c <= PEOA_OR_PEOF
11235 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011236 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011237#if ENABLE_ASH_BASH_COMPAT
11238 if (c == '\'')
11239 bash_dollar_squote = 1;
11240 else
11241#endif
11242 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011243 pungetc();
11244 } else if (c == '(') { /* $(command) or $((arith)) */
11245 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011246#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011247 PARSEARITH();
11248#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011249 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011250#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011251 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011252 pungetc();
11253 PARSEBACKQNEW();
11254 }
11255 } else {
11256 USTPUTC(CTLVAR, out);
11257 typeloc = out - (char *)stackblock();
11258 USTPUTC(VSNORMAL, out);
11259 subtype = VSNORMAL;
11260 if (c == '{') {
11261 c = pgetc();
11262 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011263 c = pgetc();
11264 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011265 c = '#';
11266 else
11267 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011268 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011269 subtype = 0;
11270 }
11271 if (c > PEOA_OR_PEOF && is_name(c)) {
11272 do {
11273 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011274 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011275 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011276 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011277 do {
11278 STPUTC(c, out);
11279 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011280 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011281 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011282 USTPUTC(c, out);
11283 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011284 } else {
11285 badsub:
11286 raise_error_syntax("bad substitution");
11287 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011288 if (c != '}' && subtype == VSLENGTH)
11289 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011290
Eric Andersenc470f442003-07-28 09:56:35 +000011291 STPUTC('=', out);
11292 flags = 0;
11293 if (subtype == 0) {
11294 switch (c) {
11295 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011296 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011297#if ENABLE_ASH_BASH_COMPAT
11298 if (c == ':' || c == '$' || isdigit(c)) {
11299 pungetc();
11300 subtype = VSSUBSTR;
11301 break;
11302 }
11303#endif
11304 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011305 /*FALLTHROUGH*/
11306 default:
11307 p = strchr(types, c);
11308 if (p == NULL)
11309 goto badsub;
11310 subtype = p - types + VSNORMAL;
11311 break;
11312 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011313 case '#': {
11314 int cc = c;
11315 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11316 c = pgetc();
11317 if (c == cc)
11318 subtype++;
11319 else
11320 pungetc();
11321 break;
11322 }
11323#if ENABLE_ASH_BASH_COMPAT
11324 case '/':
11325 subtype = VSREPLACE;
11326 c = pgetc();
11327 if (c == '/')
11328 subtype++; /* VSREPLACEALL */
11329 else
11330 pungetc();
11331 break;
11332#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011333 }
Eric Andersenc470f442003-07-28 09:56:35 +000011334 } else {
11335 pungetc();
11336 }
11337 if (dblquote || arinest)
11338 flags |= VSQUOTE;
11339 *((char *)stackblock() + typeloc) = subtype | flags;
11340 if (subtype != VSNORMAL) {
11341 varnest++;
11342 if (dblquote || arinest) {
11343 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011344 }
11345 }
11346 }
Eric Andersenc470f442003-07-28 09:56:35 +000011347 goto parsesub_return;
11348}
Eric Andersencb57d552001-06-28 07:25:16 +000011349
Eric Andersencb57d552001-06-28 07:25:16 +000011350/*
11351 * Called to parse command substitutions. Newstyle is set if the command
11352 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11353 * list of commands (passed by reference), and savelen is the number of
11354 * characters on the top of the stack which must be preserved.
11355 */
Eric Andersenc470f442003-07-28 09:56:35 +000011356parsebackq: {
11357 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011358 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011359 union node *n;
11360 char *volatile str;
11361 struct jmploc jmploc;
11362 struct jmploc *volatile savehandler;
11363 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011364 smallint saveprompt = 0;
11365
Eric Andersencb57d552001-06-28 07:25:16 +000011366#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011367 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011368#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011369 savepbq = parsebackquote;
11370 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011371 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011372 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011373 exception_handler = savehandler;
11374 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011375 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011376 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011377 str = NULL;
11378 savelen = out - (char *)stackblock();
11379 if (savelen > 0) {
11380 str = ckmalloc(savelen);
11381 memcpy(str, stackblock(), savelen);
11382 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011383 savehandler = exception_handler;
11384 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011385 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011386 if (oldstyle) {
11387 /* We must read until the closing backquote, giving special
11388 treatment to some slashes, and then push the string and
11389 reread it as input, interpreting it normally. */
11390 char *pout;
11391 int pc;
11392 size_t psavelen;
11393 char *pstr;
11394
11395
11396 STARTSTACKSTR(pout);
11397 for (;;) {
11398 if (needprompt) {
11399 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011400 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011401 pc = pgetc();
11402 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011403 case '`':
11404 goto done;
11405
11406 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011407 pc = pgetc();
11408 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011409 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011410 if (doprompt)
11411 setprompt(2);
11412 /*
11413 * If eating a newline, avoid putting
11414 * the newline into the new character
11415 * stream (via the STPUTC after the
11416 * switch).
11417 */
11418 continue;
11419 }
11420 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011421 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011422 STPUTC('\\', pout);
11423 if (pc > PEOA_OR_PEOF) {
11424 break;
11425 }
11426 /* fall through */
11427
11428 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011429#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011430 case PEOA:
11431#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011432 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011433 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011434
11435 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011436 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011437 needprompt = doprompt;
11438 break;
11439
11440 default:
11441 break;
11442 }
11443 STPUTC(pc, pout);
11444 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011445 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011446 STPUTC('\0', pout);
11447 psavelen = pout - (char *)stackblock();
11448 if (psavelen > 0) {
11449 pstr = grabstackstr(pout);
11450 setinputstring(pstr);
11451 }
11452 }
11453 nlpp = &bqlist;
11454 while (*nlpp)
11455 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011456 *nlpp = stzalloc(sizeof(**nlpp));
11457 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011458 parsebackquote = oldstyle;
11459
11460 if (oldstyle) {
11461 saveprompt = doprompt;
11462 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011463 }
11464
Eric Andersenc470f442003-07-28 09:56:35 +000011465 n = list(2);
11466
11467 if (oldstyle)
11468 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011469 else if (readtoken() != TRP)
11470 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011471
11472 (*nlpp)->n = n;
11473 if (oldstyle) {
11474 /*
11475 * Start reading from old file again, ignoring any pushed back
11476 * tokens left from the backquote parsing
11477 */
11478 popfile();
11479 tokpushback = 0;
11480 }
11481 while (stackblocksize() <= savelen)
11482 growstackblock();
11483 STARTSTACKSTR(out);
11484 if (str) {
11485 memcpy(out, str, savelen);
11486 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011487 INT_OFF;
11488 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011489 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011490 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011491 }
11492 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011493 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011494 if (arinest || dblquote)
11495 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11496 else
11497 USTPUTC(CTLBACKQ, out);
11498 if (oldstyle)
11499 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011500 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011501}
11502
Mike Frysinger98c52642009-04-02 10:02:37 +000011503#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011504/*
11505 * Parse an arithmetic expansion (indicate start of one and set state)
11506 */
Eric Andersenc470f442003-07-28 09:56:35 +000011507parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011508 if (++arinest == 1) {
11509 prevsyntax = syntax;
11510 syntax = ARISYNTAX;
11511 USTPUTC(CTLARI, out);
11512 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011513 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011514 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011515 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011516 } else {
11517 /*
11518 * we collapse embedded arithmetic expansion to
11519 * parenthesis, which should be equivalent
11520 */
11521 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011522 }
Eric Andersenc470f442003-07-28 09:56:35 +000011523 goto parsearith_return;
11524}
11525#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011526
Eric Andersenc470f442003-07-28 09:56:35 +000011527} /* end of readtoken */
11528
Eric Andersencb57d552001-06-28 07:25:16 +000011529/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011530 * Read the next input token.
11531 * If the token is a word, we set backquotelist to the list of cmds in
11532 * backquotes. We set quoteflag to true if any part of the word was
11533 * quoted.
11534 * If the token is TREDIR, then we set redirnode to a structure containing
11535 * the redirection.
11536 * In all cases, the variable startlinno is set to the number of the line
11537 * on which the token starts.
11538 *
11539 * [Change comment: here documents and internal procedures]
11540 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11541 * word parsing code into a separate routine. In this case, readtoken
11542 * doesn't need to have any internal procedures, but parseword does.
11543 * We could also make parseoperator in essence the main routine, and
11544 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011545 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011546#define NEW_xxreadtoken
11547#ifdef NEW_xxreadtoken
11548/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011549static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011550 '\n', '(', ')', /* singles */
11551 '&', '|', ';', /* doubles */
11552 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011553};
Eric Andersencb57d552001-06-28 07:25:16 +000011554
Denis Vlasenko834dee72008-10-07 09:18:30 +000011555#define xxreadtoken_singles 3
11556#define xxreadtoken_doubles 3
11557
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011558static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011559 TNL, TLP, TRP, /* only single occurrence allowed */
11560 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11561 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011562 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011563};
11564
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011565static int
11566xxreadtoken(void)
11567{
11568 int c;
11569
11570 if (tokpushback) {
11571 tokpushback = 0;
11572 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011573 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011574 if (needprompt) {
11575 setprompt(2);
11576 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011577 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011578 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011579 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011580 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011581 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011582
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011583 if (c == '#') {
11584 while ((c = pgetc()) != '\n' && c != PEOF)
11585 continue;
11586 pungetc();
11587 } else if (c == '\\') {
11588 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011590 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011592 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011593 if (doprompt)
11594 setprompt(2);
11595 } else {
11596 const char *p;
11597
11598 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11599 if (c != PEOF) {
11600 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011601 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011602 needprompt = doprompt;
11603 }
11604
11605 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011606 if (p == NULL)
11607 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608
Denis Vlasenko834dee72008-10-07 09:18:30 +000011609 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11610 int cc = pgetc();
11611 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011612 p += xxreadtoken_doubles + 1;
11613 } else {
11614 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011615#if ENABLE_ASH_BASH_COMPAT
11616 if (c == '&' && cc == '>') /* &> */
11617 break; /* return readtoken1(...) */
11618#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011619 }
11620 }
11621 }
11622 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11623 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011625 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011626
11627 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011628}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011629#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011630#define RETURN(token) return lasttoken = token
11631static int
11632xxreadtoken(void)
11633{
11634 int c;
11635
11636 if (tokpushback) {
11637 tokpushback = 0;
11638 return lasttoken;
11639 }
11640 if (needprompt) {
11641 setprompt(2);
11642 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011643 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011644 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011645 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011646 switch (c) {
11647 case ' ': case '\t':
11648#if ENABLE_ASH_ALIAS
11649 case PEOA:
11650#endif
11651 continue;
11652 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011653 while ((c = pgetc()) != '\n' && c != PEOF)
11654 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011655 pungetc();
11656 continue;
11657 case '\\':
11658 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011659 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011660 if (doprompt)
11661 setprompt(2);
11662 continue;
11663 }
11664 pungetc();
11665 goto breakloop;
11666 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011667 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011668 needprompt = doprompt;
11669 RETURN(TNL);
11670 case PEOF:
11671 RETURN(TEOF);
11672 case '&':
11673 if (pgetc() == '&')
11674 RETURN(TAND);
11675 pungetc();
11676 RETURN(TBACKGND);
11677 case '|':
11678 if (pgetc() == '|')
11679 RETURN(TOR);
11680 pungetc();
11681 RETURN(TPIPE);
11682 case ';':
11683 if (pgetc() == ';')
11684 RETURN(TENDCASE);
11685 pungetc();
11686 RETURN(TSEMI);
11687 case '(':
11688 RETURN(TLP);
11689 case ')':
11690 RETURN(TRP);
11691 default:
11692 goto breakloop;
11693 }
11694 }
11695 breakloop:
11696 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11697#undef RETURN
11698}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011699#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011700
11701static int
11702readtoken(void)
11703{
11704 int t;
11705#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011706 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011707#endif
11708
11709#if ENABLE_ASH_ALIAS
11710 top:
11711#endif
11712
11713 t = xxreadtoken();
11714
11715 /*
11716 * eat newlines
11717 */
11718 if (checkkwd & CHKNL) {
11719 while (t == TNL) {
11720 parseheredoc();
11721 t = xxreadtoken();
11722 }
11723 }
11724
11725 if (t != TWORD || quoteflag) {
11726 goto out;
11727 }
11728
11729 /*
11730 * check for keywords
11731 */
11732 if (checkkwd & CHKKWD) {
11733 const char *const *pp;
11734
11735 pp = findkwd(wordtext);
11736 if (pp) {
11737 lasttoken = t = pp - tokname_array;
11738 TRACE(("keyword %s recognized\n", tokname(t)));
11739 goto out;
11740 }
11741 }
11742
11743 if (checkkwd & CHKALIAS) {
11744#if ENABLE_ASH_ALIAS
11745 struct alias *ap;
11746 ap = lookupalias(wordtext, 1);
11747 if (ap != NULL) {
11748 if (*ap->val) {
11749 pushstring(ap->val, ap);
11750 }
11751 goto top;
11752 }
11753#endif
11754 }
11755 out:
11756 checkkwd = 0;
11757#if DEBUG
11758 if (!alreadyseen)
11759 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11760 else
11761 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11762#endif
11763 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011764}
11765
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011766static char
11767peektoken(void)
11768{
11769 int t;
11770
11771 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011772 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773 return tokname_array[t][0];
11774}
Eric Andersencb57d552001-06-28 07:25:16 +000011775
11776/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011777 * Read and parse a command. Returns NODE_EOF on end of file.
11778 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011779 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011780static union node *
11781parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011782{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011783 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011784
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785 tokpushback = 0;
11786 doprompt = interact;
11787 if (doprompt)
11788 setprompt(doprompt);
11789 needprompt = 0;
11790 t = readtoken();
11791 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011792 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011793 if (t == TNL)
11794 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011795 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011796 return list(1);
11797}
11798
11799/*
11800 * Input any here documents.
11801 */
11802static void
11803parseheredoc(void)
11804{
11805 struct heredoc *here;
11806 union node *n;
11807
11808 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011809 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011810
11811 while (here) {
11812 if (needprompt) {
11813 setprompt(2);
11814 }
11815 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11816 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011817 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011819 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011820 n->narg.text = wordtext;
11821 n->narg.backquote = backquotelist;
11822 here->here->nhere.doc = n;
11823 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011824 }
Eric Andersencb57d552001-06-28 07:25:16 +000011825}
11826
11827
11828/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011829 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011830 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011831#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011832static const char *
11833expandstr(const char *ps)
11834{
11835 union node n;
11836
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011837 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11838 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011839 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011840 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011841 popfile();
11842
11843 n.narg.type = NARG;
11844 n.narg.next = NULL;
11845 n.narg.text = wordtext;
11846 n.narg.backquote = backquotelist;
11847
11848 expandarg(&n, NULL, 0);
11849 return stackblock();
11850}
11851#endif
11852
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011853/*
11854 * Execute a command or commands contained in a string.
11855 */
11856static int
11857evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011858{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011859 union node *n;
11860 struct stackmark smark;
11861 int skip;
11862
11863 setinputstring(s);
11864 setstackmark(&smark);
11865
11866 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011867 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011868 evaltree(n, 0);
11869 popstackmark(&smark);
11870 skip = evalskip;
11871 if (skip)
11872 break;
11873 }
11874 popfile();
11875
11876 skip &= mask;
11877 evalskip = skip;
11878 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011879}
11880
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011881/*
11882 * The eval command.
11883 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011884static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011885evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011886{
11887 char *p;
11888 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011889
Denis Vlasenko68404f12008-03-17 09:00:54 +000011890 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011891 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011892 argv += 2;
11893 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011895 for (;;) {
11896 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011897 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011898 if (p == NULL)
11899 break;
11900 STPUTC(' ', concat);
11901 }
11902 STPUTC('\0', concat);
11903 p = grabstackstr(concat);
11904 }
11905 evalstring(p, ~SKIPEVAL);
11906
11907 }
11908 return exitstatus;
11909}
11910
11911/*
11912 * Read and execute commands. "Top" is nonzero for the top level command
11913 * loop; it turns on prompting if the shell is interactive.
11914 */
11915static int
11916cmdloop(int top)
11917{
11918 union node *n;
11919 struct stackmark smark;
11920 int inter;
11921 int numeof = 0;
11922
11923 TRACE(("cmdloop(%d) called\n", top));
11924 for (;;) {
11925 int skip;
11926
11927 setstackmark(&smark);
11928#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011929 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011930 showjobs(stderr, SHOW_CHANGED);
11931#endif
11932 inter = 0;
11933 if (iflag && top) {
11934 inter++;
11935#if ENABLE_ASH_MAIL
11936 chkmail();
11937#endif
11938 }
11939 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011940#if DEBUG
11941 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011942 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011943#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011944 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011945 if (!top || numeof >= 50)
11946 break;
11947 if (!stoppedjobs()) {
11948 if (!Iflag)
11949 break;
11950 out2str("\nUse \"exit\" to leave shell.\n");
11951 }
11952 numeof++;
11953 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011954 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11955 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956 numeof = 0;
11957 evaltree(n, 0);
11958 }
11959 popstackmark(&smark);
11960 skip = evalskip;
11961
11962 if (skip) {
11963 evalskip = 0;
11964 return skip & SKIPEVAL;
11965 }
11966 }
11967 return 0;
11968}
11969
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011970/*
11971 * Take commands from a file. To be compatible we should do a path
11972 * search for the file, which is necessary to find sub-commands.
11973 */
11974static char *
11975find_dot_file(char *name)
11976{
11977 char *fullname;
11978 const char *path = pathval();
11979 struct stat statb;
11980
11981 /* don't try this for absolute or relative paths */
11982 if (strchr(name, '/'))
11983 return name;
11984
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011985 /* IIRC standards do not say whether . is to be searched.
11986 * And it is even smaller this way, making it unconditional for now:
11987 */
11988 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11989 fullname = name;
11990 goto try_cur_dir;
11991 }
11992
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011993 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011994 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011995 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11996 /*
11997 * Don't bother freeing here, since it will
11998 * be freed by the caller.
11999 */
12000 return fullname;
12001 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012002 if (fullname != name)
12003 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012004 }
12005
12006 /* not found in the PATH */
12007 ash_msg_and_raise_error("%s: not found", name);
12008 /* NOTREACHED */
12009}
12010
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012011static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012012dotcmd(int argc, char **argv)
12013{
12014 struct strlist *sp;
12015 volatile struct shparam saveparam;
12016 int status = 0;
12017
12018 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012019 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012020
Denis Vlasenko68404f12008-03-17 09:00:54 +000012021 if (argv[1]) { /* That's what SVR2 does */
12022 char *fullname = find_dot_file(argv[1]);
12023 argv += 2;
12024 argc -= 2;
12025 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012026 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012027 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012028 shellparam.nparam = argc;
12029 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012030 };
12031
12032 setinputfile(fullname, INPUT_PUSH_FILE);
12033 commandname = fullname;
12034 cmdloop(0);
12035 popfile();
12036
Denis Vlasenko68404f12008-03-17 09:00:54 +000012037 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038 freeparam(&shellparam);
12039 shellparam = saveparam;
12040 };
12041 status = exitstatus;
12042 }
12043 return status;
12044}
12045
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012046static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012047exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012048{
12049 if (stoppedjobs())
12050 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012051 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012052 exitstatus = number(argv[1]);
12053 raise_exception(EXEXIT);
12054 /* NOTREACHED */
12055}
12056
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012057/*
12058 * Read a file containing shell functions.
12059 */
12060static void
12061readcmdfile(char *name)
12062{
12063 setinputfile(name, INPUT_PUSH_FILE);
12064 cmdloop(0);
12065 popfile();
12066}
12067
12068
Denis Vlasenkocc571512007-02-23 21:10:35 +000012069/* ============ find_command inplementation */
12070
12071/*
12072 * Resolve a command name. If you change this routine, you may have to
12073 * change the shellexec routine as well.
12074 */
12075static void
12076find_command(char *name, struct cmdentry *entry, int act, const char *path)
12077{
12078 struct tblentry *cmdp;
12079 int idx;
12080 int prev;
12081 char *fullname;
12082 struct stat statb;
12083 int e;
12084 int updatetbl;
12085 struct builtincmd *bcmd;
12086
12087 /* If name contains a slash, don't use PATH or hash table */
12088 if (strchr(name, '/') != NULL) {
12089 entry->u.index = -1;
12090 if (act & DO_ABS) {
12091 while (stat(name, &statb) < 0) {
12092#ifdef SYSV
12093 if (errno == EINTR)
12094 continue;
12095#endif
12096 entry->cmdtype = CMDUNKNOWN;
12097 return;
12098 }
12099 }
12100 entry->cmdtype = CMDNORMAL;
12101 return;
12102 }
12103
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012104/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012105
12106 updatetbl = (path == pathval());
12107 if (!updatetbl) {
12108 act |= DO_ALTPATH;
12109 if (strstr(path, "%builtin") != NULL)
12110 act |= DO_ALTBLTIN;
12111 }
12112
12113 /* If name is in the table, check answer will be ok */
12114 cmdp = cmdlookup(name, 0);
12115 if (cmdp != NULL) {
12116 int bit;
12117
12118 switch (cmdp->cmdtype) {
12119 default:
12120#if DEBUG
12121 abort();
12122#endif
12123 case CMDNORMAL:
12124 bit = DO_ALTPATH;
12125 break;
12126 case CMDFUNCTION:
12127 bit = DO_NOFUNC;
12128 break;
12129 case CMDBUILTIN:
12130 bit = DO_ALTBLTIN;
12131 break;
12132 }
12133 if (act & bit) {
12134 updatetbl = 0;
12135 cmdp = NULL;
12136 } else if (cmdp->rehash == 0)
12137 /* if not invalidated by cd, we're done */
12138 goto success;
12139 }
12140
12141 /* If %builtin not in path, check for builtin next */
12142 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012143 if (bcmd) {
12144 if (IS_BUILTIN_REGULAR(bcmd))
12145 goto builtin_success;
12146 if (act & DO_ALTPATH) {
12147 if (!(act & DO_ALTBLTIN))
12148 goto builtin_success;
12149 } else if (builtinloc <= 0) {
12150 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012151 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012152 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012153
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012154#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012155 {
12156 int applet_no = find_applet_by_name(name);
12157 if (applet_no >= 0) {
12158 entry->cmdtype = CMDNORMAL;
12159 entry->u.index = -2 - applet_no;
12160 return;
12161 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012162 }
12163#endif
12164
Denis Vlasenkocc571512007-02-23 21:10:35 +000012165 /* We have to search path. */
12166 prev = -1; /* where to start */
12167 if (cmdp && cmdp->rehash) { /* doing a rehash */
12168 if (cmdp->cmdtype == CMDBUILTIN)
12169 prev = builtinloc;
12170 else
12171 prev = cmdp->param.index;
12172 }
12173
12174 e = ENOENT;
12175 idx = -1;
12176 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012177 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012178 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012179 /* NB: code below will still use fullname
12180 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012181 idx++;
12182 if (pathopt) {
12183 if (prefix(pathopt, "builtin")) {
12184 if (bcmd)
12185 goto builtin_success;
12186 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012187 }
12188 if ((act & DO_NOFUNC)
12189 || !prefix(pathopt, "func")
12190 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012191 continue;
12192 }
12193 }
12194 /* if rehash, don't redo absolute path names */
12195 if (fullname[0] == '/' && idx <= prev) {
12196 if (idx < prev)
12197 continue;
12198 TRACE(("searchexec \"%s\": no change\n", name));
12199 goto success;
12200 }
12201 while (stat(fullname, &statb) < 0) {
12202#ifdef SYSV
12203 if (errno == EINTR)
12204 continue;
12205#endif
12206 if (errno != ENOENT && errno != ENOTDIR)
12207 e = errno;
12208 goto loop;
12209 }
12210 e = EACCES; /* if we fail, this will be the error */
12211 if (!S_ISREG(statb.st_mode))
12212 continue;
12213 if (pathopt) { /* this is a %func directory */
12214 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012215 /* NB: stalloc will return space pointed by fullname
12216 * (because we don't have any intervening allocations
12217 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012218 readcmdfile(fullname);
12219 cmdp = cmdlookup(name, 0);
12220 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12221 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12222 stunalloc(fullname);
12223 goto success;
12224 }
12225 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12226 if (!updatetbl) {
12227 entry->cmdtype = CMDNORMAL;
12228 entry->u.index = idx;
12229 return;
12230 }
12231 INT_OFF;
12232 cmdp = cmdlookup(name, 1);
12233 cmdp->cmdtype = CMDNORMAL;
12234 cmdp->param.index = idx;
12235 INT_ON;
12236 goto success;
12237 }
12238
12239 /* We failed. If there was an entry for this command, delete it */
12240 if (cmdp && updatetbl)
12241 delete_cmd_entry();
12242 if (act & DO_ERR)
12243 ash_msg("%s: %s", name, errmsg(e, "not found"));
12244 entry->cmdtype = CMDUNKNOWN;
12245 return;
12246
12247 builtin_success:
12248 if (!updatetbl) {
12249 entry->cmdtype = CMDBUILTIN;
12250 entry->u.cmd = bcmd;
12251 return;
12252 }
12253 INT_OFF;
12254 cmdp = cmdlookup(name, 1);
12255 cmdp->cmdtype = CMDBUILTIN;
12256 cmdp->param.cmd = bcmd;
12257 INT_ON;
12258 success:
12259 cmdp->rehash = 0;
12260 entry->cmdtype = cmdp->cmdtype;
12261 entry->u = cmdp->param;
12262}
12263
12264
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012265/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012266
Eric Andersencb57d552001-06-28 07:25:16 +000012267/*
Eric Andersencb57d552001-06-28 07:25:16 +000012268 * The trap builtin.
12269 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012270static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012271trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012272{
12273 char *action;
12274 char **ap;
12275 int signo;
12276
Eric Andersenc470f442003-07-28 09:56:35 +000012277 nextopt(nullstr);
12278 ap = argptr;
12279 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012280 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012281 char *tr = trap_ptr[signo];
12282 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012283 /* note: bash adds "SIG", but only if invoked
12284 * as "bash". If called as "sh", or if set -o posix,
12285 * then it prints short signal names.
12286 * We are printing short names: */
12287 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012288 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012289 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012290 /* trap_ptr != trap only if we are in special-cased `trap` code.
12291 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012292 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012293 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012294 }
12295 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012296 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012297 if (trap_ptr != trap) {
12298 free(trap_ptr);
12299 trap_ptr = trap;
12300 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012301 */
Eric Andersencb57d552001-06-28 07:25:16 +000012302 return 0;
12303 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012304
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012305 action = NULL;
12306 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012307 action = *ap++;
12308 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012309 signo = get_signum(*ap);
12310 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012311 ash_msg_and_raise_error("%s: bad trap", *ap);
12312 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012313 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012314 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012315 action = NULL;
12316 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012317 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012318 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012319 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012320 trap[signo] = action;
12321 if (signo != 0)
12322 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012323 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012324 ap++;
12325 }
12326 return 0;
12327}
12328
Eric Andersenc470f442003-07-28 09:56:35 +000012329
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012330/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012331
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012332#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012333/*
12334 * Lists available builtins
12335 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012336static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012337helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012338{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012339 unsigned col;
12340 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012341
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012342 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012343 "Built-in commands:\n"
12344 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012345 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012346 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012347 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012348 if (col > 60) {
12349 out1fmt("\n");
12350 col = 0;
12351 }
12352 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012353#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012354 {
12355 const char *a = applet_names;
12356 while (*a) {
12357 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12358 if (col > 60) {
12359 out1fmt("\n");
12360 col = 0;
12361 }
12362 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012363 }
12364 }
12365#endif
12366 out1fmt("\n\n");
12367 return EXIT_SUCCESS;
12368}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012369#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012370
Eric Andersencb57d552001-06-28 07:25:16 +000012371/*
Eric Andersencb57d552001-06-28 07:25:16 +000012372 * The export and readonly commands.
12373 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012374static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012375exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012376{
12377 struct var *vp;
12378 char *name;
12379 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012380 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012381 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012382
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012383 if (nextopt("p") != 'p') {
12384 aptr = argptr;
12385 name = *aptr;
12386 if (name) {
12387 do {
12388 p = strchr(name, '=');
12389 if (p != NULL) {
12390 p++;
12391 } else {
12392 vp = *findvar(hashvar(name), name);
12393 if (vp) {
12394 vp->flags |= flag;
12395 continue;
12396 }
Eric Andersencb57d552001-06-28 07:25:16 +000012397 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012398 setvar(name, p, flag);
12399 } while ((name = *++aptr) != NULL);
12400 return 0;
12401 }
Eric Andersencb57d552001-06-28 07:25:16 +000012402 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012403 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012404 return 0;
12405}
12406
Eric Andersencb57d552001-06-28 07:25:16 +000012407/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012408 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012409 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012410static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012411unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012412{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012413 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012414
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012415 cmdp = cmdlookup(name, 0);
12416 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12417 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012418}
12419
Eric Andersencb57d552001-06-28 07:25:16 +000012420/*
Eric Andersencb57d552001-06-28 07:25:16 +000012421 * The unset builtin command. We unset the function before we unset the
12422 * variable to allow a function to be unset when there is a readonly variable
12423 * with the same name.
12424 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012425static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012426unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012427{
12428 char **ap;
12429 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012430 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012431 int ret = 0;
12432
12433 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012434 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012435 }
Eric Andersencb57d552001-06-28 07:25:16 +000012436
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012437 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012438 if (flag != 'f') {
12439 i = unsetvar(*ap);
12440 ret |= i;
12441 if (!(i & 2))
12442 continue;
12443 }
12444 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012445 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012446 }
Eric Andersenc470f442003-07-28 09:56:35 +000012447 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012448}
12449
12450
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012451/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012452
Eric Andersenc470f442003-07-28 09:56:35 +000012453#include <sys/times.h>
12454
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012455static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012456 ' ', offsetof(struct tms, tms_utime),
12457 '\n', offsetof(struct tms, tms_stime),
12458 ' ', offsetof(struct tms, tms_cutime),
12459 '\n', offsetof(struct tms, tms_cstime),
12460 0
12461};
Eric Andersencb57d552001-06-28 07:25:16 +000012462
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012463static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012464timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012465{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012466 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012467 const unsigned char *p;
12468 struct tms buf;
12469
12470 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012471 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012472
12473 p = timescmd_str;
12474 do {
12475 t = *(clock_t *)(((char *) &buf) + p[1]);
12476 s = t / clk_tck;
12477 out1fmt("%ldm%ld.%.3lds%c",
12478 s/60, s%60,
12479 ((t - s * clk_tck) * 1000) / clk_tck,
12480 p[0]);
12481 } while (*(p += 2));
12482
Eric Andersencb57d552001-06-28 07:25:16 +000012483 return 0;
12484}
12485
Mike Frysinger98c52642009-04-02 10:02:37 +000012486#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012487/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012488 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12489 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012490 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012491 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012492 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012493static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012494letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012495{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012496 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012497
Denis Vlasenko68404f12008-03-17 09:00:54 +000012498 argv++;
12499 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012500 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012501 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012502 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012503 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012504
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012505 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012506}
Mike Frysinger98c52642009-04-02 10:02:37 +000012507#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012508
Eric Andersenc470f442003-07-28 09:56:35 +000012509
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012510/* ============ miscbltin.c
12511 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012512 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012513 */
12514
12515#undef rflag
12516
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012517#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012518typedef enum __rlimit_resource rlim_t;
12519#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012520
Eric Andersenc470f442003-07-28 09:56:35 +000012521/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012522 * The read builtin. Options:
12523 * -r Do not interpret '\' specially
12524 * -s Turn off echo (tty only)
12525 * -n NCHARS Read NCHARS max
12526 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12527 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12528 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012529 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012530 * TODO: bash also has:
12531 * -a ARRAY Read into array[0],[1],etc
12532 * -d DELIM End on DELIM char, not newline
12533 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012534 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012535static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012536readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012537{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012538 static const char *const arg_REPLY[] = { "REPLY", NULL };
12539
Eric Andersenc470f442003-07-28 09:56:35 +000012540 char **ap;
12541 int backslash;
12542 char c;
12543 int rflag;
12544 char *prompt;
12545 const char *ifs;
12546 char *p;
12547 int startword;
12548 int status;
12549 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012550 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012551#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012552 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012553 int silent = 0;
12554 struct termios tty, old_tty;
12555#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012556#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012557 unsigned end_ms = 0;
12558 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012559#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012560
12561 rflag = 0;
12562 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012564 IF_ASH_READ_TIMEOUT("t:")
12565 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012566 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012567 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012568 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012569 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012570 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012571#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012572 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012573 nchars = bb_strtou(optionarg, NULL, 10);
12574 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012575 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012576 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012577 break;
12578 case 's':
12579 silent = 1;
12580 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012581#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012582#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012583 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012584 timeout = bb_strtou(optionarg, NULL, 10);
12585 if (errno || timeout > UINT_MAX / 2048)
12586 ash_msg_and_raise_error("invalid timeout");
12587 timeout *= 1000;
12588#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012589 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012590 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012591 /* EINVAL means number is ok, but not terminated by NUL */
12592 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012593 char *p2;
12594 if (*++p) {
12595 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012596 ts.tv_usec = bb_strtou(p, &p2, 10);
12597 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012598 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012599 scale = p2 - p;
12600 /* normalize to usec */
12601 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012602 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012603 while (scale++ < 6)
12604 ts.tv_usec *= 10;
12605 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012606 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012607 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012608 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012609 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012610 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012611 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012612#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012613 break;
12614#endif
12615 case 'r':
12616 rflag = 1;
12617 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012618 case 'u':
12619 fd = bb_strtou(optionarg, NULL, 10);
12620 if (fd < 0 || errno)
12621 ash_msg_and_raise_error("invalid file descriptor");
12622 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012623 default:
12624 break;
12625 }
Eric Andersenc470f442003-07-28 09:56:35 +000012626 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012627 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012628 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012629 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012630 ap = argptr;
12631 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012632 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012633 ifs = bltinlookup("IFS");
12634 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012635 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012636#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012637 tcgetattr(fd, &tty);
12638 old_tty = tty;
12639 if (nchars || silent) {
12640 if (nchars) {
12641 tty.c_lflag &= ~ICANON;
12642 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012643 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012644 if (silent) {
12645 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12646 }
12647 /* if tcgetattr failed, tcsetattr will fail too.
12648 * Ignoring, it's harmless. */
12649 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012650 }
12651#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012652
Eric Andersenc470f442003-07-28 09:56:35 +000012653 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012654 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012655 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012656#if ENABLE_ASH_READ_TIMEOUT
12657 if (timeout) /* NB: ensuring end_ms is nonzero */
12658 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12659#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012660 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012661 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012662 const char *is_ifs;
12663
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012664#if ENABLE_ASH_READ_TIMEOUT
12665 if (end_ms) {
12666 struct pollfd pfd[1];
12667 pfd[0].fd = fd;
12668 pfd[0].events = POLLIN;
12669 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12670 if ((int)timeout <= 0 /* already late? */
12671 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12672 ) { /* timed out! */
12673#if ENABLE_ASH_READ_NCHARS
12674 tcsetattr(fd, TCSANOW, &old_tty);
12675#endif
12676 return 1;
12677 }
12678 }
12679#endif
12680 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012681 status = 1;
12682 break;
12683 }
12684 if (c == '\0')
12685 continue;
12686 if (backslash) {
12687 backslash = 0;
12688 if (c != '\n')
12689 goto put;
12690 continue;
12691 }
12692 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012693 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012694 continue;
12695 }
12696 if (c == '\n')
12697 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012698 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012699/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012700 is_ifs = strchr(ifs, c);
12701 if (startword && is_ifs) {
12702 if (isspace(c))
12703 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012704 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012705 startword--;
12706 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012707 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012708 }
12709 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012710 if (ap[1] != NULL && is_ifs) {
12711 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012712 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012713 beg = stackblock();
12714 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012715 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012716 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012717 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012718 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012719 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012720 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012721 put:
12722 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012723 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012724/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012725#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012726 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012727#else
12728 while (1);
12729#endif
12730
12731#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012732 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012733#endif
12734
Eric Andersenc470f442003-07-28 09:56:35 +000012735 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012736 /* Remove trailing space ifs chars */
12737 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012738 *p = '\0';
12739 setvar(*ap, stackblock(), 0);
12740 while (*++ap != NULL)
12741 setvar(*ap, nullstr, 0);
12742 return status;
12743}
12744
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012745static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012746umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012747{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012748 static const char permuser[3] ALIGN1 = "ugo";
12749 static const char permmode[3] ALIGN1 = "rwx";
12750 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012751 S_IRUSR, S_IWUSR, S_IXUSR,
12752 S_IRGRP, S_IWGRP, S_IXGRP,
12753 S_IROTH, S_IWOTH, S_IXOTH
12754 };
12755
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012756 /* TODO: use bb_parse_mode() instead */
12757
Eric Andersenc470f442003-07-28 09:56:35 +000012758 char *ap;
12759 mode_t mask;
12760 int i;
12761 int symbolic_mode = 0;
12762
12763 while (nextopt("S") != '\0') {
12764 symbolic_mode = 1;
12765 }
12766
Denis Vlasenkob012b102007-02-19 22:43:01 +000012767 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012768 mask = umask(0);
12769 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012770 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012771
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012772 ap = *argptr;
12773 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012774 if (symbolic_mode) {
12775 char buf[18];
12776 char *p = buf;
12777
12778 for (i = 0; i < 3; i++) {
12779 int j;
12780
12781 *p++ = permuser[i];
12782 *p++ = '=';
12783 for (j = 0; j < 3; j++) {
12784 if ((mask & permmask[3 * i + j]) == 0) {
12785 *p++ = permmode[j];
12786 }
12787 }
12788 *p++ = ',';
12789 }
12790 *--p = 0;
12791 puts(buf);
12792 } else {
12793 out1fmt("%.4o\n", mask);
12794 }
12795 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012796 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012797 mask = 0;
12798 do {
12799 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012800 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012801 mask = (mask << 3) + (*ap - '0');
12802 } while (*++ap != '\0');
12803 umask(mask);
12804 } else {
12805 mask = ~mask & 0777;
12806 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012807 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012808 }
12809 umask(~mask & 0777);
12810 }
12811 }
12812 return 0;
12813}
12814
12815/*
12816 * ulimit builtin
12817 *
12818 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12819 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12820 * ash by J.T. Conklin.
12821 *
12822 * Public domain.
12823 */
Eric Andersenc470f442003-07-28 09:56:35 +000012824struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012825 uint8_t cmd; /* RLIMIT_xxx fit into it */
12826 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012827 char option;
12828};
12829
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012831#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012832 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012833#endif
12834#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012835 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012836#endif
12837#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012838 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012839#endif
12840#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012841 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012842#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012843#ifdef RLIMIT_CORE
12844 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012845#endif
12846#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012847 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012848#endif
12849#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012850 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012851#endif
12852#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012853 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012854#endif
12855#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012856 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012857#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012858#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012859 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012860#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012861#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012862 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012863#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012864};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012865static const char limits_name[] =
12866#ifdef RLIMIT_CPU
12867 "time(seconds)" "\0"
12868#endif
12869#ifdef RLIMIT_FSIZE
12870 "file(blocks)" "\0"
12871#endif
12872#ifdef RLIMIT_DATA
12873 "data(kb)" "\0"
12874#endif
12875#ifdef RLIMIT_STACK
12876 "stack(kb)" "\0"
12877#endif
12878#ifdef RLIMIT_CORE
12879 "coredump(blocks)" "\0"
12880#endif
12881#ifdef RLIMIT_RSS
12882 "memory(kb)" "\0"
12883#endif
12884#ifdef RLIMIT_MEMLOCK
12885 "locked memory(kb)" "\0"
12886#endif
12887#ifdef RLIMIT_NPROC
12888 "process" "\0"
12889#endif
12890#ifdef RLIMIT_NOFILE
12891 "nofiles" "\0"
12892#endif
12893#ifdef RLIMIT_AS
12894 "vmemory(kb)" "\0"
12895#endif
12896#ifdef RLIMIT_LOCKS
12897 "locks" "\0"
12898#endif
12899;
Eric Andersenc470f442003-07-28 09:56:35 +000012900
Glenn L McGrath76620622004-01-13 10:19:37 +000012901enum limtype { SOFT = 0x1, HARD = 0x2 };
12902
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012903static void
12904printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012905 const struct limits *l)
12906{
12907 rlim_t val;
12908
12909 val = limit->rlim_max;
12910 if (how & SOFT)
12911 val = limit->rlim_cur;
12912
12913 if (val == RLIM_INFINITY)
12914 out1fmt("unlimited\n");
12915 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012916 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012917 out1fmt("%lld\n", (long long) val);
12918 }
12919}
12920
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012921static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012922ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012923{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012924 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012925 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012926 const struct limits *l;
12927 int set, all = 0;
12928 int optc, what;
12929 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012930
12931 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012932 while ((optc = nextopt("HSa"
12933#ifdef RLIMIT_CPU
12934 "t"
12935#endif
12936#ifdef RLIMIT_FSIZE
12937 "f"
12938#endif
12939#ifdef RLIMIT_DATA
12940 "d"
12941#endif
12942#ifdef RLIMIT_STACK
12943 "s"
12944#endif
12945#ifdef RLIMIT_CORE
12946 "c"
12947#endif
12948#ifdef RLIMIT_RSS
12949 "m"
12950#endif
12951#ifdef RLIMIT_MEMLOCK
12952 "l"
12953#endif
12954#ifdef RLIMIT_NPROC
12955 "p"
12956#endif
12957#ifdef RLIMIT_NOFILE
12958 "n"
12959#endif
12960#ifdef RLIMIT_AS
12961 "v"
12962#endif
12963#ifdef RLIMIT_LOCKS
12964 "w"
12965#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012966 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012967 switch (optc) {
12968 case 'H':
12969 how = HARD;
12970 break;
12971 case 'S':
12972 how = SOFT;
12973 break;
12974 case 'a':
12975 all = 1;
12976 break;
12977 default:
12978 what = optc;
12979 }
12980
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012981 for (l = limits_tbl; l->option != what; l++)
12982 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012983
12984 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012985 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012986 if (set) {
12987 char *p = *argptr;
12988
12989 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012990 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012991 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012992 val = RLIM_INFINITY;
12993 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012994 if (sizeof(val) == sizeof(int))
12995 val = bb_strtou(p, NULL, 10);
12996 else if (sizeof(val) == sizeof(long))
12997 val = bb_strtoul(p, NULL, 10);
12998 else
12999 val = bb_strtoull(p, NULL, 10);
13000 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013001 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013002 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000013003 }
13004 }
13005 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013006 const char *lname = limits_name;
13007 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000013008 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013009 out1fmt("%-20s ", lname);
13010 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000013011 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013012 }
13013 return 0;
13014 }
13015
13016 getrlimit(l->cmd, &limit);
13017 if (set) {
13018 if (how & HARD)
13019 limit.rlim_max = val;
13020 if (how & SOFT)
13021 limit.rlim_cur = val;
13022 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013023 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013024 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013025 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013026 }
13027 return 0;
13028}
13029
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013030/* ============ main() and helpers */
13031
13032/*
13033 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013034 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013035static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013036static void
13037exitshell(void)
13038{
13039 struct jmploc loc;
13040 char *p;
13041 int status;
13042
13043 status = exitstatus;
13044 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13045 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013046 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013047/* dash bug: it just does _exit(exitstatus) here
13048 * but we have to do setjobctl(0) first!
13049 * (bug is still not fixed in dash-0.5.3 - if you run dash
13050 * under Midnight Commander, on exit from dash MC is backgrounded) */
13051 status = exitstatus;
13052 goto out;
13053 }
13054 exception_handler = &loc;
13055 p = trap[0];
13056 if (p) {
13057 trap[0] = NULL;
13058 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013059 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013060 }
13061 flush_stdout_stderr();
13062 out:
13063 setjobctl(0);
13064 _exit(status);
13065 /* NOTREACHED */
13066}
13067
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013068static void
13069init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013070{
13071 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013072 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013073
13074 /* from trap.c: */
13075 signal(SIGCHLD, SIG_DFL);
13076
13077 /* from var.c: */
13078 {
13079 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013080 const char *p;
13081 struct stat st1, st2;
13082
13083 initvar();
13084 for (envp = environ; envp && *envp; envp++) {
13085 if (strchr(*envp, '=')) {
13086 setvareq(*envp, VEXPORT|VTEXTFIXED);
13087 }
13088 }
13089
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013090 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013091
13092 p = lookupvar("PWD");
13093 if (p)
13094 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13095 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13096 p = '\0';
13097 setpwd(p, 0);
13098 }
13099}
13100
13101/*
13102 * Process the shell command line arguments.
13103 */
13104static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013105procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013106{
13107 int i;
13108 const char *xminusc;
13109 char **xargv;
13110
13111 xargv = argv;
13112 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013113 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013114 xargv++;
13115 for (i = 0; i < NOPTS; i++)
13116 optlist[i] = 2;
13117 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013118 if (options(1)) {
13119 /* it already printed err message */
13120 raise_exception(EXERROR);
13121 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013122 xargv = argptr;
13123 xminusc = minusc;
13124 if (*xargv == NULL) {
13125 if (xminusc)
13126 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13127 sflag = 1;
13128 }
13129 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13130 iflag = 1;
13131 if (mflag == 2)
13132 mflag = iflag;
13133 for (i = 0; i < NOPTS; i++)
13134 if (optlist[i] == 2)
13135 optlist[i] = 0;
13136#if DEBUG == 2
13137 debug = 1;
13138#endif
13139 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13140 if (xminusc) {
13141 minusc = *xargv++;
13142 if (*xargv)
13143 goto setarg0;
13144 } else if (!sflag) {
13145 setinputfile(*xargv, 0);
13146 setarg0:
13147 arg0 = *xargv++;
13148 commandname = arg0;
13149 }
13150
13151 shellparam.p = xargv;
13152#if ENABLE_ASH_GETOPTS
13153 shellparam.optind = 1;
13154 shellparam.optoff = -1;
13155#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013156 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013157 while (*xargv) {
13158 shellparam.nparam++;
13159 xargv++;
13160 }
13161 optschanged();
13162}
13163
13164/*
13165 * Read /etc/profile or .profile.
13166 */
13167static void
13168read_profile(const char *name)
13169{
13170 int skip;
13171
13172 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13173 return;
13174 skip = cmdloop(0);
13175 popfile();
13176 if (skip)
13177 exitshell();
13178}
13179
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013180/*
13181 * This routine is called when an error or an interrupt occurs in an
13182 * interactive shell and control is returned to the main command loop.
13183 */
13184static void
13185reset(void)
13186{
13187 /* from eval.c: */
13188 evalskip = 0;
13189 loopnest = 0;
13190 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013191 g_parsefile->left_in_buffer = 0;
13192 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013193 popallfiles();
13194 /* from parser.c: */
13195 tokpushback = 0;
13196 checkkwd = 0;
13197 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013198 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013199}
13200
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013201#if PROFILE
13202static short profile_buf[16384];
13203extern int etext();
13204#endif
13205
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013206/*
13207 * Main routine. We initialize things, parse the arguments, execute
13208 * profiles if we're a login shell, and then call cmdloop to execute
13209 * commands. The setjmp call sets up the location to jump to when an
13210 * exception occurs. When an exception occurs the variable "state"
13211 * is used to figure out how far we had gotten.
13212 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013213int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013214int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013215{
Mike Frysinger98c52642009-04-02 10:02:37 +000013216 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013217 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013218 struct jmploc jmploc;
13219 struct stackmark smark;
13220
Denis Vlasenko01631112007-12-16 17:20:38 +000013221 /* Initialize global data */
13222 INIT_G_misc();
13223 INIT_G_memstack();
13224 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013225#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013226 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013227#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013228 INIT_G_cmdtable();
13229
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013230#if PROFILE
13231 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13232#endif
13233
13234#if ENABLE_FEATURE_EDITING
13235 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13236#endif
13237 state = 0;
13238 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013239 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013240 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013241
13242 reset();
13243
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013244 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013245 if (e == EXERROR)
13246 exitstatus = 2;
13247 s = state;
13248 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13249 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013250 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013252
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013253 popstackmark(&smark);
13254 FORCE_INT_ON; /* enable interrupts */
13255 if (s == 1)
13256 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013257 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013258 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013259 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013260 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013261 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013262 }
13263 exception_handler = &jmploc;
13264#if DEBUG
13265 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013266 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013267 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013268#endif
13269 rootpid = getpid();
13270
13271#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013272 /* Can use monotonic_ns() for better randomness but for now it is
13273 * not used anywhere else in busybox... so avoid bloat */
13274 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013275#endif
13276 init();
13277 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013278 procargs(argv);
13279
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013280#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13281 if (iflag) {
13282 const char *hp = lookupvar("HISTFILE");
13283
13284 if (hp == NULL) {
13285 hp = lookupvar("HOME");
13286 if (hp != NULL) {
13287 char *defhp = concat_path_file(hp, ".ash_history");
13288 setvar("HISTFILE", defhp, 0);
13289 free(defhp);
13290 }
13291 }
13292 }
13293#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013294 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013295 isloginsh = 1;
13296 if (isloginsh) {
13297 state = 1;
13298 read_profile("/etc/profile");
13299 state1:
13300 state = 2;
13301 read_profile(".profile");
13302 }
13303 state2:
13304 state = 3;
13305 if (
13306#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013307 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013308#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013309 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013310 ) {
13311 shinit = lookupvar("ENV");
13312 if (shinit != NULL && *shinit != '\0') {
13313 read_profile(shinit);
13314 }
13315 }
13316 state3:
13317 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013318 if (minusc) {
13319 /* evalstring pushes parsefile stack.
13320 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013321 * is one of stacked source fds.
13322 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013323 if (!sflag)
13324 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013325 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013326 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013327
13328 if (sflag || minusc == NULL) {
Denys Vlasenkodb9c57e2009-09-27 02:48:53 +020013329#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013330 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013331 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013332 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013333 line_input_state->hist_file = hp;
13334 }
13335#endif
13336 state4: /* XXX ??? - why isn't this before the "if" statement */
13337 cmdloop(1);
13338 }
13339#if PROFILE
13340 monitor(0);
13341#endif
13342#ifdef GPROF
13343 {
13344 extern void _mcleanup(void);
13345 _mcleanup();
13346 }
13347#endif
13348 exitshell();
13349 /* NOTREACHED */
13350}
13351
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013352
Eric Andersendf82f612001-06-28 07:46:40 +000013353/*-
13354 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013355 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013356 *
13357 * This code is derived from software contributed to Berkeley by
13358 * Kenneth Almquist.
13359 *
13360 * Redistribution and use in source and binary forms, with or without
13361 * modification, are permitted provided that the following conditions
13362 * are met:
13363 * 1. Redistributions of source code must retain the above copyright
13364 * notice, this list of conditions and the following disclaimer.
13365 * 2. Redistributions in binary form must reproduce the above copyright
13366 * notice, this list of conditions and the following disclaimer in the
13367 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013368 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013369 * may be used to endorse or promote products derived from this software
13370 * without specific prior written permission.
13371 *
13372 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13373 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13374 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13375 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13376 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13377 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13378 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13379 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13380 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13381 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13382 * SUCH DAMAGE.
13383 */