blob: ce82a965c226b393bcd4f20fb10f37398206c3eb [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 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000016 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
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
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenkob012b102007-02-19 22:43:01 +000039#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000040# ifndef _GNU_SOURCE
41# define _GNU_SOURCE
42# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000043#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000044
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000045#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000046//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
47//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000048#include <paths.h>
49#include <setjmp.h>
50#include <fnmatch.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010051
52#include "shell_common.h"
53#include "builtin_read.h"
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010054#include "builtin_ulimit.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000055#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020056#if ENABLE_ASH_RANDOM_SUPPORT
57# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020058#else
59# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020060#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000061
62#if defined SINGLE_APPLET_MAIN
63/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020064# undef CONFIG_FEATURE_SH_STANDALONE
65# undef ENABLE_FEATURE_SH_STANDALONE
66# undef IF_FEATURE_SH_STANDALONE
67# undef IF_NOT_FEATURE_SH_STANDALONE(...)
68# define ENABLE_FEATURE_SH_STANDALONE 0
69# define IF_FEATURE_SH_STANDALONE(...)
70# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000071#endif
72
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000074# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000075#endif
76
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010077#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000078# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000079#endif
80
Denis Vlasenkob012b102007-02-19 22:43:01 +000081
Denis Vlasenko01631112007-12-16 17:20:38 +000082/* ============ Hash table sizes. Configurable. */
83
84#define VTABSIZE 39
85#define ATABSIZE 39
86#define CMDTABLESIZE 31 /* should be prime */
87
88
Denis Vlasenkob012b102007-02-19 22:43:01 +000089/* ============ Shell options */
90
91static const char *const optletters_optnames[] = {
92 "e" "errexit",
93 "f" "noglob",
94 "I" "ignoreeof",
95 "i" "interactive",
96 "m" "monitor",
97 "n" "noexec",
98 "s" "stdin",
99 "x" "xtrace",
100 "v" "verbose",
101 "C" "noclobber",
102 "a" "allexport",
103 "b" "notify",
104 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100105 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100106#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100107 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100108#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000110 ,"\0" "nolog"
111 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112#endif
113};
114
Denys Vlasenko285ad152009-12-04 23:02:27 +0100115#define optletters(n) optletters_optnames[n][0]
116#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000117
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000118enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000119
Eric Andersenc470f442003-07-28 09:56:35 +0000120
Denis Vlasenkob012b102007-02-19 22:43:01 +0000121/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000122
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000123static const char homestr[] ALIGN1 = "HOME";
124static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200125static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000126
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000127/*
Eric Andersenc470f442003-07-28 09:56:35 +0000128 * We enclose jmp_buf in a structure so that we can declare pointers to
129 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000130 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000131 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000132 * exception handlers, the user should save the value of handler on entry
133 * to an inner scope, set handler to point to a jmploc structure for the
134 * inner scope, and restore handler on exit from the scope.
135 */
Eric Andersenc470f442003-07-28 09:56:35 +0000136struct jmploc {
137 jmp_buf loc;
138};
Denis Vlasenko01631112007-12-16 17:20:38 +0000139
140struct globals_misc {
141 /* pid of main shell */
142 int rootpid;
143 /* shell level: 0 for the main shell, 1 for its children, and so on */
144 int shlvl;
145#define rootshell (!shlvl)
146 char *minusc; /* argument to -c option */
147
148 char *curdir; // = nullstr; /* current working directory */
149 char *physdir; // = nullstr; /* physical working directory */
150
151 char *arg0; /* value of $0 */
152
153 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000154
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200155 volatile int suppress_int; /* counter */
156 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000157 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200158 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000159 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000160 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000161#define EXINT 0 /* SIGINT received */
162#define EXERROR 1 /* a generic error */
163#define EXSHELLPROC 2 /* execute a shell procedure */
164#define EXEXEC 3 /* command execution failed */
165#define EXEXIT 4 /* exit the shell */
166#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000167
Denis Vlasenko01631112007-12-16 17:20:38 +0000168 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000169 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000170
171 char optlist[NOPTS];
172#define eflag optlist[0]
173#define fflag optlist[1]
174#define Iflag optlist[2]
175#define iflag optlist[3]
176#define mflag optlist[4]
177#define nflag optlist[5]
178#define sflag optlist[6]
179#define xflag optlist[7]
180#define vflag optlist[8]
181#define Cflag optlist[9]
182#define aflag optlist[10]
183#define bflag optlist[11]
184#define uflag optlist[12]
185#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100186#if ENABLE_ASH_BASH_COMPAT
187# define pipefail optlist[14]
188#else
189# define pipefail 0
190#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000191#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100192# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
193# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000194#endif
195
196 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000197 /*
198 * Sigmode records the current value of the signal handlers for the various
199 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000200 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000201 */
202 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000203#define S_DFL 1 /* default signal handling (SIG_DFL) */
204#define S_CATCH 2 /* signal is caught */
205#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000206#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000207
Denis Vlasenko01631112007-12-16 17:20:38 +0000208 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000209 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000210 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200211 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000212
213 /* Rarely referenced stuff */
214#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200215 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000216#endif
217 pid_t backgndpid; /* pid of last background process */
218 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000219};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000220extern struct globals_misc *const ash_ptr_to_globals_misc;
221#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000222#define rootpid (G_misc.rootpid )
223#define shlvl (G_misc.shlvl )
224#define minusc (G_misc.minusc )
225#define curdir (G_misc.curdir )
226#define physdir (G_misc.physdir )
227#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000228#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000229#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200230#define suppress_int (G_misc.suppress_int )
231#define pending_int (G_misc.pending_int )
232#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000233#define isloginsh (G_misc.isloginsh )
234#define nullstr (G_misc.nullstr )
235#define optlist (G_misc.optlist )
236#define sigmode (G_misc.sigmode )
237#define gotsig (G_misc.gotsig )
238#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200239#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200240#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000241#define backgndpid (G_misc.backgndpid )
242#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000243#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
245 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000246 curdir = nullstr; \
247 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200248 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000249} while (0)
250
251
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252/* ============ DEBUG */
253#if DEBUG
254static void trace_printf(const char *fmt, ...);
255static void trace_vprintf(const char *fmt, va_list va);
256# define TRACE(param) trace_printf param
257# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000258# define close(fd) do { \
259 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000260 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200261 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000262 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000263} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#else
265# define TRACE(param)
266# define TRACEV(param)
267#endif
268
269
Denis Vlasenko559691a2008-10-05 18:39:31 +0000270/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000271#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272
Denis Vlasenko559691a2008-10-05 18:39:31 +0000273static int isdigit_str9(const char *str)
274{
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
277 str++;
278 return (*str == '\0');
279}
Denis Vlasenko01631112007-12-16 17:20:38 +0000280
Denis Vlasenko559691a2008-10-05 18:39:31 +0000281
282/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000283/*
Eric Andersen2870d962001-07-02 17:27:21 +0000284 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000285 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000286 * much more efficient and portable. (But hacking the kernel is so much
287 * more fun than worrying about efficiency and portability. :-))
288 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000289#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200290 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000291 xbarrier(); \
292} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000293
294/*
295 * Called to raise an exception. Since C doesn't include exceptions, we
296 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000297 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000299static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300static void
301raise_exception(int e)
302{
303#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000304 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000305 abort();
306#endif
307 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000308 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000309 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000310}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000311#if DEBUG
312#define raise_exception(e) do { \
313 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
314 raise_exception(e); \
315} while (0)
316#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317
318/*
319 * Called from trap.c when a SIGINT is received. (If the user specifies
320 * that SIGINT is to be trapped or ignored using the trap builtin, then
321 * this routine is not called.) Suppressint is nonzero when interrupts
322 * are held using the INT_OFF macro. (The test for iflag is just
323 * defensive programming.)
324 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000325static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000326static void
327raise_interrupt(void)
328{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000329 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000330
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200331 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000332 /* Signal is not automatically unmasked after it is raised,
333 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000334 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200335 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000336
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
339 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000340 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000341 signal(SIGINT, SIG_DFL);
342 raise(SIGINT);
343 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000344 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000346 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000347 /* NOTREACHED */
348}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000349#if DEBUG
350#define raise_interrupt() do { \
351 TRACE(("raising interrupt on line %d\n", __LINE__)); \
352 raise_interrupt(); \
353} while (0)
354#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000356static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000357int_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 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361 raise_interrupt();
362 }
363}
364#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000365static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000366force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000367{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000368 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200369 suppress_int = 0;
370 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000371 raise_interrupt();
372}
373#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000374
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200375#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000377#define RESTORE_INT(v) do { \
378 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200379 suppress_int = (v); \
380 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000381 raise_interrupt(); \
382} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000383
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000384
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000385/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000386
Eric Andersenc470f442003-07-28 09:56:35 +0000387static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000388outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000389{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390 INT_OFF;
391 fputs(p, file);
392 INT_ON;
393}
394
395static void
396flush_stdout_stderr(void)
397{
398 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100399 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000400 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);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100452 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000453}
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 Vlasenko2ce42e92009-11-29 02:18:13 +0100459#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200460#define CTLESC ((unsigned char)'\201') /* escape next character */
461#define CTLVAR ((unsigned char)'\202') /* variable defn */
462#define CTLENDVAR ((unsigned char)'\203')
463#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000464#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
465/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200466#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
467#define CTLENDARI ((unsigned char)'\207')
468#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100469#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000470
471/* variable substitution byte (follows CTLVAR) */
472#define VSTYPE 0x0f /* type of variable substitution */
473#define VSNUL 0x10 /* colon--treat the empty string as unset */
474#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475
476/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000477#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478#define VSMINUS 0x2 /* ${var-text} */
479#define VSPLUS 0x3 /* ${var+text} */
480#define VSQUESTION 0x4 /* ${var?message} */
481#define VSASSIGN 0x5 /* ${var=text} */
482#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484#define VSTRIMLEFT 0x8 /* ${var#pattern} */
485#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486#define VSLENGTH 0xa /* ${#var} */
487#if ENABLE_ASH_BASH_COMPAT
488#define VSSUBSTR 0xc /* ${var:position:length} */
489#define VSREPLACE 0xd /* ${var/pattern/replacement} */
490#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000492
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000493static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
495};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000496
Denis Vlasenko559691a2008-10-05 18:39:31 +0000497#define NCMD 0
498#define NPIPE 1
499#define NREDIR 2
500#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000501#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000502#define NAND 5
503#define NOR 6
504#define NSEMI 7
505#define NIF 8
506#define NWHILE 9
507#define NUNTIL 10
508#define NFOR 11
509#define NCASE 12
510#define NCLIST 13
511#define NDEFUN 14
512#define NARG 15
513#define NTO 16
514#if ENABLE_ASH_BASH_COMPAT
515#define NTO2 17
516#endif
517#define NCLOBBER 18
518#define NFROM 19
519#define NFROMTO 20
520#define NAPPEND 21
521#define NTOFD 22
522#define NFROMFD 23
523#define NHERE 24
524#define NXHERE 25
525#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000526#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000527
528union node;
529
530struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000531 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000532 union node *assign;
533 union node *args;
534 union node *redirect;
535};
536
537struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000538 smallint type;
539 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 struct nodelist *cmdlist;
541};
542
543struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000544 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000545 union node *n;
546 union node *redirect;
547};
548
549struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000550 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000551 union node *ch1;
552 union node *ch2;
553};
554
555struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000556 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000557 union node *test;
558 union node *ifpart;
559 union node *elsepart;
560};
561
562struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000563 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000564 union node *args;
565 union node *body;
566 char *var;
567};
568
569struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000570 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000571 union node *expr;
572 union node *cases;
573};
574
575struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000576 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000577 union node *next;
578 union node *pattern;
579 union node *body;
580};
581
582struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000583 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584 union node *next;
585 char *text;
586 struct nodelist *backquote;
587};
588
Denis Vlasenko559691a2008-10-05 18:39:31 +0000589/* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
592 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000594 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000595 union node *next;
596 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *fname;
599 char *expfname;
600};
601
602struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000603 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000604 union node *next;
605 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 int dupfd;
607 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000608 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609};
610
611struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000612 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000613 union node *next;
614 int fd;
615 union node *doc;
616};
617
618struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 union node *com;
621};
622
623union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000624 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000625 struct ncmd ncmd;
626 struct npipe npipe;
627 struct nredir nredir;
628 struct nbinary nbinary;
629 struct nif nif;
630 struct nfor nfor;
631 struct ncase ncase;
632 struct nclist nclist;
633 struct narg narg;
634 struct nfile nfile;
635 struct ndup ndup;
636 struct nhere nhere;
637 struct nnot nnot;
638};
639
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200640/*
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
643 */
644#define NODE_EOF ((union node *) -1L)
645
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000646struct nodelist {
647 struct nodelist *next;
648 union node *n;
649};
650
651struct funcnode {
652 int count;
653 union node n;
654};
655
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000656/*
657 * Free a parse tree.
658 */
659static void
660freefunc(struct funcnode *f)
661{
662 if (f && --f->count < 0)
663 free(f);
664}
665
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000666
667/* ============ Debugging output */
668
669#if DEBUG
670
671static FILE *tracefile;
672
673static void
674trace_printf(const char *fmt, ...)
675{
676 va_list va;
677
678 if (debug != 1)
679 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000680 if (DEBUG_TIME)
681 fprintf(tracefile, "%u ", (int) time(NULL));
682 if (DEBUG_PID)
683 fprintf(tracefile, "[%u] ", (int) getpid());
684 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000686 va_start(va, fmt);
687 vfprintf(tracefile, fmt, va);
688 va_end(va);
689}
690
691static void
692trace_vprintf(const char *fmt, va_list va)
693{
694 if (debug != 1)
695 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000696 if (DEBUG_TIME)
697 fprintf(tracefile, "%u ", (int) time(NULL));
698 if (DEBUG_PID)
699 fprintf(tracefile, "[%u] ", (int) getpid());
700 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000702 vfprintf(tracefile, fmt, va);
703}
704
705static void
706trace_puts(const char *s)
707{
708 if (debug != 1)
709 return;
710 fputs(s, tracefile);
711}
712
713static void
714trace_puts_quoted(char *s)
715{
716 char *p;
717 char c;
718
719 if (debug != 1)
720 return;
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100723 switch ((unsigned char)*p) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '\"': c = '\"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000734 backslash:
735 putc('\\', tracefile);
736 putc(c, tracefile);
737 break;
738 default:
739 if (*p >= ' ' && *p <= '~')
740 putc(*p, tracefile);
741 else {
742 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100743 putc((*p >> 6) & 03, tracefile);
744 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000745 putc(*p & 07, tracefile);
746 }
747 break;
748 }
749 }
750 putc('"', tracefile);
751}
752
753static void
754trace_puts_args(char **ap)
755{
756 if (debug != 1)
757 return;
758 if (!*ap)
759 return;
760 while (1) {
761 trace_puts_quoted(*ap);
762 if (!*++ap) {
763 putc('\n', tracefile);
764 break;
765 }
766 putc(' ', tracefile);
767 }
768}
769
770static void
771opentrace(void)
772{
773 char s[100];
774#ifdef O_APPEND
775 int flags;
776#endif
777
778 if (debug != 1) {
779 if (tracefile)
780 fflush(tracefile);
781 /* leave open because libedit might be using it */
782 return;
783 }
784 strcpy(s, "./trace");
785 if (tracefile) {
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
788 debug = 0;
789 return;
790 }
791 } else {
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
795 debug = 0;
796 return;
797 }
798 }
799#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000800 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000801 if (flags >= 0)
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
803#endif
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
806}
807
808static void
809indent(int amount, char *pfx, FILE *fp)
810{
811 int i;
812
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
815 fputs(pfx, fp);
816 putc('\t', fp);
817 }
818}
819
820/* little circular references here... */
821static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822
823static void
824sharg(union node *arg, FILE *fp)
825{
826 char *p;
827 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100828 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000829
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
832 abort();
833 }
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100836 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837 case CTLESC:
838 putc(*++p, fp);
839 break;
840 case CTLVAR:
841 putc('$', fp);
842 putc('{', fp);
843 subtype = *++p;
844 if (subtype == VSLENGTH)
845 putc('#', fp);
846
847 while (*p != '=')
848 putc(*p++, fp);
849
850 if (subtype & VSNUL)
851 putc(':', fp);
852
853 switch (subtype & VSTYPE) {
854 case VSNORMAL:
855 putc('}', fp);
856 break;
857 case VSMINUS:
858 putc('-', fp);
859 break;
860 case VSPLUS:
861 putc('+', fp);
862 break;
863 case VSQUESTION:
864 putc('?', fp);
865 break;
866 case VSASSIGN:
867 putc('=', fp);
868 break;
869 case VSTRIMLEFT:
870 putc('#', fp);
871 break;
872 case VSTRIMLEFTMAX:
873 putc('#', fp);
874 putc('#', fp);
875 break;
876 case VSTRIMRIGHT:
877 putc('%', fp);
878 break;
879 case VSTRIMRIGHTMAX:
880 putc('%', fp);
881 putc('%', fp);
882 break;
883 case VSLENGTH:
884 break;
885 default:
886 out1fmt("<subtype %d>", subtype);
887 }
888 break;
889 case CTLENDVAR:
890 putc('}', fp);
891 break;
892 case CTLBACKQ:
893 case CTLBACKQ|CTLQUOTE:
894 putc('$', fp);
895 putc('(', fp);
896 shtree(bqlist->n, -1, NULL, fp);
897 putc(')', fp);
898 break;
899 default:
900 putc(*p, fp);
901 break;
902 }
903 }
904}
905
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200906static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000907shcmd(union node *cmd, FILE *fp)
908{
909 union node *np;
910 int first;
911 const char *s;
912 int dftfd;
913
914 first = 1;
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000916 if (!first)
917 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000918 sharg(np, fp);
919 first = 0;
920 }
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000922 if (!first)
923 putc(' ', fp);
924 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000925 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000929#if ENABLE_ASH_BASH_COMPAT
930 case NTO2:
931#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000933 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000937 }
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
940 fputs(s, fp);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
943 } else {
944 sharg(np->nfile.fname, fp);
945 }
946 first = 0;
947 }
948}
949
950static void
951shtree(union node *n, int ind, char *pfx, FILE *fp)
952{
953 struct nodelist *lp;
954 const char *s;
955
956 if (n == NULL)
957 return;
958
959 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200960
961 if (n == NODE_EOF) {
962 fputs("<EOF>", fp);
963 return;
964 }
965
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000966 switch (n->type) {
967 case NSEMI:
968 s = "; ";
969 goto binop;
970 case NAND:
971 s = " && ";
972 goto binop;
973 case NOR:
974 s = " || ";
975 binop:
976 shtree(n->nbinary.ch1, ind, NULL, fp);
977 /* if (ind < 0) */
978 fputs(s, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
980 break;
981 case NCMD:
982 shcmd(n, fp);
983 if (ind >= 0)
984 putc('\n', fp);
985 break;
986 case NPIPE:
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200988 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989 if (lp->next)
990 fputs(" | ", fp);
991 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000992 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000993 fputs(" &", fp);
994 if (ind >= 0)
995 putc('\n', fp);
996 break;
997 default:
998 fprintf(fp, "<node type %d>", n->type);
999 if (ind >= 0)
1000 putc('\n', fp);
1001 break;
1002 }
1003}
1004
1005static void
1006showtree(union node *n)
1007{
1008 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001009 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010}
1011
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001012#endif /* DEBUG */
1013
1014
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001015/* ============ Parser data */
1016
1017/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001020struct strlist {
1021 struct strlist *next;
1022 char *text;
1023};
1024
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001025struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001026
Denis Vlasenkob012b102007-02-19 22:43:01 +00001027struct strpush {
1028 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001029 char *prev_string;
1030 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001031#if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1033#endif
1034 char *string; /* remember the string since it may change */
1035};
1036
1037struct parsefile {
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
1040 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1047};
1048
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001049static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001050static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051static int startlinno; /* line # where last token started */
1052static char *commandname; /* currently executing command */
1053static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001054static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001055
1056
1057/* ============ Message printing */
1058
1059static void
1060ash_vmsg(const char *msg, va_list ap)
1061{
1062 fprintf(stderr, "%s: ", arg0);
1063 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001066 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001068 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001071}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072
1073/*
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1077 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001078static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001079static void
1080ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001081{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082#if DEBUG
1083 if (msg) {
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1085 TRACEV((msg, ap));
1086 TRACE(("\") pid=%d\n", getpid()));
1087 } else
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1089 if (msg)
1090#endif
1091 ash_vmsg(msg, ap);
1092
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1095 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001096}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001098static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001099static void
1100ash_msg_and_raise_error(const char *msg, ...)
1101{
1102 va_list ap;
1103
1104 va_start(ap, msg);
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1106 /* NOTREACHED */
1107 va_end(ap);
1108}
1109
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001110static void raise_error_syntax(const char *) NORETURN;
1111static void
1112raise_error_syntax(const char *msg)
1113{
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1115 /* NOTREACHED */
1116}
1117
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001118static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001119static void
1120ash_msg_and_raise(int cond, const char *msg, ...)
1121{
1122 va_list ap;
1123
1124 va_start(ap, msg);
1125 ash_vmsg_and_raise(cond, msg, ap);
1126 /* NOTREACHED */
1127 va_end(ap);
1128}
1129
1130/*
1131 * error/warning routines for external builtins
1132 */
1133static void
1134ash_msg(const char *fmt, ...)
1135{
1136 va_list ap;
1137
1138 va_start(ap, fmt);
1139 ash_vmsg(fmt, ap);
1140 va_end(ap);
1141}
1142
1143/*
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1147 */
1148static const char *
1149errmsg(int e, const char *em)
1150{
1151 if (e == ENOENT || e == ENOTDIR) {
1152 return em;
1153 }
1154 return strerror(e);
1155}
1156
1157
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001158/* ============ Memory allocation */
1159
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001160#if 0
1161/* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1165 */
1166static void *
1167ckrealloc(void * p, size_t nbytes)
1168{
1169 p = realloc(p, nbytes);
1170 if (!p)
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1172 return p;
1173}
1174
1175static void *
1176ckmalloc(size_t nbytes)
1177{
1178 return ckrealloc(NULL, nbytes);
1179}
1180
1181static void *
1182ckzalloc(size_t nbytes)
1183{
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1185}
1186
1187static char *
1188ckstrdup(const char *s)
1189{
1190 char *p = strdup(s);
1191 if (!p)
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1193 return p;
1194}
1195#else
1196/* Using bbox equivalents. They exit if out of memory */
1197# define ckrealloc xrealloc
1198# define ckmalloc xmalloc
1199# define ckzalloc xzalloc
1200# define ckstrdup xstrdup
1201#endif
1202
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001203/*
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1206 */
1207#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1208enum {
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001214 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001215};
1216
1217struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1220};
1221
1222struct stackmark {
1223 struct stack_block *stackp;
1224 char *stacknxt;
1225 size_t stacknleft;
1226 struct stackmark *marknext;
1227};
1228
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001229
Denis Vlasenko01631112007-12-16 17:20:38 +00001230struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1238};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001239extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001241#define g_stackp (G_memstack.g_stackp )
1242#define markp (G_memstack.markp )
1243#define g_stacknxt (G_memstack.g_stacknxt )
1244#define sstrend (G_memstack.sstrend )
1245#define g_stacknleft (G_memstack.g_stacknleft)
1246#define herefd (G_memstack.herefd )
1247#define stackbase (G_memstack.stackbase )
1248#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1250 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1255 herefd = -1; \
1256} while (0)
1257
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001258
Denis Vlasenko01631112007-12-16 17:20:38 +00001259#define stackblock() ((void *)g_stacknxt)
1260#define stackblocksize() g_stacknleft
1261
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001262/*
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1266 *
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1268 * well.
1269 */
1270static void *
1271stalloc(size_t nbytes)
1272{
1273 char *p;
1274 size_t aligned;
1275
1276 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001277 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001278 size_t len;
1279 size_t blocksize;
1280 struct stack_block *sp;
1281
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1288 INT_OFF;
1289 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1294 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001295 INT_ON;
1296 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001297 p = g_stacknxt;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300 return p;
1301}
1302
Denis Vlasenko597906c2008-02-20 16:38:54 +00001303static void *
1304stzalloc(size_t nbytes)
1305{
1306 return memset(stalloc(nbytes), 0, nbytes);
1307}
1308
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001309static void
1310stunalloc(void *p)
1311{
1312#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001314 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001315 abort();
1316 }
1317#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001318 g_stacknleft += g_stacknxt - (char *)p;
1319 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001320}
1321
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001322/*
1323 * Like strdup but works with the ash stack.
1324 */
1325static char *
1326ststrdup(const char *p)
1327{
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1330}
1331
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001332static void
1333setstackmark(struct stackmark *mark)
1334{
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338 mark->marknext = markp;
1339 markp = mark;
1340}
1341
1342static void
1343popstackmark(struct stackmark *mark)
1344{
1345 struct stack_block *sp;
1346
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001347 if (!mark->stackp)
1348 return;
1349
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350 INT_OFF;
1351 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001352 while (g_stackp != mark->stackp) {
1353 sp = g_stackp;
1354 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001355 free(sp);
1356 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001359 sstrend = mark->stacknxt + mark->stacknleft;
1360 INT_ON;
1361}
1362
1363/*
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1371 */
1372static void
1373growstackblock(void)
1374{
1375 size_t newlen;
1376
Denis Vlasenko01631112007-12-16 17:20:38 +00001377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1380 if (newlen < 128)
1381 newlen += 128;
1382
Denis Vlasenko01631112007-12-16 17:20:38 +00001383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1388 size_t grosslen;
1389
1390 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 oldstackp = g_stackp;
1392 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001397 g_stackp = sp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 sstrend = sp->space + newlen;
1401
1402 /*
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1405 */
1406 xmark = markp;
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001411 xmark = xmark->marknext;
1412 }
1413 INT_ON;
1414 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001416 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001417 char *p = stalloc(newlen);
1418
1419 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001422 }
1423}
1424
1425static void
1426grabstackblock(size_t len)
1427{
1428 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001429 g_stacknxt += len;
1430 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001431}
1432
1433/*
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1445 *
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1449 */
1450static void *
1451growstackstr(void)
1452{
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1457 }
1458 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001459 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001460}
1461
1462/*
1463 * Called from CHECKSTRSPACE.
1464 */
1465static char *
1466makestrspace(size_t newlen, char *p)
1467{
Denis Vlasenko01631112007-12-16 17:20:38 +00001468 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001469 size_t size = stackblocksize();
1470
1471 for (;;) {
1472 size_t nleft;
1473
1474 size = stackblocksize();
1475 nleft = size - len;
1476 if (nleft >= newlen)
1477 break;
1478 growstackblock();
1479 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001480 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001481}
1482
1483static char *
1484stack_nputstr(const char *s, size_t n, char *p)
1485{
1486 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001487 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001488 return p;
1489}
1490
1491static char *
1492stack_putstr(const char *s, char *p)
1493{
1494 return stack_nputstr(s, strlen(s), p);
1495}
1496
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001497static char *
1498_STPUTC(int c, char *p)
1499{
1500 if (p == sstrend)
1501 p = growstackstr();
1502 *p++ = c;
1503 return p;
1504}
1505
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001506#define STARTSTACKSTR(p) ((p) = stackblock())
1507#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001508#define CHECKSTRSPACE(n, p) do { \
1509 char *q = (p); \
1510 size_t l = (n); \
1511 size_t m = sstrend - q; \
1512 if (l > m) \
1513 (p) = makestrspace(l, q); \
1514} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001515#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1519 *(p) = '\0'; \
1520} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001521#define STUNPUTC(p) (--(p))
1522#define STTOPC(p) ((p)[-1])
1523#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001524
1525#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001526#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001527#define stackstrend() ((void *)sstrend)
1528
1529
1530/* ============ String helpers */
1531
1532/*
1533 * prefix -- see if pfx is a prefix of string.
1534 */
1535static char *
1536prefix(const char *string, const char *pfx)
1537{
1538 while (*pfx) {
1539 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001540 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001541 }
1542 return (char *) string;
1543}
1544
1545/*
1546 * Check for a valid number. This should be elsewhere.
1547 */
1548static int
1549is_number(const char *p)
1550{
1551 do {
1552 if (!isdigit(*p))
1553 return 0;
1554 } while (*++p != '\0');
1555 return 1;
1556}
1557
1558/*
1559 * Convert a string of digits to an integer, printing an error message on
1560 * failure.
1561 */
1562static int
1563number(const char *s)
1564{
1565 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001566 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001567 return atoi(s);
1568}
1569
1570/*
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1573 */
1574static char *
1575single_quote(const char *s)
1576{
1577 char *p;
1578
1579 STARTSTACKSTR(p);
1580
1581 do {
1582 char *q;
1583 size_t len;
1584
1585 len = strchrnul(s, '\'') - s;
1586
1587 q = p = makestrspace(len + 3, p);
1588
1589 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001590 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001591 *q++ = '\'';
1592 s += len;
1593
1594 STADJUST(q - p, p);
1595
Denys Vlasenkocd716832009-11-28 22:14:02 +01001596 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001597 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001598 len = 0;
1599 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001600
1601 q = p = makestrspace(len + 3, p);
1602
1603 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001604 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001606
1607 STADJUST(q - p, p);
1608 } while (*s);
1609
Denys Vlasenkocd716832009-11-28 22:14:02 +01001610 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001611
1612 return stackblock();
1613}
1614
1615
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001616/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001617
1618static char **argptr; /* argument list for builtin commands */
1619static char *optionarg; /* set by nextopt (like getopt) */
1620static char *optptr; /* used by nextopt */
1621
1622/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001626 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001631 */
1632static int
1633nextopt(const char *optstring)
1634{
1635 char *p;
1636 const char *q;
1637 char c;
1638
1639 p = optptr;
1640 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 if (p == NULL)
1644 return '\0';
1645 if (*p != '-')
1646 return '\0';
1647 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 return '\0';
1649 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001656 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001658 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 if (*++q == ':')
1660 q++;
1661 }
1662 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001663 if (*p == '\0') {
1664 p = *argptr++;
1665 if (p == NULL)
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1667 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001668 optionarg = p;
1669 p = NULL;
1670 }
1671 optptr = p;
1672 return c;
1673}
1674
1675
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001676/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001677
Denis Vlasenko01631112007-12-16 17:20:38 +00001678/*
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1681 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001682struct shparam {
1683 int nparam; /* # of positional parameters (without $0) */
1684#if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1687#endif
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1690};
1691
1692/*
1693 * Free the list of positional parameters.
1694 */
1695static void
1696freeparam(volatile struct shparam *param)
1697{
Denis Vlasenko01631112007-12-16 17:20:38 +00001698 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001699 char **ap, **ap1;
1700 ap = ap1 = param->p;
1701 while (*ap)
1702 free(*ap++);
1703 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001704 }
1705}
1706
1707#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001708static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001709#endif
1710
1711struct var {
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
1714 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001715 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001716 /* the variable gets set/unset */
1717};
1718
1719struct localvar {
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1724};
1725
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726/* flags */
1727#define VEXPORT 0x01 /* variable is exported */
1728#define VREADONLY 0x02 /* variable cannot be modified */
1729#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730#define VTEXTFIXED 0x08 /* text is statically allocated */
1731#define VSTACK 0x10 /* text is allocated on the stack */
1732#define VUNSET 0x20 /* the variable is not set */
1733#define VNOFUNC 0x40 /* don't call the callback function */
1734#define VNOSET 0x80 /* do not set variable - just readonly test */
1735#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001736#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001737# define VDYNAMIC 0x200 /* dynamic variable */
1738#else
1739# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#endif
1741
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001742
Denis Vlasenko01631112007-12-16 17:20:38 +00001743/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001744#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001745static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001746change_lc_all(const char *value)
1747{
1748 if (value && *value != '\0')
1749 setlocale(LC_ALL, value);
1750}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001751static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001752change_lc_ctype(const char *value)
1753{
1754 if (value && *value != '\0')
1755 setlocale(LC_CTYPE, value);
1756}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001757#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001758#if ENABLE_ASH_MAIL
1759static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001760static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001764static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#endif
1766
Denis Vlasenko01631112007-12-16 17:20:38 +00001767static const struct {
1768 int flags;
1769 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001770 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001771} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1778 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001782 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#endif
1784#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#endif
1791#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001792 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794};
1795
Denis Vlasenko0b769642008-07-24 07:54:57 +00001796struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001797
1798struct globals_var {
1799 struct shparam shellparam; /* $@ current positional parameters */
1800 struct redirtab *redirlist;
1801 int g_nullredirs;
1802 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1803 struct var *vartab[VTABSIZE];
1804 struct var varinit[ARRAY_SIZE(varinit_data)];
1805};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001806extern struct globals_var *const ash_ptr_to_globals_var;
1807#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001808#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001809//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001810#define g_nullredirs (G_var.g_nullredirs )
1811#define preverrout_fd (G_var.preverrout_fd)
1812#define vartab (G_var.vartab )
1813#define varinit (G_var.varinit )
1814#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001815 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001816 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001818 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1819 varinit[i].flags = varinit_data[i].flags; \
1820 varinit[i].text = varinit_data[i].text; \
1821 varinit[i].func = varinit_data[i].func; \
1822 } \
1823} while (0)
1824
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001825#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001826#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827# define vmail (&vifs)[1]
1828# define vmpath (&vmail)[1]
1829# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001830#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001831# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833#define vps1 (&vpath)[1]
1834#define vps2 (&vps1)[1]
1835#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001836#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001837# define voptind (&vps4)[1]
1838# if ENABLE_ASH_RANDOM_SUPPORT
1839# define vrandom (&voptind)[1]
1840# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842# if ENABLE_ASH_RANDOM_SUPPORT
1843# define vrandom (&vps4)[1]
1844# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846
1847/*
1848 * The following macros access the values of the above variables.
1849 * They have to skip over the name. They return the null string
1850 * for unset variables.
1851 */
1852#define ifsval() (vifs.text + 4)
1853#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001854#if ENABLE_ASH_MAIL
1855# define mailval() (vmail.text + 5)
1856# define mpathval() (vmpath.text + 9)
1857# define mpathset() ((vmpath.flags & VUNSET) == 0)
1858#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001859#define pathval() (vpath.text + 5)
1860#define ps1val() (vps1.text + 4)
1861#define ps2val() (vps2.text + 4)
1862#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001863#if ENABLE_ASH_GETOPTS
1864# define optindval() (voptind.text + 7)
1865#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001866
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1869#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870
Denis Vlasenko01631112007-12-16 17:20:38 +00001871#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001872static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001873getoptsreset(const char *value)
1874{
1875 shellparam.optind = number(value);
1876 shellparam.optoff = -1;
1877}
1878#endif
1879
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001880/*
1881 * Return of a legal variable name (a letter or underscore followed by zero or
1882 * more letters, underscores, and digits).
1883 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001884static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001885endofname(const char *name)
1886{
1887 char *p;
1888
1889 p = (char *) name;
1890 if (!is_name(*p))
1891 return p;
1892 while (*++p) {
1893 if (!is_in_name(*p))
1894 break;
1895 }
1896 return p;
1897}
1898
1899/*
1900 * Compares two strings up to the first = or '\0'. The first
1901 * string must be terminated by '='; the second may be terminated by
1902 * either '=' or '\0'.
1903 */
1904static int
1905varcmp(const char *p, const char *q)
1906{
1907 int c, d;
1908
1909 while ((c = *p) == (d = *q)) {
1910 if (!c || c == '=')
1911 goto out;
1912 p++;
1913 q++;
1914 }
1915 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001916 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001917 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001918 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001919 out:
1920 return c - d;
1921}
1922
1923static int
1924varequal(const char *a, const char *b)
1925{
1926 return !varcmp(a, b);
1927}
1928
1929/*
1930 * Find the appropriate entry in the hash table from the name.
1931 */
1932static struct var **
1933hashvar(const char *p)
1934{
1935 unsigned hashval;
1936
1937 hashval = ((unsigned char) *p) << 4;
1938 while (*p && *p != '=')
1939 hashval += (unsigned char) *p++;
1940 return &vartab[hashval % VTABSIZE];
1941}
1942
1943static int
1944vpcmp(const void *a, const void *b)
1945{
1946 return varcmp(*(const char **)a, *(const char **)b);
1947}
1948
1949/*
1950 * This routine initializes the builtin variables.
1951 */
1952static void
1953initvar(void)
1954{
1955 struct var *vp;
1956 struct var *end;
1957 struct var **vpp;
1958
1959 /*
1960 * PS1 depends on uid
1961 */
1962#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1963 vps1.text = "PS1=\\w \\$ ";
1964#else
1965 if (!geteuid())
1966 vps1.text = "PS1=# ";
1967#endif
1968 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001969 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001970 do {
1971 vpp = hashvar(vp->text);
1972 vp->next = *vpp;
1973 *vpp = vp;
1974 } while (++vp < end);
1975}
1976
1977static struct var **
1978findvar(struct var **vpp, const char *name)
1979{
1980 for (; *vpp; vpp = &(*vpp)->next) {
1981 if (varequal((*vpp)->text, name)) {
1982 break;
1983 }
1984 }
1985 return vpp;
1986}
1987
1988/*
1989 * Find the value of a variable. Returns NULL if not set.
1990 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001991static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001992lookupvar(const char *name)
1993{
1994 struct var *v;
1995
1996 v = *findvar(hashvar(name), name);
1997 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001998#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001999 /*
2000 * Dynamic variables are implemented roughly the same way they are
2001 * in bash. Namely, they're "special" so long as they aren't unset.
2002 * As soon as they're unset, they're no longer dynamic, and dynamic
2003 * lookup will no longer happen at that point. -- PFM.
2004 */
2005 if ((v->flags & VDYNAMIC))
2006 (*v->func)(NULL);
2007#endif
2008 if (!(v->flags & VUNSET))
2009 return strchrnul(v->text, '=') + 1;
2010 }
2011 return NULL;
2012}
2013
2014/*
2015 * Search the environment of a builtin command.
2016 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002017static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002018bltinlookup(const char *name)
2019{
2020 struct strlist *sp;
2021
2022 for (sp = cmdenviron; sp; sp = sp->next) {
2023 if (varequal(sp->text, name))
2024 return strchrnul(sp->text, '=') + 1;
2025 }
2026 return lookupvar(name);
2027}
2028
2029/*
2030 * Same as setvar except that the variable and value are passed in
2031 * the first argument as name=value. Since the first argument will
2032 * be actually stored in the table, it should not be a string that
2033 * will go away.
2034 * Called with interrupts off.
2035 */
2036static void
2037setvareq(char *s, int flags)
2038{
2039 struct var *vp, **vpp;
2040
2041 vpp = hashvar(s);
2042 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2043 vp = *findvar(vpp, s);
2044 if (vp) {
2045 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2046 const char *n;
2047
2048 if (flags & VNOSAVE)
2049 free(s);
2050 n = vp->text;
2051 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2052 }
2053
2054 if (flags & VNOSET)
2055 return;
2056
2057 if (vp->func && (flags & VNOFUNC) == 0)
2058 (*vp->func)(strchrnul(s, '=') + 1);
2059
2060 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2061 free((char*)vp->text);
2062
2063 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2064 } else {
2065 if (flags & VNOSET)
2066 return;
2067 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002068 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002069 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002070 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002071 *vpp = vp;
2072 }
2073 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2074 s = ckstrdup(s);
2075 vp->text = s;
2076 vp->flags = flags;
2077}
2078
2079/*
2080 * Set the value of a variable. The flags argument is ored with the
2081 * flags of the variable. If val is NULL, the variable is unset.
2082 */
2083static void
2084setvar(const char *name, const char *val, int flags)
2085{
2086 char *p, *q;
2087 size_t namelen;
2088 char *nameeq;
2089 size_t vallen;
2090
2091 q = endofname(name);
2092 p = strchrnul(q, '=');
2093 namelen = p - name;
2094 if (!namelen || p != q)
2095 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2096 vallen = 0;
2097 if (val == NULL) {
2098 flags |= VUNSET;
2099 } else {
2100 vallen = strlen(val);
2101 }
2102 INT_OFF;
2103 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002104 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002105 if (val) {
2106 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002107 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002108 }
2109 *p = '\0';
2110 setvareq(nameeq, flags | VNOSAVE);
2111 INT_ON;
2112}
2113
Denys Vlasenko03dad222010-01-12 23:29:57 +01002114static void FAST_FUNC
2115setvar2(const char *name, const char *val)
2116{
2117 setvar(name, val, 0);
2118}
2119
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002120#if ENABLE_ASH_GETOPTS
2121/*
2122 * Safe version of setvar, returns 1 on success 0 on failure.
2123 */
2124static int
2125setvarsafe(const char *name, const char *val, int flags)
2126{
2127 int err;
2128 volatile int saveint;
2129 struct jmploc *volatile savehandler = exception_handler;
2130 struct jmploc jmploc;
2131
2132 SAVE_INT(saveint);
2133 if (setjmp(jmploc.loc))
2134 err = 1;
2135 else {
2136 exception_handler = &jmploc;
2137 setvar(name, val, flags);
2138 err = 0;
2139 }
2140 exception_handler = savehandler;
2141 RESTORE_INT(saveint);
2142 return err;
2143}
2144#endif
2145
2146/*
2147 * Unset the specified variable.
2148 */
2149static int
2150unsetvar(const char *s)
2151{
2152 struct var **vpp;
2153 struct var *vp;
2154 int retval;
2155
2156 vpp = findvar(hashvar(s), s);
2157 vp = *vpp;
2158 retval = 2;
2159 if (vp) {
2160 int flags = vp->flags;
2161
2162 retval = 1;
2163 if (flags & VREADONLY)
2164 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002165#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002166 vp->flags &= ~VDYNAMIC;
2167#endif
2168 if (flags & VUNSET)
2169 goto ok;
2170 if ((flags & VSTRFIXED) == 0) {
2171 INT_OFF;
2172 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2173 free((char*)vp->text);
2174 *vpp = vp->next;
2175 free(vp);
2176 INT_ON;
2177 } else {
2178 setvar(s, 0, 0);
2179 vp->flags &= ~VEXPORT;
2180 }
2181 ok:
2182 retval = 0;
2183 }
2184 out:
2185 return retval;
2186}
2187
2188/*
2189 * Process a linked list of variable assignments.
2190 */
2191static void
2192listsetvar(struct strlist *list_set_var, int flags)
2193{
2194 struct strlist *lp = list_set_var;
2195
2196 if (!lp)
2197 return;
2198 INT_OFF;
2199 do {
2200 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002201 lp = lp->next;
2202 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002203 INT_ON;
2204}
2205
2206/*
2207 * Generate a list of variables satisfying the given conditions.
2208 */
2209static char **
2210listvars(int on, int off, char ***end)
2211{
2212 struct var **vpp;
2213 struct var *vp;
2214 char **ep;
2215 int mask;
2216
2217 STARTSTACKSTR(ep);
2218 vpp = vartab;
2219 mask = on | off;
2220 do {
2221 for (vp = *vpp; vp; vp = vp->next) {
2222 if ((vp->flags & mask) == on) {
2223 if (ep == stackstrend())
2224 ep = growstackstr();
2225 *ep++ = (char *) vp->text;
2226 }
2227 }
2228 } while (++vpp < vartab + VTABSIZE);
2229 if (ep == stackstrend())
2230 ep = growstackstr();
2231 if (end)
2232 *end = ep;
2233 *ep++ = NULL;
2234 return grabstackstr(ep);
2235}
2236
2237
2238/* ============ Path search helper
2239 *
2240 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002241 * of the path before the first call; path_advance will update
2242 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002243 * the possible path expansions in sequence. If an option (indicated by
2244 * a percent sign) appears in the path entry then the global variable
2245 * pathopt will be set to point to it; otherwise pathopt will be set to
2246 * NULL.
2247 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002248static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002249
2250static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002251path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002252{
2253 const char *p;
2254 char *q;
2255 const char *start;
2256 size_t len;
2257
2258 if (*path == NULL)
2259 return NULL;
2260 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002261 for (p = start; *p && *p != ':' && *p != '%'; p++)
2262 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002263 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2264 while (stackblocksize() < len)
2265 growstackblock();
2266 q = stackblock();
2267 if (p != start) {
2268 memcpy(q, start, p - start);
2269 q += p - start;
2270 *q++ = '/';
2271 }
2272 strcpy(q, name);
2273 pathopt = NULL;
2274 if (*p == '%') {
2275 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002276 while (*p && *p != ':')
2277 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002278 }
2279 if (*p == ':')
2280 *path = p + 1;
2281 else
2282 *path = NULL;
2283 return stalloc(len);
2284}
2285
2286
2287/* ============ Prompt */
2288
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002289static smallint doprompt; /* if set, prompt the user */
2290static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002291
2292#if ENABLE_FEATURE_EDITING
2293static line_input_t *line_input_state;
2294static const char *cmdedit_prompt;
2295static void
2296putprompt(const char *s)
2297{
2298 if (ENABLE_ASH_EXPAND_PRMT) {
2299 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002300 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002301 return;
2302 }
2303 cmdedit_prompt = s;
2304}
2305#else
2306static void
2307putprompt(const char *s)
2308{
2309 out2str(s);
2310}
2311#endif
2312
2313#if ENABLE_ASH_EXPAND_PRMT
2314/* expandstr() needs parsing machinery, so it is far away ahead... */
2315static const char *expandstr(const char *ps);
2316#else
2317#define expandstr(s) s
2318#endif
2319
2320static void
2321setprompt(int whichprompt)
2322{
2323 const char *prompt;
2324#if ENABLE_ASH_EXPAND_PRMT
2325 struct stackmark smark;
2326#endif
2327
2328 needprompt = 0;
2329
2330 switch (whichprompt) {
2331 case 1:
2332 prompt = ps1val();
2333 break;
2334 case 2:
2335 prompt = ps2val();
2336 break;
2337 default: /* 0 */
2338 prompt = nullstr;
2339 }
2340#if ENABLE_ASH_EXPAND_PRMT
2341 setstackmark(&smark);
2342 stalloc(stackblocksize());
2343#endif
2344 putprompt(expandstr(prompt));
2345#if ENABLE_ASH_EXPAND_PRMT
2346 popstackmark(&smark);
2347#endif
2348}
2349
2350
2351/* ============ The cd and pwd commands */
2352
2353#define CD_PHYSICAL 1
2354#define CD_PRINT 2
2355
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002356static int
2357cdopt(void)
2358{
2359 int flags = 0;
2360 int i, j;
2361
2362 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002363 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002364 if (i != j) {
2365 flags ^= CD_PHYSICAL;
2366 j = i;
2367 }
2368 }
2369
2370 return flags;
2371}
2372
2373/*
2374 * Update curdir (the name of the current directory) in response to a
2375 * cd command.
2376 */
2377static const char *
2378updatepwd(const char *dir)
2379{
2380 char *new;
2381 char *p;
2382 char *cdcomppath;
2383 const char *lim;
2384
2385 cdcomppath = ststrdup(dir);
2386 STARTSTACKSTR(new);
2387 if (*dir != '/') {
2388 if (curdir == nullstr)
2389 return 0;
2390 new = stack_putstr(curdir, new);
2391 }
2392 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002393 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002394 if (*dir != '/') {
2395 if (new[-1] != '/')
2396 USTPUTC('/', new);
2397 if (new > lim && *lim == '/')
2398 lim++;
2399 } else {
2400 USTPUTC('/', new);
2401 cdcomppath++;
2402 if (dir[1] == '/' && dir[2] != '/') {
2403 USTPUTC('/', new);
2404 cdcomppath++;
2405 lim++;
2406 }
2407 }
2408 p = strtok(cdcomppath, "/");
2409 while (p) {
2410 switch (*p) {
2411 case '.':
2412 if (p[1] == '.' && p[2] == '\0') {
2413 while (new > lim) {
2414 STUNPUTC(new);
2415 if (new[-1] == '/')
2416 break;
2417 }
2418 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002419 }
2420 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002421 break;
2422 /* fall through */
2423 default:
2424 new = stack_putstr(p, new);
2425 USTPUTC('/', new);
2426 }
2427 p = strtok(0, "/");
2428 }
2429 if (new > lim)
2430 STUNPUTC(new);
2431 *new = 0;
2432 return stackblock();
2433}
2434
2435/*
2436 * Find out what the current directory is. If we already know the current
2437 * directory, this routine returns immediately.
2438 */
2439static char *
2440getpwd(void)
2441{
Denis Vlasenko01631112007-12-16 17:20:38 +00002442 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002443 return dir ? dir : nullstr;
2444}
2445
2446static void
2447setpwd(const char *val, int setold)
2448{
2449 char *oldcur, *dir;
2450
2451 oldcur = dir = curdir;
2452
2453 if (setold) {
2454 setvar("OLDPWD", oldcur, VEXPORT);
2455 }
2456 INT_OFF;
2457 if (physdir != nullstr) {
2458 if (physdir != oldcur)
2459 free(physdir);
2460 physdir = nullstr;
2461 }
2462 if (oldcur == val || !val) {
2463 char *s = getpwd();
2464 physdir = s;
2465 if (!val)
2466 dir = s;
2467 } else
2468 dir = ckstrdup(val);
2469 if (oldcur != dir && oldcur != nullstr) {
2470 free(oldcur);
2471 }
2472 curdir = dir;
2473 INT_ON;
2474 setvar("PWD", dir, VEXPORT);
2475}
2476
2477static void hashcd(void);
2478
2479/*
2480 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2481 * know that the current directory has changed.
2482 */
2483static int
2484docd(const char *dest, int flags)
2485{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002486 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002487 int err;
2488
2489 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2490
2491 INT_OFF;
2492 if (!(flags & CD_PHYSICAL)) {
2493 dir = updatepwd(dest);
2494 if (dir)
2495 dest = dir;
2496 }
2497 err = chdir(dest);
2498 if (err)
2499 goto out;
2500 setpwd(dir, 1);
2501 hashcd();
2502 out:
2503 INT_ON;
2504 return err;
2505}
2506
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002507static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002508cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002509{
2510 const char *dest;
2511 const char *path;
2512 const char *p;
2513 char c;
2514 struct stat statb;
2515 int flags;
2516
2517 flags = cdopt();
2518 dest = *argptr;
2519 if (!dest)
2520 dest = bltinlookup(homestr);
2521 else if (LONE_DASH(dest)) {
2522 dest = bltinlookup("OLDPWD");
2523 flags |= CD_PRINT;
2524 }
2525 if (!dest)
2526 dest = nullstr;
2527 if (*dest == '/')
2528 goto step7;
2529 if (*dest == '.') {
2530 c = dest[1];
2531 dotdot:
2532 switch (c) {
2533 case '\0':
2534 case '/':
2535 goto step6;
2536 case '.':
2537 c = dest[2];
2538 if (c != '.')
2539 goto dotdot;
2540 }
2541 }
2542 if (!*dest)
2543 dest = ".";
2544 path = bltinlookup("CDPATH");
2545 if (!path) {
2546 step6:
2547 step7:
2548 p = dest;
2549 goto docd;
2550 }
2551 do {
2552 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002553 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002554 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2555 if (c && c != ':')
2556 flags |= CD_PRINT;
2557 docd:
2558 if (!docd(p, flags))
2559 goto out;
2560 break;
2561 }
2562 } while (path);
2563 ash_msg_and_raise_error("can't cd to %s", dest);
2564 /* NOTREACHED */
2565 out:
2566 if (flags & CD_PRINT)
2567 out1fmt(snlfmt, curdir);
2568 return 0;
2569}
2570
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002571static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002572pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002573{
2574 int flags;
2575 const char *dir = curdir;
2576
2577 flags = cdopt();
2578 if (flags) {
2579 if (physdir == nullstr)
2580 setpwd(dir, 0);
2581 dir = physdir;
2582 }
2583 out1fmt(snlfmt, dir);
2584 return 0;
2585}
2586
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002587
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002588/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002589
Denis Vlasenko834dee72008-10-07 09:18:30 +00002590
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002591#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592/* buffer for top level input file */
2593#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002594
Eric Andersenc470f442003-07-28 09:56:35 +00002595/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002596#define CWORD 0 /* character is nothing special */
2597#define CNL 1 /* newline character */
2598#define CBACK 2 /* a backslash character */
2599#define CSQUOTE 3 /* single quote */
2600#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002602#define CBQUOTE 6 /* backwards single quote */
2603#define CVAR 7 /* a dollar sign */
2604#define CENDVAR 8 /* a '}' character */
2605#define CLP 9 /* a left paren in arithmetic */
2606#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002607#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002608#define CCTL 12 /* like CWORD, except it must be escaped */
2609#define CSPCL 13 /* these terminate a word */
2610#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002611
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002612#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002613#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002614# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002615#endif
2616
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002617#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002618
Mike Frysinger98c52642009-04-02 10:02:37 +00002619#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002621#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002624static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002625#if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627#endif
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002639#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2643#endif
2644#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002645};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002646/* Constants below must match table above */
2647enum {
2648#if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650#endif
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2665};
Eric Andersen2870d962001-07-02 17:27:21 +00002666
Denys Vlasenkocd716832009-11-28 22:14:02 +01002667/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2669 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002670/* Values for syntax param */
2671#define BASESYNTAX 0 /* not in quotes */
2672#define DQSYNTAX 1 /* in double quotes */
2673#define SQSYNTAX 2 /* in single quotes */
2674#define ARISYNTAX 3 /* in arithmetic */
2675#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002676
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002677#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002678
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002679static int
2680SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002681{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002683# if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2688 11, 3 /* "}~" */
2689 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002690# else
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2695 10, 2 /* "}~" */
2696 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002697# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002698 const char *s;
2699 int indx;
2700
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002702 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002703# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002706 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002707# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 ) {
2714 return CCTL;
2715 }
2716 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002717 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002719 indx = syntax_index_table[s - spec_symbls];
2720 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002722}
2723
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002724#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002725
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002726static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002985# if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2987# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002988};
2989
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002990# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002991
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002992#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002993
Eric Andersen2870d962001-07-02 17:27:21 +00002994
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002995/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002996
Denis Vlasenko131ae172007-02-18 13:00:19 +00002997#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002998
2999#define ALIASINUSE 1
3000#define ALIASDEAD 2
3001
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003002struct alias {
3003 struct alias *next;
3004 char *name;
3005 char *val;
3006 int flag;
3007};
3008
Denis Vlasenko01631112007-12-16 17:20:38 +00003009
3010static struct alias **atab; // [ATABSIZE];
3011#define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3013} while (0)
3014
Eric Andersen2870d962001-07-02 17:27:21 +00003015
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003016static struct alias **
3017__lookupalias(const char *name) {
3018 unsigned int hashval;
3019 struct alias **app;
3020 const char *p;
3021 unsigned int ch;
3022
3023 p = name;
3024
3025 ch = (unsigned char)*p;
3026 hashval = ch << 4;
3027 while (ch) {
3028 hashval += ch;
3029 ch = (unsigned char)*++p;
3030 }
3031 app = &atab[hashval % ATABSIZE];
3032
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3035 break;
3036 }
3037 }
3038
3039 return app;
3040}
3041
3042static struct alias *
3043lookupalias(const char *name, int check)
3044{
3045 struct alias *ap = *__lookupalias(name);
3046
3047 if (check && ap && (ap->flag & ALIASINUSE))
3048 return NULL;
3049 return ap;
3050}
3051
3052static struct alias *
3053freealias(struct alias *ap)
3054{
3055 struct alias *next;
3056
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3059 return ap;
3060 }
3061
3062 next = ap->next;
3063 free(ap->name);
3064 free(ap->val);
3065 free(ap);
3066 return next;
3067}
Eric Andersencb57d552001-06-28 07:25:16 +00003068
Eric Andersenc470f442003-07-28 09:56:35 +00003069static void
3070setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003071{
3072 struct alias *ap, **app;
3073
3074 app = __lookupalias(name);
3075 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003076 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003077 if (ap) {
3078 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003079 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003080 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003081 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003082 ap->flag &= ~ALIASDEAD;
3083 } else {
3084 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003085 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003090 *app = ap;
3091 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003092 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003093}
3094
Eric Andersenc470f442003-07-28 09:56:35 +00003095static int
3096unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003097{
Eric Andersencb57d552001-06-28 07:25:16 +00003098 struct alias **app;
3099
3100 app = __lookupalias(name);
3101
3102 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003103 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003104 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003106 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003107 }
3108
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003109 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003110}
3111
Eric Andersenc470f442003-07-28 09:56:35 +00003112static void
3113rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003114{
Eric Andersencb57d552001-06-28 07:25:16 +00003115 struct alias *ap, **app;
3116 int i;
3117
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003119 for (i = 0; i < ATABSIZE; i++) {
3120 app = &atab[i];
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3123 if (ap == *app) {
3124 app = &ap->next;
3125 }
3126 }
3127 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003128 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003129}
3130
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003131static void
3132printalias(const struct alias *ap)
3133{
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3135}
3136
Eric Andersencb57d552001-06-28 07:25:16 +00003137/*
3138 * TODO - sort output
3139 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003140static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003141aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003142{
3143 char *n, *v;
3144 int ret = 0;
3145 struct alias *ap;
3146
Denis Vlasenko68404f12008-03-17 09:00:54 +00003147 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003148 int i;
3149
Denis Vlasenko68404f12008-03-17 09:00:54 +00003150 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003151 for (ap = atab[i]; ap; ap = ap->next) {
3152 printalias(ap);
3153 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003154 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003155 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003156 }
3157 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3161 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003162 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003163 ret = 1;
3164 } else
3165 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003166 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003167 *v++ = '\0';
3168 setalias(n, v);
3169 }
3170 }
3171
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003172 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003173}
3174
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003175static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003176unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003177{
3178 int i;
3179
3180 while ((i = nextopt("a")) != '\0') {
3181 if (i == 'a') {
3182 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003183 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003184 }
3185 }
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003189 i = 1;
3190 }
3191 }
3192
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003193 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003194}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003195
Denis Vlasenko131ae172007-02-18 13:00:19 +00003196#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003197
Eric Andersenc470f442003-07-28 09:56:35 +00003198
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003199/* ============ jobs.c */
3200
3201/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003202#define FORK_FG 0
3203#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003204#define FORK_NOJOB 2
3205
3206/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003207#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003210
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211/*
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3215 * array of pids.
3216 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003217struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003221};
3222
3223struct job {
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3226#if JOBS
3227 int stopstatus; /* status of a stopped job */
3228#endif
3229 uint32_t
3230 nprocs: 16, /* number of processes */
3231 state: 8,
3232#define JOBRUNNING 0 /* at least one proc running */
3233#define JOBSTOPPED 1 /* all procs are stopped */
3234#define JOBDONE 2 /* all procs are completed */
3235#if JOBS
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3238#endif
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3243};
3244
Denis Vlasenko68404f12008-03-17 09:00:54 +00003245static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246static int forkshell(struct job *, union node *, int);
3247static int waitforjob(struct job *);
3248
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003249#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003250enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003251#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003253static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003254static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255#endif
3256
3257/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003258 * Ignore a signal.
3259 */
3260static void
3261ignoresig(int signo)
3262{
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3267 }
3268 sigmode[signo - 1] = S_HARD_IGN;
3269}
3270
3271/*
3272 * Signal handler. Only one usage site - in setsignal()
3273 */
3274static void
3275onsig(int signo)
3276{
3277 gotsig[signo - 1] = 1;
3278
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3281 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 raise_interrupt(); /* does not return */
3283 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003284 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003285 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003286 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 }
3288}
3289
3290/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3293 */
3294static void
3295setsignal(int signo)
3296{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003297 char *t;
3298 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003299 struct sigaction act;
3300
3301 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003302 new_act = S_DFL;
3303 if (t != NULL) { /* trap for this sig is set */
3304 new_act = S_CATCH;
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3306 new_act = S_IGN;
3307 }
3308
3309 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003310 switch (signo) {
3311 case SIGINT:
3312 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003313 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003314 break;
3315 case SIGQUIT:
3316#if DEBUG
3317 if (debug)
3318 break;
3319#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003320 /* man bash:
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3325 new_act = S_IGN;
3326 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 case SIGTERM:
3328 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 break;
3331#if JOBS
3332 case SIGTSTP:
3333 case SIGTTOU:
3334 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003335 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003336 break;
3337#endif
3338 }
3339 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003340//TODO: if !rootshell, we reset SIGQUIT to DFL,
3341//whereas we have to restore it to what shell got on entry
3342//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343
3344 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 cur_act = *t;
3346 if (cur_act == 0) {
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 return;
3354 }
3355 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003356 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 if (mflag
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003361 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 }
3363 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003366
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003367 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 case S_CATCH:
3370 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003373 break;
3374 case S_IGN:
3375 act.sa_handler = SIG_IGN;
3376 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003377 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003378 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379
3380 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003381}
3382
3383/* mode flags for set_curjob */
3384#define CUR_DELETE 2
3385#define CUR_RUNNING 1
3386#define CUR_STOPPED 0
3387
3388/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003389#define DOWAIT_NONBLOCK WNOHANG
3390#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391
3392#if JOBS
3393/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static int initialpgrp; //references:2
3395static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396#endif
3397/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003398static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003400static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003402static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003403/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003404static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405
3406static void
3407set_curjob(struct job *jp, unsigned mode)
3408{
3409 struct job *jp1;
3410 struct job **jpp, **curp;
3411
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3414 do {
3415 jp1 = *jpp;
3416 if (jp1 == jp)
3417 break;
3418 jpp = &jp1->prev_job;
3419 } while (1);
3420 *jpp = jp1->prev_job;
3421
3422 /* Then re-insert in correct position */
3423 jpp = curp;
3424 switch (mode) {
3425 default:
3426#if DEBUG
3427 abort();
3428#endif
3429 case CUR_DELETE:
3430 /* job being deleted */
3431 break;
3432 case CUR_RUNNING:
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3435 do {
3436 jp1 = *jpp;
3437#if JOBS
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3439#endif
3440 break;
3441 jpp = &jp1->prev_job;
3442 } while (1);
3443 /* FALLTHROUGH */
3444#if JOBS
3445 case CUR_STOPPED:
3446#endif
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3449 *jpp = jp;
3450 break;
3451 }
3452}
3453
3454#if JOBS || DEBUG
3455static int
3456jobno(const struct job *jp)
3457{
3458 return jp - jobtab + 1;
3459}
3460#endif
3461
3462/*
3463 * Convert a job name to a job structure.
3464 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003465#if !JOBS
3466#define getjob(name, getctl) getjob(name)
3467#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003468static struct job *
3469getjob(const char *name, int getctl)
3470{
3471 struct job *jp;
3472 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003473 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003474 unsigned num;
3475 int c;
3476 const char *p;
3477 char *(*match)(const char *, const char *);
3478
3479 jp = curjob;
3480 p = name;
3481 if (!p)
3482 goto currentjob;
3483
3484 if (*p != '%')
3485 goto err;
3486
3487 c = *++p;
3488 if (!c)
3489 goto currentjob;
3490
3491 if (!p[1]) {
3492 if (c == '+' || c == '%') {
3493 currentjob:
3494 err_msg = "No current job";
3495 goto check;
3496 }
3497 if (c == '-') {
3498 if (jp)
3499 jp = jp->prev_job;
3500 err_msg = "No previous job";
3501 check:
3502 if (!jp)
3503 goto err;
3504 goto gotit;
3505 }
3506 }
3507
3508 if (is_number(p)) {
3509 num = atoi(p);
3510 if (num < njobs) {
3511 jp = jobtab + num - 1;
3512 if (jp->used)
3513 goto gotit;
3514 goto err;
3515 }
3516 }
3517
3518 match = prefix;
3519 if (*p == '?') {
3520 match = strstr;
3521 p++;
3522 }
3523
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003524 found = NULL;
3525 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003526 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003527 if (found)
3528 goto err;
3529 found = jp;
3530 err_msg = "%s: ambiguous";
3531 }
3532 jp = jp->prev_job;
3533 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003534 if (!found)
3535 goto err;
3536 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003537
3538 gotit:
3539#if JOBS
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3542 goto err;
3543#endif
3544 return jp;
3545 err:
3546 ash_msg_and_raise_error(err_msg, name);
3547}
3548
3549/*
3550 * Mark a job structure as unused.
3551 */
3552static void
3553freejob(struct job *jp)
3554{
3555 struct procstat *ps;
3556 int i;
3557
3558 INT_OFF;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003560 if (ps->ps_cmd != nullstr)
3561 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003562 }
3563 if (jp->ps != &jp->ps0)
3564 free(jp->ps);
3565 jp->used = 0;
3566 set_curjob(jp, CUR_DELETE);
3567 INT_ON;
3568}
3569
3570#if JOBS
3571static void
3572xtcsetpgrp(int fd, pid_t pgrp)
3573{
3574 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003575 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003576}
3577
3578/*
3579 * Turn job control on and off.
3580 *
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3584 *
3585 * Called with interrupts off.
3586 */
3587static void
3588setjobctl(int on)
3589{
3590 int fd;
3591 int pgrp;
3592
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003593 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003594 return;
3595 if (on) {
3596 int ofd;
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 if (fd < 0) {
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003603 fd = 2;
3604 while (!isatty(fd))
3605 if (--fd < 0)
3606 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003607 }
3608 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003609 if (ofd >= 0)
3610 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003611 if (fd < 0)
3612 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003613 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003614 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3617 if (pgrp < 0) {
3618 out:
3619 ash_msg("can't access tty; job control turned off");
3620 mflag = on = 0;
3621 goto close;
3622 }
3623 if (pgrp == getpgrp())
3624 break;
3625 killpg(0, SIGTTIN);
3626 } while (1);
3627 initialpgrp = pgrp;
3628
3629 setsignal(SIGTSTP);
3630 setsignal(SIGTTOU);
3631 setsignal(SIGTTIN);
3632 pgrp = rootpid;
3633 setpgid(0, pgrp);
3634 xtcsetpgrp(fd, pgrp);
3635 } else {
3636 /* turning job control off */
3637 fd = ttyfd;
3638 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003639 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003640 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003641 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003642 setpgid(0, pgrp);
3643 setsignal(SIGTSTP);
3644 setsignal(SIGTTOU);
3645 setsignal(SIGTTIN);
3646 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003647 if (fd >= 0)
3648 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003649 fd = -1;
3650 }
3651 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003652 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653}
3654
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003655static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656killcmd(int argc, char **argv)
3657{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003658 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003660 do {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003663 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003670 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003671 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003673 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674}
3675
3676static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003677showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003679 struct procstat *ps;
3680 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681
Denys Vlasenko285ad152009-12-04 23:02:27 +01003682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003686 flush_stdout_stderr();
3687}
3688
3689
3690static int
3691restartjob(struct job *jp, int mode)
3692{
3693 struct procstat *ps;
3694 int i;
3695 int status;
3696 pid_t pgid;
3697
3698 INT_OFF;
3699 if (jp->state == JOBDONE)
3700 goto out;
3701 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003702 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3706 ps = jp->ps;
3707 i = jp->nprocs;
3708 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003709 if (WIFSTOPPED(ps->ps_status)) {
3710 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 ps++;
3713 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714 out:
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3716 INT_ON;
3717 return status;
3718}
3719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003720static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003721fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003722{
3723 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003724 int mode;
3725 int retval;
3726
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 nextopt(nullstr);
3729 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 do {
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003734 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003735 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3740 return retval;
3741}
3742#endif
3743
3744static int
3745sprint_status(char *s, int status, int sigonly)
3746{
3747 int col;
3748 int st;
3749
3750 col = 0;
3751 if (!WIFEXITED(status)) {
3752#if JOBS
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3755 else
3756#endif
3757 st = WTERMSIG(status);
3758 if (sigonly) {
3759 if (st == SIGINT || st == SIGPIPE)
3760 goto out;
3761#if JOBS
3762 if (WIFSTOPPED(status))
3763 goto out;
3764#endif
3765 }
3766 st &= 0x7f;
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3770 }
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3773 if (st)
3774 col = fmtstr(s, 16, "Done(%d)", st);
3775 else
3776 col = fmtstr(s, 16, "Done");
3777 }
3778 out:
3779 return col;
3780}
3781
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003782static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003783dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784{
3785 int pid;
3786 int status;
3787 struct job *jp;
3788 struct job *thisjob;
3789 int state;
3790
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003791 TRACE(("dowait(0x%x) called\n", wait_flags));
3792
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003796 if (doing_jobctl)
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003801 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003802 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003803
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003804 INT_OFF;
3805 thisjob = NULL;
3806 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 struct procstat *ps;
3808 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809 if (jp->state == JOBDONE)
3810 continue;
3811 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 ps = jp->ps;
3813 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003814 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003820 thisjob = jp;
3821 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003822 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 state = JOBRUNNING;
3824#if JOBS
3825 if (state == JOBRUNNING)
3826 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003829 state = JOBSTOPPED;
3830 }
3831#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003832 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003833 if (thisjob)
3834 goto gotjob;
3835 }
3836#if JOBS
3837 if (!WIFSTOPPED(status))
3838#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003839 jobless--;
3840 goto out;
3841
3842 gotjob:
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3845
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3850#if JOBS
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3853 }
3854#endif
3855 }
3856 }
3857
3858 out:
3859 INT_ON;
3860
3861 if (thisjob && thisjob == job) {
3862 char s[48 + 1];
3863 int len;
3864
3865 len = sprint_status(s, status, 1);
3866 if (len) {
3867 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003868 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 out2str(s);
3870 }
3871 }
3872 return pid;
3873}
3874
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003875static int
3876blocking_wait_with_raise_on_sig(struct job *job)
3877{
3878 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003879 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003880 raise_exception(EXSIG);
3881 return pid;
3882}
3883
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884#if JOBS
3885static void
3886showjob(FILE *out, struct job *jp, int mode)
3887{
3888 struct procstat *ps;
3889 struct procstat *psend;
3890 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003891 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 char s[80];
3893
3894 ps = jp->ps;
3895
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003897 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003898 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 return;
3900 }
3901
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003903 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
3905 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003906 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003908 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003910 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912
3913 psend = ps + jp->nprocs;
3914
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3918 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003919 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3923 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3933 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003935 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003937 s[0] = '\0';
3938 col = 33;
3939 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003942 fprintf(out, "%s%*c%s%s",
3943 s,
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3946 ps->ps_cmd
3947 );
3948 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003949 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003950
3951 jp->changed = 0;
3952
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3955 freejob(jp);
3956 }
3957}
3958
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003959/*
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3962 */
3963static void
3964showjobs(FILE *out, int mode)
3965{
3966 struct job *jp;
3967
Denys Vlasenko883cea42009-07-11 15:31:59 +02003968 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003970 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972 continue;
3973
3974 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 }
3979}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003981static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003982jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983{
3984 int mode, m;
3985
3986 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003987 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003988 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003990 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003991 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 }
3993
3994 argv = argptr;
3995 if (*argv) {
3996 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003997 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003998 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003999 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004000 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004001 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004002
4003 return 0;
4004}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005#endif /* JOBS */
4006
Michael Abbott359da5e2009-12-04 23:03:29 +01004007/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008static int
4009getstatus(struct job *job)
4010{
4011 int status;
4012 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004013 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004014
Michael Abbott359da5e2009-12-04 23:03:29 +01004015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4018 if (pipefail) {
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4022 }
4023
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4026#if JOBS
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4029#endif
4030 {
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4033#if JOBS
4034 if (retval == SIGINT)
4035 job->sigint = 1;
4036#endif
4037 }
4038 retval += 128;
4039 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041 jobno(job), job->nprocs, status, retval));
4042 return retval;
4043}
4044
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004045static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004046waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004047{
4048 struct job *job;
4049 int retval;
4050 struct job *jp;
4051
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004052 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004053 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004054
4055 nextopt(nullstr);
4056 retval = 0;
4057
4058 argv = argptr;
4059 if (!*argv) {
4060 /* wait for all jobs */
4061 for (;;) {
4062 jp = curjob;
4063 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004064 if (!jp) /* no running procs */
4065 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066 if (jp->state == JOBRUNNING)
4067 break;
4068 jp->waited = 1;
4069 jp = jp->prev_job;
4070 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004071 /* man bash:
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
4077 * Do we do it that way? */
4078 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004079 }
4080 }
4081
4082 retval = 127;
4083 do {
4084 if (**argv != '%') {
4085 pid_t pid = number(*argv);
4086 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004087 while (1) {
4088 if (!job)
4089 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004090 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004091 break;
4092 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004093 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004094 } else
4095 job = getjob(*argv, 0);
4096 /* loop until process terminated or stopped */
4097 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004098 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004099 job->waited = 1;
4100 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004101 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004102 } while (*++argv);
4103
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004104 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004105 return retval;
4106}
4107
4108static struct job *
4109growjobtab(void)
4110{
4111 size_t len;
4112 ptrdiff_t offset;
4113 struct job *jp, *jq;
4114
4115 len = njobs * sizeof(*jp);
4116 jq = jobtab;
4117 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4118
4119 offset = (char *)jp - (char *)jq;
4120 if (offset) {
4121 /* Relocate pointers */
4122 size_t l = len;
4123
4124 jq = (struct job *)((char *)jq + l);
4125 while (l) {
4126 l -= sizeof(*jp);
4127 jq--;
4128#define joff(p) ((struct job *)((char *)(p) + l))
4129#define jmove(p) (p) = (void *)((char *)(p) + offset)
4130 if (joff(jp)->ps == &jq->ps0)
4131 jmove(joff(jp)->ps);
4132 if (joff(jp)->prev_job)
4133 jmove(joff(jp)->prev_job);
4134 }
4135 if (curjob)
4136 jmove(curjob);
4137#undef joff
4138#undef jmove
4139 }
4140
4141 njobs += 4;
4142 jobtab = jp;
4143 jp = (struct job *)((char *)jp + len);
4144 jq = jp + 3;
4145 do {
4146 jq->used = 0;
4147 } while (--jq >= jp);
4148 return jp;
4149}
4150
4151/*
4152 * Return a new job structure.
4153 * Called with interrupts off.
4154 */
4155static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004156makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004157{
4158 int i;
4159 struct job *jp;
4160
4161 for (i = njobs, jp = jobtab; ; jp++) {
4162 if (--i < 0) {
4163 jp = growjobtab();
4164 break;
4165 }
4166 if (jp->used == 0)
4167 break;
4168 if (jp->state != JOBDONE || !jp->waited)
4169 continue;
4170#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004171 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004172 continue;
4173#endif
4174 freejob(jp);
4175 break;
4176 }
4177 memset(jp, 0, sizeof(*jp));
4178#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004179 /* jp->jobctl is a bitfield.
4180 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004181 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004182 jp->jobctl = 1;
4183#endif
4184 jp->prev_job = curjob;
4185 curjob = jp;
4186 jp->used = 1;
4187 jp->ps = &jp->ps0;
4188 if (nprocs > 1) {
4189 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4190 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004191 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004192 jobno(jp)));
4193 return jp;
4194}
4195
4196#if JOBS
4197/*
4198 * Return a string identifying a command (to be printed by the
4199 * jobs command).
4200 */
4201static char *cmdnextc;
4202
4203static void
4204cmdputs(const char *s)
4205{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004206 static const char vstype[VSTYPE + 1][3] = {
4207 "", "}", "-", "+", "?", "=",
4208 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004209 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004210 };
4211
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004212 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004213 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004215 unsigned char c;
4216 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004218
Denys Vlasenko46a14772009-12-10 21:27:13 +01004219 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4221 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004222 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004223 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224 switch (c) {
4225 case CTLESC:
4226 c = *p++;
4227 break;
4228 case CTLVAR:
4229 subtype = *p++;
4230 if ((subtype & VSTYPE) == VSLENGTH)
4231 str = "${#";
4232 else
4233 str = "${";
4234 if (!(subtype & VSQUOTE) == !(quoted & 1))
4235 goto dostr;
4236 quoted ^= 1;
4237 c = '"';
4238 break;
4239 case CTLENDVAR:
4240 str = "\"}" + !(quoted & 1);
4241 quoted >>= 1;
4242 subtype = 0;
4243 goto dostr;
4244 case CTLBACKQ:
4245 str = "$(...)";
4246 goto dostr;
4247 case CTLBACKQ+CTLQUOTE:
4248 str = "\"$(...)\"";
4249 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004250#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004251 case CTLARI:
4252 str = "$((";
4253 goto dostr;
4254 case CTLENDARI:
4255 str = "))";
4256 goto dostr;
4257#endif
4258 case CTLQUOTEMARK:
4259 quoted ^= 1;
4260 c = '"';
4261 break;
4262 case '=':
4263 if (subtype == 0)
4264 break;
4265 if ((subtype & VSTYPE) != VSNORMAL)
4266 quoted <<= 1;
4267 str = vstype[subtype & VSTYPE];
4268 if (subtype & VSNUL)
4269 c = ':';
4270 else
4271 goto checkstr;
4272 break;
4273 case '\'':
4274 case '\\':
4275 case '"':
4276 case '$':
4277 /* These can only happen inside quotes */
4278 cc[0] = c;
4279 str = cc;
4280 c = '\\';
4281 break;
4282 default:
4283 break;
4284 }
4285 USTPUTC(c, nextc);
4286 checkstr:
4287 if (!str)
4288 continue;
4289 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004290 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004291 USTPUTC(c, nextc);
4292 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004293 } /* while *p++ not NUL */
4294
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004295 if (quoted & 1) {
4296 USTPUTC('"', nextc);
4297 }
4298 *nextc = 0;
4299 cmdnextc = nextc;
4300}
4301
4302/* cmdtxt() and cmdlist() call each other */
4303static void cmdtxt(union node *n);
4304
4305static void
4306cmdlist(union node *np, int sep)
4307{
4308 for (; np; np = np->narg.next) {
4309 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004310 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004311 cmdtxt(np);
4312 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004313 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004314 }
4315}
4316
4317static void
4318cmdtxt(union node *n)
4319{
4320 union node *np;
4321 struct nodelist *lp;
4322 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004323
4324 if (!n)
4325 return;
4326 switch (n->type) {
4327 default:
4328#if DEBUG
4329 abort();
4330#endif
4331 case NPIPE:
4332 lp = n->npipe.cmdlist;
4333 for (;;) {
4334 cmdtxt(lp->n);
4335 lp = lp->next;
4336 if (!lp)
4337 break;
4338 cmdputs(" | ");
4339 }
4340 break;
4341 case NSEMI:
4342 p = "; ";
4343 goto binop;
4344 case NAND:
4345 p = " && ";
4346 goto binop;
4347 case NOR:
4348 p = " || ";
4349 binop:
4350 cmdtxt(n->nbinary.ch1);
4351 cmdputs(p);
4352 n = n->nbinary.ch2;
4353 goto donode;
4354 case NREDIR:
4355 case NBACKGND:
4356 n = n->nredir.n;
4357 goto donode;
4358 case NNOT:
4359 cmdputs("!");
4360 n = n->nnot.com;
4361 donode:
4362 cmdtxt(n);
4363 break;
4364 case NIF:
4365 cmdputs("if ");
4366 cmdtxt(n->nif.test);
4367 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004368 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004369 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004370 cmdputs("; else ");
4371 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004372 } else {
4373 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004374 }
4375 p = "; fi";
4376 goto dotail;
4377 case NSUBSHELL:
4378 cmdputs("(");
4379 n = n->nredir.n;
4380 p = ")";
4381 goto dotail;
4382 case NWHILE:
4383 p = "while ";
4384 goto until;
4385 case NUNTIL:
4386 p = "until ";
4387 until:
4388 cmdputs(p);
4389 cmdtxt(n->nbinary.ch1);
4390 n = n->nbinary.ch2;
4391 p = "; done";
4392 dodo:
4393 cmdputs("; do ");
4394 dotail:
4395 cmdtxt(n);
4396 goto dotail2;
4397 case NFOR:
4398 cmdputs("for ");
4399 cmdputs(n->nfor.var);
4400 cmdputs(" in ");
4401 cmdlist(n->nfor.args, 1);
4402 n = n->nfor.body;
4403 p = "; done";
4404 goto dodo;
4405 case NDEFUN:
4406 cmdputs(n->narg.text);
4407 p = "() { ... }";
4408 goto dotail2;
4409 case NCMD:
4410 cmdlist(n->ncmd.args, 1);
4411 cmdlist(n->ncmd.redirect, 0);
4412 break;
4413 case NARG:
4414 p = n->narg.text;
4415 dotail2:
4416 cmdputs(p);
4417 break;
4418 case NHERE:
4419 case NXHERE:
4420 p = "<<...";
4421 goto dotail2;
4422 case NCASE:
4423 cmdputs("case ");
4424 cmdputs(n->ncase.expr->narg.text);
4425 cmdputs(" in ");
4426 for (np = n->ncase.cases; np; np = np->nclist.next) {
4427 cmdtxt(np->nclist.pattern);
4428 cmdputs(") ");
4429 cmdtxt(np->nclist.body);
4430 cmdputs(";; ");
4431 }
4432 p = "esac";
4433 goto dotail2;
4434 case NTO:
4435 p = ">";
4436 goto redir;
4437 case NCLOBBER:
4438 p = ">|";
4439 goto redir;
4440 case NAPPEND:
4441 p = ">>";
4442 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004443#if ENABLE_ASH_BASH_COMPAT
4444 case NTO2:
4445#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004446 case NTOFD:
4447 p = ">&";
4448 goto redir;
4449 case NFROM:
4450 p = "<";
4451 goto redir;
4452 case NFROMFD:
4453 p = "<&";
4454 goto redir;
4455 case NFROMTO:
4456 p = "<>";
4457 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004458 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004459 cmdputs(p);
4460 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004461 cmdputs(utoa(n->ndup.dupfd));
4462 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004463 }
4464 n = n->nfile.fname;
4465 goto donode;
4466 }
4467}
4468
4469static char *
4470commandtext(union node *n)
4471{
4472 char *name;
4473
4474 STARTSTACKSTR(cmdnextc);
4475 cmdtxt(n);
4476 name = stackblock();
4477 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4478 name, cmdnextc, cmdnextc));
4479 return ckstrdup(name);
4480}
4481#endif /* JOBS */
4482
4483/*
4484 * Fork off a subshell. If we are doing job control, give the subshell its
4485 * own process group. Jp is a job structure that the job is to be added to.
4486 * N is the command that will be evaluated by the child. Both jp and n may
4487 * be NULL. The mode parameter can be one of the following:
4488 * FORK_FG - Fork off a foreground process.
4489 * FORK_BG - Fork off a background process.
4490 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4491 * process group even if job control is on.
4492 *
4493 * When job control is turned off, background processes have their standard
4494 * input redirected to /dev/null (except for the second and later processes
4495 * in a pipeline).
4496 *
4497 * Called with interrupts off.
4498 */
4499/*
4500 * Clear traps on a fork.
4501 */
4502static void
4503clear_traps(void)
4504{
4505 char **tp;
4506
4507 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004508 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004509 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004510 if (trap_ptr == trap)
4511 free(*tp);
4512 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004513 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004514 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004515 setsignal(tp - trap);
4516 INT_ON;
4517 }
4518 }
4519}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004520
4521/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004522static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004523
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004524/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004525static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004526forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004527{
4528 int oldlvl;
4529
4530 TRACE(("Child shell %d\n", getpid()));
4531 oldlvl = shlvl;
4532 shlvl++;
4533
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004534 /* man bash: "Non-builtin commands run by bash have signal handlers
4535 * set to the values inherited by the shell from its parent".
4536 * Do we do it correctly? */
4537
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004538 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004539
4540 if (mode == FORK_NOJOB /* is it `xxx` ? */
4541 && n && n->type == NCMD /* is it single cmd? */
4542 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004543 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004544 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4545 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4546 ) {
4547 TRACE(("Trap hack\n"));
4548 /* Awful hack for `trap` or $(trap).
4549 *
4550 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4551 * contains an example where "trap" is executed in a subshell:
4552 *
4553 * save_traps=$(trap)
4554 * ...
4555 * eval "$save_traps"
4556 *
4557 * Standard does not say that "trap" in subshell shall print
4558 * parent shell's traps. It only says that its output
4559 * must have suitable form, but then, in the above example
4560 * (which is not supposed to be normative), it implies that.
4561 *
4562 * bash (and probably other shell) does implement it
4563 * (traps are reset to defaults, but "trap" still shows them),
4564 * but as a result, "trap" logic is hopelessly messed up:
4565 *
4566 * # trap
4567 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4568 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4569 * # true | trap <--- trap is in subshell - no output (ditto)
4570 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4571 * trap -- 'echo Ho' SIGWINCH
4572 * # echo `(trap)` <--- in subshell in subshell - output
4573 * trap -- 'echo Ho' SIGWINCH
4574 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4575 * trap -- 'echo Ho' SIGWINCH
4576 *
4577 * The rules when to forget and when to not forget traps
4578 * get really complex and nonsensical.
4579 *
4580 * Our solution: ONLY bare $(trap) or `trap` is special.
4581 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004582 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004583 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004584 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004585 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004586 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004587#if JOBS
4588 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004589 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004590 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4591 pid_t pgrp;
4592
4593 if (jp->nprocs == 0)
4594 pgrp = getpid();
4595 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004596 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004597 /* this can fail because we are doing it in the parent also */
4598 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004599 if (mode == FORK_FG)
4600 xtcsetpgrp(ttyfd, pgrp);
4601 setsignal(SIGTSTP);
4602 setsignal(SIGTTOU);
4603 } else
4604#endif
4605 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004606 /* man bash: "When job control is not in effect,
4607 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004608 ignoresig(SIGINT);
4609 ignoresig(SIGQUIT);
4610 if (jp->nprocs == 0) {
4611 close(0);
4612 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004613 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004614 }
4615 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004616 if (!oldlvl) {
4617 if (iflag) { /* why if iflag only? */
4618 setsignal(SIGINT);
4619 setsignal(SIGTERM);
4620 }
4621 /* man bash:
4622 * "In all cases, bash ignores SIGQUIT. Non-builtin
4623 * commands run by bash have signal handlers
4624 * set to the values inherited by the shell
4625 * from its parent".
4626 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004628 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004629#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004630 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004631 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004632 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004633 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004634 /* "jobs": we do not want to clear job list for it,
4635 * instead we remove only _its_ own_ job from job list.
4636 * This makes "jobs .... | cat" more useful.
4637 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004638 freejob(curjob);
4639 return;
4640 }
4641#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004642 for (jp = curjob; jp; jp = jp->prev_job)
4643 freejob(jp);
4644 jobless = 0;
4645}
4646
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004647/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004648#if !JOBS
4649#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4650#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004651static void
4652forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4653{
4654 TRACE(("In parent shell: child = %d\n", pid));
4655 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004656 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4657 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004658 jobless++;
4659 return;
4660 }
4661#if JOBS
4662 if (mode != FORK_NOJOB && jp->jobctl) {
4663 int pgrp;
4664
4665 if (jp->nprocs == 0)
4666 pgrp = pid;
4667 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004668 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004669 /* This can fail because we are doing it in the child also */
4670 setpgid(pid, pgrp);
4671 }
4672#endif
4673 if (mode == FORK_BG) {
4674 backgndpid = pid; /* set $! */
4675 set_curjob(jp, CUR_RUNNING);
4676 }
4677 if (jp) {
4678 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004679 ps->ps_pid = pid;
4680 ps->ps_status = -1;
4681 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004682#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004683 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004684 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004685#endif
4686 }
4687}
4688
4689static int
4690forkshell(struct job *jp, union node *n, int mode)
4691{
4692 int pid;
4693
4694 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4695 pid = fork();
4696 if (pid < 0) {
4697 TRACE(("Fork failed, errno=%d", errno));
4698 if (jp)
4699 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004700 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004701 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004702 if (pid == 0) {
4703 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004704 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004705 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004706 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004707 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004708 return pid;
4709}
4710
4711/*
4712 * Wait for job to finish.
4713 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004714 * Under job control we have the problem that while a child process
4715 * is running interrupts generated by the user are sent to the child
4716 * but not to the shell. This means that an infinite loop started by
4717 * an interactive user may be hard to kill. With job control turned off,
4718 * an interactive user may place an interactive program inside a loop.
4719 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004720 * these interrupts to also abort the loop. The approach we take here
4721 * is to have the shell ignore interrupt signals while waiting for a
4722 * foreground process to terminate, and then send itself an interrupt
4723 * signal if the child process was terminated by an interrupt signal.
4724 * Unfortunately, some programs want to do a bit of cleanup and then
4725 * exit on interrupt; unless these processes terminate themselves by
4726 * sending a signal to themselves (instead of calling exit) they will
4727 * confuse this approach.
4728 *
4729 * Called with interrupts off.
4730 */
4731static int
4732waitforjob(struct job *jp)
4733{
4734 int st;
4735
4736 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004737
4738 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004739 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004740 /* In non-interactive shells, we _can_ get
4741 * a keyboard signal here and be EINTRed,
4742 * but we just loop back, waiting for command to complete.
4743 *
4744 * man bash:
4745 * "If bash is waiting for a command to complete and receives
4746 * a signal for which a trap has been set, the trap
4747 * will not be executed until the command completes."
4748 *
4749 * Reality is that even if trap is not set, bash
4750 * will not act on the signal until command completes.
4751 * Try this. sleep5intoff.c:
4752 * #include <signal.h>
4753 * #include <unistd.h>
4754 * int main() {
4755 * sigset_t set;
4756 * sigemptyset(&set);
4757 * sigaddset(&set, SIGINT);
4758 * sigaddset(&set, SIGQUIT);
4759 * sigprocmask(SIG_BLOCK, &set, NULL);
4760 * sleep(5);
4761 * return 0;
4762 * }
4763 * $ bash -c './sleep5intoff; echo hi'
4764 * ^C^C^C^C <--- pressing ^C once a second
4765 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004766 * $ bash -c './sleep5intoff; echo hi'
4767 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4768 * $ _
4769 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004770 dowait(DOWAIT_BLOCK, jp);
4771 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004772 INT_ON;
4773
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004774 st = getstatus(jp);
4775#if JOBS
4776 if (jp->jobctl) {
4777 xtcsetpgrp(ttyfd, rootpid);
4778 /*
4779 * This is truly gross.
4780 * If we're doing job control, then we did a TIOCSPGRP which
4781 * caused us (the shell) to no longer be in the controlling
4782 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4783 * intuit from the subprocess exit status whether a SIGINT
4784 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4785 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004786 if (jp->sigint) /* TODO: do the same with all signals */
4787 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004788 }
4789 if (jp->state == JOBDONE)
4790#endif
4791 freejob(jp);
4792 return st;
4793}
4794
4795/*
4796 * return 1 if there are stopped jobs, otherwise 0
4797 */
4798static int
4799stoppedjobs(void)
4800{
4801 struct job *jp;
4802 int retval;
4803
4804 retval = 0;
4805 if (job_warning)
4806 goto out;
4807 jp = curjob;
4808 if (jp && jp->state == JOBSTOPPED) {
4809 out2str("You have stopped jobs.\n");
4810 job_warning = 2;
4811 retval++;
4812 }
4813 out:
4814 return retval;
4815}
4816
4817
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004818/* ============ redir.c
4819 *
4820 * Code for dealing with input/output redirection.
4821 */
4822
4823#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004824#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004825
4826/*
4827 * Open a file in noclobber mode.
4828 * The code was copied from bash.
4829 */
4830static int
4831noclobberopen(const char *fname)
4832{
4833 int r, fd;
4834 struct stat finfo, finfo2;
4835
4836 /*
4837 * If the file exists and is a regular file, return an error
4838 * immediately.
4839 */
4840 r = stat(fname, &finfo);
4841 if (r == 0 && S_ISREG(finfo.st_mode)) {
4842 errno = EEXIST;
4843 return -1;
4844 }
4845
4846 /*
4847 * If the file was not present (r != 0), make sure we open it
4848 * exclusively so that if it is created before we open it, our open
4849 * will fail. Make sure that we do not truncate an existing file.
4850 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4851 * file was not a regular file, we leave O_EXCL off.
4852 */
4853 if (r != 0)
4854 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4855 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4856
4857 /* If the open failed, return the file descriptor right away. */
4858 if (fd < 0)
4859 return fd;
4860
4861 /*
4862 * OK, the open succeeded, but the file may have been changed from a
4863 * non-regular file to a regular file between the stat and the open.
4864 * We are assuming that the O_EXCL open handles the case where FILENAME
4865 * did not exist and is symlinked to an existing file between the stat
4866 * and open.
4867 */
4868
4869 /*
4870 * If we can open it and fstat the file descriptor, and neither check
4871 * revealed that it was a regular file, and the file has not been
4872 * replaced, return the file descriptor.
4873 */
4874 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4875 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4876 return fd;
4877
4878 /* The file has been replaced. badness. */
4879 close(fd);
4880 errno = EEXIST;
4881 return -1;
4882}
4883
4884/*
4885 * Handle here documents. Normally we fork off a process to write the
4886 * data to a pipe. If the document is short, we can stuff the data in
4887 * the pipe without forking.
4888 */
4889/* openhere needs this forward reference */
4890static void expandhere(union node *arg, int fd);
4891static int
4892openhere(union node *redir)
4893{
4894 int pip[2];
4895 size_t len = 0;
4896
4897 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004898 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004899 if (redir->type == NHERE) {
4900 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004901 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004902 full_write(pip[1], redir->nhere.doc->narg.text, len);
4903 goto out;
4904 }
4905 }
4906 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004907 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004908 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004909 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4910 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4911 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4912 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004913 signal(SIGPIPE, SIG_DFL);
4914 if (redir->type == NHERE)
4915 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004916 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004917 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004918 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004919 }
4920 out:
4921 close(pip[1]);
4922 return pip[0];
4923}
4924
4925static int
4926openredirect(union node *redir)
4927{
4928 char *fname;
4929 int f;
4930
4931 switch (redir->nfile.type) {
4932 case NFROM:
4933 fname = redir->nfile.expfname;
4934 f = open(fname, O_RDONLY);
4935 if (f < 0)
4936 goto eopen;
4937 break;
4938 case NFROMTO:
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4941 if (f < 0)
4942 goto ecreate;
4943 break;
4944 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004945#if ENABLE_ASH_BASH_COMPAT
4946 case NTO2:
4947#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004948 /* Take care of noclobber mode. */
4949 if (Cflag) {
4950 fname = redir->nfile.expfname;
4951 f = noclobberopen(fname);
4952 if (f < 0)
4953 goto ecreate;
4954 break;
4955 }
4956 /* FALLTHROUGH */
4957 case NCLOBBER:
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4960 if (f < 0)
4961 goto ecreate;
4962 break;
4963 case NAPPEND:
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4966 if (f < 0)
4967 goto ecreate;
4968 break;
4969 default:
4970#if DEBUG
4971 abort();
4972#endif
4973 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004974/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004975// case NTOFD:
4976// case NFROMFD:
4977// f = -1;
4978// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004979 case NHERE:
4980 case NXHERE:
4981 f = openhere(redir);
4982 break;
4983 }
4984
4985 return f;
4986 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004987 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004988 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004989 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004990}
4991
4992/*
4993 * Copy a file descriptor to be >= to. Returns -1
4994 * if the source file descriptor is closed, EMPTY if there are no unused
4995 * file descriptors left.
4996 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004997/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4998 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004999enum {
5000 COPYFD_EXACT = (int)~(INT_MAX),
5001 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5002};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003static int
5004copyfd(int from, int to)
5005{
5006 int newfd;
5007
Denis Vlasenko5a867312008-07-24 19:46:38 +00005008 if (to & COPYFD_EXACT) {
5009 to &= ~COPYFD_EXACT;
5010 /*if (from != to)*/
5011 newfd = dup2(from, to);
5012 } else {
5013 newfd = fcntl(from, F_DUPFD, to);
5014 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005015 if (newfd < 0) {
5016 if (errno == EMFILE)
5017 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005018 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005019 ash_msg_and_raise_error("%d: %m", from);
5020 }
5021 return newfd;
5022}
5023
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005024/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005025struct two_fd_t {
5026 int orig, copy;
5027};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005028struct redirtab {
5029 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005030 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005031 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005032 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005033};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005034#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005035
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005036static int need_to_remember(struct redirtab *rp, int fd)
5037{
5038 int i;
5039
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005040 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005041 return 0;
5042
5043 for (i = 0; i < rp->pair_count; i++) {
5044 if (rp->two_fd[i].orig == fd) {
5045 /* already remembered */
5046 return 0;
5047 }
5048 }
5049 return 1;
5050}
5051
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005052/* "hidden" fd is a fd used to read scripts, or a copy of such */
5053static int is_hidden_fd(struct redirtab *rp, int fd)
5054{
5055 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005056 struct parsefile *pf;
5057
5058 if (fd == -1)
5059 return 0;
5060 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005061 while (pf) {
5062 if (fd == pf->fd) {
5063 return 1;
5064 }
5065 pf = pf->prev;
5066 }
5067 if (!rp)
5068 return 0;
5069 fd |= COPYFD_RESTORE;
5070 for (i = 0; i < rp->pair_count; i++) {
5071 if (rp->two_fd[i].copy == fd) {
5072 return 1;
5073 }
5074 }
5075 return 0;
5076}
5077
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005078/*
5079 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5080 * old file descriptors are stashed away so that the redirection can be
5081 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5082 * standard output, and the standard error if it becomes a duplicate of
5083 * stdout, is saved in memory.
5084 */
5085/* flags passed to redirect */
5086#define REDIR_PUSH 01 /* save previous values of file descriptors */
5087#define REDIR_SAVEFD2 03 /* set preverrout */
5088static void
5089redirect(union node *redir, int flags)
5090{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005091 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005092 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005093 int i;
5094 int fd;
5095 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005096 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005097
Denis Vlasenko01631112007-12-16 17:20:38 +00005098 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 if (!redir) {
5100 return;
5101 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005102
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005103 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005104 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005105 INT_OFF;
5106 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005107 union node *tmp = redir;
5108 do {
5109 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005110#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005111 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005112 sv_pos++;
5113#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005114 tmp = tmp->nfile.next;
5115 } while (tmp);
5116 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005117 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005119 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005120 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005121 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 while (sv_pos > 0) {
5123 sv_pos--;
5124 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5125 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005126 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005127
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005128 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005129 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005130 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005131 int right_fd = redir->ndup.dupfd;
5132 /* redirect from/to same file descriptor? */
5133 if (right_fd == fd)
5134 continue;
5135 /* echo >&10 and 10 is a fd opened to the sh script? */
5136 if (is_hidden_fd(sv, right_fd)) {
5137 errno = EBADF; /* as if it is closed */
5138 ash_msg_and_raise_error("%d: %m", right_fd);
5139 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005140 newfd = -1;
5141 } else {
5142 newfd = openredirect(redir); /* always >= 0 */
5143 if (fd == newfd) {
5144 /* Descriptor wasn't open before redirect.
5145 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005146 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005147 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005148 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005149 continue;
5150 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005151 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005152#if ENABLE_ASH_BASH_COMPAT
5153 redirect_more:
5154#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005155 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005156 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005157 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005158/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5159 * are closed in popredir() in the child, preventing them from leaking
5160 * into child. (popredir() also cleans up the mess in case of failures)
5161 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005162 if (i == -1) {
5163 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005164 if (i != EBADF) {
5165 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005166 if (newfd >= 0)
5167 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005168 errno = i;
5169 ash_msg_and_raise_error("%d: %m", fd);
5170 /* NOTREACHED */
5171 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005172 /* EBADF: it is not open - good, remember to close it */
5173 remember_to_close:
5174 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005175 } else { /* fd is open, save its copy */
5176 /* "exec fd>&-" should not close fds
5177 * which point to script file(s).
5178 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005179 if (is_hidden_fd(sv, fd))
5180 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005181 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005182 if (fd == 2)
5183 copied_fd2 = i;
5184 sv->two_fd[sv_pos].orig = fd;
5185 sv->two_fd[sv_pos].copy = i;
5186 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005187 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005188 if (newfd < 0) {
5189 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005190 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005191 /* Don't want to trigger debugging */
5192 if (fd != -1)
5193 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005194 } else {
5195 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005196 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005197 } else if (fd != newfd) { /* move newfd to fd */
5198 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005199#if ENABLE_ASH_BASH_COMPAT
5200 if (!(redir->nfile.type == NTO2 && fd == 2))
5201#endif
5202 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005203 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005204#if ENABLE_ASH_BASH_COMPAT
5205 if (redir->nfile.type == NTO2 && fd == 1) {
5206 /* We already redirected it to fd 1, now copy it to 2 */
5207 newfd = 1;
5208 fd = 2;
5209 goto redirect_more;
5210 }
5211#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005212 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005213
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005214 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005215 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5216 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005217}
5218
5219/*
5220 * Undo the effects of the last redirection.
5221 */
5222static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005223popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005224{
5225 struct redirtab *rp;
5226 int i;
5227
Denis Vlasenko01631112007-12-16 17:20:38 +00005228 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005229 return;
5230 INT_OFF;
5231 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005232 for (i = 0; i < rp->pair_count; i++) {
5233 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005234 int copy = rp->two_fd[i].copy;
5235 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005236 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005237 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005238 continue;
5239 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005240 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005241 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005242 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005243 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005244 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005246 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005247 }
5248 }
5249 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005250 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005251 free(rp);
5252 INT_ON;
5253}
5254
5255/*
5256 * Undo all redirections. Called on error or interrupt.
5257 */
5258
5259/*
5260 * Discard all saved file descriptors.
5261 */
5262static void
5263clearredir(int drop)
5264{
5265 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005266 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005267 if (!redirlist)
5268 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005269 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005270 }
5271}
5272
5273static int
5274redirectsafe(union node *redir, int flags)
5275{
5276 int err;
5277 volatile int saveint;
5278 struct jmploc *volatile savehandler = exception_handler;
5279 struct jmploc jmploc;
5280
5281 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005282 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5283 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005284 if (!err) {
5285 exception_handler = &jmploc;
5286 redirect(redir, flags);
5287 }
5288 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005289 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005290 longjmp(exception_handler->loc, 1);
5291 RESTORE_INT(saveint);
5292 return err;
5293}
5294
5295
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005296/* ============ Routines to expand arguments to commands
5297 *
5298 * We have to deal with backquotes, shell variables, and file metacharacters.
5299 */
5300
Mike Frysinger98c52642009-04-02 10:02:37 +00005301#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005302static arith_t
5303ash_arith(const char *s)
5304{
5305 arith_eval_hooks_t math_hooks;
5306 arith_t result;
5307 int errcode = 0;
5308
5309 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005310 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005311 math_hooks.endofname = endofname;
5312
5313 INT_OFF;
5314 result = arith(s, &errcode, &math_hooks);
5315 if (errcode < 0) {
5316 if (errcode == -3)
5317 ash_msg_and_raise_error("exponent less than 0");
5318 if (errcode == -2)
5319 ash_msg_and_raise_error("divide by zero");
5320 if (errcode == -5)
5321 ash_msg_and_raise_error("expression recursion loop detected");
5322 raise_error_syntax(s);
5323 }
5324 INT_ON;
5325
5326 return result;
5327}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005328#endif
5329
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005330/*
5331 * expandarg flags
5332 */
5333#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5334#define EXP_TILDE 0x2 /* do normal tilde expansion */
5335#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5336#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5337#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5338#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5339#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5340#define EXP_WORD 0x80 /* expand word in parameter expansion */
5341#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5342/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005343 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005344 */
5345#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5346#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5347#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5348#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5349#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5350
5351/*
5352 * Structure specifying which parts of the string should be searched
5353 * for IFS characters.
5354 */
5355struct ifsregion {
5356 struct ifsregion *next; /* next region in list */
5357 int begoff; /* offset of start of region */
5358 int endoff; /* offset of end of region */
5359 int nulonly; /* search for nul bytes only */
5360};
5361
5362struct arglist {
5363 struct strlist *list;
5364 struct strlist **lastp;
5365};
5366
5367/* output of current string */
5368static char *expdest;
5369/* list of back quote expressions */
5370static struct nodelist *argbackq;
5371/* first struct in list of ifs regions */
5372static struct ifsregion ifsfirst;
5373/* last struct in list */
5374static struct ifsregion *ifslastp;
5375/* holds expanded arg list */
5376static struct arglist exparg;
5377
5378/*
5379 * Our own itoa().
5380 */
5381static int
5382cvtnum(arith_t num)
5383{
5384 int len;
5385
5386 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005387 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005388 STADJUST(len, expdest);
5389 return len;
5390}
5391
5392static size_t
5393esclen(const char *start, const char *p)
5394{
5395 size_t esc = 0;
5396
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005397 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005398 esc++;
5399 }
5400 return esc;
5401}
5402
5403/*
5404 * Remove any CTLESC characters from a string.
5405 */
5406static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005407rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005408{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005409 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005410
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005412 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005413 unsigned protect_against_glob;
5414 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005415
5416 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005417 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005418 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005419
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005420 q = p;
5421 r = str;
5422 if (flag & RMESCAPE_ALLOC) {
5423 size_t len = p - str;
5424 size_t fulllen = len + strlen(p) + 1;
5425
5426 if (flag & RMESCAPE_GROW) {
5427 r = makestrspace(fulllen, expdest);
5428 } else if (flag & RMESCAPE_HEAP) {
5429 r = ckmalloc(fulllen);
5430 } else {
5431 r = stalloc(fulllen);
5432 }
5433 q = r;
5434 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005435 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436 }
5437 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5440 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005442 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005443 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005444// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5445// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5446// Note: both inquotes and protect_against_glob only affect whether
5447// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 inquotes = ~inquotes;
5449 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005450 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005451 continue;
5452 }
5453 if (*p == '\\') {
5454 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005455 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005456 goto copy;
5457 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005458 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005459 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 *q++ = '\\';
5462 }
5463 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005464 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005465 copy:
5466 *q++ = *p++;
5467 }
5468 *q = '\0';
5469 if (flag & RMESCAPE_GROW) {
5470 expdest = r;
5471 STADJUST(q - r + 1, expdest);
5472 }
5473 return r;
5474}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475#define pmatch(a, b) !fnmatch((a), (b), 0)
5476
5477/*
5478 * Prepare a pattern for a expmeta (internal glob(3)) call.
5479 *
5480 * Returns an stalloced string.
5481 */
5482static char *
5483preglob(const char *pattern, int quoted, int flag)
5484{
5485 flag |= RMESCAPE_GLOB;
5486 if (quoted) {
5487 flag |= RMESCAPE_QUOTED;
5488 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005489 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005490}
5491
5492/*
5493 * Put a string on the stack.
5494 */
5495static void
5496memtodest(const char *p, size_t len, int syntax, int quotes)
5497{
5498 char *q = expdest;
5499
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005500 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005501
5502 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005503 unsigned char c = *p++;
5504 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005505 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005506 if (quotes) {
5507 int n = SIT(c, syntax);
5508 if (n == CCTL || n == CBACK)
5509 USTPUTC(CTLESC, q);
5510 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005511 USTPUTC(c, q);
5512 }
5513
5514 expdest = q;
5515}
5516
5517static void
5518strtodest(const char *p, int syntax, int quotes)
5519{
5520 memtodest(p, strlen(p), syntax, quotes);
5521}
5522
5523/*
5524 * Record the fact that we have to scan this region of the
5525 * string for IFS characters.
5526 */
5527static void
5528recordregion(int start, int end, int nulonly)
5529{
5530 struct ifsregion *ifsp;
5531
5532 if (ifslastp == NULL) {
5533 ifsp = &ifsfirst;
5534 } else {
5535 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005536 ifsp = ckzalloc(sizeof(*ifsp));
5537 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005538 ifslastp->next = ifsp;
5539 INT_ON;
5540 }
5541 ifslastp = ifsp;
5542 ifslastp->begoff = start;
5543 ifslastp->endoff = end;
5544 ifslastp->nulonly = nulonly;
5545}
5546
5547static void
5548removerecordregions(int endoff)
5549{
5550 if (ifslastp == NULL)
5551 return;
5552
5553 if (ifsfirst.endoff > endoff) {
5554 while (ifsfirst.next != NULL) {
5555 struct ifsregion *ifsp;
5556 INT_OFF;
5557 ifsp = ifsfirst.next->next;
5558 free(ifsfirst.next);
5559 ifsfirst.next = ifsp;
5560 INT_ON;
5561 }
5562 if (ifsfirst.begoff > endoff)
5563 ifslastp = NULL;
5564 else {
5565 ifslastp = &ifsfirst;
5566 ifsfirst.endoff = endoff;
5567 }
5568 return;
5569 }
5570
5571 ifslastp = &ifsfirst;
5572 while (ifslastp->next && ifslastp->next->begoff < endoff)
5573 ifslastp=ifslastp->next;
5574 while (ifslastp->next != NULL) {
5575 struct ifsregion *ifsp;
5576 INT_OFF;
5577 ifsp = ifslastp->next->next;
5578 free(ifslastp->next);
5579 ifslastp->next = ifsp;
5580 INT_ON;
5581 }
5582 if (ifslastp->endoff > endoff)
5583 ifslastp->endoff = endoff;
5584}
5585
5586static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005587exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005588{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005589 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005590 char *name;
5591 struct passwd *pw;
5592 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005593 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005594 int startloc;
5595
5596 name = p + 1;
5597
5598 while ((c = *++p) != '\0') {
5599 switch (c) {
5600 case CTLESC:
5601 return startp;
5602 case CTLQUOTEMARK:
5603 return startp;
5604 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005605 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005606 goto done;
5607 break;
5608 case '/':
5609 case CTLENDVAR:
5610 goto done;
5611 }
5612 }
5613 done:
5614 *p = '\0';
5615 if (*name == '\0') {
5616 home = lookupvar(homestr);
5617 } else {
5618 pw = getpwnam(name);
5619 if (pw == NULL)
5620 goto lose;
5621 home = pw->pw_dir;
5622 }
5623 if (!home || !*home)
5624 goto lose;
5625 *p = c;
5626 startloc = expdest - (char *)stackblock();
5627 strtodest(home, SQSYNTAX, quotes);
5628 recordregion(startloc, expdest - (char *)stackblock(), 0);
5629 return p;
5630 lose:
5631 *p = c;
5632 return startp;
5633}
5634
5635/*
5636 * Execute a command inside back quotes. If it's a builtin command, we
5637 * want to save its output in a block obtained from malloc. Otherwise
5638 * we fork off a subprocess and get the output of the command via a pipe.
5639 * Should be called with interrupts off.
5640 */
5641struct backcmd { /* result of evalbackcmd */
5642 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005643 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005644 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005645 struct job *jp; /* job structure for command */
5646};
5647
5648/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005649static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005650#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005651static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005652
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005653static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005654evalbackcmd(union node *n, struct backcmd *result)
5655{
5656 int saveherefd;
5657
5658 result->fd = -1;
5659 result->buf = NULL;
5660 result->nleft = 0;
5661 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005662 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005663 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664
5665 saveherefd = herefd;
5666 herefd = -1;
5667
5668 {
5669 int pip[2];
5670 struct job *jp;
5671
5672 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005673 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005674 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005675 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5676 FORCE_INT_ON;
5677 close(pip[0]);
5678 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005679 /*close(1);*/
5680 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005681 close(pip[1]);
5682 }
5683 eflag = 0;
5684 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5685 /* NOTREACHED */
5686 }
5687 close(pip[1]);
5688 result->fd = pip[0];
5689 result->jp = jp;
5690 }
5691 herefd = saveherefd;
5692 out:
5693 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5694 result->fd, result->buf, result->nleft, result->jp));
5695}
5696
5697/*
5698 * Expand stuff in backwards quotes.
5699 */
5700static void
5701expbackq(union node *cmd, int quoted, int quotes)
5702{
5703 struct backcmd in;
5704 int i;
5705 char buf[128];
5706 char *p;
5707 char *dest;
5708 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005709 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005710 struct stackmark smark;
5711
5712 INT_OFF;
5713 setstackmark(&smark);
5714 dest = expdest;
5715 startloc = dest - (char *)stackblock();
5716 grabstackstr(dest);
5717 evalbackcmd(cmd, &in);
5718 popstackmark(&smark);
5719
5720 p = in.buf;
5721 i = in.nleft;
5722 if (i == 0)
5723 goto read;
5724 for (;;) {
5725 memtodest(p, i, syntax, quotes);
5726 read:
5727 if (in.fd < 0)
5728 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005729 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005730 TRACE(("expbackq: read returns %d\n", i));
5731 if (i <= 0)
5732 break;
5733 p = buf;
5734 }
5735
Denis Vlasenko60818682007-09-28 22:07:23 +00005736 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005737 if (in.fd >= 0) {
5738 close(in.fd);
5739 back_exitstatus = waitforjob(in.jp);
5740 }
5741 INT_ON;
5742
5743 /* Eat all trailing newlines */
5744 dest = expdest;
5745 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5746 STUNPUTC(dest);
5747 expdest = dest;
5748
5749 if (quoted == 0)
5750 recordregion(startloc, dest - (char *)stackblock(), 0);
5751 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5752 (dest - (char *)stackblock()) - startloc,
5753 (dest - (char *)stackblock()) - startloc,
5754 stackblock() + startloc));
5755}
5756
Mike Frysinger98c52642009-04-02 10:02:37 +00005757#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005758/*
5759 * Expand arithmetic expression. Backup to start of expression,
5760 * evaluate, place result in (backed up) result, adjust string position.
5761 */
5762static void
5763expari(int quotes)
5764{
5765 char *p, *start;
5766 int begoff;
5767 int flag;
5768 int len;
5769
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005770 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005771
5772 /*
5773 * This routine is slightly over-complicated for
5774 * efficiency. Next we scan backwards looking for the
5775 * start of arithmetic.
5776 */
5777 start = stackblock();
5778 p = expdest - 1;
5779 *p = '\0';
5780 p--;
5781 do {
5782 int esc;
5783
Denys Vlasenkocd716832009-11-28 22:14:02 +01005784 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005785 p--;
5786#if DEBUG
5787 if (p < start) {
5788 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5789 }
5790#endif
5791 }
5792
5793 esc = esclen(start, p);
5794 if (!(esc % 2)) {
5795 break;
5796 }
5797
5798 p -= esc + 1;
5799 } while (1);
5800
5801 begoff = p - start;
5802
5803 removerecordregions(begoff);
5804
5805 flag = p[1];
5806
5807 expdest = p;
5808
5809 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005810 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005811
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005812 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005813
5814 if (flag != '"')
5815 recordregion(begoff, begoff + len, 0);
5816}
5817#endif
5818
5819/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005820static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005821
5822/*
5823 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5824 * characters to allow for further processing. Otherwise treat
5825 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005826 *
5827 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5828 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5829 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830 */
5831static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005832argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005833{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005834 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005835 '=',
5836 ':',
5837 CTLQUOTEMARK,
5838 CTLENDVAR,
5839 CTLESC,
5840 CTLVAR,
5841 CTLBACKQ,
5842 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005843#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005844 CTLENDARI,
5845#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005846 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847 };
5848 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005849 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5850 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005851 int inquotes;
5852 size_t length;
5853 int startloc;
5854
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005855 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005856 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005857 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858 reject++;
5859 }
5860 inquotes = 0;
5861 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005862 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 char *q;
5864
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005865 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 tilde:
5867 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 q++;
5870 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005871 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 }
5873 start:
5874 startloc = expdest - (char *)stackblock();
5875 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005876 unsigned char c;
5877
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005879 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (c) {
5881 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005882#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005883 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005884#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 ) {
5886 /* c == '=' || c == ':' || c == CTLENDARI */
5887 length++;
5888 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005889 }
5890 if (length > 0) {
5891 int newloc;
5892 expdest = stack_nputstr(p, length, expdest);
5893 newloc = expdest - (char *)stackblock();
5894 if (breakall && !inquotes && newloc > startloc) {
5895 recordregion(startloc, newloc, 0);
5896 }
5897 startloc = newloc;
5898 }
5899 p += length + 1;
5900 length = 0;
5901
5902 switch (c) {
5903 case '\0':
5904 goto breakloop;
5905 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005906 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005907 p--;
5908 continue;
5909 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005910 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005911 reject++;
5912 /* fall through */
5913 case ':':
5914 /*
5915 * sort of a hack - expand tildes in variable
5916 * assignments (after the first '=' and after ':'s).
5917 */
5918 if (*--p == '~') {
5919 goto tilde;
5920 }
5921 continue;
5922 }
5923
5924 switch (c) {
5925 case CTLENDVAR: /* ??? */
5926 goto breakloop;
5927 case CTLQUOTEMARK:
5928 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005929 if (!inquotes
5930 && memcmp(p, dolatstr, 4) == 0
5931 && ( p[4] == CTLQUOTEMARK
5932 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5933 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005934 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005935 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005936 goto start;
5937 }
5938 inquotes = !inquotes;
5939 addquote:
5940 if (quotes) {
5941 p--;
5942 length++;
5943 startloc++;
5944 }
5945 break;
5946 case CTLESC:
5947 startloc++;
5948 length++;
5949 goto addquote;
5950 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005951 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005952 goto start;
5953 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005955 case CTLBACKQ|CTLQUOTE:
5956 expbackq(argbackq->n, c, quotes);
5957 argbackq = argbackq->next;
5958 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005959#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005960 case CTLENDARI:
5961 p--;
5962 expari(quotes);
5963 goto start;
5964#endif
5965 }
5966 }
5967 breakloop:
5968 ;
5969}
5970
5971static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005972scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 int zero)
5974{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005975// This commented out code was added by James Simmons <jsimmons@infradead.org>
5976// as part of a larger change when he added support for ${var/a/b}.
5977// However, it broke # and % operators:
5978//
5979//var=ababcdcd
5980// ok bad
5981//echo ${var#ab} abcdcd abcdcd
5982//echo ${var##ab} abcdcd abcdcd
5983//echo ${var#a*b} abcdcd ababcdcd (!)
5984//echo ${var##a*b} cdcd cdcd
5985//echo ${var#?} babcdcd ababcdcd (!)
5986//echo ${var##?} babcdcd babcdcd
5987//echo ${var#*} ababcdcd babcdcd (!)
5988//echo ${var##*}
5989//echo ${var%cd} ababcd ababcd
5990//echo ${var%%cd} ababcd abab (!)
5991//echo ${var%c*d} ababcd ababcd
5992//echo ${var%%c*d} abab ababcdcd (!)
5993//echo ${var%?} ababcdc ababcdc
5994//echo ${var%%?} ababcdc ababcdcd (!)
5995//echo ${var%*} ababcdcd ababcdcd
5996//echo ${var%%*}
5997//
5998// Commenting it back out helped. Remove it completely if it really
5999// is not needed.
6000
6001 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006002 char c;
6003
6004 loc = startp;
6005 loc2 = rmesc;
6006 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006007 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006008 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006009
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006010 c = *loc2;
6011 if (zero) {
6012 *loc2 = '\0';
6013 s = rmesc;
6014 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006015 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006016
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006017// // chop off end if its '*'
6018// full = strrchr(str, '*');
6019// if (full && full != str)
6020// match--;
6021//
6022// // If str starts with '*' replace with s.
6023// if ((*str == '*') && strlen(s) >= match) {
6024// full = xstrdup(s);
6025// strncpy(full+strlen(s)-match+1, str+1, match-1);
6026// } else
6027// full = xstrndup(str, match);
6028// match = strncmp(s, full, strlen(full));
6029// free(full);
6030//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006031 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006032 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006034 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006035 loc++;
6036 loc++;
6037 loc2++;
6038 } while (c);
6039 return 0;
6040}
6041
6042static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006043scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006044{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006045#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6046 int try2optimize = match_at_start;
6047#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006048 int esc = 0;
6049 char *loc;
6050 char *loc2;
6051
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006052 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6053 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6054 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6055 * Logic:
6056 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6057 * and on each iteration they go back two/one char until they reach the beginning.
6058 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6059 */
6060 /* TODO: document in what other circumstances we are called. */
6061
6062 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006063 int match;
6064 char c = *loc2;
6065 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006066 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006067 *loc2 = '\0';
6068 s = rmesc;
6069 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006070 match = pmatch(pattern, s);
6071 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006072 *loc2 = c;
6073 if (match)
6074 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006075#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6076 if (try2optimize) {
6077 /* Maybe we can optimize this:
6078 * if pattern ends with unescaped *, we can avoid checking
6079 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6080 * it wont match truncated "raw_value_of_" strings too.
6081 */
6082 unsigned plen = strlen(pattern);
6083 /* Does it end with "*"? */
6084 if (plen != 0 && pattern[--plen] == '*') {
6085 /* "xxxx*" is not escaped */
6086 /* "xxx\*" is escaped */
6087 /* "xx\\*" is not escaped */
6088 /* "x\\\*" is escaped */
6089 int slashes = 0;
6090 while (plen != 0 && pattern[--plen] == '\\')
6091 slashes++;
6092 if (!(slashes & 1))
6093 break; /* ends with unescaped "*" */
6094 }
6095 try2optimize = 0;
6096 }
6097#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006098 loc--;
6099 if (quotes) {
6100 if (--esc < 0) {
6101 esc = esclen(startp, loc);
6102 }
6103 if (esc % 2) {
6104 esc--;
6105 loc--;
6106 }
6107 }
6108 }
6109 return 0;
6110}
6111
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006112static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006113static void
6114varunset(const char *end, const char *var, const char *umsg, int varflags)
6115{
6116 const char *msg;
6117 const char *tail;
6118
6119 tail = nullstr;
6120 msg = "parameter not set";
6121 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006122 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123 if (varflags & VSNUL)
6124 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006125 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006126 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006127 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006128 }
6129 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6130}
6131
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006132#if ENABLE_ASH_BASH_COMPAT
6133static char *
6134parse_sub_pattern(char *arg, int inquotes)
6135{
6136 char *idx, *repl = NULL;
6137 unsigned char c;
6138
Denis Vlasenko2659c632008-06-14 06:04:59 +00006139 idx = arg;
6140 while (1) {
6141 c = *arg;
6142 if (!c)
6143 break;
6144 if (c == '/') {
6145 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006146 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006147 repl = idx + 1;
6148 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006149 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006150 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006151 *idx++ = c;
6152 if (!inquotes && c == '\\' && arg[1] == '\\')
6153 arg++; /* skip both \\, not just first one */
6154 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006155 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006156 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157
6158 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006159}
6160#endif /* ENABLE_ASH_BASH_COMPAT */
6161
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006162static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006163subevalvar(char *p, char *str, int strloc, int subtype,
6164 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006165{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006166 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006167 char *startp;
6168 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006169 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006170 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6171 IF_ASH_BASH_COMPAT(char null = '\0';)
6172 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006173 int saveherefd = herefd;
6174 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006175 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006176 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006177
6178 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006179 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6180 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006181 STPUTC('\0', expdest);
6182 herefd = saveherefd;
6183 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006184 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006185
6186 switch (subtype) {
6187 case VSASSIGN:
6188 setvar(str, startp, 0);
6189 amount = startp - expdest;
6190 STADJUST(amount, expdest);
6191 return startp;
6192
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006193#if ENABLE_ASH_BASH_COMPAT
6194 case VSSUBSTR:
6195 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006196 /* Read POS in ${var:POS:LEN} */
6197 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198 len = str - startp - 1;
6199
6200 /* *loc != '\0', guaranteed by parser */
6201 if (quotes) {
6202 char *ptr;
6203
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006204 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006205 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006206 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006207 len--;
6208 ptr++;
6209 }
6210 }
6211 }
6212 orig_len = len;
6213
6214 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006215 /* ${var::LEN} */
6216 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006217 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006218 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006219 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006220 while (*loc && *loc != ':') {
6221 /* TODO?
6222 * bash complains on: var=qwe; echo ${var:1a:123}
6223 if (!isdigit(*loc))
6224 ash_msg_and_raise_error(msg_illnum, str);
6225 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006226 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006227 }
6228 if (*loc++ == ':') {
6229 len = number(loc);
6230 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006231 }
6232 if (pos >= orig_len) {
6233 pos = 0;
6234 len = 0;
6235 }
6236 if (len > (orig_len - pos))
6237 len = orig_len - pos;
6238
6239 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006240 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006241 str++;
6242 }
6243 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006244 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006245 *loc++ = *str++;
6246 *loc++ = *str++;
6247 }
6248 *loc = '\0';
6249 amount = loc - expdest;
6250 STADJUST(amount, expdest);
6251 return loc;
6252#endif
6253
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006254 case VSQUESTION:
6255 varunset(p, str, startp, varflags);
6256 /* NOTREACHED */
6257 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006258 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006259
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006260 /* We'll comeback here if we grow the stack while handling
6261 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6262 * stack will need rebasing, and we'll need to remove our work
6263 * areas each time
6264 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006265 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006266
6267 amount = expdest - ((char *)stackblock() + resetloc);
6268 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006269 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006270
6271 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006272 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006273 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006274 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006275 if (rmesc != startp) {
6276 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006277 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006278 }
6279 }
6280 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006281 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006282 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006283 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006284
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006285#if ENABLE_ASH_BASH_COMPAT
6286 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006287 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006288
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006289 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006290 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6291 if (!repl)
6292 repl = &null;
6293 }
6294
6295 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006296 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006297 return 0;
6298
6299 len = 0;
6300 idx = startp;
6301 end = str - 1;
6302 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006303 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006304 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6305 if (!loc) {
6306 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006307 char *restart_detect = stackblock();
6308 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006309 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006310 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006311 idx++;
6312 len++;
6313 STPUTC(*idx, expdest);
6314 }
6315 if (stackblock() != restart_detect)
6316 goto restart;
6317 idx++;
6318 len++;
6319 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006320 /* continue; - prone to quadratic behavior, smarter code: */
6321 if (idx >= end)
6322 break;
6323 if (str[0] == '*') {
6324 /* Pattern is "*foo". If "*foo" does not match "long_string",
6325 * it would never match "ong_string" etc, no point in trying.
6326 */
6327 goto skip_matching;
6328 }
6329 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006330 }
6331
6332 if (subtype == VSREPLACEALL) {
6333 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006334 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006335 idx++;
6336 idx++;
6337 rmesc++;
6338 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006339 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006340 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006341 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006342
6343 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006344 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006345 STPUTC(*loc, expdest);
6346 if (stackblock() != restart_detect)
6347 goto restart;
6348 len++;
6349 }
6350
6351 if (subtype == VSREPLACE) {
6352 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006353 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006354 STPUTC(*idx, expdest);
6355 if (stackblock() != restart_detect)
6356 goto restart;
6357 len++;
6358 idx++;
6359 }
6360 break;
6361 }
6362 }
6363
6364 /* We've put the replaced text into a buffer at workloc, now
6365 * move it to the right place and adjust the stack.
6366 */
6367 startp = stackblock() + startloc;
6368 STPUTC('\0', expdest);
6369 memmove(startp, stackblock() + workloc, len);
6370 startp[len++] = '\0';
6371 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6372 STADJUST(-amount, expdest);
6373 return startp;
6374 }
6375#endif /* ENABLE_ASH_BASH_COMPAT */
6376
6377 subtype -= VSTRIMRIGHT;
6378#if DEBUG
6379 if (subtype < 0 || subtype > 7)
6380 abort();
6381#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006382 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006383 zero = subtype >> 1;
6384 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6385 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6386
6387 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6388 if (loc) {
6389 if (zero) {
6390 memmove(startp, loc, str - loc);
6391 loc = startp + (str - loc) - 1;
6392 }
6393 *loc = '\0';
6394 amount = loc - expdest;
6395 STADJUST(amount, expdest);
6396 }
6397 return loc;
6398}
6399
6400/*
6401 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006402 * name parameter (examples):
6403 * ash -c 'echo $1' name:'1='
6404 * ash -c 'echo $qwe' name:'qwe='
6405 * ash -c 'echo $$' name:'$='
6406 * ash -c 'echo ${$}' name:'$='
6407 * ash -c 'echo ${$##q}' name:'$=q'
6408 * ash -c 'echo ${#$}' name:'$='
6409 * note: examples with bad shell syntax:
6410 * ash -c 'echo ${#$1}' name:'$=1'
6411 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006412 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006413static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006414varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415{
Mike Frysinger98c52642009-04-02 10:02:37 +00006416 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006417 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006418 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006419 int sepq = 0;
6420 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006421 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006422 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006423 int quoted = varflags & VSQUOTE;
6424 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006426 switch (*name) {
6427 case '$':
6428 num = rootpid;
6429 goto numvar;
6430 case '?':
6431 num = exitstatus;
6432 goto numvar;
6433 case '#':
6434 num = shellparam.nparam;
6435 goto numvar;
6436 case '!':
6437 num = backgndpid;
6438 if (num == 0)
6439 return -1;
6440 numvar:
6441 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006442 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006444 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006445 for (i = NOPTS - 1; i >= 0; i--) {
6446 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006447 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006448 len++;
6449 }
6450 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006451 check_1char_name:
6452#if 0
6453 /* handles cases similar to ${#$1} */
6454 if (name[2] != '\0')
6455 raise_error_syntax("bad substitution");
6456#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006457 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006458 case '@': {
6459 char **ap;
6460 int sep;
6461
6462 if (quoted && (flags & EXP_FULL)) {
6463 /* note: this is not meant as PEOF value */
6464 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006465 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006466 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006467 /* fall through */
6468 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006469 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006470 i = SIT(sep, syntax);
6471 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006472 sepq = 1;
6473 param:
6474 ap = shellparam.p;
6475 if (!ap)
6476 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006477 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006478 size_t partlen;
6479
6480 partlen = strlen(p);
6481 len += partlen;
6482
6483 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6484 memtodest(p, partlen, syntax, quotes);
6485
6486 if (*ap && sep) {
6487 char *q;
6488
6489 len++;
6490 if (subtype == VSPLUS || subtype == VSLENGTH) {
6491 continue;
6492 }
6493 q = expdest;
6494 if (sepq)
6495 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006496 /* note: may put NUL despite sep != 0
6497 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006498 STPUTC(sep, q);
6499 expdest = q;
6500 }
6501 }
6502 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006503 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006504 case '0':
6505 case '1':
6506 case '2':
6507 case '3':
6508 case '4':
6509 case '5':
6510 case '6':
6511 case '7':
6512 case '8':
6513 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006514 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006515 if (num < 0 || num > shellparam.nparam)
6516 return -1;
6517 p = num ? shellparam.p[num - 1] : arg0;
6518 goto value;
6519 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006520 /* NB: name has form "VAR=..." */
6521
6522 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6523 * which should be considered before we check variables. */
6524 if (var_str_list) {
6525 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6526 p = NULL;
6527 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006528 char *str, *eq;
6529 str = var_str_list->text;
6530 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006531 if (!eq) /* stop at first non-assignment */
6532 break;
6533 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006534 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006535 && strncmp(str, name, name_len) == 0
6536 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006537 p = eq;
6538 /* goto value; - WRONG! */
6539 /* think "A=1 A=2 B=$A" */
6540 }
6541 var_str_list = var_str_list->next;
6542 } while (var_str_list);
6543 if (p)
6544 goto value;
6545 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 p = lookupvar(name);
6547 value:
6548 if (!p)
6549 return -1;
6550
6551 len = strlen(p);
6552 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6553 memtodest(p, len, syntax, quotes);
6554 return len;
6555 }
6556
6557 if (subtype == VSPLUS || subtype == VSLENGTH)
6558 STADJUST(-len, expdest);
6559 return len;
6560}
6561
6562/*
6563 * Expand a variable, and return a pointer to the next character in the
6564 * input string.
6565 */
6566static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006567evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006568{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006569 char varflags;
6570 char subtype;
6571 char quoted;
6572 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006573 char *var;
6574 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006575 int startloc;
6576 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006577
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006578 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006579 subtype = varflags & VSTYPE;
6580 quoted = varflags & VSQUOTE;
6581 var = p;
6582 easy = (!quoted || (*var == '@' && shellparam.nparam));
6583 startloc = expdest - (char *)stackblock();
6584 p = strchr(p, '=') + 1;
6585
6586 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006587 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006588 if (varflags & VSNUL)
6589 varlen--;
6590
6591 if (subtype == VSPLUS) {
6592 varlen = -1 - varlen;
6593 goto vsplus;
6594 }
6595
6596 if (subtype == VSMINUS) {
6597 vsplus:
6598 if (varlen < 0) {
6599 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006600 p, flags | EXP_TILDE |
6601 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006602 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006603 );
6604 goto end;
6605 }
6606 if (easy)
6607 goto record;
6608 goto end;
6609 }
6610
6611 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6612 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006613 if (subevalvar(p, var, /* strloc: */ 0,
6614 subtype, startloc, varflags,
6615 /* quotes: */ 0,
6616 var_str_list)
6617 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006618 varflags &= ~VSNUL;
6619 /*
6620 * Remove any recorded regions beyond
6621 * start of variable
6622 */
6623 removerecordregions(startloc);
6624 goto again;
6625 }
6626 goto end;
6627 }
6628 if (easy)
6629 goto record;
6630 goto end;
6631 }
6632
6633 if (varlen < 0 && uflag)
6634 varunset(p, var, 0, 0);
6635
6636 if (subtype == VSLENGTH) {
6637 cvtnum(varlen > 0 ? varlen : 0);
6638 goto record;
6639 }
6640
6641 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006642 if (easy)
6643 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006644 goto end;
6645 }
6646
6647#if DEBUG
6648 switch (subtype) {
6649 case VSTRIMLEFT:
6650 case VSTRIMLEFTMAX:
6651 case VSTRIMRIGHT:
6652 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006653#if ENABLE_ASH_BASH_COMPAT
6654 case VSSUBSTR:
6655 case VSREPLACE:
6656 case VSREPLACEALL:
6657#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006658 break;
6659 default:
6660 abort();
6661 }
6662#endif
6663
6664 if (varlen >= 0) {
6665 /*
6666 * Terminate the string and start recording the pattern
6667 * right after it
6668 */
6669 STPUTC('\0', expdest);
6670 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006671 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6672 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006673//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006674 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006675 var_str_list)
6676 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006677 int amount = expdest - (
6678 (char *)stackblock() + patloc - 1
6679 );
6680 STADJUST(-amount, expdest);
6681 }
6682 /* Remove any recorded regions beyond start of variable */
6683 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006684 record:
6685 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006686 }
6687
6688 end:
6689 if (subtype != VSNORMAL) { /* skip to end of alternative */
6690 int nesting = 1;
6691 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006692 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006693 if (c == CTLESC)
6694 p++;
6695 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6696 if (varlen >= 0)
6697 argbackq = argbackq->next;
6698 } else if (c == CTLVAR) {
6699 if ((*p++ & VSTYPE) != VSNORMAL)
6700 nesting++;
6701 } else if (c == CTLENDVAR) {
6702 if (--nesting == 0)
6703 break;
6704 }
6705 }
6706 }
6707 return p;
6708}
6709
6710/*
6711 * Break the argument string into pieces based upon IFS and add the
6712 * strings to the argument list. The regions of the string to be
6713 * searched for IFS characters have been stored by recordregion.
6714 */
6715static void
6716ifsbreakup(char *string, struct arglist *arglist)
6717{
6718 struct ifsregion *ifsp;
6719 struct strlist *sp;
6720 char *start;
6721 char *p;
6722 char *q;
6723 const char *ifs, *realifs;
6724 int ifsspc;
6725 int nulonly;
6726
6727 start = string;
6728 if (ifslastp != NULL) {
6729 ifsspc = 0;
6730 nulonly = 0;
6731 realifs = ifsset() ? ifsval() : defifs;
6732 ifsp = &ifsfirst;
6733 do {
6734 p = string + ifsp->begoff;
6735 nulonly = ifsp->nulonly;
6736 ifs = nulonly ? nullstr : realifs;
6737 ifsspc = 0;
6738 while (p < string + ifsp->endoff) {
6739 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006740 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006741 p++;
6742 if (!strchr(ifs, *p)) {
6743 p++;
6744 continue;
6745 }
6746 if (!nulonly)
6747 ifsspc = (strchr(defifs, *p) != NULL);
6748 /* Ignore IFS whitespace at start */
6749 if (q == start && ifsspc) {
6750 p++;
6751 start = p;
6752 continue;
6753 }
6754 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006755 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006756 sp->text = start;
6757 *arglist->lastp = sp;
6758 arglist->lastp = &sp->next;
6759 p++;
6760 if (!nulonly) {
6761 for (;;) {
6762 if (p >= string + ifsp->endoff) {
6763 break;
6764 }
6765 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006766 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006767 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006768 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006769 p = q;
6770 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006771 }
6772 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006773 if (ifsspc) {
6774 p++;
6775 ifsspc = 0;
6776 } else {
6777 p = q;
6778 break;
6779 }
6780 } else
6781 p++;
6782 }
6783 }
6784 start = p;
6785 } /* while */
6786 ifsp = ifsp->next;
6787 } while (ifsp != NULL);
6788 if (nulonly)
6789 goto add;
6790 }
6791
6792 if (!*start)
6793 return;
6794
6795 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006796 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006797 sp->text = start;
6798 *arglist->lastp = sp;
6799 arglist->lastp = &sp->next;
6800}
6801
6802static void
6803ifsfree(void)
6804{
6805 struct ifsregion *p;
6806
6807 INT_OFF;
6808 p = ifsfirst.next;
6809 do {
6810 struct ifsregion *ifsp;
6811 ifsp = p->next;
6812 free(p);
6813 p = ifsp;
6814 } while (p);
6815 ifslastp = NULL;
6816 ifsfirst.next = NULL;
6817 INT_ON;
6818}
6819
6820/*
6821 * Add a file name to the list.
6822 */
6823static void
6824addfname(const char *name)
6825{
6826 struct strlist *sp;
6827
Denis Vlasenko597906c2008-02-20 16:38:54 +00006828 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006829 sp->text = ststrdup(name);
6830 *exparg.lastp = sp;
6831 exparg.lastp = &sp->next;
6832}
6833
6834static char *expdir;
6835
6836/*
6837 * Do metacharacter (i.e. *, ?, [...]) expansion.
6838 */
6839static void
6840expmeta(char *enddir, char *name)
6841{
6842 char *p;
6843 const char *cp;
6844 char *start;
6845 char *endname;
6846 int metaflag;
6847 struct stat statb;
6848 DIR *dirp;
6849 struct dirent *dp;
6850 int atend;
6851 int matchdot;
6852
6853 metaflag = 0;
6854 start = name;
6855 for (p = name; *p; p++) {
6856 if (*p == '*' || *p == '?')
6857 metaflag = 1;
6858 else if (*p == '[') {
6859 char *q = p + 1;
6860 if (*q == '!')
6861 q++;
6862 for (;;) {
6863 if (*q == '\\')
6864 q++;
6865 if (*q == '/' || *q == '\0')
6866 break;
6867 if (*++q == ']') {
6868 metaflag = 1;
6869 break;
6870 }
6871 }
6872 } else if (*p == '\\')
6873 p++;
6874 else if (*p == '/') {
6875 if (metaflag)
6876 goto out;
6877 start = p + 1;
6878 }
6879 }
6880 out:
6881 if (metaflag == 0) { /* we've reached the end of the file name */
6882 if (enddir != expdir)
6883 metaflag++;
6884 p = name;
6885 do {
6886 if (*p == '\\')
6887 p++;
6888 *enddir++ = *p;
6889 } while (*p++);
6890 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6891 addfname(expdir);
6892 return;
6893 }
6894 endname = p;
6895 if (name < start) {
6896 p = name;
6897 do {
6898 if (*p == '\\')
6899 p++;
6900 *enddir++ = *p++;
6901 } while (p < start);
6902 }
6903 if (enddir == expdir) {
6904 cp = ".";
6905 } else if (enddir == expdir + 1 && *expdir == '/') {
6906 cp = "/";
6907 } else {
6908 cp = expdir;
6909 enddir[-1] = '\0';
6910 }
6911 dirp = opendir(cp);
6912 if (dirp == NULL)
6913 return;
6914 if (enddir != expdir)
6915 enddir[-1] = '/';
6916 if (*endname == 0) {
6917 atend = 1;
6918 } else {
6919 atend = 0;
6920 *endname++ = '\0';
6921 }
6922 matchdot = 0;
6923 p = start;
6924 if (*p == '\\')
6925 p++;
6926 if (*p == '.')
6927 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006928 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006929 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006930 continue;
6931 if (pmatch(start, dp->d_name)) {
6932 if (atend) {
6933 strcpy(enddir, dp->d_name);
6934 addfname(expdir);
6935 } else {
6936 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6937 continue;
6938 p[-1] = '/';
6939 expmeta(p, endname);
6940 }
6941 }
6942 }
6943 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006944 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006945 endname[-1] = '/';
6946}
6947
6948static struct strlist *
6949msort(struct strlist *list, int len)
6950{
6951 struct strlist *p, *q = NULL;
6952 struct strlist **lpp;
6953 int half;
6954 int n;
6955
6956 if (len <= 1)
6957 return list;
6958 half = len >> 1;
6959 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006960 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006961 q = p;
6962 p = p->next;
6963 }
6964 q->next = NULL; /* terminate first half of list */
6965 q = msort(list, half); /* sort first half of list */
6966 p = msort(p, len - half); /* sort second half */
6967 lpp = &list;
6968 for (;;) {
6969#if ENABLE_LOCALE_SUPPORT
6970 if (strcoll(p->text, q->text) < 0)
6971#else
6972 if (strcmp(p->text, q->text) < 0)
6973#endif
6974 {
6975 *lpp = p;
6976 lpp = &p->next;
6977 p = *lpp;
6978 if (p == NULL) {
6979 *lpp = q;
6980 break;
6981 }
6982 } else {
6983 *lpp = q;
6984 lpp = &q->next;
6985 q = *lpp;
6986 if (q == NULL) {
6987 *lpp = p;
6988 break;
6989 }
6990 }
6991 }
6992 return list;
6993}
6994
6995/*
6996 * Sort the results of file name expansion. It calculates the number of
6997 * strings to sort and then calls msort (short for merge sort) to do the
6998 * work.
6999 */
7000static struct strlist *
7001expsort(struct strlist *str)
7002{
7003 int len;
7004 struct strlist *sp;
7005
7006 len = 0;
7007 for (sp = str; sp; sp = sp->next)
7008 len++;
7009 return msort(str, len);
7010}
7011
7012static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007013expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007014{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007015 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007016 '*', '?', '[', 0
7017 };
7018 /* TODO - EXP_REDIR */
7019
7020 while (str) {
7021 struct strlist **savelastp;
7022 struct strlist *sp;
7023 char *p;
7024
7025 if (fflag)
7026 goto nometa;
7027 if (!strpbrk(str->text, metachars))
7028 goto nometa;
7029 savelastp = exparg.lastp;
7030
7031 INT_OFF;
7032 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7033 {
7034 int i = strlen(str->text);
7035 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7036 }
7037
7038 expmeta(expdir, p);
7039 free(expdir);
7040 if (p != str->text)
7041 free(p);
7042 INT_ON;
7043 if (exparg.lastp == savelastp) {
7044 /*
7045 * no matches
7046 */
7047 nometa:
7048 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007049 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007050 exparg.lastp = &str->next;
7051 } else {
7052 *exparg.lastp = NULL;
7053 *savelastp = sp = expsort(*savelastp);
7054 while (sp->next != NULL)
7055 sp = sp->next;
7056 exparg.lastp = &sp->next;
7057 }
7058 str = str->next;
7059 }
7060}
7061
7062/*
7063 * Perform variable substitution and command substitution on an argument,
7064 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7065 * perform splitting and file name expansion. When arglist is NULL, perform
7066 * here document expansion.
7067 */
7068static void
7069expandarg(union node *arg, struct arglist *arglist, int flag)
7070{
7071 struct strlist *sp;
7072 char *p;
7073
7074 argbackq = arg->narg.backquote;
7075 STARTSTACKSTR(expdest);
7076 ifsfirst.next = NULL;
7077 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007078 argstr(arg->narg.text, flag,
7079 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007080 p = _STPUTC('\0', expdest);
7081 expdest = p - 1;
7082 if (arglist == NULL) {
7083 return; /* here document expanded */
7084 }
7085 p = grabstackstr(p);
7086 exparg.lastp = &exparg.list;
7087 /*
7088 * TODO - EXP_REDIR
7089 */
7090 if (flag & EXP_FULL) {
7091 ifsbreakup(p, &exparg);
7092 *exparg.lastp = NULL;
7093 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007094 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007095 } else {
7096 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007097 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007098 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007099 sp->text = p;
7100 *exparg.lastp = sp;
7101 exparg.lastp = &sp->next;
7102 }
7103 if (ifsfirst.next)
7104 ifsfree();
7105 *exparg.lastp = NULL;
7106 if (exparg.list) {
7107 *arglist->lastp = exparg.list;
7108 arglist->lastp = exparg.lastp;
7109 }
7110}
7111
7112/*
7113 * Expand shell variables and backquotes inside a here document.
7114 */
7115static void
7116expandhere(union node *arg, int fd)
7117{
7118 herefd = fd;
7119 expandarg(arg, (struct arglist *)NULL, 0);
7120 full_write(fd, stackblock(), expdest - (char *)stackblock());
7121}
7122
7123/*
7124 * Returns true if the pattern matches the string.
7125 */
7126static int
7127patmatch(char *pattern, const char *string)
7128{
7129 return pmatch(preglob(pattern, 0, 0), string);
7130}
7131
7132/*
7133 * See if a pattern matches in a case statement.
7134 */
7135static int
7136casematch(union node *pattern, char *val)
7137{
7138 struct stackmark smark;
7139 int result;
7140
7141 setstackmark(&smark);
7142 argbackq = pattern->narg.backquote;
7143 STARTSTACKSTR(expdest);
7144 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007145 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7146 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007147 STACKSTRNUL(expdest);
7148 result = patmatch(stackblock(), val);
7149 popstackmark(&smark);
7150 return result;
7151}
7152
7153
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007154/* ============ find_command */
7155
7156struct builtincmd {
7157 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007158 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007159 /* unsigned flags; */
7160};
7161#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007162/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007163 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007164#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007165#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007166
7167struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007168 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007169 union param {
7170 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007171 /* index >= 0 for commands without path (slashes) */
7172 /* (TODO: what exactly does the value mean? PATH position?) */
7173 /* index == -1 for commands with slashes */
7174 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007175 const struct builtincmd *cmd;
7176 struct funcnode *func;
7177 } u;
7178};
7179/* values of cmdtype */
7180#define CMDUNKNOWN -1 /* no entry in table for command */
7181#define CMDNORMAL 0 /* command is an executable program */
7182#define CMDFUNCTION 1 /* command is a shell function */
7183#define CMDBUILTIN 2 /* command is a shell builtin */
7184
7185/* action to find_command() */
7186#define DO_ERR 0x01 /* prints errors */
7187#define DO_ABS 0x02 /* checks absolute paths */
7188#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7189#define DO_ALTPATH 0x08 /* using alternate path */
7190#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7191
7192static void find_command(char *, struct cmdentry *, int, const char *);
7193
7194
7195/* ============ Hashing commands */
7196
7197/*
7198 * When commands are first encountered, they are entered in a hash table.
7199 * This ensures that a full path search will not have to be done for them
7200 * on each invocation.
7201 *
7202 * We should investigate converting to a linear search, even though that
7203 * would make the command name "hash" a misnomer.
7204 */
7205
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007206struct tblentry {
7207 struct tblentry *next; /* next entry in hash chain */
7208 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007209 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007210 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007211 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007212};
7213
Denis Vlasenko01631112007-12-16 17:20:38 +00007214static struct tblentry **cmdtable;
7215#define INIT_G_cmdtable() do { \
7216 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7217} while (0)
7218
7219static int builtinloc = -1; /* index in path of %builtin, or -1 */
7220
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007221
7222static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007223tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007224{
7225 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007226
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007227#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007228 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007229 if (APPLET_IS_NOEXEC(applet_no)) {
7230 while (*envp)
7231 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007232 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007233 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007234 /* re-exec ourselves with the new arguments */
7235 execve(bb_busybox_exec_path, argv, envp);
7236 /* If they called chroot or otherwise made the binary no longer
7237 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007238 }
7239#endif
7240
7241 repeat:
7242#ifdef SYSV
7243 do {
7244 execve(cmd, argv, envp);
7245 } while (errno == EINTR);
7246#else
7247 execve(cmd, argv, envp);
7248#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007249 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007250 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007251 return;
7252 }
7253 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007254 char **ap;
7255 char **new;
7256
7257 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007258 continue;
7259 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007260 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007261 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007262 ap += 2;
7263 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007264 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007265 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007266 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007267 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007268 goto repeat;
7269 }
7270}
7271
7272/*
7273 * Exec a program. Never returns. If you change this routine, you may
7274 * have to change the find_command routine as well.
7275 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007276static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007277static void
7278shellexec(char **argv, const char *path, int idx)
7279{
7280 char *cmdname;
7281 int e;
7282 char **envp;
7283 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007284#if ENABLE_FEATURE_SH_STANDALONE
7285 int applet_no = -1;
7286#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007287
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007288 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007289 envp = listvars(VEXPORT, VUNSET, 0);
7290 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007291#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007292 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007293#endif
7294 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007295 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007296 e = errno;
7297 } else {
7298 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007299 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007300 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007301 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007302 if (errno != ENOENT && errno != ENOTDIR)
7303 e = errno;
7304 }
7305 stunalloc(cmdname);
7306 }
7307 }
7308
7309 /* Map to POSIX errors */
7310 switch (e) {
7311 case EACCES:
7312 exerrno = 126;
7313 break;
7314 case ENOENT:
7315 exerrno = 127;
7316 break;
7317 default:
7318 exerrno = 2;
7319 break;
7320 }
7321 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007322 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7323 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007324 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7325 /* NOTREACHED */
7326}
7327
7328static void
7329printentry(struct tblentry *cmdp)
7330{
7331 int idx;
7332 const char *path;
7333 char *name;
7334
7335 idx = cmdp->param.index;
7336 path = pathval();
7337 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007338 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007339 stunalloc(name);
7340 } while (--idx >= 0);
7341 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7342}
7343
7344/*
7345 * Clear out command entries. The argument specifies the first entry in
7346 * PATH which has changed.
7347 */
7348static void
7349clearcmdentry(int firstchange)
7350{
7351 struct tblentry **tblp;
7352 struct tblentry **pp;
7353 struct tblentry *cmdp;
7354
7355 INT_OFF;
7356 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7357 pp = tblp;
7358 while ((cmdp = *pp) != NULL) {
7359 if ((cmdp->cmdtype == CMDNORMAL &&
7360 cmdp->param.index >= firstchange)
7361 || (cmdp->cmdtype == CMDBUILTIN &&
7362 builtinloc >= firstchange)
7363 ) {
7364 *pp = cmdp->next;
7365 free(cmdp);
7366 } else {
7367 pp = &cmdp->next;
7368 }
7369 }
7370 }
7371 INT_ON;
7372}
7373
7374/*
7375 * Locate a command in the command hash table. If "add" is nonzero,
7376 * add the command to the table if it is not already present. The
7377 * variable "lastcmdentry" is set to point to the address of the link
7378 * pointing to the entry, so that delete_cmd_entry can delete the
7379 * entry.
7380 *
7381 * Interrupts must be off if called with add != 0.
7382 */
7383static struct tblentry **lastcmdentry;
7384
7385static struct tblentry *
7386cmdlookup(const char *name, int add)
7387{
7388 unsigned int hashval;
7389 const char *p;
7390 struct tblentry *cmdp;
7391 struct tblentry **pp;
7392
7393 p = name;
7394 hashval = (unsigned char)*p << 4;
7395 while (*p)
7396 hashval += (unsigned char)*p++;
7397 hashval &= 0x7FFF;
7398 pp = &cmdtable[hashval % CMDTABLESIZE];
7399 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7400 if (strcmp(cmdp->cmdname, name) == 0)
7401 break;
7402 pp = &cmdp->next;
7403 }
7404 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007405 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7406 + strlen(name)
7407 /* + 1 - already done because
7408 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007409 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007410 cmdp->cmdtype = CMDUNKNOWN;
7411 strcpy(cmdp->cmdname, name);
7412 }
7413 lastcmdentry = pp;
7414 return cmdp;
7415}
7416
7417/*
7418 * Delete the command entry returned on the last lookup.
7419 */
7420static void
7421delete_cmd_entry(void)
7422{
7423 struct tblentry *cmdp;
7424
7425 INT_OFF;
7426 cmdp = *lastcmdentry;
7427 *lastcmdentry = cmdp->next;
7428 if (cmdp->cmdtype == CMDFUNCTION)
7429 freefunc(cmdp->param.func);
7430 free(cmdp);
7431 INT_ON;
7432}
7433
7434/*
7435 * Add a new command entry, replacing any existing command entry for
7436 * the same name - except special builtins.
7437 */
7438static void
7439addcmdentry(char *name, struct cmdentry *entry)
7440{
7441 struct tblentry *cmdp;
7442
7443 cmdp = cmdlookup(name, 1);
7444 if (cmdp->cmdtype == CMDFUNCTION) {
7445 freefunc(cmdp->param.func);
7446 }
7447 cmdp->cmdtype = entry->cmdtype;
7448 cmdp->param = entry->u;
7449 cmdp->rehash = 0;
7450}
7451
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007452static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007453hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007454{
7455 struct tblentry **pp;
7456 struct tblentry *cmdp;
7457 int c;
7458 struct cmdentry entry;
7459 char *name;
7460
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007461 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007462 clearcmdentry(0);
7463 return 0;
7464 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007465
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007466 if (*argptr == NULL) {
7467 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7468 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7469 if (cmdp->cmdtype == CMDNORMAL)
7470 printentry(cmdp);
7471 }
7472 }
7473 return 0;
7474 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007475
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007476 c = 0;
7477 while ((name = *argptr) != NULL) {
7478 cmdp = cmdlookup(name, 0);
7479 if (cmdp != NULL
7480 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007481 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7482 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007483 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007484 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007485 find_command(name, &entry, DO_ERR, pathval());
7486 if (entry.cmdtype == CMDUNKNOWN)
7487 c = 1;
7488 argptr++;
7489 }
7490 return c;
7491}
7492
7493/*
7494 * Called when a cd is done. Marks all commands so the next time they
7495 * are executed they will be rehashed.
7496 */
7497static void
7498hashcd(void)
7499{
7500 struct tblentry **pp;
7501 struct tblentry *cmdp;
7502
7503 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7504 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007505 if (cmdp->cmdtype == CMDNORMAL
7506 || (cmdp->cmdtype == CMDBUILTIN
7507 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7508 && builtinloc > 0)
7509 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007510 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007511 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007512 }
7513 }
7514}
7515
7516/*
7517 * Fix command hash table when PATH changed.
7518 * Called before PATH is changed. The argument is the new value of PATH;
7519 * pathval() still returns the old value at this point.
7520 * Called with interrupts off.
7521 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007522static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007523changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007524{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007525 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007526 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007527 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007528 int idx_bltin;
7529
7530 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007531 firstchange = 9999; /* assume no change */
7532 idx = 0;
7533 idx_bltin = -1;
7534 for (;;) {
7535 if (*old != *new) {
7536 firstchange = idx;
7537 if ((*old == '\0' && *new == ':')
7538 || (*old == ':' && *new == '\0'))
7539 firstchange++;
7540 old = new; /* ignore subsequent differences */
7541 }
7542 if (*new == '\0')
7543 break;
7544 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7545 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007546 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007547 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007548 new++, old++;
7549 }
7550 if (builtinloc < 0 && idx_bltin >= 0)
7551 builtinloc = idx_bltin; /* zap builtins */
7552 if (builtinloc >= 0 && idx_bltin < 0)
7553 firstchange = 0;
7554 clearcmdentry(firstchange);
7555 builtinloc = idx_bltin;
7556}
7557
7558#define TEOF 0
7559#define TNL 1
7560#define TREDIR 2
7561#define TWORD 3
7562#define TSEMI 4
7563#define TBACKGND 5
7564#define TAND 6
7565#define TOR 7
7566#define TPIPE 8
7567#define TLP 9
7568#define TRP 10
7569#define TENDCASE 11
7570#define TENDBQUOTE 12
7571#define TNOT 13
7572#define TCASE 14
7573#define TDO 15
7574#define TDONE 16
7575#define TELIF 17
7576#define TELSE 18
7577#define TESAC 19
7578#define TFI 20
7579#define TFOR 21
7580#define TIF 22
7581#define TIN 23
7582#define TTHEN 24
7583#define TUNTIL 25
7584#define TWHILE 26
7585#define TBEGIN 27
7586#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007587typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007588
7589/* first char is indicating which tokens mark the end of a list */
7590static const char *const tokname_array[] = {
7591 "\1end of file",
7592 "\0newline",
7593 "\0redirection",
7594 "\0word",
7595 "\0;",
7596 "\0&",
7597 "\0&&",
7598 "\0||",
7599 "\0|",
7600 "\0(",
7601 "\1)",
7602 "\1;;",
7603 "\1`",
7604#define KWDOFFSET 13
7605 /* the following are keywords */
7606 "\0!",
7607 "\0case",
7608 "\1do",
7609 "\1done",
7610 "\1elif",
7611 "\1else",
7612 "\1esac",
7613 "\1fi",
7614 "\0for",
7615 "\0if",
7616 "\0in",
7617 "\1then",
7618 "\0until",
7619 "\0while",
7620 "\0{",
7621 "\1}",
7622};
7623
7624static const char *
7625tokname(int tok)
7626{
7627 static char buf[16];
7628
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007629//try this:
7630//if (tok < TSEMI) return tokname_array[tok] + 1;
7631//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7632//return buf;
7633
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634 if (tok >= TSEMI)
7635 buf[0] = '"';
7636 sprintf(buf + (tok >= TSEMI), "%s%c",
7637 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7638 return buf;
7639}
7640
7641/* Wrapper around strcmp for qsort/bsearch/... */
7642static int
7643pstrcmp(const void *a, const void *b)
7644{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007645 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007646}
7647
7648static const char *const *
7649findkwd(const char *s)
7650{
7651 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007652 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7653 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007654}
7655
7656/*
7657 * Locate and print what a word is...
7658 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007659static int
7660describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007661{
7662 struct cmdentry entry;
7663 struct tblentry *cmdp;
7664#if ENABLE_ASH_ALIAS
7665 const struct alias *ap;
7666#endif
7667 const char *path = pathval();
7668
7669 if (describe_command_verbose) {
7670 out1str(command);
7671 }
7672
7673 /* First look at the keywords */
7674 if (findkwd(command)) {
7675 out1str(describe_command_verbose ? " is a shell keyword" : command);
7676 goto out;
7677 }
7678
7679#if ENABLE_ASH_ALIAS
7680 /* Then look at the aliases */
7681 ap = lookupalias(command, 0);
7682 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007683 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007684 out1str("alias ");
7685 printalias(ap);
7686 return 0;
7687 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007688 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007689 goto out;
7690 }
7691#endif
7692 /* Then check if it is a tracked alias */
7693 cmdp = cmdlookup(command, 0);
7694 if (cmdp != NULL) {
7695 entry.cmdtype = cmdp->cmdtype;
7696 entry.u = cmdp->param;
7697 } else {
7698 /* Finally use brute force */
7699 find_command(command, &entry, DO_ABS, path);
7700 }
7701
7702 switch (entry.cmdtype) {
7703 case CMDNORMAL: {
7704 int j = entry.u.index;
7705 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007706 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007707 p = command;
7708 } else {
7709 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007710 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007711 stunalloc(p);
7712 } while (--j >= 0);
7713 }
7714 if (describe_command_verbose) {
7715 out1fmt(" is%s %s",
7716 (cmdp ? " a tracked alias for" : nullstr), p
7717 );
7718 } else {
7719 out1str(p);
7720 }
7721 break;
7722 }
7723
7724 case CMDFUNCTION:
7725 if (describe_command_verbose) {
7726 out1str(" is a shell function");
7727 } else {
7728 out1str(command);
7729 }
7730 break;
7731
7732 case CMDBUILTIN:
7733 if (describe_command_verbose) {
7734 out1fmt(" is a %sshell builtin",
7735 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7736 "special " : nullstr
7737 );
7738 } else {
7739 out1str(command);
7740 }
7741 break;
7742
7743 default:
7744 if (describe_command_verbose) {
7745 out1str(": not found\n");
7746 }
7747 return 127;
7748 }
7749 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007750 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007751 return 0;
7752}
7753
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007754static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007755typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007756{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007757 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007758 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007759 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007760
Denis Vlasenko46846e22007-05-20 13:08:31 +00007761 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007762 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007763 i++;
7764 verbose = 0;
7765 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007766 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007767 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007768 }
7769 return err;
7770}
7771
7772#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007773static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007774commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007775{
7776 int c;
7777 enum {
7778 VERIFY_BRIEF = 1,
7779 VERIFY_VERBOSE = 2,
7780 } verify = 0;
7781
7782 while ((c = nextopt("pvV")) != '\0')
7783 if (c == 'V')
7784 verify |= VERIFY_VERBOSE;
7785 else if (c == 'v')
7786 verify |= VERIFY_BRIEF;
7787#if DEBUG
7788 else if (c != 'p')
7789 abort();
7790#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007791 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7792 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007793 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007794 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007795
7796 return 0;
7797}
7798#endif
7799
7800
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007801/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007802
Denis Vlasenko340299a2008-11-21 10:36:36 +00007803static int funcblocksize; /* size of structures in function */
7804static int funcstringsize; /* size of strings in node */
7805static void *funcblock; /* block to allocate function from */
7806static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007807
Eric Andersencb57d552001-06-28 07:25:16 +00007808/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007809#define EV_EXIT 01 /* exit after evaluating tree */
7810#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007811#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007812
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007813static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007814 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7815 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7816 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7817 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7818 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7819 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7820 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7821 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7822 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7823 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7824 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7826 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7827 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7828 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7829 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7830 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007831#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007832 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007833#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007834 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7835 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7836 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7837 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7838 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7839 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7840 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7841 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7842 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007843};
7844
7845static void calcsize(union node *n);
7846
7847static void
7848sizenodelist(struct nodelist *lp)
7849{
7850 while (lp) {
7851 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7852 calcsize(lp->n);
7853 lp = lp->next;
7854 }
7855}
7856
7857static void
7858calcsize(union node *n)
7859{
7860 if (n == NULL)
7861 return;
7862 funcblocksize += nodesize[n->type];
7863 switch (n->type) {
7864 case NCMD:
7865 calcsize(n->ncmd.redirect);
7866 calcsize(n->ncmd.args);
7867 calcsize(n->ncmd.assign);
7868 break;
7869 case NPIPE:
7870 sizenodelist(n->npipe.cmdlist);
7871 break;
7872 case NREDIR:
7873 case NBACKGND:
7874 case NSUBSHELL:
7875 calcsize(n->nredir.redirect);
7876 calcsize(n->nredir.n);
7877 break;
7878 case NAND:
7879 case NOR:
7880 case NSEMI:
7881 case NWHILE:
7882 case NUNTIL:
7883 calcsize(n->nbinary.ch2);
7884 calcsize(n->nbinary.ch1);
7885 break;
7886 case NIF:
7887 calcsize(n->nif.elsepart);
7888 calcsize(n->nif.ifpart);
7889 calcsize(n->nif.test);
7890 break;
7891 case NFOR:
7892 funcstringsize += strlen(n->nfor.var) + 1;
7893 calcsize(n->nfor.body);
7894 calcsize(n->nfor.args);
7895 break;
7896 case NCASE:
7897 calcsize(n->ncase.cases);
7898 calcsize(n->ncase.expr);
7899 break;
7900 case NCLIST:
7901 calcsize(n->nclist.body);
7902 calcsize(n->nclist.pattern);
7903 calcsize(n->nclist.next);
7904 break;
7905 case NDEFUN:
7906 case NARG:
7907 sizenodelist(n->narg.backquote);
7908 funcstringsize += strlen(n->narg.text) + 1;
7909 calcsize(n->narg.next);
7910 break;
7911 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007912#if ENABLE_ASH_BASH_COMPAT
7913 case NTO2:
7914#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007915 case NCLOBBER:
7916 case NFROM:
7917 case NFROMTO:
7918 case NAPPEND:
7919 calcsize(n->nfile.fname);
7920 calcsize(n->nfile.next);
7921 break;
7922 case NTOFD:
7923 case NFROMFD:
7924 calcsize(n->ndup.vname);
7925 calcsize(n->ndup.next);
7926 break;
7927 case NHERE:
7928 case NXHERE:
7929 calcsize(n->nhere.doc);
7930 calcsize(n->nhere.next);
7931 break;
7932 case NNOT:
7933 calcsize(n->nnot.com);
7934 break;
7935 };
7936}
7937
7938static char *
7939nodeckstrdup(char *s)
7940{
7941 char *rtn = funcstring;
7942
7943 strcpy(funcstring, s);
7944 funcstring += strlen(s) + 1;
7945 return rtn;
7946}
7947
7948static union node *copynode(union node *);
7949
7950static struct nodelist *
7951copynodelist(struct nodelist *lp)
7952{
7953 struct nodelist *start;
7954 struct nodelist **lpp;
7955
7956 lpp = &start;
7957 while (lp) {
7958 *lpp = funcblock;
7959 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7960 (*lpp)->n = copynode(lp->n);
7961 lp = lp->next;
7962 lpp = &(*lpp)->next;
7963 }
7964 *lpp = NULL;
7965 return start;
7966}
7967
7968static union node *
7969copynode(union node *n)
7970{
7971 union node *new;
7972
7973 if (n == NULL)
7974 return NULL;
7975 new = funcblock;
7976 funcblock = (char *) funcblock + nodesize[n->type];
7977
7978 switch (n->type) {
7979 case NCMD:
7980 new->ncmd.redirect = copynode(n->ncmd.redirect);
7981 new->ncmd.args = copynode(n->ncmd.args);
7982 new->ncmd.assign = copynode(n->ncmd.assign);
7983 break;
7984 case NPIPE:
7985 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007986 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007987 break;
7988 case NREDIR:
7989 case NBACKGND:
7990 case NSUBSHELL:
7991 new->nredir.redirect = copynode(n->nredir.redirect);
7992 new->nredir.n = copynode(n->nredir.n);
7993 break;
7994 case NAND:
7995 case NOR:
7996 case NSEMI:
7997 case NWHILE:
7998 case NUNTIL:
7999 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8000 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8001 break;
8002 case NIF:
8003 new->nif.elsepart = copynode(n->nif.elsepart);
8004 new->nif.ifpart = copynode(n->nif.ifpart);
8005 new->nif.test = copynode(n->nif.test);
8006 break;
8007 case NFOR:
8008 new->nfor.var = nodeckstrdup(n->nfor.var);
8009 new->nfor.body = copynode(n->nfor.body);
8010 new->nfor.args = copynode(n->nfor.args);
8011 break;
8012 case NCASE:
8013 new->ncase.cases = copynode(n->ncase.cases);
8014 new->ncase.expr = copynode(n->ncase.expr);
8015 break;
8016 case NCLIST:
8017 new->nclist.body = copynode(n->nclist.body);
8018 new->nclist.pattern = copynode(n->nclist.pattern);
8019 new->nclist.next = copynode(n->nclist.next);
8020 break;
8021 case NDEFUN:
8022 case NARG:
8023 new->narg.backquote = copynodelist(n->narg.backquote);
8024 new->narg.text = nodeckstrdup(n->narg.text);
8025 new->narg.next = copynode(n->narg.next);
8026 break;
8027 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008028#if ENABLE_ASH_BASH_COMPAT
8029 case NTO2:
8030#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008031 case NCLOBBER:
8032 case NFROM:
8033 case NFROMTO:
8034 case NAPPEND:
8035 new->nfile.fname = copynode(n->nfile.fname);
8036 new->nfile.fd = n->nfile.fd;
8037 new->nfile.next = copynode(n->nfile.next);
8038 break;
8039 case NTOFD:
8040 case NFROMFD:
8041 new->ndup.vname = copynode(n->ndup.vname);
8042 new->ndup.dupfd = n->ndup.dupfd;
8043 new->ndup.fd = n->ndup.fd;
8044 new->ndup.next = copynode(n->ndup.next);
8045 break;
8046 case NHERE:
8047 case NXHERE:
8048 new->nhere.doc = copynode(n->nhere.doc);
8049 new->nhere.fd = n->nhere.fd;
8050 new->nhere.next = copynode(n->nhere.next);
8051 break;
8052 case NNOT:
8053 new->nnot.com = copynode(n->nnot.com);
8054 break;
8055 };
8056 new->type = n->type;
8057 return new;
8058}
8059
8060/*
8061 * Make a copy of a parse tree.
8062 */
8063static struct funcnode *
8064copyfunc(union node *n)
8065{
8066 struct funcnode *f;
8067 size_t blocksize;
8068
8069 funcblocksize = offsetof(struct funcnode, n);
8070 funcstringsize = 0;
8071 calcsize(n);
8072 blocksize = funcblocksize;
8073 f = ckmalloc(blocksize + funcstringsize);
8074 funcblock = (char *) f + offsetof(struct funcnode, n);
8075 funcstring = (char *) f + blocksize;
8076 copynode(n);
8077 f->count = 0;
8078 return f;
8079}
8080
8081/*
8082 * Define a shell function.
8083 */
8084static void
8085defun(char *name, union node *func)
8086{
8087 struct cmdentry entry;
8088
8089 INT_OFF;
8090 entry.cmdtype = CMDFUNCTION;
8091 entry.u.func = copyfunc(func);
8092 addcmdentry(name, &entry);
8093 INT_ON;
8094}
8095
Denis Vlasenko4b875702009-03-19 13:30:04 +00008096/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008097#define SKIPBREAK (1 << 0)
8098#define SKIPCONT (1 << 1)
8099#define SKIPFUNC (1 << 2)
8100#define SKIPFILE (1 << 3)
8101#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008102static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008103static int skipcount; /* number of levels to skip */
8104static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008105static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008106
Denis Vlasenko4b875702009-03-19 13:30:04 +00008107/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008108static int evalstring(char *s, int mask);
8109
Denis Vlasenko4b875702009-03-19 13:30:04 +00008110/* Called to execute a trap.
8111 * Single callsite - at the end of evaltree().
8112 * If we return non-zero, exaltree raises EXEXIT exception.
8113 *
8114 * Perhaps we should avoid entering new trap handlers
8115 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008116 */
8117static int
8118dotrap(void)
8119{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008120 uint8_t *g;
8121 int sig;
8122 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008123
8124 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008125 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008126 xbarrier();
8127
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008128 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008129 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8130 int want_exexit;
8131 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008132
Denis Vlasenko4b875702009-03-19 13:30:04 +00008133 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008134 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008135 t = trap[sig];
8136 /* non-trapped SIGINT is handled separately by raise_interrupt,
8137 * don't upset it by resetting gotsig[SIGINT-1] */
8138 if (sig == SIGINT && !t)
8139 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008140
8141 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008142 *g = 0;
8143 if (!t)
8144 continue;
8145 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008146 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008147 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008148 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008149 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008150 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008151 }
8152
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008153 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008154 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008155}
8156
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008157/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008158static void evalloop(union node *, int);
8159static void evalfor(union node *, int);
8160static void evalcase(union node *, int);
8161static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008162static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008163static void evalpipe(union node *, int);
8164static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008165static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008166static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008167
Eric Andersen62483552001-07-10 06:09:16 +00008168/*
Eric Andersenc470f442003-07-28 09:56:35 +00008169 * Evaluate a parse tree. The value is left in the global variable
8170 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008171 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008172static void
Eric Andersenc470f442003-07-28 09:56:35 +00008173evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008174{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008175 struct jmploc *volatile savehandler = exception_handler;
8176 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008177 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008178 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008179 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008180 int int_level;
8181
8182 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008183
Eric Andersenc470f442003-07-28 09:56:35 +00008184 if (n == NULL) {
8185 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008186 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008187 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008188 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008189
8190 exception_handler = &jmploc;
8191 {
8192 int err = setjmp(jmploc.loc);
8193 if (err) {
8194 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008195 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008196 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8197 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008198 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008199 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008200 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008201 TRACE(("exception %d in evaltree, propagating err=%d\n",
8202 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008203 exception_handler = savehandler;
8204 longjmp(exception_handler->loc, err);
8205 }
8206 }
8207
Eric Andersenc470f442003-07-28 09:56:35 +00008208 switch (n->type) {
8209 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008210#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008211 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008212 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008213 break;
8214#endif
8215 case NNOT:
8216 evaltree(n->nnot.com, EV_TESTED);
8217 status = !exitstatus;
8218 goto setstatus;
8219 case NREDIR:
8220 expredir(n->nredir.redirect);
8221 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8222 if (!status) {
8223 evaltree(n->nredir.n, flags & EV_TESTED);
8224 status = exitstatus;
8225 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008226 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008227 goto setstatus;
8228 case NCMD:
8229 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008230 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008231 if (eflag && !(flags & EV_TESTED))
8232 checkexit = ~0;
8233 goto calleval;
8234 case NFOR:
8235 evalfn = evalfor;
8236 goto calleval;
8237 case NWHILE:
8238 case NUNTIL:
8239 evalfn = evalloop;
8240 goto calleval;
8241 case NSUBSHELL:
8242 case NBACKGND:
8243 evalfn = evalsubshell;
8244 goto calleval;
8245 case NPIPE:
8246 evalfn = evalpipe;
8247 goto checkexit;
8248 case NCASE:
8249 evalfn = evalcase;
8250 goto calleval;
8251 case NAND:
8252 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008253 case NSEMI: {
8254
Eric Andersenc470f442003-07-28 09:56:35 +00008255#if NAND + 1 != NOR
8256#error NAND + 1 != NOR
8257#endif
8258#if NOR + 1 != NSEMI
8259#error NOR + 1 != NSEMI
8260#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008261 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008262 evaltree(
8263 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008264 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008265 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008266 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008267 break;
8268 if (!evalskip) {
8269 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008270 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008271 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008272 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008273 evalfn(n, flags);
8274 break;
8275 }
8276 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008277 }
Eric Andersenc470f442003-07-28 09:56:35 +00008278 case NIF:
8279 evaltree(n->nif.test, EV_TESTED);
8280 if (evalskip)
8281 break;
8282 if (exitstatus == 0) {
8283 n = n->nif.ifpart;
8284 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008285 }
8286 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008287 n = n->nif.elsepart;
8288 goto evaln;
8289 }
8290 goto success;
8291 case NDEFUN:
8292 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008293 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008294 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008295 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008296 exitstatus = status;
8297 break;
8298 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008299
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008300 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008301 exception_handler = savehandler;
8302 out1:
8303 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008304 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008305 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008306 goto exexit;
8307
8308 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008309 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008310 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008311 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008312
8313 RESTORE_INT(int_level);
8314 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008315}
8316
Eric Andersenc470f442003-07-28 09:56:35 +00008317#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8318static
8319#endif
8320void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8321
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008322static void
Eric Andersenc470f442003-07-28 09:56:35 +00008323evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008324{
8325 int status;
8326
8327 loopnest++;
8328 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008329 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008330 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008331 int i;
8332
Eric Andersencb57d552001-06-28 07:25:16 +00008333 evaltree(n->nbinary.ch1, EV_TESTED);
8334 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008335 skipping:
8336 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008337 evalskip = 0;
8338 continue;
8339 }
8340 if (evalskip == SKIPBREAK && --skipcount <= 0)
8341 evalskip = 0;
8342 break;
8343 }
Eric Andersenc470f442003-07-28 09:56:35 +00008344 i = exitstatus;
8345 if (n->type != NWHILE)
8346 i = !i;
8347 if (i != 0)
8348 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008349 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008350 status = exitstatus;
8351 if (evalskip)
8352 goto skipping;
8353 }
8354 loopnest--;
8355 exitstatus = status;
8356}
8357
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008358static void
Eric Andersenc470f442003-07-28 09:56:35 +00008359evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008360{
8361 struct arglist arglist;
8362 union node *argp;
8363 struct strlist *sp;
8364 struct stackmark smark;
8365
8366 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008367 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008368 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008369 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008370 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008371 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008372 if (evalskip)
8373 goto out;
8374 }
8375 *arglist.lastp = NULL;
8376
8377 exitstatus = 0;
8378 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008379 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008380 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008381 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008382 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008383 if (evalskip) {
8384 if (evalskip == SKIPCONT && --skipcount <= 0) {
8385 evalskip = 0;
8386 continue;
8387 }
8388 if (evalskip == SKIPBREAK && --skipcount <= 0)
8389 evalskip = 0;
8390 break;
8391 }
8392 }
8393 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008394 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008395 popstackmark(&smark);
8396}
8397
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008398static void
Eric Andersenc470f442003-07-28 09:56:35 +00008399evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008400{
8401 union node *cp;
8402 union node *patp;
8403 struct arglist arglist;
8404 struct stackmark smark;
8405
8406 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008407 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008408 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008409 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008410 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008411 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8412 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008413 if (casematch(patp, arglist.list->text)) {
8414 if (evalskip == 0) {
8415 evaltree(cp->nclist.body, flags);
8416 }
8417 goto out;
8418 }
8419 }
8420 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008421 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008422 popstackmark(&smark);
8423}
8424
Eric Andersenc470f442003-07-28 09:56:35 +00008425/*
8426 * Kick off a subshell to evaluate a tree.
8427 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008428static void
Eric Andersenc470f442003-07-28 09:56:35 +00008429evalsubshell(union node *n, int flags)
8430{
8431 struct job *jp;
8432 int backgnd = (n->type == NBACKGND);
8433 int status;
8434
8435 expredir(n->nredir.redirect);
8436 if (!backgnd && flags & EV_EXIT && !trap[0])
8437 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008438 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008439 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008440 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008441 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008442 flags |= EV_EXIT;
8443 if (backgnd)
8444 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008445 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008446 redirect(n->nredir.redirect, 0);
8447 evaltreenr(n->nredir.n, flags);
8448 /* never returns */
8449 }
8450 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008451 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008452 status = waitforjob(jp);
8453 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008454 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008455}
8456
Eric Andersenc470f442003-07-28 09:56:35 +00008457/*
8458 * Compute the names of the files in a redirection list.
8459 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008460static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008461static void
8462expredir(union node *n)
8463{
8464 union node *redir;
8465
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008466 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008467 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008468
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008469 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008470 fn.lastp = &fn.list;
8471 switch (redir->type) {
8472 case NFROMTO:
8473 case NFROM:
8474 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008475#if ENABLE_ASH_BASH_COMPAT
8476 case NTO2:
8477#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008478 case NCLOBBER:
8479 case NAPPEND:
8480 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008481#if ENABLE_ASH_BASH_COMPAT
8482 store_expfname:
8483#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008484 redir->nfile.expfname = fn.list->text;
8485 break;
8486 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008487 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008488 if (redir->ndup.vname) {
8489 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008490 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008491 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008492#if ENABLE_ASH_BASH_COMPAT
8493//FIXME: we used expandarg with different args!
8494 if (!isdigit_str9(fn.list->text)) {
8495 /* >&file, not >&fd */
8496 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8497 ash_msg_and_raise_error("redir error");
8498 redir->type = NTO2;
8499 goto store_expfname;
8500 }
8501#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008502 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008503 }
8504 break;
8505 }
8506 }
8507}
8508
Eric Andersencb57d552001-06-28 07:25:16 +00008509/*
Eric Andersencb57d552001-06-28 07:25:16 +00008510 * Evaluate a pipeline. All the processes in the pipeline are children
8511 * of the process creating the pipeline. (This differs from some versions
8512 * of the shell, which make the last process in a pipeline the parent
8513 * of all the rest.)
8514 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008515static void
Eric Andersenc470f442003-07-28 09:56:35 +00008516evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008517{
8518 struct job *jp;
8519 struct nodelist *lp;
8520 int pipelen;
8521 int prevfd;
8522 int pip[2];
8523
Eric Andersenc470f442003-07-28 09:56:35 +00008524 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008525 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008526 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008527 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008528 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008529 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008530 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008531 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008532 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008533 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008534 pip[1] = -1;
8535 if (lp->next) {
8536 if (pipe(pip) < 0) {
8537 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008538 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008539 }
8540 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008541 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008542 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008543 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008544 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008545 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008546 if (prevfd > 0) {
8547 dup2(prevfd, 0);
8548 close(prevfd);
8549 }
8550 if (pip[1] > 1) {
8551 dup2(pip[1], 1);
8552 close(pip[1]);
8553 }
Eric Andersenc470f442003-07-28 09:56:35 +00008554 evaltreenr(lp->n, flags);
8555 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008556 }
8557 if (prevfd >= 0)
8558 close(prevfd);
8559 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008560 /* Don't want to trigger debugging */
8561 if (pip[1] != -1)
8562 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008563 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008564 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008565 exitstatus = waitforjob(jp);
8566 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008567 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008568 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008569}
8570
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008571/*
8572 * Controls whether the shell is interactive or not.
8573 */
8574static void
8575setinteractive(int on)
8576{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008577 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008578
8579 if (++on == is_interactive)
8580 return;
8581 is_interactive = on;
8582 setsignal(SIGINT);
8583 setsignal(SIGQUIT);
8584 setsignal(SIGTERM);
8585#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8586 if (is_interactive > 1) {
8587 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008588 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008589
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008590 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008591 /* note: ash and hush share this string */
8592 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008593 "Enter 'help' for a list of built-in commands."
8594 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008595 bb_banner,
8596 "built-in shell (ash)"
8597 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008598 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008599 }
8600 }
8601#endif
8602}
8603
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008604static void
8605optschanged(void)
8606{
8607#if DEBUG
8608 opentrace();
8609#endif
8610 setinteractive(iflag);
8611 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008612#if ENABLE_FEATURE_EDITING_VI
8613 if (viflag)
8614 line_input_state->flags |= VI_MODE;
8615 else
8616 line_input_state->flags &= ~VI_MODE;
8617#else
8618 viflag = 0; /* forcibly keep the option off */
8619#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008620}
8621
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008622static struct localvar *localvars;
8623
8624/*
8625 * Called after a function returns.
8626 * Interrupts must be off.
8627 */
8628static void
8629poplocalvars(void)
8630{
8631 struct localvar *lvp;
8632 struct var *vp;
8633
8634 while ((lvp = localvars) != NULL) {
8635 localvars = lvp->next;
8636 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008637 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008638 if (vp == NULL) { /* $- saved */
8639 memcpy(optlist, lvp->text, sizeof(optlist));
8640 free((char*)lvp->text);
8641 optschanged();
8642 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8643 unsetvar(vp->text);
8644 } else {
8645 if (vp->func)
8646 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8647 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8648 free((char*)vp->text);
8649 vp->flags = lvp->flags;
8650 vp->text = lvp->text;
8651 }
8652 free(lvp);
8653 }
8654}
8655
8656static int
8657evalfun(struct funcnode *func, int argc, char **argv, int flags)
8658{
8659 volatile struct shparam saveparam;
8660 struct localvar *volatile savelocalvars;
8661 struct jmploc *volatile savehandler;
8662 struct jmploc jmploc;
8663 int e;
8664
8665 saveparam = shellparam;
8666 savelocalvars = localvars;
8667 e = setjmp(jmploc.loc);
8668 if (e) {
8669 goto funcdone;
8670 }
8671 INT_OFF;
8672 savehandler = exception_handler;
8673 exception_handler = &jmploc;
8674 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008675 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008676 func->count++;
8677 funcnest++;
8678 INT_ON;
8679 shellparam.nparam = argc - 1;
8680 shellparam.p = argv + 1;
8681#if ENABLE_ASH_GETOPTS
8682 shellparam.optind = 1;
8683 shellparam.optoff = -1;
8684#endif
8685 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008686 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008687 INT_OFF;
8688 funcnest--;
8689 freefunc(func);
8690 poplocalvars();
8691 localvars = savelocalvars;
8692 freeparam(&shellparam);
8693 shellparam = saveparam;
8694 exception_handler = savehandler;
8695 INT_ON;
8696 evalskip &= ~SKIPFUNC;
8697 return e;
8698}
8699
Denis Vlasenko131ae172007-02-18 13:00:19 +00008700#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008701static char **
8702parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008703{
8704 char *cp, c;
8705
8706 for (;;) {
8707 cp = *++argv;
8708 if (!cp)
8709 return 0;
8710 if (*cp++ != '-')
8711 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008712 c = *cp++;
8713 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008714 break;
8715 if (c == '-' && !*cp) {
8716 argv++;
8717 break;
8718 }
8719 do {
8720 switch (c) {
8721 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008722 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008723 break;
8724 default:
8725 /* run 'typecmd' for other options */
8726 return 0;
8727 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008728 c = *cp++;
8729 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008730 }
8731 return argv;
8732}
8733#endif
8734
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008735/*
8736 * Make a variable a local variable. When a variable is made local, it's
8737 * value and flags are saved in a localvar structure. The saved values
8738 * will be restored when the shell function returns. We handle the name
8739 * "-" as a special case.
8740 */
8741static void
8742mklocal(char *name)
8743{
8744 struct localvar *lvp;
8745 struct var **vpp;
8746 struct var *vp;
8747
8748 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008749 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008750 if (LONE_DASH(name)) {
8751 char *p;
8752 p = ckmalloc(sizeof(optlist));
8753 lvp->text = memcpy(p, optlist, sizeof(optlist));
8754 vp = NULL;
8755 } else {
8756 char *eq;
8757
8758 vpp = hashvar(name);
8759 vp = *findvar(vpp, name);
8760 eq = strchr(name, '=');
8761 if (vp == NULL) {
8762 if (eq)
8763 setvareq(name, VSTRFIXED);
8764 else
8765 setvar(name, NULL, VSTRFIXED);
8766 vp = *vpp; /* the new variable */
8767 lvp->flags = VUNSET;
8768 } else {
8769 lvp->text = vp->text;
8770 lvp->flags = vp->flags;
8771 vp->flags |= VSTRFIXED|VTEXTFIXED;
8772 if (eq)
8773 setvareq(name, 0);
8774 }
8775 }
8776 lvp->vp = vp;
8777 lvp->next = localvars;
8778 localvars = lvp;
8779 INT_ON;
8780}
8781
8782/*
8783 * The "local" command.
8784 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008786localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008787{
8788 char *name;
8789
8790 argv = argptr;
8791 while ((name = *argv++) != NULL) {
8792 mklocal(name);
8793 }
8794 return 0;
8795}
8796
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008798falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008799{
8800 return 1;
8801}
8802
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008803static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008804truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008805{
8806 return 0;
8807}
8808
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008810execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008811{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008812 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008813 iflag = 0; /* exit on error */
8814 mflag = 0;
8815 optschanged();
8816 shellexec(argv + 1, pathval(), 0);
8817 }
8818 return 0;
8819}
8820
8821/*
8822 * The return command.
8823 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008824static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008825returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008826{
8827 /*
8828 * If called outside a function, do what ksh does;
8829 * skip the rest of the file.
8830 */
8831 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8832 return argv[1] ? number(argv[1]) : exitstatus;
8833}
8834
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008835/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008836static int breakcmd(int, char **) FAST_FUNC;
8837static int dotcmd(int, char **) FAST_FUNC;
8838static int evalcmd(int, char **) FAST_FUNC;
8839static int exitcmd(int, char **) FAST_FUNC;
8840static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008841#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008842static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008843#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008844#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008845static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008846#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008847#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008848static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008849#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008850static int readcmd(int, char **) FAST_FUNC;
8851static int setcmd(int, char **) FAST_FUNC;
8852static int shiftcmd(int, char **) FAST_FUNC;
8853static int timescmd(int, char **) FAST_FUNC;
8854static int trapcmd(int, char **) FAST_FUNC;
8855static int umaskcmd(int, char **) FAST_FUNC;
8856static int unsetcmd(int, char **) FAST_FUNC;
8857static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008858
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008859#define BUILTIN_NOSPEC "0"
8860#define BUILTIN_SPECIAL "1"
8861#define BUILTIN_REGULAR "2"
8862#define BUILTIN_SPEC_REG "3"
8863#define BUILTIN_ASSIGN "4"
8864#define BUILTIN_SPEC_ASSG "5"
8865#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008866#define BUILTIN_SPEC_REG_ASSG "7"
8867
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008868/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008869#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008870static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008871#endif
8872#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008873static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008874#endif
8875#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008876static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008877#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008878
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008879/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008880static const struct builtincmd builtintab[] = {
8881 { BUILTIN_SPEC_REG ".", dotcmd },
8882 { BUILTIN_SPEC_REG ":", truecmd },
8883#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008884 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008885#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008886 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008887#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008888#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008889#if ENABLE_ASH_ALIAS
8890 { BUILTIN_REG_ASSG "alias", aliascmd },
8891#endif
8892#if JOBS
8893 { BUILTIN_REGULAR "bg", fg_bgcmd },
8894#endif
8895 { BUILTIN_SPEC_REG "break", breakcmd },
8896 { BUILTIN_REGULAR "cd", cdcmd },
8897 { BUILTIN_NOSPEC "chdir", cdcmd },
8898#if ENABLE_ASH_CMDCMD
8899 { BUILTIN_REGULAR "command", commandcmd },
8900#endif
8901 { BUILTIN_SPEC_REG "continue", breakcmd },
8902#if ENABLE_ASH_BUILTIN_ECHO
8903 { BUILTIN_REGULAR "echo", echocmd },
8904#endif
8905 { BUILTIN_SPEC_REG "eval", evalcmd },
8906 { BUILTIN_SPEC_REG "exec", execcmd },
8907 { BUILTIN_SPEC_REG "exit", exitcmd },
8908 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8909 { BUILTIN_REGULAR "false", falsecmd },
8910#if JOBS
8911 { BUILTIN_REGULAR "fg", fg_bgcmd },
8912#endif
8913#if ENABLE_ASH_GETOPTS
8914 { BUILTIN_REGULAR "getopts", getoptscmd },
8915#endif
8916 { BUILTIN_NOSPEC "hash", hashcmd },
8917#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8918 { BUILTIN_NOSPEC "help", helpcmd },
8919#endif
8920#if JOBS
8921 { BUILTIN_REGULAR "jobs", jobscmd },
8922 { BUILTIN_REGULAR "kill", killcmd },
8923#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008924#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008925 { BUILTIN_NOSPEC "let", letcmd },
8926#endif
8927 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008928#if ENABLE_ASH_BUILTIN_PRINTF
8929 { BUILTIN_REGULAR "printf", printfcmd },
8930#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008931 { BUILTIN_NOSPEC "pwd", pwdcmd },
8932 { BUILTIN_REGULAR "read", readcmd },
8933 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8934 { BUILTIN_SPEC_REG "return", returncmd },
8935 { BUILTIN_SPEC_REG "set", setcmd },
8936 { BUILTIN_SPEC_REG "shift", shiftcmd },
8937 { BUILTIN_SPEC_REG "source", dotcmd },
8938#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008939 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008940#endif
8941 { BUILTIN_SPEC_REG "times", timescmd },
8942 { BUILTIN_SPEC_REG "trap", trapcmd },
8943 { BUILTIN_REGULAR "true", truecmd },
8944 { BUILTIN_NOSPEC "type", typecmd },
8945 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8946 { BUILTIN_REGULAR "umask", umaskcmd },
8947#if ENABLE_ASH_ALIAS
8948 { BUILTIN_REGULAR "unalias", unaliascmd },
8949#endif
8950 { BUILTIN_SPEC_REG "unset", unsetcmd },
8951 { BUILTIN_REGULAR "wait", waitcmd },
8952};
8953
Denis Vlasenko80591b02008-03-25 07:49:43 +00008954/* Should match the above table! */
8955#define COMMANDCMD (builtintab + \
8956 2 + \
8957 1 * ENABLE_ASH_BUILTIN_TEST + \
8958 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8959 1 * ENABLE_ASH_ALIAS + \
8960 1 * ENABLE_ASH_JOB_CONTROL + \
8961 3)
8962#define EXECCMD (builtintab + \
8963 2 + \
8964 1 * ENABLE_ASH_BUILTIN_TEST + \
8965 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8966 1 * ENABLE_ASH_ALIAS + \
8967 1 * ENABLE_ASH_JOB_CONTROL + \
8968 3 + \
8969 1 * ENABLE_ASH_CMDCMD + \
8970 1 + \
8971 ENABLE_ASH_BUILTIN_ECHO + \
8972 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008973
8974/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008975 * Search the table of builtin commands.
8976 */
8977static struct builtincmd *
8978find_builtin(const char *name)
8979{
8980 struct builtincmd *bp;
8981
8982 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008983 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008984 pstrcmp
8985 );
8986 return bp;
8987}
8988
8989/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008990 * Execute a simple command.
8991 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008992static int
8993isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008994{
8995 const char *q = endofname(p);
8996 if (p == q)
8997 return 0;
8998 return *q == '=';
8999}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009000static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009001bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009002{
9003 /* Preserve exitstatus of a previous possible redirection
9004 * as POSIX mandates */
9005 return back_exitstatus;
9006}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009007static void
Eric Andersenc470f442003-07-28 09:56:35 +00009008evalcommand(union node *cmd, int flags)
9009{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009010 static const struct builtincmd null_bltin = {
9011 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009012 };
Eric Andersenc470f442003-07-28 09:56:35 +00009013 struct stackmark smark;
9014 union node *argp;
9015 struct arglist arglist;
9016 struct arglist varlist;
9017 char **argv;
9018 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009019 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009020 struct cmdentry cmdentry;
9021 struct job *jp;
9022 char *lastarg;
9023 const char *path;
9024 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009025 int status;
9026 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009027 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009028 smallint cmd_is_exec;
9029 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009030
9031 /* First expand the arguments. */
9032 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9033 setstackmark(&smark);
9034 back_exitstatus = 0;
9035
9036 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009037 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009038 varlist.lastp = &varlist.list;
9039 *varlist.lastp = NULL;
9040 arglist.lastp = &arglist.list;
9041 *arglist.lastp = NULL;
9042
9043 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009044 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009045 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9046 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9047 }
9048
Eric Andersenc470f442003-07-28 09:56:35 +00009049 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9050 struct strlist **spp;
9051
9052 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009053 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009054 expandarg(argp, &arglist, EXP_VARTILDE);
9055 else
9056 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9057
Eric Andersenc470f442003-07-28 09:56:35 +00009058 for (sp = *spp; sp; sp = sp->next)
9059 argc++;
9060 }
9061
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009062 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009063 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009064 TRACE(("evalcommand arg: %s\n", sp->text));
9065 *nargv++ = sp->text;
9066 }
9067 *nargv = NULL;
9068
9069 lastarg = NULL;
9070 if (iflag && funcnest == 0 && argc > 0)
9071 lastarg = nargv[-1];
9072
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009073 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009074 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009075 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009076
9077 path = vpath.text;
9078 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9079 struct strlist **spp;
9080 char *p;
9081
9082 spp = varlist.lastp;
9083 expandarg(argp, &varlist, EXP_VARTILDE);
9084
9085 /*
9086 * Modify the command lookup path, if a PATH= assignment
9087 * is present
9088 */
9089 p = (*spp)->text;
9090 if (varequal(p, path))
9091 path = p;
9092 }
9093
9094 /* Print the command if xflag is set. */
9095 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009096 int n;
9097 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009098
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009099 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009100 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009101
9102 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009103 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009104 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009105 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009106 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009107 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009108 p--;
9109 }
9110 }
9111 sp = arglist.list;
9112 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009113 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009114 }
9115
9116 cmd_is_exec = 0;
9117 spclbltin = -1;
9118
9119 /* Now locate the command. */
9120 if (argc) {
9121 const char *oldpath;
9122 int cmd_flag = DO_ERR;
9123
9124 path += 5;
9125 oldpath = path;
9126 for (;;) {
9127 find_command(argv[0], &cmdentry, cmd_flag, path);
9128 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009129 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009130 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009131 goto bail;
9132 }
9133
9134 /* implement bltin and command here */
9135 if (cmdentry.cmdtype != CMDBUILTIN)
9136 break;
9137 if (spclbltin < 0)
9138 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9139 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009140 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009141#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009142 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009143 path = oldpath;
9144 nargv = parse_command_args(argv, &path);
9145 if (!nargv)
9146 break;
9147 argc -= nargv - argv;
9148 argv = nargv;
9149 cmd_flag |= DO_NOFUNC;
9150 } else
9151#endif
9152 break;
9153 }
9154 }
9155
9156 if (status) {
9157 /* We have a redirection error. */
9158 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009159 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009160 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009161 exitstatus = status;
9162 goto out;
9163 }
9164
9165 /* Execute the command. */
9166 switch (cmdentry.cmdtype) {
9167 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009168
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009169#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009170/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9171 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009172 {
9173 /* find_command() encodes applet_no as (-2 - applet_no) */
9174 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009175 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009176 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009177 /* run <applet>_main() */
9178 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009179 break;
9180 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009181 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009182#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009183 /* Fork off a child process if necessary. */
9184 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009185 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009186 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009187 if (forkshell(jp, cmd, FORK_FG) != 0) {
9188 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009189 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009190 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009191 break;
9192 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009193 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009194 }
9195 listsetvar(varlist.list, VEXPORT|VSTACK);
9196 shellexec(argv, path, cmdentry.u.index);
9197 /* NOTREACHED */
9198
9199 case CMDBUILTIN:
9200 cmdenviron = varlist.list;
9201 if (cmdenviron) {
9202 struct strlist *list = cmdenviron;
9203 int i = VNOSET;
9204 if (spclbltin > 0 || argc == 0) {
9205 i = 0;
9206 if (cmd_is_exec && argc > 1)
9207 i = VEXPORT;
9208 }
9209 listsetvar(list, i);
9210 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009211 /* Tight loop with builtins only:
9212 * "while kill -0 $child; do true; done"
9213 * will never exit even if $child died, unless we do this
9214 * to reap the zombie and make kill detect that it's gone: */
9215 dowait(DOWAIT_NONBLOCK, NULL);
9216
Eric Andersenc470f442003-07-28 09:56:35 +00009217 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9218 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009219 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009220 if (i == EXEXIT)
9221 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009222 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009223 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009224 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009225 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009226 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009227 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009228 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009229 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009230 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009231 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009232 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009233 }
9234 break;
9235
9236 case CMDFUNCTION:
9237 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009238 /* See above for the rationale */
9239 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009240 if (evalfun(cmdentry.u.func, argc, argv, flags))
9241 goto raise;
9242 break;
9243 }
9244
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009245 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009246 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009247 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009248 /* dsl: I think this is intended to be used to support
9249 * '_' in 'vi' command mode during line editing...
9250 * However I implemented that within libedit itself.
9251 */
9252 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009253 }
Eric Andersenc470f442003-07-28 09:56:35 +00009254 popstackmark(&smark);
9255}
9256
9257static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009258evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9259{
Eric Andersenc470f442003-07-28 09:56:35 +00009260 char *volatile savecmdname;
9261 struct jmploc *volatile savehandler;
9262 struct jmploc jmploc;
9263 int i;
9264
9265 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009266 i = setjmp(jmploc.loc);
9267 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009268 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009269 savehandler = exception_handler;
9270 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009271 commandname = argv[0];
9272 argptr = argv + 1;
9273 optptr = NULL; /* initialize nextopt */
9274 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009275 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009276 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009277 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009278 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009279 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009280 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009281
9282 return i;
9283}
9284
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009285static int
9286goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009287{
9288 return !*endofname(p);
9289}
9290
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009291
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009292/*
9293 * Search for a command. This is called before we fork so that the
9294 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009295 * the child. The check for "goodname" is an overly conservative
9296 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009297 */
Eric Andersenc470f442003-07-28 09:56:35 +00009298static void
9299prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009300{
9301 struct cmdentry entry;
9302
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009303 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9304 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009305}
9306
Eric Andersencb57d552001-06-28 07:25:16 +00009307
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009308/* ============ Builtin commands
9309 *
9310 * Builtin commands whose functions are closely tied to evaluation
9311 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009312 */
9313
9314/*
Eric Andersencb57d552001-06-28 07:25:16 +00009315 * Handle break and continue commands. Break, continue, and return are
9316 * all handled by setting the evalskip flag. The evaluation routines
9317 * above all check this flag, and if it is set they start skipping
9318 * commands rather than executing them. The variable skipcount is
9319 * the number of loops to break/continue, or the number of function
9320 * levels to return. (The latter is always 1.) It should probably
9321 * be an error to break out of more loops than exist, but it isn't
9322 * in the standard shell so we don't make it one here.
9323 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009324static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009325breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009326{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009327 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009328
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009329 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009330 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009331 if (n > loopnest)
9332 n = loopnest;
9333 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009334 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009335 skipcount = n;
9336 }
9337 return 0;
9338}
9339
Eric Andersenc470f442003-07-28 09:56:35 +00009340
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009341/* ============ input.c
9342 *
Eric Andersen90898442003-08-06 11:20:52 +00009343 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009344 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009345
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009346enum {
9347 INPUT_PUSH_FILE = 1,
9348 INPUT_NOFILE_OK = 2,
9349};
Eric Andersencb57d552001-06-28 07:25:16 +00009350
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009351static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009352/* values of checkkwd variable */
9353#define CHKALIAS 0x1
9354#define CHKKWD 0x2
9355#define CHKNL 0x4
9356
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009357/*
9358 * Push a string back onto the input at this current parsefile level.
9359 * We handle aliases this way.
9360 */
9361#if !ENABLE_ASH_ALIAS
9362#define pushstring(s, ap) pushstring(s)
9363#endif
9364static void
9365pushstring(char *s, struct alias *ap)
9366{
9367 struct strpush *sp;
9368 int len;
9369
9370 len = strlen(s);
9371 INT_OFF;
9372 if (g_parsefile->strpush) {
9373 sp = ckzalloc(sizeof(*sp));
9374 sp->prev = g_parsefile->strpush;
9375 } else {
9376 sp = &(g_parsefile->basestrpush);
9377 }
9378 g_parsefile->strpush = sp;
9379 sp->prev_string = g_parsefile->next_to_pgetc;
9380 sp->prev_left_in_line = g_parsefile->left_in_line;
9381#if ENABLE_ASH_ALIAS
9382 sp->ap = ap;
9383 if (ap) {
9384 ap->flag |= ALIASINUSE;
9385 sp->string = s;
9386 }
9387#endif
9388 g_parsefile->next_to_pgetc = s;
9389 g_parsefile->left_in_line = len;
9390 INT_ON;
9391}
9392
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009393static void
9394popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009395{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009396 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009397
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009398 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009399#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009400 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009401 if (g_parsefile->next_to_pgetc[-1] == ' '
9402 || g_parsefile->next_to_pgetc[-1] == '\t'
9403 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009404 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009405 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009406 if (sp->string != sp->ap->val) {
9407 free(sp->string);
9408 }
9409 sp->ap->flag &= ~ALIASINUSE;
9410 if (sp->ap->flag & ALIASDEAD) {
9411 unalias(sp->ap->name);
9412 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009413 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009414#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009415 g_parsefile->next_to_pgetc = sp->prev_string;
9416 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009417 g_parsefile->strpush = sp->prev;
9418 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009419 free(sp);
9420 INT_ON;
9421}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009422
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009423//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9424//it peeks whether it is &>, and then pushes back both chars.
9425//This function needs to save last *next_to_pgetc to buf[0]
9426//to make two pungetc() reliable. Currently,
9427// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009428static int
9429preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009430{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009431 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009432 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009433
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009434 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009435#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009436 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009437 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009438 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009439 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009440#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009441 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009442#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009443 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9444 if (nr == 0) {
9445 /* Ctrl+C pressed */
9446 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009447 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009448 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009449 raise(SIGINT);
9450 return 1;
9451 }
Eric Andersenc470f442003-07-28 09:56:35 +00009452 goto retry;
9453 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009454 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009455 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009456 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009457 }
Eric Andersencb57d552001-06-28 07:25:16 +00009458 }
9459#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009460 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009461#endif
9462
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009463#if 0
9464/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009465 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009466 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009467 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009468 if (flags >= 0 && (flags & O_NONBLOCK)) {
9469 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009470 if (fcntl(0, F_SETFL, flags) >= 0) {
9471 out2str("sh: turning off NDELAY mode\n");
9472 goto retry;
9473 }
9474 }
9475 }
9476 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009477#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009478 return nr;
9479}
9480
9481/*
9482 * Refill the input buffer and return the next input character:
9483 *
9484 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009485 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9486 * or we are reading from a string so we can't refill the buffer,
9487 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009488 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009489 * 4) Process input up to the next newline, deleting nul characters.
9490 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009491//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9492#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009493static int
Eric Andersenc470f442003-07-28 09:56:35 +00009494preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009495{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009496 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009497 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009498
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009499 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009500#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 if (g_parsefile->left_in_line == -1
9502 && g_parsefile->strpush->ap
9503 && g_parsefile->next_to_pgetc[-1] != ' '
9504 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009505 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009506 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009507 return PEOA;
9508 }
Eric Andersen2870d962001-07-02 17:27:21 +00009509#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009510 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009511 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009512 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9513 g_parsefile->left_in_line,
9514 g_parsefile->next_to_pgetc,
9515 g_parsefile->next_to_pgetc);
9516 if (--g_parsefile->left_in_line >= 0)
9517 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009518 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009519 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009520 * "pgetc" needs refilling.
9521 */
9522
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009523 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009525 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009526 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009527 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009528 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009529 /* even in failure keep left_in_line and next_to_pgetc
9530 * in lock step, for correct multi-layer pungetc.
9531 * left_in_line was decremented before preadbuffer(),
9532 * must inc next_to_pgetc: */
9533 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009534 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009535 }
Eric Andersencb57d552001-06-28 07:25:16 +00009536
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009537 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009538 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009539 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009540 again:
9541 more = preadfd();
9542 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009543 /* don't try reading again */
9544 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009545 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009546 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009547 return PEOF;
9548 }
9549 }
9550
Denis Vlasenko727752d2008-11-28 03:41:47 +00009551 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552 * Set g_parsefile->left_in_line
9553 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009554 * NUL chars are deleted.
9555 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009556 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009557 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009558 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009559
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009560 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009561
Denis Vlasenko727752d2008-11-28 03:41:47 +00009562 c = *q;
9563 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009564 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009565 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009566 q++;
9567 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009568 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009569 break;
9570 }
Eric Andersencb57d552001-06-28 07:25:16 +00009571 }
9572
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009573 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009574 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9575 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009576 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009577 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009578 }
9579 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009580 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009581
Eric Andersencb57d552001-06-28 07:25:16 +00009582 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009583 char save = *q;
9584 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009585 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009586 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009587 }
9588
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009589 pgetc_debug("preadbuffer at %d:%p'%s'",
9590 g_parsefile->left_in_line,
9591 g_parsefile->next_to_pgetc,
9592 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009593 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009594}
9595
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009596#define pgetc_as_macro() \
9597 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009598 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009599 : preadbuffer() \
9600 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009601
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009602static int
9603pgetc(void)
9604{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009605 pgetc_debug("pgetc_fast at %d:%p'%s'",
9606 g_parsefile->left_in_line,
9607 g_parsefile->next_to_pgetc,
9608 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009609 return pgetc_as_macro();
9610}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009611
9612#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009613# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009614#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009615# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009616#endif
9617
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009618#if ENABLE_ASH_ALIAS
9619static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009620pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009621{
9622 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009623 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009624 pgetc_debug("pgetc_fast at %d:%p'%s'",
9625 g_parsefile->left_in_line,
9626 g_parsefile->next_to_pgetc,
9627 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009628 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009629 } while (c == PEOA);
9630 return c;
9631}
9632#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009633# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009634#endif
9635
9636/*
9637 * Read a line from the script.
9638 */
9639static char *
9640pfgets(char *line, int len)
9641{
9642 char *p = line;
9643 int nleft = len;
9644 int c;
9645
9646 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009647 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009648 if (c == PEOF) {
9649 if (p == line)
9650 return NULL;
9651 break;
9652 }
9653 *p++ = c;
9654 if (c == '\n')
9655 break;
9656 }
9657 *p = '\0';
9658 return line;
9659}
9660
Eric Andersenc470f442003-07-28 09:56:35 +00009661/*
9662 * Undo the last call to pgetc. Only one character may be pushed back.
9663 * PEOF may be pushed back.
9664 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009665static void
Eric Andersenc470f442003-07-28 09:56:35 +00009666pungetc(void)
9667{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009668 g_parsefile->left_in_line++;
9669 g_parsefile->next_to_pgetc--;
9670 pgetc_debug("pushed back to %d:%p'%s'",
9671 g_parsefile->left_in_line,
9672 g_parsefile->next_to_pgetc,
9673 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009674}
9675
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009676/*
9677 * To handle the "." command, a stack of input files is used. Pushfile
9678 * adds a new entry to the stack and popfile restores the previous level.
9679 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009680static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009681pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009682{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009683 struct parsefile *pf;
9684
Denis Vlasenko597906c2008-02-20 16:38:54 +00009685 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009686 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009687 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009688 /*pf->strpush = NULL; - ckzalloc did it */
9689 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009690 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009691}
9692
9693static void
9694popfile(void)
9695{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009696 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009697
Denis Vlasenkob012b102007-02-19 22:43:01 +00009698 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699 if (pf->fd >= 0)
9700 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009701 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009702 while (pf->strpush)
9703 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009704 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009705 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009706 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009707}
9708
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009709/*
9710 * Return to top level.
9711 */
9712static void
9713popallfiles(void)
9714{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009715 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009716 popfile();
9717}
9718
9719/*
9720 * Close the file(s) that the shell is reading commands from. Called
9721 * after a fork is done.
9722 */
9723static void
9724closescript(void)
9725{
9726 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009727 if (g_parsefile->fd > 0) {
9728 close(g_parsefile->fd);
9729 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009730 }
9731}
9732
9733/*
9734 * Like setinputfile, but takes an open file descriptor. Call this with
9735 * interrupts off.
9736 */
9737static void
9738setinputfd(int fd, int push)
9739{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009740 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009741 if (push) {
9742 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009743 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009744 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009745 g_parsefile->fd = fd;
9746 if (g_parsefile->buf == NULL)
9747 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009748 g_parsefile->left_in_buffer = 0;
9749 g_parsefile->left_in_line = 0;
9750 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009751}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009752
Eric Andersenc470f442003-07-28 09:56:35 +00009753/*
9754 * Set the input to take input from a file. If push is set, push the
9755 * old input onto the stack first.
9756 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009757static int
9758setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009759{
9760 int fd;
9761 int fd2;
9762
Denis Vlasenkob012b102007-02-19 22:43:01 +00009763 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009764 fd = open(fname, O_RDONLY);
9765 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009766 if (flags & INPUT_NOFILE_OK)
9767 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009768 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009769 }
Eric Andersenc470f442003-07-28 09:56:35 +00009770 if (fd < 10) {
9771 fd2 = copyfd(fd, 10);
9772 close(fd);
9773 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009774 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009775 fd = fd2;
9776 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009777 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009778 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009779 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009780 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009781}
9782
Eric Andersencb57d552001-06-28 07:25:16 +00009783/*
9784 * Like setinputfile, but takes input from a string.
9785 */
Eric Andersenc470f442003-07-28 09:56:35 +00009786static void
9787setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009788{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009789 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009790 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009791 g_parsefile->next_to_pgetc = string;
9792 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009793 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009794 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009795 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009796}
9797
9798
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009799/* ============ mail.c
9800 *
9801 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009802 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009803
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009804#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009805
Eric Andersencb57d552001-06-28 07:25:16 +00009806#define MAXMBOXES 10
9807
Eric Andersenc470f442003-07-28 09:56:35 +00009808/* times of mailboxes */
9809static time_t mailtime[MAXMBOXES];
9810/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009811static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009812
Eric Andersencb57d552001-06-28 07:25:16 +00009813/*
Eric Andersenc470f442003-07-28 09:56:35 +00009814 * Print appropriate message(s) if mail has arrived.
9815 * If mail_var_path_changed is set,
9816 * then the value of MAIL has mail_var_path_changed,
9817 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009818 */
Eric Andersenc470f442003-07-28 09:56:35 +00009819static void
9820chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009821{
Eric Andersencb57d552001-06-28 07:25:16 +00009822 const char *mpath;
9823 char *p;
9824 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009825 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009826 struct stackmark smark;
9827 struct stat statb;
9828
Eric Andersencb57d552001-06-28 07:25:16 +00009829 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009830 mpath = mpathset() ? mpathval() : mailval();
9831 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009832 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009833 if (p == NULL)
9834 break;
9835 if (*p == '\0')
9836 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009837 for (q = p; *q; q++)
9838 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009839#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009840 if (q[-1] != '/')
9841 abort();
9842#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009843 q[-1] = '\0'; /* delete trailing '/' */
9844 if (stat(p, &statb) < 0) {
9845 *mtp = 0;
9846 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009847 }
Eric Andersenc470f442003-07-28 09:56:35 +00009848 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9849 fprintf(
9850 stderr, snlfmt,
9851 pathopt ? pathopt : "you have mail"
9852 );
9853 }
9854 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009855 }
Eric Andersenc470f442003-07-28 09:56:35 +00009856 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009857 popstackmark(&smark);
9858}
Eric Andersencb57d552001-06-28 07:25:16 +00009859
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009860static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009861changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009862{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009863 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009864}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009865
Denis Vlasenko131ae172007-02-18 13:00:19 +00009866#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009867
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009868
9869/* ============ ??? */
9870
Eric Andersencb57d552001-06-28 07:25:16 +00009871/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009872 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009873 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009874static void
9875setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009876{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009877 char **newparam;
9878 char **ap;
9879 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009880
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009881 for (nparam = 0; argv[nparam]; nparam++)
9882 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009883 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9884 while (*argv) {
9885 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009886 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009887 *ap = NULL;
9888 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009889 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009890 shellparam.nparam = nparam;
9891 shellparam.p = newparam;
9892#if ENABLE_ASH_GETOPTS
9893 shellparam.optind = 1;
9894 shellparam.optoff = -1;
9895#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009896}
9897
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009898/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009899 * Process shell options. The global variable argptr contains a pointer
9900 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009901 *
9902 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9903 * For a non-interactive shell, an error condition encountered
9904 * by a special built-in ... shall cause the shell to write a diagnostic message
9905 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009906 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009907 * ...
9908 * Utility syntax error (option or operand error) Shall exit
9909 * ...
9910 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9911 * we see that bash does not do that (set "finishes" with error code 1 instead,
9912 * and shell continues), and people rely on this behavior!
9913 * Testcase:
9914 * set -o barfoo 2>/dev/null
9915 * echo $?
9916 *
9917 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009918 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009919static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009920plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009921{
9922 int i;
9923
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009924 if (name) {
9925 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009926 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009927 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009928 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009929 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009930 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009931 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009932 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009933 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009934 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009935 if (val) {
9936 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9937 } else {
9938 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9939 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009940 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009941 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009942}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009943static void
9944setoption(int flag, int val)
9945{
9946 int i;
9947
9948 for (i = 0; i < NOPTS; i++) {
9949 if (optletters(i) == flag) {
9950 optlist[i] = val;
9951 return;
9952 }
9953 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009954 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009955 /* NOTREACHED */
9956}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009957static int
Eric Andersenc470f442003-07-28 09:56:35 +00009958options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009959{
9960 char *p;
9961 int val;
9962 int c;
9963
9964 if (cmdline)
9965 minusc = NULL;
9966 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009967 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009968 if (c != '-' && c != '+')
9969 break;
9970 argptr++;
9971 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009972 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009973 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009974 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009975 if (!cmdline) {
9976 /* "-" means turn off -x and -v */
9977 if (p[0] == '\0')
9978 xflag = vflag = 0;
9979 /* "--" means reset params */
9980 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009981 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009982 }
Eric Andersenc470f442003-07-28 09:56:35 +00009983 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009984 }
Eric Andersencb57d552001-06-28 07:25:16 +00009985 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009986 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009987 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009988 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009989 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009990 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009991 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009992 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009993 /* it already printed err message */
9994 return 1; /* error */
9995 }
Eric Andersencb57d552001-06-28 07:25:16 +00009996 if (*argptr)
9997 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009998 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9999 isloginsh = 1;
10000 /* bash does not accept +-login, we also won't */
10001 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010002 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010003 isloginsh = 1;
10004 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010005 } else {
10006 setoption(c, val);
10007 }
10008 }
10009 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010010 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010011}
10012
Eric Andersencb57d552001-06-28 07:25:16 +000010013/*
Eric Andersencb57d552001-06-28 07:25:16 +000010014 * The shift builtin command.
10015 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010016static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010017shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010018{
10019 int n;
10020 char **ap1, **ap2;
10021
10022 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010023 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010024 n = number(argv[1]);
10025 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010026 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010027 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010028 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010029 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010030 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010031 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010032 }
10033 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010034 while ((*ap2++ = *ap1++) != NULL)
10035 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010036#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010037 shellparam.optind = 1;
10038 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010039#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010040 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010041 return 0;
10042}
10043
Eric Andersencb57d552001-06-28 07:25:16 +000010044/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010045 * POSIX requires that 'set' (but not export or readonly) output the
10046 * variables in lexicographic order - by the locale's collating order (sigh).
10047 * Maybe we could keep them in an ordered balanced binary tree
10048 * instead of hashed lists.
10049 * For now just roll 'em through qsort for printing...
10050 */
10051static int
10052showvars(const char *sep_prefix, int on, int off)
10053{
10054 const char *sep;
10055 char **ep, **epend;
10056
10057 ep = listvars(on, off, &epend);
10058 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10059
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010060 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010061
10062 for (; ep < epend; ep++) {
10063 const char *p;
10064 const char *q;
10065
10066 p = strchrnul(*ep, '=');
10067 q = nullstr;
10068 if (*p)
10069 q = single_quote(++p);
10070 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10071 }
10072 return 0;
10073}
10074
10075/*
Eric Andersencb57d552001-06-28 07:25:16 +000010076 * The set command builtin.
10077 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010078static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010079setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010080{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010081 int retval;
10082
Denis Vlasenko68404f12008-03-17 09:00:54 +000010083 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010084 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010085 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010086 retval = 1;
10087 if (!options(0)) { /* if no parse error... */
10088 retval = 0;
10089 optschanged();
10090 if (*argptr != NULL) {
10091 setparam(argptr);
10092 }
Eric Andersencb57d552001-06-28 07:25:16 +000010093 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010094 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010095 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010096}
10097
Denis Vlasenko131ae172007-02-18 13:00:19 +000010098#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010099static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010100change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010101{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010102 uint32_t t;
10103
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010104 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010105 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010106 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010107 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010108 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010109 vrandom.flags &= ~VNOFUNC;
10110 } else {
10111 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010112 t = strtoul(value, NULL, 10);
10113 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010114 }
Eric Andersenef02f822004-03-11 13:34:24 +000010115}
Eric Andersen16767e22004-03-16 05:14:10 +000010116#endif
10117
Denis Vlasenko131ae172007-02-18 13:00:19 +000010118#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010119static int
Eric Andersenc470f442003-07-28 09:56:35 +000010120getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010121{
10122 char *p, *q;
10123 char c = '?';
10124 int done = 0;
10125 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010126 char s[12];
10127 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010128
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010129 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010130 return 1;
10131 optnext = optfirst + *param_optind - 1;
10132
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010133 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010134 p = NULL;
10135 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010136 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010137 if (p == NULL || *p == '\0') {
10138 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010139 p = *optnext;
10140 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010141 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010142 p = NULL;
10143 done = 1;
10144 goto out;
10145 }
10146 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010147 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010148 goto atend;
10149 }
10150
10151 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010152 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010153 if (*q == '\0') {
10154 if (optstr[0] == ':') {
10155 s[0] = c;
10156 s[1] = '\0';
10157 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010158 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010159 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010160 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010161 }
10162 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010163 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010164 }
10165 if (*++q == ':')
10166 q++;
10167 }
10168
10169 if (*++q == ':') {
10170 if (*p == '\0' && (p = *optnext) == NULL) {
10171 if (optstr[0] == ':') {
10172 s[0] = c;
10173 s[1] = '\0';
10174 err |= setvarsafe("OPTARG", s, 0);
10175 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010176 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010177 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010178 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010179 c = '?';
10180 }
Eric Andersenc470f442003-07-28 09:56:35 +000010181 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010182 }
10183
10184 if (p == *optnext)
10185 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010186 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010187 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010188 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010189 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010190 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010191 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010192 *param_optind = optnext - optfirst + 1;
10193 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010194 err |= setvarsafe("OPTIND", s, VNOFUNC);
10195 s[0] = c;
10196 s[1] = '\0';
10197 err |= setvarsafe(optvar, s, 0);
10198 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010199 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010200 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010201 flush_stdout_stderr();
10202 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010203 }
10204 return done;
10205}
Eric Andersenc470f442003-07-28 09:56:35 +000010206
10207/*
10208 * The getopts builtin. Shellparam.optnext points to the next argument
10209 * to be processed. Shellparam.optptr points to the next character to
10210 * be processed in the current argument. If shellparam.optnext is NULL,
10211 * then it's the first time getopts has been called.
10212 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010213static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010214getoptscmd(int argc, char **argv)
10215{
10216 char **optbase;
10217
10218 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010219 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010220 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010221 optbase = shellparam.p;
10222 if (shellparam.optind > shellparam.nparam + 1) {
10223 shellparam.optind = 1;
10224 shellparam.optoff = -1;
10225 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010226 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010227 optbase = &argv[3];
10228 if (shellparam.optind > argc - 2) {
10229 shellparam.optind = 1;
10230 shellparam.optoff = -1;
10231 }
10232 }
10233
10234 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010235 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010236}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010237#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010238
Eric Andersencb57d552001-06-28 07:25:16 +000010239
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010240/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010241
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010242struct heredoc {
10243 struct heredoc *next; /* next here document in list */
10244 union node *here; /* redirection node */
10245 char *eofmark; /* string indicating end of input */
10246 smallint striptabs; /* if set, strip leading tabs */
10247};
10248
10249static smallint tokpushback; /* last token pushed back */
10250static smallint parsebackquote; /* nonzero if we are inside backquotes */
10251static smallint quoteflag; /* set if (part of) last token was quoted */
10252static token_id_t lasttoken; /* last token read (integer id Txxx) */
10253static struct heredoc *heredoclist; /* list of here documents to read */
10254static char *wordtext; /* text of last word returned by readtoken */
10255static struct nodelist *backquotelist;
10256static union node *redirnode;
10257static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010258
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010259/*
10260 * Called when an unexpected token is read during the parse. The argument
10261 * is the token that is expected, or -1 if more than one type of token can
10262 * occur at this point.
10263 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010264static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010265static void
10266raise_error_unexpected_syntax(int token)
10267{
10268 char msg[64];
10269 int l;
10270
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010271 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010272 if (token >= 0)
10273 sprintf(msg + l, " (expecting %s)", tokname(token));
10274 raise_error_syntax(msg);
10275 /* NOTREACHED */
10276}
Eric Andersencb57d552001-06-28 07:25:16 +000010277
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010278#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010279
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010280/* parsing is heavily cross-recursive, need these forward decls */
10281static union node *andor(void);
10282static union node *pipeline(void);
10283static union node *parse_command(void);
10284static void parseheredoc(void);
10285static char peektoken(void);
10286static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010287
Eric Andersenc470f442003-07-28 09:56:35 +000010288static union node *
10289list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010290{
10291 union node *n1, *n2, *n3;
10292 int tok;
10293
Eric Andersenc470f442003-07-28 09:56:35 +000010294 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10295 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010296 return NULL;
10297 n1 = NULL;
10298 for (;;) {
10299 n2 = andor();
10300 tok = readtoken();
10301 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010302 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010303 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010304 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010305 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010306 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010307 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010308 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010309 n2 = n3;
10310 }
10311 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010312 }
10313 }
10314 if (n1 == NULL) {
10315 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010316 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010317 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010318 n3->type = NSEMI;
10319 n3->nbinary.ch1 = n1;
10320 n3->nbinary.ch2 = n2;
10321 n1 = n3;
10322 }
10323 switch (tok) {
10324 case TBACKGND:
10325 case TSEMI:
10326 tok = readtoken();
10327 /* fall through */
10328 case TNL:
10329 if (tok == TNL) {
10330 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010331 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010332 return n1;
10333 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010334 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010335 }
Eric Andersenc470f442003-07-28 09:56:35 +000010336 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010337 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010338 return n1;
10339 break;
10340 case TEOF:
10341 if (heredoclist)
10342 parseheredoc();
10343 else
Eric Andersenc470f442003-07-28 09:56:35 +000010344 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010345 return n1;
10346 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010347 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010348 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010349 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010350 return n1;
10351 }
10352 }
10353}
10354
Eric Andersenc470f442003-07-28 09:56:35 +000010355static union node *
10356andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010357{
Eric Andersencb57d552001-06-28 07:25:16 +000010358 union node *n1, *n2, *n3;
10359 int t;
10360
Eric Andersencb57d552001-06-28 07:25:16 +000010361 n1 = pipeline();
10362 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010363 t = readtoken();
10364 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010365 t = NAND;
10366 } else if (t == TOR) {
10367 t = NOR;
10368 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010369 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010370 return n1;
10371 }
Eric Andersenc470f442003-07-28 09:56:35 +000010372 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010373 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010374 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010375 n3->type = t;
10376 n3->nbinary.ch1 = n1;
10377 n3->nbinary.ch2 = n2;
10378 n1 = n3;
10379 }
10380}
10381
Eric Andersenc470f442003-07-28 09:56:35 +000010382static union node *
10383pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010384{
Eric Andersencb57d552001-06-28 07:25:16 +000010385 union node *n1, *n2, *pipenode;
10386 struct nodelist *lp, *prev;
10387 int negate;
10388
10389 negate = 0;
10390 TRACE(("pipeline: entered\n"));
10391 if (readtoken() == TNOT) {
10392 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010393 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010394 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010395 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010396 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010397 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010398 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010399 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010400 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010401 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010402 pipenode->npipe.cmdlist = lp;
10403 lp->n = n1;
10404 do {
10405 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010406 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010407 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010408 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010409 prev->next = lp;
10410 } while (readtoken() == TPIPE);
10411 lp->next = NULL;
10412 n1 = pipenode;
10413 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010414 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010415 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010416 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010417 n2->type = NNOT;
10418 n2->nnot.com = n1;
10419 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010420 }
10421 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010422}
10423
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424static union node *
10425makename(void)
10426{
10427 union node *n;
10428
Denis Vlasenko597906c2008-02-20 16:38:54 +000010429 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010430 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010431 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010432 n->narg.text = wordtext;
10433 n->narg.backquote = backquotelist;
10434 return n;
10435}
10436
10437static void
10438fixredir(union node *n, const char *text, int err)
10439{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010440 int fd;
10441
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010442 TRACE(("Fix redir %s %d\n", text, err));
10443 if (!err)
10444 n->ndup.vname = NULL;
10445
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010446 fd = bb_strtou(text, NULL, 10);
10447 if (!errno && fd >= 0)
10448 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010449 else if (LONE_DASH(text))
10450 n->ndup.dupfd = -1;
10451 else {
10452 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010453 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010454 n->ndup.vname = makename();
10455 }
10456}
10457
10458/*
10459 * Returns true if the text contains nothing to expand (no dollar signs
10460 * or backquotes).
10461 */
10462static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010463noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010464{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010465 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010466
Denys Vlasenkocd716832009-11-28 22:14:02 +010010467 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010468 if (c == CTLQUOTEMARK)
10469 continue;
10470 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010471 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010472 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010473 return 0;
10474 }
10475 return 1;
10476}
10477
10478static void
10479parsefname(void)
10480{
10481 union node *n = redirnode;
10482
10483 if (readtoken() != TWORD)
10484 raise_error_unexpected_syntax(-1);
10485 if (n->type == NHERE) {
10486 struct heredoc *here = heredoc;
10487 struct heredoc *p;
10488 int i;
10489
10490 if (quoteflag == 0)
10491 n->type = NXHERE;
10492 TRACE(("Here document %d\n", n->type));
10493 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010494 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010495 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010496 here->eofmark = wordtext;
10497 here->next = NULL;
10498 if (heredoclist == NULL)
10499 heredoclist = here;
10500 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010501 for (p = heredoclist; p->next; p = p->next)
10502 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010503 p->next = here;
10504 }
10505 } else if (n->type == NTOFD || n->type == NFROMFD) {
10506 fixredir(n, wordtext, 0);
10507 } else {
10508 n->nfile.fname = makename();
10509 }
10510}
Eric Andersencb57d552001-06-28 07:25:16 +000010511
Eric Andersenc470f442003-07-28 09:56:35 +000010512static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010513simplecmd(void)
10514{
10515 union node *args, **app;
10516 union node *n = NULL;
10517 union node *vars, **vpp;
10518 union node **rpp, *redir;
10519 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010520#if ENABLE_ASH_BASH_COMPAT
10521 smallint double_brackets_flag = 0;
10522#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010523
10524 args = NULL;
10525 app = &args;
10526 vars = NULL;
10527 vpp = &vars;
10528 redir = NULL;
10529 rpp = &redir;
10530
10531 savecheckkwd = CHKALIAS;
10532 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010533 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010535 t = readtoken();
10536 switch (t) {
10537#if ENABLE_ASH_BASH_COMPAT
10538 case TAND: /* "&&" */
10539 case TOR: /* "||" */
10540 if (!double_brackets_flag) {
10541 tokpushback = 1;
10542 goto out;
10543 }
10544 wordtext = (char *) (t == TAND ? "-a" : "-o");
10545#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010546 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010547 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010548 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010549 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010550 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010551#if ENABLE_ASH_BASH_COMPAT
10552 if (strcmp("[[", wordtext) == 0)
10553 double_brackets_flag = 1;
10554 else if (strcmp("]]", wordtext) == 0)
10555 double_brackets_flag = 0;
10556#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010557 n->narg.backquote = backquotelist;
10558 if (savecheckkwd && isassignment(wordtext)) {
10559 *vpp = n;
10560 vpp = &n->narg.next;
10561 } else {
10562 *app = n;
10563 app = &n->narg.next;
10564 savecheckkwd = 0;
10565 }
10566 break;
10567 case TREDIR:
10568 *rpp = n = redirnode;
10569 rpp = &n->nfile.next;
10570 parsefname(); /* read name of redirection file */
10571 break;
10572 case TLP:
10573 if (args && app == &args->narg.next
10574 && !vars && !redir
10575 ) {
10576 struct builtincmd *bcmd;
10577 const char *name;
10578
10579 /* We have a function */
10580 if (readtoken() != TRP)
10581 raise_error_unexpected_syntax(TRP);
10582 name = n->narg.text;
10583 if (!goodname(name)
10584 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10585 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010586 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010587 }
10588 n->type = NDEFUN;
10589 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10590 n->narg.next = parse_command();
10591 return n;
10592 }
10593 /* fall through */
10594 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010595 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010596 goto out;
10597 }
10598 }
10599 out:
10600 *app = NULL;
10601 *vpp = NULL;
10602 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010603 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010604 n->type = NCMD;
10605 n->ncmd.args = args;
10606 n->ncmd.assign = vars;
10607 n->ncmd.redirect = redir;
10608 return n;
10609}
10610
10611static union node *
10612parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010613{
Eric Andersencb57d552001-06-28 07:25:16 +000010614 union node *n1, *n2;
10615 union node *ap, **app;
10616 union node *cp, **cpp;
10617 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010618 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010619 int t;
10620
10621 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010622 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010623
Eric Andersencb57d552001-06-28 07:25:16 +000010624 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010625 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010626 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010627 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010628 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010629 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010630 n1->type = NIF;
10631 n1->nif.test = list(0);
10632 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010633 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010634 n1->nif.ifpart = list(0);
10635 n2 = n1;
10636 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010637 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010638 n2 = n2->nif.elsepart;
10639 n2->type = NIF;
10640 n2->nif.test = list(0);
10641 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010642 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010643 n2->nif.ifpart = list(0);
10644 }
10645 if (lasttoken == TELSE)
10646 n2->nif.elsepart = list(0);
10647 else {
10648 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010649 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010650 }
Eric Andersenc470f442003-07-28 09:56:35 +000010651 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010652 break;
10653 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010654 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010655 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010656 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010657 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010658 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010659 got = readtoken();
10660 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010661 TRACE(("expecting DO got %s %s\n", tokname(got),
10662 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010663 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010664 }
10665 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010666 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010667 break;
10668 }
10669 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010670 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010671 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010672 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010673 n1->type = NFOR;
10674 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010675 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 if (readtoken() == TIN) {
10677 app = &ap;
10678 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010679 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010680 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010681 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010682 n2->narg.text = wordtext;
10683 n2->narg.backquote = backquotelist;
10684 *app = n2;
10685 app = &n2->narg.next;
10686 }
10687 *app = NULL;
10688 n1->nfor.args = ap;
10689 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010690 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010691 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010692 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010693 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010694 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010695 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010696 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010697 n1->nfor.args = n2;
10698 /*
10699 * Newline or semicolon here is optional (but note
10700 * that the original Bourne shell only allowed NL).
10701 */
10702 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010703 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010704 }
Eric Andersenc470f442003-07-28 09:56:35 +000010705 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010706 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010707 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010708 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010709 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010710 break;
10711 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010712 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010713 n1->type = NCASE;
10714 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010715 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010716 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010717 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010718 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010719 n2->narg.text = wordtext;
10720 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010721 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010722 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010723 } while (readtoken() == TNL);
10724 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010725 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010726 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010727 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010728 checkkwd = CHKNL | CHKKWD;
10729 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010730 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010731 if (lasttoken == TLP)
10732 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010733 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010734 cp->type = NCLIST;
10735 app = &cp->nclist.pattern;
10736 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010737 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010738 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010739 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010740 ap->narg.text = wordtext;
10741 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010742 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010743 break;
10744 app = &ap->narg.next;
10745 readtoken();
10746 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010747 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010748 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010749 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010750 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010751
Eric Andersenc470f442003-07-28 09:56:35 +000010752 cpp = &cp->nclist.next;
10753
10754 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010755 t = readtoken();
10756 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010757 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010758 raise_error_unexpected_syntax(TENDCASE);
10759 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010760 }
Eric Andersenc470f442003-07-28 09:56:35 +000010761 }
Eric Andersencb57d552001-06-28 07:25:16 +000010762 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010763 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010764 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010765 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010766 n1->type = NSUBSHELL;
10767 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010768 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010769 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010770 break;
10771 case TBEGIN:
10772 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010773 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010774 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010775 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010776 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010777 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010778 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010779 }
10780
Eric Andersenc470f442003-07-28 09:56:35 +000010781 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010782 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010783
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010784 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010785 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010786 checkkwd = CHKKWD | CHKALIAS;
10787 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010788 while (readtoken() == TREDIR) {
10789 *rpp = n2 = redirnode;
10790 rpp = &n2->nfile.next;
10791 parsefname();
10792 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010793 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010794 *rpp = NULL;
10795 if (redir) {
10796 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010797 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010798 n2->type = NREDIR;
10799 n2->nredir.n = n1;
10800 n1 = n2;
10801 }
10802 n1->nredir.redirect = redir;
10803 }
Eric Andersencb57d552001-06-28 07:25:16 +000010804 return n1;
10805}
10806
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010807#if ENABLE_ASH_BASH_COMPAT
10808static int decode_dollar_squote(void)
10809{
10810 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10811 int c, cnt;
10812 char *p;
10813 char buf[4];
10814
10815 c = pgetc();
10816 p = strchr(C_escapes, c);
10817 if (p) {
10818 buf[0] = c;
10819 p = buf;
10820 cnt = 3;
10821 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10822 do {
10823 c = pgetc();
10824 *++p = c;
10825 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10826 pungetc();
10827 } else if (c == 'x') { /* \xHH */
10828 do {
10829 c = pgetc();
10830 *++p = c;
10831 } while (isxdigit(c) && --cnt);
10832 pungetc();
10833 if (cnt == 3) { /* \x but next char is "bad" */
10834 c = 'x';
10835 goto unrecognized;
10836 }
10837 } else { /* simple seq like \\ or \t */
10838 p++;
10839 }
10840 *p = '\0';
10841 p = buf;
10842 c = bb_process_escape_sequence((void*)&p);
10843 } else { /* unrecognized "\z": print both chars unless ' or " */
10844 if (c != '\'' && c != '"') {
10845 unrecognized:
10846 c |= 0x100; /* "please encode \, then me" */
10847 }
10848 }
10849 return c;
10850}
10851#endif
10852
Eric Andersencb57d552001-06-28 07:25:16 +000010853/*
10854 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10855 * is not NULL, read a here document. In the latter case, eofmark is the
10856 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010857 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010858 * is the first character of the input token or document.
10859 *
10860 * Because C does not have internal subroutines, I have simulated them
10861 * using goto's to implement the subroutine linkage. The following macros
10862 * will run code that appears at the end of readtoken1.
10863 */
Eric Andersen2870d962001-07-02 17:27:21 +000010864#define CHECKEND() {goto checkend; checkend_return:;}
10865#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10866#define PARSESUB() {goto parsesub; parsesub_return:;}
10867#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10868#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10869#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010870static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010871readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010872{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010873 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010874 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010875 char *out;
10876 int len;
10877 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010878 struct nodelist *bqlist;
10879 smallint quotef;
10880 smallint dblquote;
10881 smallint oldstyle;
10882 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010883#if ENABLE_ASH_EXPAND_PRMT
10884 smallint pssyntax; /* we are expanding a prompt string */
10885#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010886 int varnest; /* levels of variables expansion */
10887 int arinest; /* levels of arithmetic expansion */
10888 int parenlevel; /* levels of parens in arithmetic */
10889 int dqvarnest; /* levels of variables expansion within double quotes */
10890
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010891 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010892
Eric Andersencb57d552001-06-28 07:25:16 +000010893#if __GNUC__
10894 /* Avoid longjmp clobbering */
10895 (void) &out;
10896 (void) &quotef;
10897 (void) &dblquote;
10898 (void) &varnest;
10899 (void) &arinest;
10900 (void) &parenlevel;
10901 (void) &dqvarnest;
10902 (void) &oldstyle;
10903 (void) &prevsyntax;
10904 (void) &syntax;
10905#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010906 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010907 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010908 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010909 oldstyle = 0;
10910 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010911#if ENABLE_ASH_EXPAND_PRMT
10912 pssyntax = (syntax == PSSYNTAX);
10913 if (pssyntax)
10914 syntax = DQSYNTAX;
10915#endif
10916 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010917 varnest = 0;
10918 arinest = 0;
10919 parenlevel = 0;
10920 dqvarnest = 0;
10921
10922 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010923 loop:
10924 /* For each line, until end of word */
10925 {
Eric Andersenc470f442003-07-28 09:56:35 +000010926 CHECKEND(); /* set c to PEOF if at end of here document */
10927 for (;;) { /* until end of line or end of word */
10928 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010929 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010930 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010931 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010932 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010933 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010934 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010935 if (doprompt)
10936 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010937 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010938 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010939 case CWORD:
10940 USTPUTC(c, out);
10941 break;
10942 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010943 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010944 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010945#if ENABLE_ASH_BASH_COMPAT
10946 if (c == '\\' && bash_dollar_squote) {
10947 c = decode_dollar_squote();
10948 if (c & 0x100) {
10949 USTPUTC('\\', out);
10950 c = (unsigned char)c;
10951 }
10952 }
10953#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010954 USTPUTC(c, out);
10955 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010956 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010957 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010958 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010959 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010960 USTPUTC('\\', out);
10961 pungetc();
10962 } else if (c == '\n') {
10963 if (doprompt)
10964 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010965 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010966#if ENABLE_ASH_EXPAND_PRMT
10967 if (c == '$' && pssyntax) {
10968 USTPUTC(CTLESC, out);
10969 USTPUTC('\\', out);
10970 }
10971#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010972 if (dblquote && c != '\\'
10973 && c != '`' && c != '$'
10974 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010975 ) {
10976 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010977 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010978 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010979 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010980 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010981 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010982 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010983 }
10984 break;
10985 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010986 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010987 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010988 if (eofmark == NULL) {
10989 USTPUTC(CTLQUOTEMARK, out);
10990 }
Eric Andersencb57d552001-06-28 07:25:16 +000010991 break;
10992 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010993 syntax = DQSYNTAX;
10994 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010995 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010996 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010997 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010998 if (eofmark != NULL && arinest == 0
10999 && varnest == 0
11000 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011001 USTPUTC(c, out);
11002 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011003 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011004 syntax = BASESYNTAX;
11005 dblquote = 0;
11006 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011007 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011008 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011009 }
11010 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011011 case CVAR: /* '$' */
11012 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011013 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011014 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011015 if (varnest > 0) {
11016 varnest--;
11017 if (dqvarnest > 0) {
11018 dqvarnest--;
11019 }
11020 USTPUTC(CTLENDVAR, out);
11021 } else {
11022 USTPUTC(c, out);
11023 }
11024 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011025#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011026 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011027 parenlevel++;
11028 USTPUTC(c, out);
11029 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011030 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011031 if (parenlevel > 0) {
11032 USTPUTC(c, out);
11033 --parenlevel;
11034 } else {
11035 if (pgetc() == ')') {
11036 if (--arinest == 0) {
11037 USTPUTC(CTLENDARI, out);
11038 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011039 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011040 } else
11041 USTPUTC(')', out);
11042 } else {
11043 /*
11044 * unbalanced parens
11045 * (don't 2nd guess - no error)
11046 */
11047 pungetc();
11048 USTPUTC(')', out);
11049 }
11050 }
11051 break;
11052#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011053 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011054 PARSEBACKQOLD();
11055 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011056 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011057 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011058 case CIGN:
11059 break;
11060 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011061 if (varnest == 0) {
11062#if ENABLE_ASH_BASH_COMPAT
11063 if (c == '&') {
11064 if (pgetc() == '>')
11065 c = 0x100 + '>'; /* flag &> */
11066 pungetc();
11067 }
11068#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011069 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011070 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011071 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011072 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011073
Eric Andersencb57d552001-06-28 07:25:16 +000011074 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011075 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011076 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011077 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011078 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011079#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011080 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011081 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011082#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011083 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011084 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011085 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011086 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011087 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011088 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011089 }
11090 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011091 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011092 out = stackblock();
11093 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011094 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011095 && quotef == 0
11096 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011097 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011098 PARSEREDIR(); /* passed as params: out, c */
11099 lasttoken = TREDIR;
11100 return lasttoken;
11101 }
11102 /* else: non-number X seen, interpret it
11103 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011104 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011105 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011106 }
11107 quoteflag = quotef;
11108 backquotelist = bqlist;
11109 grabstackblock(len);
11110 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011111 lasttoken = TWORD;
11112 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011113/* end of readtoken routine */
11114
Eric Andersencb57d552001-06-28 07:25:16 +000011115/*
11116 * Check to see whether we are at the end of the here document. When this
11117 * is called, c is set to the first character of the next input line. If
11118 * we are at the end of the here document, this routine sets the c to PEOF.
11119 */
Eric Andersenc470f442003-07-28 09:56:35 +000011120checkend: {
11121 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011122#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011123 if (c == PEOA)
11124 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011125#endif
11126 if (striptabs) {
11127 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011128 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011129 }
Eric Andersenc470f442003-07-28 09:56:35 +000011130 }
11131 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011132 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011133 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011134
Eric Andersenc470f442003-07-28 09:56:35 +000011135 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011136 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11137 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011138 if (*p == '\n' && *q == '\0') {
11139 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011140 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011141 needprompt = doprompt;
11142 } else {
11143 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011144 }
11145 }
11146 }
11147 }
Eric Andersenc470f442003-07-28 09:56:35 +000011148 goto checkend_return;
11149}
Eric Andersencb57d552001-06-28 07:25:16 +000011150
Eric Andersencb57d552001-06-28 07:25:16 +000011151/*
11152 * Parse a redirection operator. The variable "out" points to a string
11153 * specifying the fd to be redirected. The variable "c" contains the
11154 * first character of the redirection operator.
11155 */
Eric Andersenc470f442003-07-28 09:56:35 +000011156parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011157 /* out is already checked to be a valid number or "" */
11158 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011159 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011160
Denis Vlasenko597906c2008-02-20 16:38:54 +000011161 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011162 if (c == '>') {
11163 np->nfile.fd = 1;
11164 c = pgetc();
11165 if (c == '>')
11166 np->type = NAPPEND;
11167 else if (c == '|')
11168 np->type = NCLOBBER;
11169 else if (c == '&')
11170 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011171 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011172 else {
11173 np->type = NTO;
11174 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011175 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011176 }
11177#if ENABLE_ASH_BASH_COMPAT
11178 else if (c == 0x100 + '>') { /* this flags &> redirection */
11179 np->nfile.fd = 1;
11180 pgetc(); /* this is '>', no need to check */
11181 np->type = NTO2;
11182 }
11183#endif
11184 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011185 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011186 c = pgetc();
11187 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011188 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011189 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011190 np = stzalloc(sizeof(struct nhere));
11191 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011192 }
11193 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011194 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011195 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011196 c = pgetc();
11197 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011198 heredoc->striptabs = 1;
11199 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011200 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011201 pungetc();
11202 }
11203 break;
11204
11205 case '&':
11206 np->type = NFROMFD;
11207 break;
11208
11209 case '>':
11210 np->type = NFROMTO;
11211 break;
11212
11213 default:
11214 np->type = NFROM;
11215 pungetc();
11216 break;
11217 }
Eric Andersencb57d552001-06-28 07:25:16 +000011218 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011219 if (fd >= 0)
11220 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011221 redirnode = np;
11222 goto parseredir_return;
11223}
Eric Andersencb57d552001-06-28 07:25:16 +000011224
Eric Andersencb57d552001-06-28 07:25:16 +000011225/*
11226 * Parse a substitution. At this point, we have read the dollar sign
11227 * and nothing else.
11228 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011229
11230/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11231 * (assuming ascii char codes, as the original implementation did) */
11232#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011233 (((unsigned)(c) - 33 < 32) \
11234 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011235parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011236 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011237 int typeloc;
11238 int flags;
11239 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011240 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011241
Eric Andersenc470f442003-07-28 09:56:35 +000011242 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011243 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011244 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011245 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011246#if ENABLE_ASH_BASH_COMPAT
11247 if (c == '\'')
11248 bash_dollar_squote = 1;
11249 else
11250#endif
11251 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011252 pungetc();
11253 } else if (c == '(') { /* $(command) or $((arith)) */
11254 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011255#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011256 PARSEARITH();
11257#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011258 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011259#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011260 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011261 pungetc();
11262 PARSEBACKQNEW();
11263 }
11264 } else {
11265 USTPUTC(CTLVAR, out);
11266 typeloc = out - (char *)stackblock();
11267 USTPUTC(VSNORMAL, out);
11268 subtype = VSNORMAL;
11269 if (c == '{') {
11270 c = pgetc();
11271 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011272 c = pgetc();
11273 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011274 c = '#';
11275 else
11276 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011277 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011278 subtype = 0;
11279 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011280 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011281 do {
11282 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011283 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011284 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011285 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011286 do {
11287 STPUTC(c, out);
11288 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011289 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011290 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011291 USTPUTC(c, out);
11292 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011293 } else {
11294 badsub:
11295 raise_error_syntax("bad substitution");
11296 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011297 if (c != '}' && subtype == VSLENGTH)
11298 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011299
Eric Andersenc470f442003-07-28 09:56:35 +000011300 STPUTC('=', out);
11301 flags = 0;
11302 if (subtype == 0) {
11303 switch (c) {
11304 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011305 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011306#if ENABLE_ASH_BASH_COMPAT
11307 if (c == ':' || c == '$' || isdigit(c)) {
11308 pungetc();
11309 subtype = VSSUBSTR;
11310 break;
11311 }
11312#endif
11313 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011314 /*FALLTHROUGH*/
11315 default:
11316 p = strchr(types, c);
11317 if (p == NULL)
11318 goto badsub;
11319 subtype = p - types + VSNORMAL;
11320 break;
11321 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011322 case '#': {
11323 int cc = c;
11324 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11325 c = pgetc();
11326 if (c == cc)
11327 subtype++;
11328 else
11329 pungetc();
11330 break;
11331 }
11332#if ENABLE_ASH_BASH_COMPAT
11333 case '/':
11334 subtype = VSREPLACE;
11335 c = pgetc();
11336 if (c == '/')
11337 subtype++; /* VSREPLACEALL */
11338 else
11339 pungetc();
11340 break;
11341#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011342 }
Eric Andersenc470f442003-07-28 09:56:35 +000011343 } else {
11344 pungetc();
11345 }
11346 if (dblquote || arinest)
11347 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011348 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011349 if (subtype != VSNORMAL) {
11350 varnest++;
11351 if (dblquote || arinest) {
11352 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011353 }
11354 }
11355 }
Eric Andersenc470f442003-07-28 09:56:35 +000011356 goto parsesub_return;
11357}
Eric Andersencb57d552001-06-28 07:25:16 +000011358
Eric Andersencb57d552001-06-28 07:25:16 +000011359/*
11360 * Called to parse command substitutions. Newstyle is set if the command
11361 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11362 * list of commands (passed by reference), and savelen is the number of
11363 * characters on the top of the stack which must be preserved.
11364 */
Eric Andersenc470f442003-07-28 09:56:35 +000011365parsebackq: {
11366 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011367 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011368 union node *n;
11369 char *volatile str;
11370 struct jmploc jmploc;
11371 struct jmploc *volatile savehandler;
11372 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011373 smallint saveprompt = 0;
11374
Eric Andersencb57d552001-06-28 07:25:16 +000011375#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011376 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011377#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011378 savepbq = parsebackquote;
11379 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011380 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011381 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011382 exception_handler = savehandler;
11383 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011384 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011385 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011386 str = NULL;
11387 savelen = out - (char *)stackblock();
11388 if (savelen > 0) {
11389 str = ckmalloc(savelen);
11390 memcpy(str, stackblock(), savelen);
11391 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011392 savehandler = exception_handler;
11393 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011394 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011395 if (oldstyle) {
11396 /* We must read until the closing backquote, giving special
11397 treatment to some slashes, and then push the string and
11398 reread it as input, interpreting it normally. */
11399 char *pout;
11400 int pc;
11401 size_t psavelen;
11402 char *pstr;
11403
11404
11405 STARTSTACKSTR(pout);
11406 for (;;) {
11407 if (needprompt) {
11408 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011409 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011410 pc = pgetc();
11411 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011412 case '`':
11413 goto done;
11414
11415 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011416 pc = pgetc();
11417 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011418 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011419 if (doprompt)
11420 setprompt(2);
11421 /*
11422 * If eating a newline, avoid putting
11423 * the newline into the new character
11424 * stream (via the STPUTC after the
11425 * switch).
11426 */
11427 continue;
11428 }
11429 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011430 && (!dblquote || pc != '"')
11431 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011432 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011433 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011434 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011435 break;
11436 }
11437 /* fall through */
11438
11439 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011440 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011441 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011442 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011443
11444 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011445 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011446 needprompt = doprompt;
11447 break;
11448
11449 default:
11450 break;
11451 }
11452 STPUTC(pc, pout);
11453 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011454 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011455 STPUTC('\0', pout);
11456 psavelen = pout - (char *)stackblock();
11457 if (psavelen > 0) {
11458 pstr = grabstackstr(pout);
11459 setinputstring(pstr);
11460 }
11461 }
11462 nlpp = &bqlist;
11463 while (*nlpp)
11464 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011465 *nlpp = stzalloc(sizeof(**nlpp));
11466 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011467 parsebackquote = oldstyle;
11468
11469 if (oldstyle) {
11470 saveprompt = doprompt;
11471 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011472 }
11473
Eric Andersenc470f442003-07-28 09:56:35 +000011474 n = list(2);
11475
11476 if (oldstyle)
11477 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011478 else if (readtoken() != TRP)
11479 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011480
11481 (*nlpp)->n = n;
11482 if (oldstyle) {
11483 /*
11484 * Start reading from old file again, ignoring any pushed back
11485 * tokens left from the backquote parsing
11486 */
11487 popfile();
11488 tokpushback = 0;
11489 }
11490 while (stackblocksize() <= savelen)
11491 growstackblock();
11492 STARTSTACKSTR(out);
11493 if (str) {
11494 memcpy(out, str, savelen);
11495 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011496 INT_OFF;
11497 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011498 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011499 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011500 }
11501 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011502 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011503 if (arinest || dblquote)
11504 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11505 else
11506 USTPUTC(CTLBACKQ, out);
11507 if (oldstyle)
11508 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011509 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011510}
11511
Mike Frysinger98c52642009-04-02 10:02:37 +000011512#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011513/*
11514 * Parse an arithmetic expansion (indicate start of one and set state)
11515 */
Eric Andersenc470f442003-07-28 09:56:35 +000011516parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011517 if (++arinest == 1) {
11518 prevsyntax = syntax;
11519 syntax = ARISYNTAX;
11520 USTPUTC(CTLARI, out);
11521 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011522 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011523 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011524 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011525 } else {
11526 /*
11527 * we collapse embedded arithmetic expansion to
11528 * parenthesis, which should be equivalent
11529 */
11530 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011531 }
Eric Andersenc470f442003-07-28 09:56:35 +000011532 goto parsearith_return;
11533}
11534#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011535
Eric Andersenc470f442003-07-28 09:56:35 +000011536} /* end of readtoken */
11537
Eric Andersencb57d552001-06-28 07:25:16 +000011538/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011539 * Read the next input token.
11540 * If the token is a word, we set backquotelist to the list of cmds in
11541 * backquotes. We set quoteflag to true if any part of the word was
11542 * quoted.
11543 * If the token is TREDIR, then we set redirnode to a structure containing
11544 * the redirection.
11545 * In all cases, the variable startlinno is set to the number of the line
11546 * on which the token starts.
11547 *
11548 * [Change comment: here documents and internal procedures]
11549 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11550 * word parsing code into a separate routine. In this case, readtoken
11551 * doesn't need to have any internal procedures, but parseword does.
11552 * We could also make parseoperator in essence the main routine, and
11553 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011554 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011555#define NEW_xxreadtoken
11556#ifdef NEW_xxreadtoken
11557/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011558static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011559 '\n', '(', ')', /* singles */
11560 '&', '|', ';', /* doubles */
11561 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011562};
Eric Andersencb57d552001-06-28 07:25:16 +000011563
Denis Vlasenko834dee72008-10-07 09:18:30 +000011564#define xxreadtoken_singles 3
11565#define xxreadtoken_doubles 3
11566
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011567static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011568 TNL, TLP, TRP, /* only single occurrence allowed */
11569 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11570 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011571 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011572};
11573
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011574static int
11575xxreadtoken(void)
11576{
11577 int c;
11578
11579 if (tokpushback) {
11580 tokpushback = 0;
11581 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011582 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011583 if (needprompt) {
11584 setprompt(2);
11585 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011586 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011587 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011588 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011589 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011590 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011592 if (c == '#') {
11593 while ((c = pgetc()) != '\n' && c != PEOF)
11594 continue;
11595 pungetc();
11596 } else if (c == '\\') {
11597 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011598 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011599 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011600 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011601 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011602 if (doprompt)
11603 setprompt(2);
11604 } else {
11605 const char *p;
11606
11607 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11608 if (c != PEOF) {
11609 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011610 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011611 needprompt = doprompt;
11612 }
11613
11614 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011615 if (p == NULL)
11616 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011617
Denis Vlasenko834dee72008-10-07 09:18:30 +000011618 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11619 int cc = pgetc();
11620 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011621 p += xxreadtoken_doubles + 1;
11622 } else {
11623 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011624#if ENABLE_ASH_BASH_COMPAT
11625 if (c == '&' && cc == '>') /* &> */
11626 break; /* return readtoken1(...) */
11627#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011628 }
11629 }
11630 }
11631 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11632 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011633 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011634 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011635
11636 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011637}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011638#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011639#define RETURN(token) return lasttoken = token
11640static int
11641xxreadtoken(void)
11642{
11643 int c;
11644
11645 if (tokpushback) {
11646 tokpushback = 0;
11647 return lasttoken;
11648 }
11649 if (needprompt) {
11650 setprompt(2);
11651 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011652 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011653 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011654 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011655 switch (c) {
11656 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011657 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011658 continue;
11659 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011660 while ((c = pgetc()) != '\n' && c != PEOF)
11661 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011662 pungetc();
11663 continue;
11664 case '\\':
11665 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011666 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011667 if (doprompt)
11668 setprompt(2);
11669 continue;
11670 }
11671 pungetc();
11672 goto breakloop;
11673 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011674 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011675 needprompt = doprompt;
11676 RETURN(TNL);
11677 case PEOF:
11678 RETURN(TEOF);
11679 case '&':
11680 if (pgetc() == '&')
11681 RETURN(TAND);
11682 pungetc();
11683 RETURN(TBACKGND);
11684 case '|':
11685 if (pgetc() == '|')
11686 RETURN(TOR);
11687 pungetc();
11688 RETURN(TPIPE);
11689 case ';':
11690 if (pgetc() == ';')
11691 RETURN(TENDCASE);
11692 pungetc();
11693 RETURN(TSEMI);
11694 case '(':
11695 RETURN(TLP);
11696 case ')':
11697 RETURN(TRP);
11698 default:
11699 goto breakloop;
11700 }
11701 }
11702 breakloop:
11703 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11704#undef RETURN
11705}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011706#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011707
11708static int
11709readtoken(void)
11710{
11711 int t;
11712#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011713 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011714#endif
11715
11716#if ENABLE_ASH_ALIAS
11717 top:
11718#endif
11719
11720 t = xxreadtoken();
11721
11722 /*
11723 * eat newlines
11724 */
11725 if (checkkwd & CHKNL) {
11726 while (t == TNL) {
11727 parseheredoc();
11728 t = xxreadtoken();
11729 }
11730 }
11731
11732 if (t != TWORD || quoteflag) {
11733 goto out;
11734 }
11735
11736 /*
11737 * check for keywords
11738 */
11739 if (checkkwd & CHKKWD) {
11740 const char *const *pp;
11741
11742 pp = findkwd(wordtext);
11743 if (pp) {
11744 lasttoken = t = pp - tokname_array;
11745 TRACE(("keyword %s recognized\n", tokname(t)));
11746 goto out;
11747 }
11748 }
11749
11750 if (checkkwd & CHKALIAS) {
11751#if ENABLE_ASH_ALIAS
11752 struct alias *ap;
11753 ap = lookupalias(wordtext, 1);
11754 if (ap != NULL) {
11755 if (*ap->val) {
11756 pushstring(ap->val, ap);
11757 }
11758 goto top;
11759 }
11760#endif
11761 }
11762 out:
11763 checkkwd = 0;
11764#if DEBUG
11765 if (!alreadyseen)
11766 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11767 else
11768 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11769#endif
11770 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011771}
11772
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773static char
11774peektoken(void)
11775{
11776 int t;
11777
11778 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011779 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011780 return tokname_array[t][0];
11781}
Eric Andersencb57d552001-06-28 07:25:16 +000011782
11783/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011784 * Read and parse a command. Returns NODE_EOF on end of file.
11785 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011786 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011787static union node *
11788parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011789{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011790 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011791
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011792 tokpushback = 0;
11793 doprompt = interact;
11794 if (doprompt)
11795 setprompt(doprompt);
11796 needprompt = 0;
11797 t = readtoken();
11798 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011799 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011800 if (t == TNL)
11801 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011802 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011803 return list(1);
11804}
11805
11806/*
11807 * Input any here documents.
11808 */
11809static void
11810parseheredoc(void)
11811{
11812 struct heredoc *here;
11813 union node *n;
11814
11815 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011816 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011817
11818 while (here) {
11819 if (needprompt) {
11820 setprompt(2);
11821 }
11822 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11823 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011824 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011825 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011826 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011827 n->narg.text = wordtext;
11828 n->narg.backquote = backquotelist;
11829 here->here->nhere.doc = n;
11830 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011831 }
Eric Andersencb57d552001-06-28 07:25:16 +000011832}
11833
11834
11835/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011836 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011837 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011838#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011839static const char *
11840expandstr(const char *ps)
11841{
11842 union node n;
11843
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011844 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11845 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011846 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011847 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011848 popfile();
11849
11850 n.narg.type = NARG;
11851 n.narg.next = NULL;
11852 n.narg.text = wordtext;
11853 n.narg.backquote = backquotelist;
11854
11855 expandarg(&n, NULL, 0);
11856 return stackblock();
11857}
11858#endif
11859
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011860/*
11861 * Execute a command or commands contained in a string.
11862 */
11863static int
11864evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011865{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011866 union node *n;
11867 struct stackmark smark;
11868 int skip;
11869
11870 setinputstring(s);
11871 setstackmark(&smark);
11872
11873 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011874 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011875 evaltree(n, 0);
11876 popstackmark(&smark);
11877 skip = evalskip;
11878 if (skip)
11879 break;
11880 }
11881 popfile();
11882
11883 skip &= mask;
11884 evalskip = skip;
11885 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011886}
11887
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011888/*
11889 * The eval command.
11890 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011891static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011892evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011893{
11894 char *p;
11895 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011896
Denis Vlasenko68404f12008-03-17 09:00:54 +000011897 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011898 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011899 argv += 2;
11900 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011901 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011902 for (;;) {
11903 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011904 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011905 if (p == NULL)
11906 break;
11907 STPUTC(' ', concat);
11908 }
11909 STPUTC('\0', concat);
11910 p = grabstackstr(concat);
11911 }
11912 evalstring(p, ~SKIPEVAL);
11913
11914 }
11915 return exitstatus;
11916}
11917
11918/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011919 * Read and execute commands.
11920 * "Top" is nonzero for the top level command loop;
11921 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011922 */
11923static int
11924cmdloop(int top)
11925{
11926 union node *n;
11927 struct stackmark smark;
11928 int inter;
11929 int numeof = 0;
11930
11931 TRACE(("cmdloop(%d) called\n", top));
11932 for (;;) {
11933 int skip;
11934
11935 setstackmark(&smark);
11936#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011937 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011938 showjobs(stderr, SHOW_CHANGED);
11939#endif
11940 inter = 0;
11941 if (iflag && top) {
11942 inter++;
11943#if ENABLE_ASH_MAIL
11944 chkmail();
11945#endif
11946 }
11947 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011948#if DEBUG
11949 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011950 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011951#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011952 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011953 if (!top || numeof >= 50)
11954 break;
11955 if (!stoppedjobs()) {
11956 if (!Iflag)
11957 break;
11958 out2str("\nUse \"exit\" to leave shell.\n");
11959 }
11960 numeof++;
11961 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011962 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11963 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011964 numeof = 0;
11965 evaltree(n, 0);
11966 }
11967 popstackmark(&smark);
11968 skip = evalskip;
11969
11970 if (skip) {
11971 evalskip = 0;
11972 return skip & SKIPEVAL;
11973 }
11974 }
11975 return 0;
11976}
11977
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011978/*
11979 * Take commands from a file. To be compatible we should do a path
11980 * search for the file, which is necessary to find sub-commands.
11981 */
11982static char *
11983find_dot_file(char *name)
11984{
11985 char *fullname;
11986 const char *path = pathval();
11987 struct stat statb;
11988
11989 /* don't try this for absolute or relative paths */
11990 if (strchr(name, '/'))
11991 return name;
11992
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011993 /* IIRC standards do not say whether . is to be searched.
11994 * And it is even smaller this way, making it unconditional for now:
11995 */
11996 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11997 fullname = name;
11998 goto try_cur_dir;
11999 }
12000
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012001 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012002 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012003 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12004 /*
12005 * Don't bother freeing here, since it will
12006 * be freed by the caller.
12007 */
12008 return fullname;
12009 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012010 if (fullname != name)
12011 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012012 }
12013
12014 /* not found in the PATH */
12015 ash_msg_and_raise_error("%s: not found", name);
12016 /* NOTREACHED */
12017}
12018
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012019static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012020dotcmd(int argc, char **argv)
12021{
12022 struct strlist *sp;
12023 volatile struct shparam saveparam;
12024 int status = 0;
12025
12026 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012027 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012028
Denis Vlasenko68404f12008-03-17 09:00:54 +000012029 if (argv[1]) { /* That's what SVR2 does */
12030 char *fullname = find_dot_file(argv[1]);
12031 argv += 2;
12032 argc -= 2;
12033 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012034 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012035 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012036 shellparam.nparam = argc;
12037 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038 };
12039
12040 setinputfile(fullname, INPUT_PUSH_FILE);
12041 commandname = fullname;
12042 cmdloop(0);
12043 popfile();
12044
Denis Vlasenko68404f12008-03-17 09:00:54 +000012045 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046 freeparam(&shellparam);
12047 shellparam = saveparam;
12048 };
12049 status = exitstatus;
12050 }
12051 return status;
12052}
12053
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012054static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012055exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012056{
12057 if (stoppedjobs())
12058 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012059 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012060 exitstatus = number(argv[1]);
12061 raise_exception(EXEXIT);
12062 /* NOTREACHED */
12063}
12064
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012065/*
12066 * Read a file containing shell functions.
12067 */
12068static void
12069readcmdfile(char *name)
12070{
12071 setinputfile(name, INPUT_PUSH_FILE);
12072 cmdloop(0);
12073 popfile();
12074}
12075
12076
Denis Vlasenkocc571512007-02-23 21:10:35 +000012077/* ============ find_command inplementation */
12078
12079/*
12080 * Resolve a command name. If you change this routine, you may have to
12081 * change the shellexec routine as well.
12082 */
12083static void
12084find_command(char *name, struct cmdentry *entry, int act, const char *path)
12085{
12086 struct tblentry *cmdp;
12087 int idx;
12088 int prev;
12089 char *fullname;
12090 struct stat statb;
12091 int e;
12092 int updatetbl;
12093 struct builtincmd *bcmd;
12094
12095 /* If name contains a slash, don't use PATH or hash table */
12096 if (strchr(name, '/') != NULL) {
12097 entry->u.index = -1;
12098 if (act & DO_ABS) {
12099 while (stat(name, &statb) < 0) {
12100#ifdef SYSV
12101 if (errno == EINTR)
12102 continue;
12103#endif
12104 entry->cmdtype = CMDUNKNOWN;
12105 return;
12106 }
12107 }
12108 entry->cmdtype = CMDNORMAL;
12109 return;
12110 }
12111
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012112/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012113
12114 updatetbl = (path == pathval());
12115 if (!updatetbl) {
12116 act |= DO_ALTPATH;
12117 if (strstr(path, "%builtin") != NULL)
12118 act |= DO_ALTBLTIN;
12119 }
12120
12121 /* If name is in the table, check answer will be ok */
12122 cmdp = cmdlookup(name, 0);
12123 if (cmdp != NULL) {
12124 int bit;
12125
12126 switch (cmdp->cmdtype) {
12127 default:
12128#if DEBUG
12129 abort();
12130#endif
12131 case CMDNORMAL:
12132 bit = DO_ALTPATH;
12133 break;
12134 case CMDFUNCTION:
12135 bit = DO_NOFUNC;
12136 break;
12137 case CMDBUILTIN:
12138 bit = DO_ALTBLTIN;
12139 break;
12140 }
12141 if (act & bit) {
12142 updatetbl = 0;
12143 cmdp = NULL;
12144 } else if (cmdp->rehash == 0)
12145 /* if not invalidated by cd, we're done */
12146 goto success;
12147 }
12148
12149 /* If %builtin not in path, check for builtin next */
12150 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012151 if (bcmd) {
12152 if (IS_BUILTIN_REGULAR(bcmd))
12153 goto builtin_success;
12154 if (act & DO_ALTPATH) {
12155 if (!(act & DO_ALTBLTIN))
12156 goto builtin_success;
12157 } else if (builtinloc <= 0) {
12158 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012159 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012160 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012161
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012162#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012163 {
12164 int applet_no = find_applet_by_name(name);
12165 if (applet_no >= 0) {
12166 entry->cmdtype = CMDNORMAL;
12167 entry->u.index = -2 - applet_no;
12168 return;
12169 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012170 }
12171#endif
12172
Denis Vlasenkocc571512007-02-23 21:10:35 +000012173 /* We have to search path. */
12174 prev = -1; /* where to start */
12175 if (cmdp && cmdp->rehash) { /* doing a rehash */
12176 if (cmdp->cmdtype == CMDBUILTIN)
12177 prev = builtinloc;
12178 else
12179 prev = cmdp->param.index;
12180 }
12181
12182 e = ENOENT;
12183 idx = -1;
12184 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012185 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012186 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012187 /* NB: code below will still use fullname
12188 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012189 idx++;
12190 if (pathopt) {
12191 if (prefix(pathopt, "builtin")) {
12192 if (bcmd)
12193 goto builtin_success;
12194 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012195 }
12196 if ((act & DO_NOFUNC)
12197 || !prefix(pathopt, "func")
12198 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012199 continue;
12200 }
12201 }
12202 /* if rehash, don't redo absolute path names */
12203 if (fullname[0] == '/' && idx <= prev) {
12204 if (idx < prev)
12205 continue;
12206 TRACE(("searchexec \"%s\": no change\n", name));
12207 goto success;
12208 }
12209 while (stat(fullname, &statb) < 0) {
12210#ifdef SYSV
12211 if (errno == EINTR)
12212 continue;
12213#endif
12214 if (errno != ENOENT && errno != ENOTDIR)
12215 e = errno;
12216 goto loop;
12217 }
12218 e = EACCES; /* if we fail, this will be the error */
12219 if (!S_ISREG(statb.st_mode))
12220 continue;
12221 if (pathopt) { /* this is a %func directory */
12222 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012223 /* NB: stalloc will return space pointed by fullname
12224 * (because we don't have any intervening allocations
12225 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012226 readcmdfile(fullname);
12227 cmdp = cmdlookup(name, 0);
12228 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12229 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12230 stunalloc(fullname);
12231 goto success;
12232 }
12233 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12234 if (!updatetbl) {
12235 entry->cmdtype = CMDNORMAL;
12236 entry->u.index = idx;
12237 return;
12238 }
12239 INT_OFF;
12240 cmdp = cmdlookup(name, 1);
12241 cmdp->cmdtype = CMDNORMAL;
12242 cmdp->param.index = idx;
12243 INT_ON;
12244 goto success;
12245 }
12246
12247 /* We failed. If there was an entry for this command, delete it */
12248 if (cmdp && updatetbl)
12249 delete_cmd_entry();
12250 if (act & DO_ERR)
12251 ash_msg("%s: %s", name, errmsg(e, "not found"));
12252 entry->cmdtype = CMDUNKNOWN;
12253 return;
12254
12255 builtin_success:
12256 if (!updatetbl) {
12257 entry->cmdtype = CMDBUILTIN;
12258 entry->u.cmd = bcmd;
12259 return;
12260 }
12261 INT_OFF;
12262 cmdp = cmdlookup(name, 1);
12263 cmdp->cmdtype = CMDBUILTIN;
12264 cmdp->param.cmd = bcmd;
12265 INT_ON;
12266 success:
12267 cmdp->rehash = 0;
12268 entry->cmdtype = cmdp->cmdtype;
12269 entry->u = cmdp->param;
12270}
12271
12272
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012273/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012274
Eric Andersencb57d552001-06-28 07:25:16 +000012275/*
Eric Andersencb57d552001-06-28 07:25:16 +000012276 * The trap builtin.
12277 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012278static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012279trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012280{
12281 char *action;
12282 char **ap;
12283 int signo;
12284
Eric Andersenc470f442003-07-28 09:56:35 +000012285 nextopt(nullstr);
12286 ap = argptr;
12287 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012288 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012289 char *tr = trap_ptr[signo];
12290 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012291 /* note: bash adds "SIG", but only if invoked
12292 * as "bash". If called as "sh", or if set -o posix,
12293 * then it prints short signal names.
12294 * We are printing short names: */
12295 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012296 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012297 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012298 /* trap_ptr != trap only if we are in special-cased `trap` code.
12299 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012300 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012301 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012302 }
12303 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012304 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012305 if (trap_ptr != trap) {
12306 free(trap_ptr);
12307 trap_ptr = trap;
12308 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012309 */
Eric Andersencb57d552001-06-28 07:25:16 +000012310 return 0;
12311 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012312
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012313 action = NULL;
12314 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012315 action = *ap++;
12316 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012317 signo = get_signum(*ap);
12318 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012319 ash_msg_and_raise_error("%s: bad trap", *ap);
12320 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012321 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012322 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012323 action = NULL;
12324 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012325 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012326 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012327 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012328 trap[signo] = action;
12329 if (signo != 0)
12330 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012331 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012332 ap++;
12333 }
12334 return 0;
12335}
12336
Eric Andersenc470f442003-07-28 09:56:35 +000012337
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012338/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012339
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012340#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012341/*
12342 * Lists available builtins
12343 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012344static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012345helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012346{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012347 unsigned col;
12348 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012349
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012350 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012351 "Built-in commands:\n"
12352 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012353 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012354 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012355 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012356 if (col > 60) {
12357 out1fmt("\n");
12358 col = 0;
12359 }
12360 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012361#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012362 {
12363 const char *a = applet_names;
12364 while (*a) {
12365 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12366 if (col > 60) {
12367 out1fmt("\n");
12368 col = 0;
12369 }
12370 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012371 }
12372 }
12373#endif
12374 out1fmt("\n\n");
12375 return EXIT_SUCCESS;
12376}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012377#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012378
Eric Andersencb57d552001-06-28 07:25:16 +000012379/*
Eric Andersencb57d552001-06-28 07:25:16 +000012380 * The export and readonly commands.
12381 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012382static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012383exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012384{
12385 struct var *vp;
12386 char *name;
12387 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012388 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012389 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012390
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012391 if (nextopt("p") != 'p') {
12392 aptr = argptr;
12393 name = *aptr;
12394 if (name) {
12395 do {
12396 p = strchr(name, '=');
12397 if (p != NULL) {
12398 p++;
12399 } else {
12400 vp = *findvar(hashvar(name), name);
12401 if (vp) {
12402 vp->flags |= flag;
12403 continue;
12404 }
Eric Andersencb57d552001-06-28 07:25:16 +000012405 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012406 setvar(name, p, flag);
12407 } while ((name = *++aptr) != NULL);
12408 return 0;
12409 }
Eric Andersencb57d552001-06-28 07:25:16 +000012410 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012411 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012412 return 0;
12413}
12414
Eric Andersencb57d552001-06-28 07:25:16 +000012415/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012416 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012417 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012418static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012419unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012420{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012421 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012422
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012423 cmdp = cmdlookup(name, 0);
12424 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12425 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012426}
12427
Eric Andersencb57d552001-06-28 07:25:16 +000012428/*
Eric Andersencb57d552001-06-28 07:25:16 +000012429 * The unset builtin command. We unset the function before we unset the
12430 * variable to allow a function to be unset when there is a readonly variable
12431 * with the same name.
12432 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012433static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012434unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012435{
12436 char **ap;
12437 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012438 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012439 int ret = 0;
12440
12441 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012442 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012443 }
Eric Andersencb57d552001-06-28 07:25:16 +000012444
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012445 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012446 if (flag != 'f') {
12447 i = unsetvar(*ap);
12448 ret |= i;
12449 if (!(i & 2))
12450 continue;
12451 }
12452 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012453 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012454 }
Eric Andersenc470f442003-07-28 09:56:35 +000012455 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012456}
12457
12458
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012459/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012460
Eric Andersenc470f442003-07-28 09:56:35 +000012461#include <sys/times.h>
12462
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012463static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012464 ' ', offsetof(struct tms, tms_utime),
12465 '\n', offsetof(struct tms, tms_stime),
12466 ' ', offsetof(struct tms, tms_cutime),
12467 '\n', offsetof(struct tms, tms_cstime),
12468 0
12469};
Eric Andersencb57d552001-06-28 07:25:16 +000012470
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012471static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012472timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012473{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012474 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012475 const unsigned char *p;
12476 struct tms buf;
12477
12478 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012479 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012480
12481 p = timescmd_str;
12482 do {
12483 t = *(clock_t *)(((char *) &buf) + p[1]);
12484 s = t / clk_tck;
12485 out1fmt("%ldm%ld.%.3lds%c",
12486 s/60, s%60,
12487 ((t - s * clk_tck) * 1000) / clk_tck,
12488 p[0]);
12489 } while (*(p += 2));
12490
Eric Andersencb57d552001-06-28 07:25:16 +000012491 return 0;
12492}
12493
Mike Frysinger98c52642009-04-02 10:02:37 +000012494#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012495/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012496 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12497 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012498 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012499 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012500 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012501static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012502letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012503{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012504 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012505
Denis Vlasenko68404f12008-03-17 09:00:54 +000012506 argv++;
12507 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012508 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012509 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012510 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012511 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012512
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012513 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012514}
Mike Frysinger98c52642009-04-02 10:02:37 +000012515#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012516
Eric Andersenc470f442003-07-28 09:56:35 +000012517
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012518/* ============ miscbltin.c
12519 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012520 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012521 */
12522
12523#undef rflag
12524
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012525#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012526typedef enum __rlimit_resource rlim_t;
12527#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012528
Eric Andersenc470f442003-07-28 09:56:35 +000012529/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012530 * The read builtin. Options:
12531 * -r Do not interpret '\' specially
12532 * -s Turn off echo (tty only)
12533 * -n NCHARS Read NCHARS max
12534 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12535 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12536 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012537 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012538 * TODO: bash also has:
12539 * -a ARRAY Read into array[0],[1],etc
12540 * -d DELIM End on DELIM char, not newline
12541 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012542 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012543static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012544readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012545{
Denys Vlasenko73067272010-01-12 22:11:24 +010012546 char *opt_n = NULL;
12547 char *opt_p = NULL;
12548 char *opt_t = NULL;
12549 char *opt_u = NULL;
12550 int read_flags = 0;
12551 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012552 int i;
12553
Denys Vlasenko73067272010-01-12 22:11:24 +010012554 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012555 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012556 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012557 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012558 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012559 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012560 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012561 break;
12562 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012563 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012564 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012565 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012566 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012567 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012568 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012569 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012570 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012572 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012573 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012574 default:
12575 break;
12576 }
Eric Andersenc470f442003-07-28 09:56:35 +000012577 }
Paul Fox02eb9342005-09-07 16:56:02 +000012578
Denys Vlasenko03dad222010-01-12 23:29:57 +010012579 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012580 argptr,
12581 bltinlookup("IFS"), /* can be NULL */
12582 read_flags,
12583 opt_n,
12584 opt_p,
12585 opt_t,
12586 opt_u
12587 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012588
Denys Vlasenko73067272010-01-12 22:11:24 +010012589 if ((uintptr_t)r > 1)
12590 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012591
Denys Vlasenko73067272010-01-12 22:11:24 +010012592 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012593}
12594
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012595static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012596umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012597{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012598 static const char permuser[3] ALIGN1 = "ugo";
12599 static const char permmode[3] ALIGN1 = "rwx";
12600 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012601 S_IRUSR, S_IWUSR, S_IXUSR,
12602 S_IRGRP, S_IWGRP, S_IXGRP,
12603 S_IROTH, S_IWOTH, S_IXOTH
12604 };
12605
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012606 /* TODO: use bb_parse_mode() instead */
12607
Eric Andersenc470f442003-07-28 09:56:35 +000012608 char *ap;
12609 mode_t mask;
12610 int i;
12611 int symbolic_mode = 0;
12612
12613 while (nextopt("S") != '\0') {
12614 symbolic_mode = 1;
12615 }
12616
Denis Vlasenkob012b102007-02-19 22:43:01 +000012617 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012618 mask = umask(0);
12619 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012620 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012621
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012622 ap = *argptr;
12623 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012624 if (symbolic_mode) {
12625 char buf[18];
12626 char *p = buf;
12627
12628 for (i = 0; i < 3; i++) {
12629 int j;
12630
12631 *p++ = permuser[i];
12632 *p++ = '=';
12633 for (j = 0; j < 3; j++) {
12634 if ((mask & permmask[3 * i + j]) == 0) {
12635 *p++ = permmode[j];
12636 }
12637 }
12638 *p++ = ',';
12639 }
12640 *--p = 0;
12641 puts(buf);
12642 } else {
12643 out1fmt("%.4o\n", mask);
12644 }
12645 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012646 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012647 mask = 0;
12648 do {
12649 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012650 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012651 mask = (mask << 3) + (*ap - '0');
12652 } while (*++ap != '\0');
12653 umask(mask);
12654 } else {
12655 mask = ~mask & 0777;
12656 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012657 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012658 }
12659 umask(~mask & 0777);
12660 }
12661 }
12662 return 0;
12663}
12664
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012665static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012666ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012667{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012668 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012669}
12670
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012671/* ============ main() and helpers */
12672
12673/*
12674 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012675 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012676static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012677static void
12678exitshell(void)
12679{
12680 struct jmploc loc;
12681 char *p;
12682 int status;
12683
12684 status = exitstatus;
12685 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12686 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012687 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012688/* dash bug: it just does _exit(exitstatus) here
12689 * but we have to do setjobctl(0) first!
12690 * (bug is still not fixed in dash-0.5.3 - if you run dash
12691 * under Midnight Commander, on exit from dash MC is backgrounded) */
12692 status = exitstatus;
12693 goto out;
12694 }
12695 exception_handler = &loc;
12696 p = trap[0];
12697 if (p) {
12698 trap[0] = NULL;
12699 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012700 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012701 }
12702 flush_stdout_stderr();
12703 out:
12704 setjobctl(0);
12705 _exit(status);
12706 /* NOTREACHED */
12707}
12708
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012709static void
12710init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012711{
12712 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012713 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012714
12715 /* from trap.c: */
12716 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012717 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12718 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12719 */
12720 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012721
12722 /* from var.c: */
12723 {
12724 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012725 const char *p;
12726 struct stat st1, st2;
12727
12728 initvar();
12729 for (envp = environ; envp && *envp; envp++) {
12730 if (strchr(*envp, '=')) {
12731 setvareq(*envp, VEXPORT|VTEXTFIXED);
12732 }
12733 }
12734
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012735 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012736
12737 p = lookupvar("PWD");
12738 if (p)
12739 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12740 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12741 p = '\0';
12742 setpwd(p, 0);
12743 }
12744}
12745
12746/*
12747 * Process the shell command line arguments.
12748 */
12749static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012750procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012751{
12752 int i;
12753 const char *xminusc;
12754 char **xargv;
12755
12756 xargv = argv;
12757 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012758 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012759 xargv++;
12760 for (i = 0; i < NOPTS; i++)
12761 optlist[i] = 2;
12762 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012763 if (options(1)) {
12764 /* it already printed err message */
12765 raise_exception(EXERROR);
12766 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012767 xargv = argptr;
12768 xminusc = minusc;
12769 if (*xargv == NULL) {
12770 if (xminusc)
12771 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12772 sflag = 1;
12773 }
12774 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12775 iflag = 1;
12776 if (mflag == 2)
12777 mflag = iflag;
12778 for (i = 0; i < NOPTS; i++)
12779 if (optlist[i] == 2)
12780 optlist[i] = 0;
12781#if DEBUG == 2
12782 debug = 1;
12783#endif
12784 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12785 if (xminusc) {
12786 minusc = *xargv++;
12787 if (*xargv)
12788 goto setarg0;
12789 } else if (!sflag) {
12790 setinputfile(*xargv, 0);
12791 setarg0:
12792 arg0 = *xargv++;
12793 commandname = arg0;
12794 }
12795
12796 shellparam.p = xargv;
12797#if ENABLE_ASH_GETOPTS
12798 shellparam.optind = 1;
12799 shellparam.optoff = -1;
12800#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012801 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012802 while (*xargv) {
12803 shellparam.nparam++;
12804 xargv++;
12805 }
12806 optschanged();
12807}
12808
12809/*
12810 * Read /etc/profile or .profile.
12811 */
12812static void
12813read_profile(const char *name)
12814{
12815 int skip;
12816
12817 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12818 return;
12819 skip = cmdloop(0);
12820 popfile();
12821 if (skip)
12822 exitshell();
12823}
12824
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012825/*
12826 * This routine is called when an error or an interrupt occurs in an
12827 * interactive shell and control is returned to the main command loop.
12828 */
12829static void
12830reset(void)
12831{
12832 /* from eval.c: */
12833 evalskip = 0;
12834 loopnest = 0;
12835 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012836 g_parsefile->left_in_buffer = 0;
12837 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012838 popallfiles();
12839 /* from parser.c: */
12840 tokpushback = 0;
12841 checkkwd = 0;
12842 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012843 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012844}
12845
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012846#if PROFILE
12847static short profile_buf[16384];
12848extern int etext();
12849#endif
12850
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012851/*
12852 * Main routine. We initialize things, parse the arguments, execute
12853 * profiles if we're a login shell, and then call cmdloop to execute
12854 * commands. The setjmp call sets up the location to jump to when an
12855 * exception occurs. When an exception occurs the variable "state"
12856 * is used to figure out how far we had gotten.
12857 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012858int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012859int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012860{
Mike Frysinger98c52642009-04-02 10:02:37 +000012861 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012862 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012863 struct jmploc jmploc;
12864 struct stackmark smark;
12865
Denis Vlasenko01631112007-12-16 17:20:38 +000012866 /* Initialize global data */
12867 INIT_G_misc();
12868 INIT_G_memstack();
12869 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012870#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012871 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012872#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012873 INIT_G_cmdtable();
12874
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012875#if PROFILE
12876 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12877#endif
12878
12879#if ENABLE_FEATURE_EDITING
12880 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12881#endif
12882 state = 0;
12883 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012884 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012885 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012886
12887 reset();
12888
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012889 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012890 if (e == EXERROR)
12891 exitstatus = 2;
12892 s = state;
12893 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12894 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012895 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012896 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012897
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012898 popstackmark(&smark);
12899 FORCE_INT_ON; /* enable interrupts */
12900 if (s == 1)
12901 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012902 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012903 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012904 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012905 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012906 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012907 }
12908 exception_handler = &jmploc;
12909#if DEBUG
12910 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012911 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012912 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012913#endif
12914 rootpid = getpid();
12915
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012916 init();
12917 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012918 procargs(argv);
12919
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012920#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12921 if (iflag) {
12922 const char *hp = lookupvar("HISTFILE");
12923
12924 if (hp == NULL) {
12925 hp = lookupvar("HOME");
12926 if (hp != NULL) {
12927 char *defhp = concat_path_file(hp, ".ash_history");
12928 setvar("HISTFILE", defhp, 0);
12929 free(defhp);
12930 }
12931 }
12932 }
12933#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012934 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012935 isloginsh = 1;
12936 if (isloginsh) {
12937 state = 1;
12938 read_profile("/etc/profile");
12939 state1:
12940 state = 2;
12941 read_profile(".profile");
12942 }
12943 state2:
12944 state = 3;
12945 if (
12946#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012947 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012948#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012949 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012950 ) {
12951 shinit = lookupvar("ENV");
12952 if (shinit != NULL && *shinit != '\0') {
12953 read_profile(shinit);
12954 }
12955 }
12956 state3:
12957 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012958 if (minusc) {
12959 /* evalstring pushes parsefile stack.
12960 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012961 * is one of stacked source fds.
12962 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012963 if (!sflag)
12964 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012965 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012966 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012967
12968 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010012969#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000012970 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012971 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012972 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012973 line_input_state->hist_file = hp;
12974 }
12975#endif
12976 state4: /* XXX ??? - why isn't this before the "if" statement */
12977 cmdloop(1);
12978 }
12979#if PROFILE
12980 monitor(0);
12981#endif
12982#ifdef GPROF
12983 {
12984 extern void _mcleanup(void);
12985 _mcleanup();
12986 }
12987#endif
12988 exitshell();
12989 /* NOTREACHED */
12990}
12991
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012992
Eric Andersendf82f612001-06-28 07:46:40 +000012993/*-
12994 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000012995 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000012996 *
12997 * This code is derived from software contributed to Berkeley by
12998 * Kenneth Almquist.
12999 *
13000 * Redistribution and use in source and binary forms, with or without
13001 * modification, are permitted provided that the following conditions
13002 * are met:
13003 * 1. Redistributions of source code must retain the above copyright
13004 * notice, this list of conditions and the following disclaimer.
13005 * 2. Redistributions in binary form must reproduce the above copyright
13006 * notice, this list of conditions and the following disclaimer in the
13007 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013008 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013009 * may be used to endorse or promote products derived from this software
13010 * without specific prior written permission.
13011 *
13012 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13013 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13014 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13015 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13016 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13017 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13018 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13019 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13020 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13021 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13022 * SUCH DAMAGE.
13023 */