blob: c7deffd08ea08dcd2ff70ede0ac66d71b94277b0 [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"
Mike Frysinger98c52642009-04-02 10:02:37 +000054#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020055#if ENABLE_ASH_RANDOM_SUPPORT
56# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020057#else
58# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020059#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000060
61#if defined SINGLE_APPLET_MAIN
62/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020063# undef CONFIG_FEATURE_SH_STANDALONE
64# undef ENABLE_FEATURE_SH_STANDALONE
65# undef IF_FEATURE_SH_STANDALONE
66# undef IF_NOT_FEATURE_SH_STANDALONE(...)
67# define ENABLE_FEATURE_SH_STANDALONE 0
68# define IF_FEATURE_SH_STANDALONE(...)
69# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000070#endif
71
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000072#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000073# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000074#endif
75
Denis Vlasenkob012b102007-02-19 22:43:01 +000076#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000077# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000078#endif
79
Denis Vlasenkob012b102007-02-19 22:43:01 +000080
Denis Vlasenko01631112007-12-16 17:20:38 +000081/* ============ Hash table sizes. Configurable. */
82
83#define VTABSIZE 39
84#define ATABSIZE 39
85#define CMDTABLESIZE 31 /* should be prime */
86
87
Denis Vlasenkob012b102007-02-19 22:43:01 +000088/* ============ Shell options */
89
90static const char *const optletters_optnames[] = {
91 "e" "errexit",
92 "f" "noglob",
93 "I" "ignoreeof",
94 "i" "interactive",
95 "m" "monitor",
96 "n" "noexec",
97 "s" "stdin",
98 "x" "xtrace",
99 "v" "verbose",
100 "C" "noclobber",
101 "a" "allexport",
102 "b" "notify",
103 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100104 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100105#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100106 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100107#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000108#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000109 ,"\0" "nolog"
110 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111#endif
112};
113
Denys Vlasenko285ad152009-12-04 23:02:27 +0100114#define optletters(n) optletters_optnames[n][0]
115#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000116
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000117enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000118
Eric Andersenc470f442003-07-28 09:56:35 +0000119
Denis Vlasenkob012b102007-02-19 22:43:01 +0000120/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000121
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000122static const char homestr[] ALIGN1 = "HOME";
123static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200124static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000125
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000126/*
Eric Andersenc470f442003-07-28 09:56:35 +0000127 * We enclose jmp_buf in a structure so that we can declare pointers to
128 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000129 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000130 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000131 * exception handlers, the user should save the value of handler on entry
132 * to an inner scope, set handler to point to a jmploc structure for the
133 * inner scope, and restore handler on exit from the scope.
134 */
Eric Andersenc470f442003-07-28 09:56:35 +0000135struct jmploc {
136 jmp_buf loc;
137};
Denis Vlasenko01631112007-12-16 17:20:38 +0000138
139struct globals_misc {
140 /* pid of main shell */
141 int rootpid;
142 /* shell level: 0 for the main shell, 1 for its children, and so on */
143 int shlvl;
144#define rootshell (!shlvl)
145 char *minusc; /* argument to -c option */
146
147 char *curdir; // = nullstr; /* current working directory */
148 char *physdir; // = nullstr; /* physical working directory */
149
150 char *arg0; /* value of $0 */
151
152 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000153
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200154 volatile int suppress_int; /* counter */
155 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000156 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200157 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000158 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000159 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000160#define EXINT 0 /* SIGINT received */
161#define EXERROR 1 /* a generic error */
162#define EXSHELLPROC 2 /* execute a shell procedure */
163#define EXEXEC 3 /* command execution failed */
164#define EXEXIT 4 /* exit the shell */
165#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000166
Denis Vlasenko01631112007-12-16 17:20:38 +0000167 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000168 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000169
170 char optlist[NOPTS];
171#define eflag optlist[0]
172#define fflag optlist[1]
173#define Iflag optlist[2]
174#define iflag optlist[3]
175#define mflag optlist[4]
176#define nflag optlist[5]
177#define sflag optlist[6]
178#define xflag optlist[7]
179#define vflag optlist[8]
180#define Cflag optlist[9]
181#define aflag optlist[10]
182#define bflag optlist[11]
183#define uflag optlist[12]
184#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100185#if ENABLE_ASH_BASH_COMPAT
186# define pipefail optlist[14]
187#else
188# define pipefail 0
189#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000190#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100191# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
192# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000193#endif
194
195 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000196 /*
197 * Sigmode records the current value of the signal handlers for the various
198 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000199 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000200 */
201 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000202#define S_DFL 1 /* default signal handling (SIG_DFL) */
203#define S_CATCH 2 /* signal is caught */
204#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000205#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000206
Denis Vlasenko01631112007-12-16 17:20:38 +0000207 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000208 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000209 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200210 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000211
212 /* Rarely referenced stuff */
213#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200214 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000215#endif
216 pid_t backgndpid; /* pid of last background process */
217 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000218};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000219extern struct globals_misc *const ash_ptr_to_globals_misc;
220#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000221#define rootpid (G_misc.rootpid )
222#define shlvl (G_misc.shlvl )
223#define minusc (G_misc.minusc )
224#define curdir (G_misc.curdir )
225#define physdir (G_misc.physdir )
226#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000227#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000228#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200229#define suppress_int (G_misc.suppress_int )
230#define pending_int (G_misc.pending_int )
231#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000232#define isloginsh (G_misc.isloginsh )
233#define nullstr (G_misc.nullstr )
234#define optlist (G_misc.optlist )
235#define sigmode (G_misc.sigmode )
236#define gotsig (G_misc.gotsig )
237#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200238#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200239#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000240#define backgndpid (G_misc.backgndpid )
241#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000242#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
244 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000245 curdir = nullstr; \
246 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200247 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000248} while (0)
249
250
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000251/* ============ DEBUG */
252#if DEBUG
253static void trace_printf(const char *fmt, ...);
254static void trace_vprintf(const char *fmt, va_list va);
255# define TRACE(param) trace_printf param
256# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000257# define close(fd) do { \
258 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000259 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200260 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000261 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000262} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000263#else
264# define TRACE(param)
265# define TRACEV(param)
266#endif
267
268
Denis Vlasenko559691a2008-10-05 18:39:31 +0000269/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000270#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
271
Denis Vlasenko559691a2008-10-05 18:39:31 +0000272static int isdigit_str9(const char *str)
273{
274 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
275 while (--maxlen && isdigit(*str))
276 str++;
277 return (*str == '\0');
278}
Denis Vlasenko01631112007-12-16 17:20:38 +0000279
Denis Vlasenko559691a2008-10-05 18:39:31 +0000280
281/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000282/*
Eric Andersen2870d962001-07-02 17:27:21 +0000283 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000284 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000285 * much more efficient and portable. (But hacking the kernel is so much
286 * more fun than worrying about efficiency and portability. :-))
287 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000288#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200289 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000290 xbarrier(); \
291} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000292
293/*
294 * Called to raise an exception. Since C doesn't include exceptions, we
295 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000296 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000297 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000298static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000299static void
300raise_exception(int e)
301{
302#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000303 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000304 abort();
305#endif
306 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000307 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000308 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000309}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000310#if DEBUG
311#define raise_exception(e) do { \
312 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
313 raise_exception(e); \
314} while (0)
315#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000316
317/*
318 * Called from trap.c when a SIGINT is received. (If the user specifies
319 * that SIGINT is to be trapped or ignored using the trap builtin, then
320 * this routine is not called.) Suppressint is nonzero when interrupts
321 * are held using the INT_OFF macro. (The test for iflag is just
322 * defensive programming.)
323 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000324static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000325static void
326raise_interrupt(void)
327{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000328 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200330 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000331 /* Signal is not automatically unmasked after it is raised,
332 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000333 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200334 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000335
Denis Vlasenko4b875702009-03-19 13:30:04 +0000336 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000337 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
338 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000339 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000340 signal(SIGINT, SIG_DFL);
341 raise(SIGINT);
342 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000343 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000344 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000345 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346 /* NOTREACHED */
347}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000348#if DEBUG
349#define raise_interrupt() do { \
350 TRACE(("raising interrupt on line %d\n", __LINE__)); \
351 raise_interrupt(); \
352} while (0)
353#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000354
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000355static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000356int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000357{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000358 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200359 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000360 raise_interrupt();
361 }
362}
363#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000364static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000365force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000366{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000367 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200368 suppress_int = 0;
369 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000370 raise_interrupt();
371}
372#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000373
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200374#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000375
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000376#define RESTORE_INT(v) do { \
377 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200378 suppress_int = (v); \
379 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000380 raise_interrupt(); \
381} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000382
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000383
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000384/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000385
Eric Andersenc470f442003-07-28 09:56:35 +0000386static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000387outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000388{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000389 INT_OFF;
390 fputs(p, file);
391 INT_ON;
392}
393
394static void
395flush_stdout_stderr(void)
396{
397 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100398 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000399 INT_ON;
400}
401
402static void
403outcslow(int c, FILE *dest)
404{
405 INT_OFF;
406 putc(c, dest);
407 fflush(dest);
408 INT_ON;
409}
410
411static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
412static int
413out1fmt(const char *fmt, ...)
414{
415 va_list ap;
416 int r;
417
418 INT_OFF;
419 va_start(ap, fmt);
420 r = vprintf(fmt, ap);
421 va_end(ap);
422 INT_ON;
423 return r;
424}
425
426static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
427static int
428fmtstr(char *outbuf, size_t length, const char *fmt, ...)
429{
430 va_list ap;
431 int ret;
432
433 va_start(ap, fmt);
434 INT_OFF;
435 ret = vsnprintf(outbuf, length, fmt, ap);
436 va_end(ap);
437 INT_ON;
438 return ret;
439}
440
441static void
442out1str(const char *p)
443{
444 outstr(p, stdout);
445}
446
447static void
448out2str(const char *p)
449{
450 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100451 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000452}
453
454
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000455/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000456
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000457/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100458#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200459#define CTLESC ((unsigned char)'\201') /* escape next character */
460#define CTLVAR ((unsigned char)'\202') /* variable defn */
461#define CTLENDVAR ((unsigned char)'\203')
462#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000463#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200465#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466#define CTLENDARI ((unsigned char)'\207')
467#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100468#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000469
470/* variable substitution byte (follows CTLVAR) */
471#define VSTYPE 0x0f /* type of variable substitution */
472#define VSNUL 0x10 /* colon--treat the empty string as unset */
473#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
474
475/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000476#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
477#define VSMINUS 0x2 /* ${var-text} */
478#define VSPLUS 0x3 /* ${var+text} */
479#define VSQUESTION 0x4 /* ${var?message} */
480#define VSASSIGN 0x5 /* ${var=text} */
481#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
482#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
483#define VSTRIMLEFT 0x8 /* ${var#pattern} */
484#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
485#define VSLENGTH 0xa /* ${#var} */
486#if ENABLE_ASH_BASH_COMPAT
487#define VSSUBSTR 0xc /* ${var:position:length} */
488#define VSREPLACE 0xd /* ${var/pattern/replacement} */
489#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
490#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000491
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000492static const char dolatstr[] ALIGN1 = {
493 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
494};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000495
Denis Vlasenko559691a2008-10-05 18:39:31 +0000496#define NCMD 0
497#define NPIPE 1
498#define NREDIR 2
499#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000500#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000501#define NAND 5
502#define NOR 6
503#define NSEMI 7
504#define NIF 8
505#define NWHILE 9
506#define NUNTIL 10
507#define NFOR 11
508#define NCASE 12
509#define NCLIST 13
510#define NDEFUN 14
511#define NARG 15
512#define NTO 16
513#if ENABLE_ASH_BASH_COMPAT
514#define NTO2 17
515#endif
516#define NCLOBBER 18
517#define NFROM 19
518#define NFROMTO 20
519#define NAPPEND 21
520#define NTOFD 22
521#define NFROMFD 23
522#define NHERE 24
523#define NXHERE 25
524#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000525#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000526
527union node;
528
529struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000530 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000531 union node *assign;
532 union node *args;
533 union node *redirect;
534};
535
536struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000537 smallint type;
538 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000539 struct nodelist *cmdlist;
540};
541
542struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000543 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000544 union node *n;
545 union node *redirect;
546};
547
548struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000549 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000550 union node *ch1;
551 union node *ch2;
552};
553
554struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000555 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000556 union node *test;
557 union node *ifpart;
558 union node *elsepart;
559};
560
561struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000562 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000563 union node *args;
564 union node *body;
565 char *var;
566};
567
568struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000569 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000570 union node *expr;
571 union node *cases;
572};
573
574struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000575 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000576 union node *next;
577 union node *pattern;
578 union node *body;
579};
580
581struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000582 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000583 union node *next;
584 char *text;
585 struct nodelist *backquote;
586};
587
Denis Vlasenko559691a2008-10-05 18:39:31 +0000588/* nfile and ndup layout must match!
589 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
590 * that it is actually NTO2 (>&file), and change its type.
591 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000592struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000593 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000594 union node *next;
595 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000596 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000597 union node *fname;
598 char *expfname;
599};
600
601struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000602 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000603 union node *next;
604 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000605 int dupfd;
606 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000607 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000608};
609
610struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000611 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000612 union node *next;
613 int fd;
614 union node *doc;
615};
616
617struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000618 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000619 union node *com;
620};
621
622union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000623 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000624 struct ncmd ncmd;
625 struct npipe npipe;
626 struct nredir nredir;
627 struct nbinary nbinary;
628 struct nif nif;
629 struct nfor nfor;
630 struct ncase ncase;
631 struct nclist nclist;
632 struct narg narg;
633 struct nfile nfile;
634 struct ndup ndup;
635 struct nhere nhere;
636 struct nnot nnot;
637};
638
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200639/*
640 * NODE_EOF is returned by parsecmd when it encounters an end of file.
641 * It must be distinct from NULL.
642 */
643#define NODE_EOF ((union node *) -1L)
644
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000645struct nodelist {
646 struct nodelist *next;
647 union node *n;
648};
649
650struct funcnode {
651 int count;
652 union node n;
653};
654
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000655/*
656 * Free a parse tree.
657 */
658static void
659freefunc(struct funcnode *f)
660{
661 if (f && --f->count < 0)
662 free(f);
663}
664
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000665
666/* ============ Debugging output */
667
668#if DEBUG
669
670static FILE *tracefile;
671
672static void
673trace_printf(const char *fmt, ...)
674{
675 va_list va;
676
677 if (debug != 1)
678 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000679 if (DEBUG_TIME)
680 fprintf(tracefile, "%u ", (int) time(NULL));
681 if (DEBUG_PID)
682 fprintf(tracefile, "[%u] ", (int) getpid());
683 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200684 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000685 va_start(va, fmt);
686 vfprintf(tracefile, fmt, va);
687 va_end(va);
688}
689
690static void
691trace_vprintf(const char *fmt, va_list va)
692{
693 if (debug != 1)
694 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000695 if (DEBUG_TIME)
696 fprintf(tracefile, "%u ", (int) time(NULL));
697 if (DEBUG_PID)
698 fprintf(tracefile, "[%u] ", (int) getpid());
699 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200700 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000701 vfprintf(tracefile, fmt, va);
702}
703
704static void
705trace_puts(const char *s)
706{
707 if (debug != 1)
708 return;
709 fputs(s, tracefile);
710}
711
712static void
713trace_puts_quoted(char *s)
714{
715 char *p;
716 char c;
717
718 if (debug != 1)
719 return;
720 putc('"', tracefile);
721 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100722 switch ((unsigned char)*p) {
723 case '\n': c = 'n'; goto backslash;
724 case '\t': c = 't'; goto backslash;
725 case '\r': c = 'r'; goto backslash;
726 case '\"': c = '\"'; goto backslash;
727 case '\\': c = '\\'; goto backslash;
728 case CTLESC: c = 'e'; goto backslash;
729 case CTLVAR: c = 'v'; goto backslash;
730 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
731 case CTLBACKQ: c = 'q'; goto backslash;
732 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000733 backslash:
734 putc('\\', tracefile);
735 putc(c, tracefile);
736 break;
737 default:
738 if (*p >= ' ' && *p <= '~')
739 putc(*p, tracefile);
740 else {
741 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100742 putc((*p >> 6) & 03, tracefile);
743 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000744 putc(*p & 07, tracefile);
745 }
746 break;
747 }
748 }
749 putc('"', tracefile);
750}
751
752static void
753trace_puts_args(char **ap)
754{
755 if (debug != 1)
756 return;
757 if (!*ap)
758 return;
759 while (1) {
760 trace_puts_quoted(*ap);
761 if (!*++ap) {
762 putc('\n', tracefile);
763 break;
764 }
765 putc(' ', tracefile);
766 }
767}
768
769static void
770opentrace(void)
771{
772 char s[100];
773#ifdef O_APPEND
774 int flags;
775#endif
776
777 if (debug != 1) {
778 if (tracefile)
779 fflush(tracefile);
780 /* leave open because libedit might be using it */
781 return;
782 }
783 strcpy(s, "./trace");
784 if (tracefile) {
785 if (!freopen(s, "a", tracefile)) {
786 fprintf(stderr, "Can't re-open %s\n", s);
787 debug = 0;
788 return;
789 }
790 } else {
791 tracefile = fopen(s, "a");
792 if (tracefile == NULL) {
793 fprintf(stderr, "Can't open %s\n", s);
794 debug = 0;
795 return;
796 }
797 }
798#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000799 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000800 if (flags >= 0)
801 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
802#endif
803 setlinebuf(tracefile);
804 fputs("\nTracing started.\n", tracefile);
805}
806
807static void
808indent(int amount, char *pfx, FILE *fp)
809{
810 int i;
811
812 for (i = 0; i < amount; i++) {
813 if (pfx && i == amount - 1)
814 fputs(pfx, fp);
815 putc('\t', fp);
816 }
817}
818
819/* little circular references here... */
820static void shtree(union node *n, int ind, char *pfx, FILE *fp);
821
822static void
823sharg(union node *arg, FILE *fp)
824{
825 char *p;
826 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100827 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000828
829 if (arg->type != NARG) {
830 out1fmt("<node type %d>\n", arg->type);
831 abort();
832 }
833 bqlist = arg->narg.backquote;
834 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100835 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000836 case CTLESC:
837 putc(*++p, fp);
838 break;
839 case CTLVAR:
840 putc('$', fp);
841 putc('{', fp);
842 subtype = *++p;
843 if (subtype == VSLENGTH)
844 putc('#', fp);
845
846 while (*p != '=')
847 putc(*p++, fp);
848
849 if (subtype & VSNUL)
850 putc(':', fp);
851
852 switch (subtype & VSTYPE) {
853 case VSNORMAL:
854 putc('}', fp);
855 break;
856 case VSMINUS:
857 putc('-', fp);
858 break;
859 case VSPLUS:
860 putc('+', fp);
861 break;
862 case VSQUESTION:
863 putc('?', fp);
864 break;
865 case VSASSIGN:
866 putc('=', fp);
867 break;
868 case VSTRIMLEFT:
869 putc('#', fp);
870 break;
871 case VSTRIMLEFTMAX:
872 putc('#', fp);
873 putc('#', fp);
874 break;
875 case VSTRIMRIGHT:
876 putc('%', fp);
877 break;
878 case VSTRIMRIGHTMAX:
879 putc('%', fp);
880 putc('%', fp);
881 break;
882 case VSLENGTH:
883 break;
884 default:
885 out1fmt("<subtype %d>", subtype);
886 }
887 break;
888 case CTLENDVAR:
889 putc('}', fp);
890 break;
891 case CTLBACKQ:
892 case CTLBACKQ|CTLQUOTE:
893 putc('$', fp);
894 putc('(', fp);
895 shtree(bqlist->n, -1, NULL, fp);
896 putc(')', fp);
897 break;
898 default:
899 putc(*p, fp);
900 break;
901 }
902 }
903}
904
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200905static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000906shcmd(union node *cmd, FILE *fp)
907{
908 union node *np;
909 int first;
910 const char *s;
911 int dftfd;
912
913 first = 1;
914 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000915 if (!first)
916 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000917 sharg(np, fp);
918 first = 0;
919 }
920 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000921 if (!first)
922 putc(' ', fp);
923 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000924 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000925 case NTO: s = ">>"+1; dftfd = 1; break;
926 case NCLOBBER: s = ">|"; dftfd = 1; break;
927 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000928#if ENABLE_ASH_BASH_COMPAT
929 case NTO2:
930#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000931 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000932 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000933 case NFROMFD: s = "<&"; break;
934 case NFROMTO: s = "<>"; break;
935 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000936 }
937 if (np->nfile.fd != dftfd)
938 fprintf(fp, "%d", np->nfile.fd);
939 fputs(s, fp);
940 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
941 fprintf(fp, "%d", np->ndup.dupfd);
942 } else {
943 sharg(np->nfile.fname, fp);
944 }
945 first = 0;
946 }
947}
948
949static void
950shtree(union node *n, int ind, char *pfx, FILE *fp)
951{
952 struct nodelist *lp;
953 const char *s;
954
955 if (n == NULL)
956 return;
957
958 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200959
960 if (n == NODE_EOF) {
961 fputs("<EOF>", fp);
962 return;
963 }
964
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000965 switch (n->type) {
966 case NSEMI:
967 s = "; ";
968 goto binop;
969 case NAND:
970 s = " && ";
971 goto binop;
972 case NOR:
973 s = " || ";
974 binop:
975 shtree(n->nbinary.ch1, ind, NULL, fp);
976 /* if (ind < 0) */
977 fputs(s, fp);
978 shtree(n->nbinary.ch2, ind, NULL, fp);
979 break;
980 case NCMD:
981 shcmd(n, fp);
982 if (ind >= 0)
983 putc('\n', fp);
984 break;
985 case NPIPE:
986 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200987 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000988 if (lp->next)
989 fputs(" | ", fp);
990 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000991 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000992 fputs(" &", fp);
993 if (ind >= 0)
994 putc('\n', fp);
995 break;
996 default:
997 fprintf(fp, "<node type %d>", n->type);
998 if (ind >= 0)
999 putc('\n', fp);
1000 break;
1001 }
1002}
1003
1004static void
1005showtree(union node *n)
1006{
1007 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001008 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001009}
1010
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001011#endif /* DEBUG */
1012
1013
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001014/* ============ Parser data */
1015
1016/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001017 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1018 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001019struct strlist {
1020 struct strlist *next;
1021 char *text;
1022};
1023
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001024struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001025
Denis Vlasenkob012b102007-02-19 22:43:01 +00001026struct strpush {
1027 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001028 char *prev_string;
1029 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001030#if ENABLE_ASH_ALIAS
1031 struct alias *ap; /* if push was associated with an alias */
1032#endif
1033 char *string; /* remember the string since it may change */
1034};
1035
1036struct parsefile {
1037 struct parsefile *prev; /* preceding file on stack */
1038 int linno; /* current line */
1039 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001040 int left_in_line; /* number of chars left in this line */
1041 int left_in_buffer; /* number of chars left in this buffer past the line */
1042 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001043 char *buf; /* input buffer */
1044 struct strpush *strpush; /* for pushing strings at this level */
1045 struct strpush basestrpush; /* so pushing one is fast */
1046};
1047
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001048static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001049static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001050static int startlinno; /* line # where last token started */
1051static char *commandname; /* currently executing command */
1052static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001053static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001054
1055
1056/* ============ Message printing */
1057
1058static void
1059ash_vmsg(const char *msg, va_list ap)
1060{
1061 fprintf(stderr, "%s: ", arg0);
1062 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001063 if (strcmp(arg0, commandname))
1064 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001065 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001066 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001067 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001068 vfprintf(stderr, msg, ap);
1069 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001070}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001071
1072/*
1073 * Exverror is called to raise the error exception. If the second argument
1074 * is not NULL then error prints an error message using printf style
1075 * formatting. It then raises the error exception.
1076 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001077static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001078static void
1079ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001080{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001081#if DEBUG
1082 if (msg) {
1083 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1084 TRACEV((msg, ap));
1085 TRACE(("\") pid=%d\n", getpid()));
1086 } else
1087 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1088 if (msg)
1089#endif
1090 ash_vmsg(msg, ap);
1091
1092 flush_stdout_stderr();
1093 raise_exception(cond);
1094 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001095}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001096
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001097static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001098static void
1099ash_msg_and_raise_error(const char *msg, ...)
1100{
1101 va_list ap;
1102
1103 va_start(ap, msg);
1104 ash_vmsg_and_raise(EXERROR, msg, ap);
1105 /* NOTREACHED */
1106 va_end(ap);
1107}
1108
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001109static void raise_error_syntax(const char *) NORETURN;
1110static void
1111raise_error_syntax(const char *msg)
1112{
1113 ash_msg_and_raise_error("syntax error: %s", msg);
1114 /* NOTREACHED */
1115}
1116
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001117static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001118static void
1119ash_msg_and_raise(int cond, const char *msg, ...)
1120{
1121 va_list ap;
1122
1123 va_start(ap, msg);
1124 ash_vmsg_and_raise(cond, msg, ap);
1125 /* NOTREACHED */
1126 va_end(ap);
1127}
1128
1129/*
1130 * error/warning routines for external builtins
1131 */
1132static void
1133ash_msg(const char *fmt, ...)
1134{
1135 va_list ap;
1136
1137 va_start(ap, fmt);
1138 ash_vmsg(fmt, ap);
1139 va_end(ap);
1140}
1141
1142/*
1143 * Return a string describing an error. The returned string may be a
1144 * pointer to a static buffer that will be overwritten on the next call.
1145 * Action describes the operation that got the error.
1146 */
1147static const char *
1148errmsg(int e, const char *em)
1149{
1150 if (e == ENOENT || e == ENOTDIR) {
1151 return em;
1152 }
1153 return strerror(e);
1154}
1155
1156
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001157/* ============ Memory allocation */
1158
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001159#if 0
1160/* I consider these wrappers nearly useless:
1161 * ok, they return you to nearest exception handler, but
1162 * how much memory do you leak in the process, making
1163 * memory starvation worse?
1164 */
1165static void *
1166ckrealloc(void * p, size_t nbytes)
1167{
1168 p = realloc(p, nbytes);
1169 if (!p)
1170 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1171 return p;
1172}
1173
1174static void *
1175ckmalloc(size_t nbytes)
1176{
1177 return ckrealloc(NULL, nbytes);
1178}
1179
1180static void *
1181ckzalloc(size_t nbytes)
1182{
1183 return memset(ckmalloc(nbytes), 0, nbytes);
1184}
1185
1186static char *
1187ckstrdup(const char *s)
1188{
1189 char *p = strdup(s);
1190 if (!p)
1191 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1192 return p;
1193}
1194#else
1195/* Using bbox equivalents. They exit if out of memory */
1196# define ckrealloc xrealloc
1197# define ckmalloc xmalloc
1198# define ckzalloc xzalloc
1199# define ckstrdup xstrdup
1200#endif
1201
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001202/*
1203 * It appears that grabstackstr() will barf with such alignments
1204 * because stalloc() will return a string allocated in a new stackblock.
1205 */
1206#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1207enum {
1208 /* Most machines require the value returned from malloc to be aligned
1209 * in some way. The following macro will get this right
1210 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001211 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001212 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001213 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001214};
1215
1216struct stack_block {
1217 struct stack_block *prev;
1218 char space[MINSIZE];
1219};
1220
1221struct stackmark {
1222 struct stack_block *stackp;
1223 char *stacknxt;
1224 size_t stacknleft;
1225 struct stackmark *marknext;
1226};
1227
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001228
Denis Vlasenko01631112007-12-16 17:20:38 +00001229struct globals_memstack {
1230 struct stack_block *g_stackp; // = &stackbase;
1231 struct stackmark *markp;
1232 char *g_stacknxt; // = stackbase.space;
1233 char *sstrend; // = stackbase.space + MINSIZE;
1234 size_t g_stacknleft; // = MINSIZE;
1235 int herefd; // = -1;
1236 struct stack_block stackbase;
1237};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001238extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1239#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001240#define g_stackp (G_memstack.g_stackp )
1241#define markp (G_memstack.markp )
1242#define g_stacknxt (G_memstack.g_stacknxt )
1243#define sstrend (G_memstack.sstrend )
1244#define g_stacknleft (G_memstack.g_stacknleft)
1245#define herefd (G_memstack.herefd )
1246#define stackbase (G_memstack.stackbase )
1247#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001248 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1249 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001250 g_stackp = &stackbase; \
1251 g_stacknxt = stackbase.space; \
1252 g_stacknleft = MINSIZE; \
1253 sstrend = stackbase.space + MINSIZE; \
1254 herefd = -1; \
1255} while (0)
1256
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001257
Denis Vlasenko01631112007-12-16 17:20:38 +00001258#define stackblock() ((void *)g_stacknxt)
1259#define stackblocksize() g_stacknleft
1260
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001261/*
1262 * Parse trees for commands are allocated in lifo order, so we use a stack
1263 * to make this more efficient, and also to avoid all sorts of exception
1264 * handling code to handle interrupts in the middle of a parse.
1265 *
1266 * The size 504 was chosen because the Ultrix malloc handles that size
1267 * well.
1268 */
1269static void *
1270stalloc(size_t nbytes)
1271{
1272 char *p;
1273 size_t aligned;
1274
1275 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001276 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001277 size_t len;
1278 size_t blocksize;
1279 struct stack_block *sp;
1280
1281 blocksize = aligned;
1282 if (blocksize < MINSIZE)
1283 blocksize = MINSIZE;
1284 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1285 if (len < blocksize)
1286 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1287 INT_OFF;
1288 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001289 sp->prev = g_stackp;
1290 g_stacknxt = sp->space;
1291 g_stacknleft = blocksize;
1292 sstrend = g_stacknxt + blocksize;
1293 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001294 INT_ON;
1295 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001296 p = g_stacknxt;
1297 g_stacknxt += aligned;
1298 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001299 return p;
1300}
1301
Denis Vlasenko597906c2008-02-20 16:38:54 +00001302static void *
1303stzalloc(size_t nbytes)
1304{
1305 return memset(stalloc(nbytes), 0, nbytes);
1306}
1307
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001308static void
1309stunalloc(void *p)
1310{
1311#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001312 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001313 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001314 abort();
1315 }
1316#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001317 g_stacknleft += g_stacknxt - (char *)p;
1318 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001319}
1320
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001321/*
1322 * Like strdup but works with the ash stack.
1323 */
1324static char *
1325ststrdup(const char *p)
1326{
1327 size_t len = strlen(p) + 1;
1328 return memcpy(stalloc(len), p, len);
1329}
1330
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001331static void
1332setstackmark(struct stackmark *mark)
1333{
Denis Vlasenko01631112007-12-16 17:20:38 +00001334 mark->stackp = g_stackp;
1335 mark->stacknxt = g_stacknxt;
1336 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001337 mark->marknext = markp;
1338 markp = mark;
1339}
1340
1341static void
1342popstackmark(struct stackmark *mark)
1343{
1344 struct stack_block *sp;
1345
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001346 if (!mark->stackp)
1347 return;
1348
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001349 INT_OFF;
1350 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001351 while (g_stackp != mark->stackp) {
1352 sp = g_stackp;
1353 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001354 free(sp);
1355 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001356 g_stacknxt = mark->stacknxt;
1357 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001358 sstrend = mark->stacknxt + mark->stacknleft;
1359 INT_ON;
1360}
1361
1362/*
1363 * When the parser reads in a string, it wants to stick the string on the
1364 * stack and only adjust the stack pointer when it knows how big the
1365 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1366 * of space on top of the stack and stackblocklen returns the length of
1367 * this block. Growstackblock will grow this space by at least one byte,
1368 * possibly moving it (like realloc). Grabstackblock actually allocates the
1369 * part of the block that has been used.
1370 */
1371static void
1372growstackblock(void)
1373{
1374 size_t newlen;
1375
Denis Vlasenko01631112007-12-16 17:20:38 +00001376 newlen = g_stacknleft * 2;
1377 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001378 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1379 if (newlen < 128)
1380 newlen += 128;
1381
Denis Vlasenko01631112007-12-16 17:20:38 +00001382 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001383 struct stack_block *oldstackp;
1384 struct stackmark *xmark;
1385 struct stack_block *sp;
1386 struct stack_block *prevstackp;
1387 size_t grosslen;
1388
1389 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001390 oldstackp = g_stackp;
1391 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001392 prevstackp = sp->prev;
1393 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1394 sp = ckrealloc(sp, grosslen);
1395 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001396 g_stackp = sp;
1397 g_stacknxt = sp->space;
1398 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001399 sstrend = sp->space + newlen;
1400
1401 /*
1402 * Stack marks pointing to the start of the old block
1403 * must be relocated to point to the new block
1404 */
1405 xmark = markp;
1406 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001407 xmark->stackp = g_stackp;
1408 xmark->stacknxt = g_stacknxt;
1409 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001410 xmark = xmark->marknext;
1411 }
1412 INT_ON;
1413 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001414 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001415 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001416 char *p = stalloc(newlen);
1417
1418 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001419 g_stacknxt = memcpy(p, oldspace, oldlen);
1420 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001421 }
1422}
1423
1424static void
1425grabstackblock(size_t len)
1426{
1427 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001428 g_stacknxt += len;
1429 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001430}
1431
1432/*
1433 * The following routines are somewhat easier to use than the above.
1434 * The user declares a variable of type STACKSTR, which may be declared
1435 * to be a register. The macro STARTSTACKSTR initializes things. Then
1436 * the user uses the macro STPUTC to add characters to the string. In
1437 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1438 * grown as necessary. When the user is done, she can just leave the
1439 * string there and refer to it using stackblock(). Or she can allocate
1440 * the space for it using grabstackstr(). If it is necessary to allow
1441 * someone else to use the stack temporarily and then continue to grow
1442 * the string, the user should use grabstack to allocate the space, and
1443 * then call ungrabstr(p) to return to the previous mode of operation.
1444 *
1445 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1446 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1447 * is space for at least one character.
1448 */
1449static void *
1450growstackstr(void)
1451{
1452 size_t len = stackblocksize();
1453 if (herefd >= 0 && len >= 1024) {
1454 full_write(herefd, stackblock(), len);
1455 return stackblock();
1456 }
1457 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001458 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001459}
1460
1461/*
1462 * Called from CHECKSTRSPACE.
1463 */
1464static char *
1465makestrspace(size_t newlen, char *p)
1466{
Denis Vlasenko01631112007-12-16 17:20:38 +00001467 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001468 size_t size = stackblocksize();
1469
1470 for (;;) {
1471 size_t nleft;
1472
1473 size = stackblocksize();
1474 nleft = size - len;
1475 if (nleft >= newlen)
1476 break;
1477 growstackblock();
1478 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001479 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001480}
1481
1482static char *
1483stack_nputstr(const char *s, size_t n, char *p)
1484{
1485 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001486 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001487 return p;
1488}
1489
1490static char *
1491stack_putstr(const char *s, char *p)
1492{
1493 return stack_nputstr(s, strlen(s), p);
1494}
1495
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001496static char *
1497_STPUTC(int c, char *p)
1498{
1499 if (p == sstrend)
1500 p = growstackstr();
1501 *p++ = c;
1502 return p;
1503}
1504
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001505#define STARTSTACKSTR(p) ((p) = stackblock())
1506#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001507#define CHECKSTRSPACE(n, p) do { \
1508 char *q = (p); \
1509 size_t l = (n); \
1510 size_t m = sstrend - q; \
1511 if (l > m) \
1512 (p) = makestrspace(l, q); \
1513} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001514#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001515#define STACKSTRNUL(p) do { \
1516 if ((p) == sstrend) \
1517 (p) = growstackstr(); \
1518 *(p) = '\0'; \
1519} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001520#define STUNPUTC(p) (--(p))
1521#define STTOPC(p) ((p)[-1])
1522#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001523
1524#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001525#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001526#define stackstrend() ((void *)sstrend)
1527
1528
1529/* ============ String helpers */
1530
1531/*
1532 * prefix -- see if pfx is a prefix of string.
1533 */
1534static char *
1535prefix(const char *string, const char *pfx)
1536{
1537 while (*pfx) {
1538 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001539 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001540 }
1541 return (char *) string;
1542}
1543
1544/*
1545 * Check for a valid number. This should be elsewhere.
1546 */
1547static int
1548is_number(const char *p)
1549{
1550 do {
1551 if (!isdigit(*p))
1552 return 0;
1553 } while (*++p != '\0');
1554 return 1;
1555}
1556
1557/*
1558 * Convert a string of digits to an integer, printing an error message on
1559 * failure.
1560 */
1561static int
1562number(const char *s)
1563{
1564 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001565 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001566 return atoi(s);
1567}
1568
1569/*
1570 * Produce a possibly single quoted string suitable as input to the shell.
1571 * The return string is allocated on the stack.
1572 */
1573static char *
1574single_quote(const char *s)
1575{
1576 char *p;
1577
1578 STARTSTACKSTR(p);
1579
1580 do {
1581 char *q;
1582 size_t len;
1583
1584 len = strchrnul(s, '\'') - s;
1585
1586 q = p = makestrspace(len + 3, p);
1587
1588 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001589 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001590 *q++ = '\'';
1591 s += len;
1592
1593 STADJUST(q - p, p);
1594
Denys Vlasenkocd716832009-11-28 22:14:02 +01001595 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001596 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001597 len = 0;
1598 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001599
1600 q = p = makestrspace(len + 3, p);
1601
1602 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001603 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605
1606 STADJUST(q - p, p);
1607 } while (*s);
1608
Denys Vlasenkocd716832009-11-28 22:14:02 +01001609 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001610
1611 return stackblock();
1612}
1613
1614
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001615/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001616
1617static char **argptr; /* argument list for builtin commands */
1618static char *optionarg; /* set by nextopt (like getopt) */
1619static char *optptr; /* used by nextopt */
1620
1621/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001622 * XXX - should get rid of. Have all builtins use getopt(3).
1623 * The library getopt must have the BSD extension static variable
1624 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001625 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001626 * Standard option processing (a la getopt) for builtin routines.
1627 * The only argument that is passed to nextopt is the option string;
1628 * the other arguments are unnecessary. It returns the character,
1629 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001630 */
1631static int
1632nextopt(const char *optstring)
1633{
1634 char *p;
1635 const char *q;
1636 char c;
1637
1638 p = optptr;
1639 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001640 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001641 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001642 if (p == NULL)
1643 return '\0';
1644 if (*p != '-')
1645 return '\0';
1646 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001647 return '\0';
1648 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001649 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001651 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001652 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001653 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001654 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001655 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001657 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001658 if (*++q == ':')
1659 q++;
1660 }
1661 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001662 if (*p == '\0') {
1663 p = *argptr++;
1664 if (p == NULL)
1665 ash_msg_and_raise_error("no arg for -%c option", c);
1666 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001667 optionarg = p;
1668 p = NULL;
1669 }
1670 optptr = p;
1671 return c;
1672}
1673
1674
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001675/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001676
Denis Vlasenko01631112007-12-16 17:20:38 +00001677/*
1678 * The parsefile structure pointed to by the global variable parsefile
1679 * contains information about the current file being read.
1680 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001681struct shparam {
1682 int nparam; /* # of positional parameters (without $0) */
1683#if ENABLE_ASH_GETOPTS
1684 int optind; /* next parameter to be processed by getopts */
1685 int optoff; /* used by getopts */
1686#endif
1687 unsigned char malloced; /* if parameter list dynamically allocated */
1688 char **p; /* parameter list */
1689};
1690
1691/*
1692 * Free the list of positional parameters.
1693 */
1694static void
1695freeparam(volatile struct shparam *param)
1696{
Denis Vlasenko01631112007-12-16 17:20:38 +00001697 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001698 char **ap, **ap1;
1699 ap = ap1 = param->p;
1700 while (*ap)
1701 free(*ap++);
1702 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001703 }
1704}
1705
1706#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001707static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001708#endif
1709
1710struct var {
1711 struct var *next; /* next entry in hash list */
1712 int flags; /* flags are defined above */
1713 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001714 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001715 /* the variable gets set/unset */
1716};
1717
1718struct localvar {
1719 struct localvar *next; /* next local variable in list */
1720 struct var *vp; /* the variable that was made local */
1721 int flags; /* saved flags */
1722 const char *text; /* saved text */
1723};
1724
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001725/* flags */
1726#define VEXPORT 0x01 /* variable is exported */
1727#define VREADONLY 0x02 /* variable cannot be modified */
1728#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1729#define VTEXTFIXED 0x08 /* text is statically allocated */
1730#define VSTACK 0x10 /* text is allocated on the stack */
1731#define VUNSET 0x20 /* the variable is not set */
1732#define VNOFUNC 0x40 /* don't call the callback function */
1733#define VNOSET 0x80 /* do not set variable - just readonly test */
1734#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001735#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001736# define VDYNAMIC 0x200 /* dynamic variable */
1737#else
1738# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001739#endif
1740
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001741
Denis Vlasenko01631112007-12-16 17:20:38 +00001742/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001743#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001744static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001745change_lc_all(const char *value)
1746{
1747 if (value && *value != '\0')
1748 setlocale(LC_ALL, value);
1749}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001750static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001751change_lc_ctype(const char *value)
1752{
1753 if (value && *value != '\0')
1754 setlocale(LC_CTYPE, value);
1755}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001756#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001757#if ENABLE_ASH_MAIL
1758static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001759static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001760#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001761static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001763static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001764#endif
1765
Denis Vlasenko01631112007-12-16 17:20:38 +00001766static const struct {
1767 int flags;
1768 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001769 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001770} varinit_data[] = {
Denys Vlasenko73067272010-01-12 22:11:24 +01001771#if IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001774 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001775#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1781 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#endif
1790#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001795 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001796#endif
1797};
1798
Denis Vlasenko0b769642008-07-24 07:54:57 +00001799struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001800
1801struct globals_var {
1802 struct shparam shellparam; /* $@ current positional parameters */
1803 struct redirtab *redirlist;
1804 int g_nullredirs;
1805 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1806 struct var *vartab[VTABSIZE];
1807 struct var varinit[ARRAY_SIZE(varinit_data)];
1808};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001809extern struct globals_var *const ash_ptr_to_globals_var;
1810#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001811#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001812//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001813#define g_nullredirs (G_var.g_nullredirs )
1814#define preverrout_fd (G_var.preverrout_fd)
1815#define vartab (G_var.vartab )
1816#define varinit (G_var.varinit )
1817#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001818 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001819 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1820 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001821 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1822 varinit[i].flags = varinit_data[i].flags; \
1823 varinit[i].text = varinit_data[i].text; \
1824 varinit[i].func = varinit_data[i].func; \
1825 } \
1826} while (0)
1827
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001828#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001829#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001830# define vmail (&vifs)[1]
1831# define vmpath (&vmail)[1]
1832# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001833#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836#define vps1 (&vpath)[1]
1837#define vps2 (&vps1)[1]
1838#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001839#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001840# define voptind (&vps4)[1]
1841# if ENABLE_ASH_RANDOM_SUPPORT
1842# define vrandom (&voptind)[1]
1843# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001845# if ENABLE_ASH_RANDOM_SUPPORT
1846# define vrandom (&vps4)[1]
1847# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849
1850/*
1851 * The following macros access the values of the above variables.
1852 * They have to skip over the name. They return the null string
1853 * for unset variables.
1854 */
1855#define ifsval() (vifs.text + 4)
1856#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001857#if ENABLE_ASH_MAIL
1858# define mailval() (vmail.text + 5)
1859# define mpathval() (vmpath.text + 9)
1860# define mpathset() ((vmpath.flags & VUNSET) == 0)
1861#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001862#define pathval() (vpath.text + 5)
1863#define ps1val() (vps1.text + 4)
1864#define ps2val() (vps2.text + 4)
1865#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001866#if ENABLE_ASH_GETOPTS
1867# define optindval() (voptind.text + 7)
1868#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001871#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1872#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1873
Denis Vlasenko01631112007-12-16 17:20:38 +00001874#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001875static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001876getoptsreset(const char *value)
1877{
1878 shellparam.optind = number(value);
1879 shellparam.optoff = -1;
1880}
1881#endif
1882
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001883/*
1884 * Return of a legal variable name (a letter or underscore followed by zero or
1885 * more letters, underscores, and digits).
1886 */
1887static char *
1888endofname(const char *name)
1889{
1890 char *p;
1891
1892 p = (char *) name;
1893 if (!is_name(*p))
1894 return p;
1895 while (*++p) {
1896 if (!is_in_name(*p))
1897 break;
1898 }
1899 return p;
1900}
1901
1902/*
1903 * Compares two strings up to the first = or '\0'. The first
1904 * string must be terminated by '='; the second may be terminated by
1905 * either '=' or '\0'.
1906 */
1907static int
1908varcmp(const char *p, const char *q)
1909{
1910 int c, d;
1911
1912 while ((c = *p) == (d = *q)) {
1913 if (!c || c == '=')
1914 goto out;
1915 p++;
1916 q++;
1917 }
1918 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001919 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001920 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001921 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001922 out:
1923 return c - d;
1924}
1925
1926static int
1927varequal(const char *a, const char *b)
1928{
1929 return !varcmp(a, b);
1930}
1931
1932/*
1933 * Find the appropriate entry in the hash table from the name.
1934 */
1935static struct var **
1936hashvar(const char *p)
1937{
1938 unsigned hashval;
1939
1940 hashval = ((unsigned char) *p) << 4;
1941 while (*p && *p != '=')
1942 hashval += (unsigned char) *p++;
1943 return &vartab[hashval % VTABSIZE];
1944}
1945
1946static int
1947vpcmp(const void *a, const void *b)
1948{
1949 return varcmp(*(const char **)a, *(const char **)b);
1950}
1951
1952/*
1953 * This routine initializes the builtin variables.
1954 */
1955static void
1956initvar(void)
1957{
1958 struct var *vp;
1959 struct var *end;
1960 struct var **vpp;
1961
1962 /*
1963 * PS1 depends on uid
1964 */
1965#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1966 vps1.text = "PS1=\\w \\$ ";
1967#else
1968 if (!geteuid())
1969 vps1.text = "PS1=# ";
1970#endif
1971 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001972 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001973 do {
1974 vpp = hashvar(vp->text);
1975 vp->next = *vpp;
1976 *vpp = vp;
1977 } while (++vp < end);
1978}
1979
1980static struct var **
1981findvar(struct var **vpp, const char *name)
1982{
1983 for (; *vpp; vpp = &(*vpp)->next) {
1984 if (varequal((*vpp)->text, name)) {
1985 break;
1986 }
1987 }
1988 return vpp;
1989}
1990
1991/*
1992 * Find the value of a variable. Returns NULL if not set.
1993 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001994static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001995lookupvar(const char *name)
1996{
1997 struct var *v;
1998
1999 v = *findvar(hashvar(name), name);
2000 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002001#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002002 /*
2003 * Dynamic variables are implemented roughly the same way they are
2004 * in bash. Namely, they're "special" so long as they aren't unset.
2005 * As soon as they're unset, they're no longer dynamic, and dynamic
2006 * lookup will no longer happen at that point. -- PFM.
2007 */
2008 if ((v->flags & VDYNAMIC))
2009 (*v->func)(NULL);
2010#endif
2011 if (!(v->flags & VUNSET))
2012 return strchrnul(v->text, '=') + 1;
2013 }
2014 return NULL;
2015}
2016
2017/*
2018 * Search the environment of a builtin command.
2019 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002020static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002021bltinlookup(const char *name)
2022{
2023 struct strlist *sp;
2024
2025 for (sp = cmdenviron; sp; sp = sp->next) {
2026 if (varequal(sp->text, name))
2027 return strchrnul(sp->text, '=') + 1;
2028 }
2029 return lookupvar(name);
2030}
2031
2032/*
2033 * Same as setvar except that the variable and value are passed in
2034 * the first argument as name=value. Since the first argument will
2035 * be actually stored in the table, it should not be a string that
2036 * will go away.
2037 * Called with interrupts off.
2038 */
2039static void
2040setvareq(char *s, int flags)
2041{
2042 struct var *vp, **vpp;
2043
2044 vpp = hashvar(s);
2045 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2046 vp = *findvar(vpp, s);
2047 if (vp) {
2048 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 const char *n;
2050
2051 if (flags & VNOSAVE)
2052 free(s);
2053 n = vp->text;
2054 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2055 }
2056
2057 if (flags & VNOSET)
2058 return;
2059
2060 if (vp->func && (flags & VNOFUNC) == 0)
2061 (*vp->func)(strchrnul(s, '=') + 1);
2062
2063 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2064 free((char*)vp->text);
2065
2066 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 } else {
2068 if (flags & VNOSET)
2069 return;
2070 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002071 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002073 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002074 *vpp = vp;
2075 }
2076 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2077 s = ckstrdup(s);
2078 vp->text = s;
2079 vp->flags = flags;
2080}
2081
2082/*
2083 * Set the value of a variable. The flags argument is ored with the
2084 * flags of the variable. If val is NULL, the variable is unset.
2085 */
2086static void
2087setvar(const char *name, const char *val, int flags)
2088{
2089 char *p, *q;
2090 size_t namelen;
2091 char *nameeq;
2092 size_t vallen;
2093
2094 q = endofname(name);
2095 p = strchrnul(q, '=');
2096 namelen = p - name;
2097 if (!namelen || p != q)
2098 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = 0;
2100 if (val == NULL) {
2101 flags |= VUNSET;
2102 } else {
2103 vallen = strlen(val);
2104 }
2105 INT_OFF;
2106 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002107 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002108 if (val) {
2109 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002110 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002111 }
2112 *p = '\0';
2113 setvareq(nameeq, flags | VNOSAVE);
2114 INT_ON;
2115}
2116
2117#if ENABLE_ASH_GETOPTS
2118/*
2119 * Safe version of setvar, returns 1 on success 0 on failure.
2120 */
2121static int
2122setvarsafe(const char *name, const char *val, int flags)
2123{
2124 int err;
2125 volatile int saveint;
2126 struct jmploc *volatile savehandler = exception_handler;
2127 struct jmploc jmploc;
2128
2129 SAVE_INT(saveint);
2130 if (setjmp(jmploc.loc))
2131 err = 1;
2132 else {
2133 exception_handler = &jmploc;
2134 setvar(name, val, flags);
2135 err = 0;
2136 }
2137 exception_handler = savehandler;
2138 RESTORE_INT(saveint);
2139 return err;
2140}
2141#endif
2142
2143/*
2144 * Unset the specified variable.
2145 */
2146static int
2147unsetvar(const char *s)
2148{
2149 struct var **vpp;
2150 struct var *vp;
2151 int retval;
2152
2153 vpp = findvar(hashvar(s), s);
2154 vp = *vpp;
2155 retval = 2;
2156 if (vp) {
2157 int flags = vp->flags;
2158
2159 retval = 1;
2160 if (flags & VREADONLY)
2161 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002162#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002163 vp->flags &= ~VDYNAMIC;
2164#endif
2165 if (flags & VUNSET)
2166 goto ok;
2167 if ((flags & VSTRFIXED) == 0) {
2168 INT_OFF;
2169 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2170 free((char*)vp->text);
2171 *vpp = vp->next;
2172 free(vp);
2173 INT_ON;
2174 } else {
2175 setvar(s, 0, 0);
2176 vp->flags &= ~VEXPORT;
2177 }
2178 ok:
2179 retval = 0;
2180 }
2181 out:
2182 return retval;
2183}
2184
2185/*
2186 * Process a linked list of variable assignments.
2187 */
2188static void
2189listsetvar(struct strlist *list_set_var, int flags)
2190{
2191 struct strlist *lp = list_set_var;
2192
2193 if (!lp)
2194 return;
2195 INT_OFF;
2196 do {
2197 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002198 lp = lp->next;
2199 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002200 INT_ON;
2201}
2202
2203/*
2204 * Generate a list of variables satisfying the given conditions.
2205 */
2206static char **
2207listvars(int on, int off, char ***end)
2208{
2209 struct var **vpp;
2210 struct var *vp;
2211 char **ep;
2212 int mask;
2213
2214 STARTSTACKSTR(ep);
2215 vpp = vartab;
2216 mask = on | off;
2217 do {
2218 for (vp = *vpp; vp; vp = vp->next) {
2219 if ((vp->flags & mask) == on) {
2220 if (ep == stackstrend())
2221 ep = growstackstr();
2222 *ep++ = (char *) vp->text;
2223 }
2224 }
2225 } while (++vpp < vartab + VTABSIZE);
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 if (end)
2229 *end = ep;
2230 *ep++ = NULL;
2231 return grabstackstr(ep);
2232}
2233
2234
2235/* ============ Path search helper
2236 *
2237 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002238 * of the path before the first call; path_advance will update
2239 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002240 * the possible path expansions in sequence. If an option (indicated by
2241 * a percent sign) appears in the path entry then the global variable
2242 * pathopt will be set to point to it; otherwise pathopt will be set to
2243 * NULL.
2244 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002245static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246
2247static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002248path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002249{
2250 const char *p;
2251 char *q;
2252 const char *start;
2253 size_t len;
2254
2255 if (*path == NULL)
2256 return NULL;
2257 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002258 for (p = start; *p && *p != ':' && *p != '%'; p++)
2259 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002260 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2261 while (stackblocksize() < len)
2262 growstackblock();
2263 q = stackblock();
2264 if (p != start) {
2265 memcpy(q, start, p - start);
2266 q += p - start;
2267 *q++ = '/';
2268 }
2269 strcpy(q, name);
2270 pathopt = NULL;
2271 if (*p == '%') {
2272 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002273 while (*p && *p != ':')
2274 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002275 }
2276 if (*p == ':')
2277 *path = p + 1;
2278 else
2279 *path = NULL;
2280 return stalloc(len);
2281}
2282
2283
2284/* ============ Prompt */
2285
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002286static smallint doprompt; /* if set, prompt the user */
2287static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002288
2289#if ENABLE_FEATURE_EDITING
2290static line_input_t *line_input_state;
2291static const char *cmdedit_prompt;
2292static void
2293putprompt(const char *s)
2294{
2295 if (ENABLE_ASH_EXPAND_PRMT) {
2296 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002297 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002298 return;
2299 }
2300 cmdedit_prompt = s;
2301}
2302#else
2303static void
2304putprompt(const char *s)
2305{
2306 out2str(s);
2307}
2308#endif
2309
2310#if ENABLE_ASH_EXPAND_PRMT
2311/* expandstr() needs parsing machinery, so it is far away ahead... */
2312static const char *expandstr(const char *ps);
2313#else
2314#define expandstr(s) s
2315#endif
2316
2317static void
2318setprompt(int whichprompt)
2319{
2320 const char *prompt;
2321#if ENABLE_ASH_EXPAND_PRMT
2322 struct stackmark smark;
2323#endif
2324
2325 needprompt = 0;
2326
2327 switch (whichprompt) {
2328 case 1:
2329 prompt = ps1val();
2330 break;
2331 case 2:
2332 prompt = ps2val();
2333 break;
2334 default: /* 0 */
2335 prompt = nullstr;
2336 }
2337#if ENABLE_ASH_EXPAND_PRMT
2338 setstackmark(&smark);
2339 stalloc(stackblocksize());
2340#endif
2341 putprompt(expandstr(prompt));
2342#if ENABLE_ASH_EXPAND_PRMT
2343 popstackmark(&smark);
2344#endif
2345}
2346
2347
2348/* ============ The cd and pwd commands */
2349
2350#define CD_PHYSICAL 1
2351#define CD_PRINT 2
2352
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002353static int
2354cdopt(void)
2355{
2356 int flags = 0;
2357 int i, j;
2358
2359 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002360 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002361 if (i != j) {
2362 flags ^= CD_PHYSICAL;
2363 j = i;
2364 }
2365 }
2366
2367 return flags;
2368}
2369
2370/*
2371 * Update curdir (the name of the current directory) in response to a
2372 * cd command.
2373 */
2374static const char *
2375updatepwd(const char *dir)
2376{
2377 char *new;
2378 char *p;
2379 char *cdcomppath;
2380 const char *lim;
2381
2382 cdcomppath = ststrdup(dir);
2383 STARTSTACKSTR(new);
2384 if (*dir != '/') {
2385 if (curdir == nullstr)
2386 return 0;
2387 new = stack_putstr(curdir, new);
2388 }
2389 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002390 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002391 if (*dir != '/') {
2392 if (new[-1] != '/')
2393 USTPUTC('/', new);
2394 if (new > lim && *lim == '/')
2395 lim++;
2396 } else {
2397 USTPUTC('/', new);
2398 cdcomppath++;
2399 if (dir[1] == '/' && dir[2] != '/') {
2400 USTPUTC('/', new);
2401 cdcomppath++;
2402 lim++;
2403 }
2404 }
2405 p = strtok(cdcomppath, "/");
2406 while (p) {
2407 switch (*p) {
2408 case '.':
2409 if (p[1] == '.' && p[2] == '\0') {
2410 while (new > lim) {
2411 STUNPUTC(new);
2412 if (new[-1] == '/')
2413 break;
2414 }
2415 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002416 }
2417 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002418 break;
2419 /* fall through */
2420 default:
2421 new = stack_putstr(p, new);
2422 USTPUTC('/', new);
2423 }
2424 p = strtok(0, "/");
2425 }
2426 if (new > lim)
2427 STUNPUTC(new);
2428 *new = 0;
2429 return stackblock();
2430}
2431
2432/*
2433 * Find out what the current directory is. If we already know the current
2434 * directory, this routine returns immediately.
2435 */
2436static char *
2437getpwd(void)
2438{
Denis Vlasenko01631112007-12-16 17:20:38 +00002439 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002440 return dir ? dir : nullstr;
2441}
2442
2443static void
2444setpwd(const char *val, int setold)
2445{
2446 char *oldcur, *dir;
2447
2448 oldcur = dir = curdir;
2449
2450 if (setold) {
2451 setvar("OLDPWD", oldcur, VEXPORT);
2452 }
2453 INT_OFF;
2454 if (physdir != nullstr) {
2455 if (physdir != oldcur)
2456 free(physdir);
2457 physdir = nullstr;
2458 }
2459 if (oldcur == val || !val) {
2460 char *s = getpwd();
2461 physdir = s;
2462 if (!val)
2463 dir = s;
2464 } else
2465 dir = ckstrdup(val);
2466 if (oldcur != dir && oldcur != nullstr) {
2467 free(oldcur);
2468 }
2469 curdir = dir;
2470 INT_ON;
2471 setvar("PWD", dir, VEXPORT);
2472}
2473
2474static void hashcd(void);
2475
2476/*
2477 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2478 * know that the current directory has changed.
2479 */
2480static int
2481docd(const char *dest, int flags)
2482{
2483 const char *dir = 0;
2484 int err;
2485
2486 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2487
2488 INT_OFF;
2489 if (!(flags & CD_PHYSICAL)) {
2490 dir = updatepwd(dest);
2491 if (dir)
2492 dest = dir;
2493 }
2494 err = chdir(dest);
2495 if (err)
2496 goto out;
2497 setpwd(dir, 1);
2498 hashcd();
2499 out:
2500 INT_ON;
2501 return err;
2502}
2503
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002504static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002505cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002506{
2507 const char *dest;
2508 const char *path;
2509 const char *p;
2510 char c;
2511 struct stat statb;
2512 int flags;
2513
2514 flags = cdopt();
2515 dest = *argptr;
2516 if (!dest)
2517 dest = bltinlookup(homestr);
2518 else if (LONE_DASH(dest)) {
2519 dest = bltinlookup("OLDPWD");
2520 flags |= CD_PRINT;
2521 }
2522 if (!dest)
2523 dest = nullstr;
2524 if (*dest == '/')
2525 goto step7;
2526 if (*dest == '.') {
2527 c = dest[1];
2528 dotdot:
2529 switch (c) {
2530 case '\0':
2531 case '/':
2532 goto step6;
2533 case '.':
2534 c = dest[2];
2535 if (c != '.')
2536 goto dotdot;
2537 }
2538 }
2539 if (!*dest)
2540 dest = ".";
2541 path = bltinlookup("CDPATH");
2542 if (!path) {
2543 step6:
2544 step7:
2545 p = dest;
2546 goto docd;
2547 }
2548 do {
2549 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002550 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002551 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2552 if (c && c != ':')
2553 flags |= CD_PRINT;
2554 docd:
2555 if (!docd(p, flags))
2556 goto out;
2557 break;
2558 }
2559 } while (path);
2560 ash_msg_and_raise_error("can't cd to %s", dest);
2561 /* NOTREACHED */
2562 out:
2563 if (flags & CD_PRINT)
2564 out1fmt(snlfmt, curdir);
2565 return 0;
2566}
2567
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002568static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002569pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002570{
2571 int flags;
2572 const char *dir = curdir;
2573
2574 flags = cdopt();
2575 if (flags) {
2576 if (physdir == nullstr)
2577 setpwd(dir, 0);
2578 dir = physdir;
2579 }
2580 out1fmt(snlfmt, dir);
2581 return 0;
2582}
2583
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002584
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002585/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002586
Denis Vlasenko834dee72008-10-07 09:18:30 +00002587
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002588#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002589/* buffer for top level input file */
2590#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002591
Eric Andersenc470f442003-07-28 09:56:35 +00002592/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593#define CWORD 0 /* character is nothing special */
2594#define CNL 1 /* newline character */
2595#define CBACK 2 /* a backslash character */
2596#define CSQUOTE 3 /* single quote */
2597#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002598#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002599#define CBQUOTE 6 /* backwards single quote */
2600#define CVAR 7 /* a dollar sign */
2601#define CENDVAR 8 /* a '}' character */
2602#define CLP 9 /* a left paren in arithmetic */
2603#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002604#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002605#define CCTL 12 /* like CWORD, except it must be escaped */
2606#define CSPCL 13 /* these terminate a word */
2607#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002608
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002609#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002610#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002611# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002612#endif
2613
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002614#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002615
Mike Frysinger98c52642009-04-02 10:02:37 +00002616#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002617# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002618#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002619# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002621static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622#if ENABLE_ASH_ALIAS
2623 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2624#endif
2625 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2626 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2627 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2628 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2629 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2630 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2631 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2632 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2633 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2634 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2635 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002636#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002637 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2638 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2639 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2640#endif
2641#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002642};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002643/* Constants below must match table above */
2644enum {
2645#if ENABLE_ASH_ALIAS
2646 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2647#endif
2648 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2649 CNL_CNL_CNL_CNL , /* 2 */
2650 CWORD_CCTL_CCTL_CWORD , /* 3 */
2651 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2652 CVAR_CVAR_CWORD_CVAR , /* 5 */
2653 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2654 CSPCL_CWORD_CWORD_CLP , /* 7 */
2655 CSPCL_CWORD_CWORD_CRP , /* 8 */
2656 CBACK_CBACK_CCTL_CBACK , /* 9 */
2657 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2658 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2659 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2660 CWORD_CWORD_CWORD_CWORD , /* 13 */
2661 CCTL_CCTL_CCTL_CCTL , /* 14 */
2662};
Eric Andersen2870d962001-07-02 17:27:21 +00002663
Denys Vlasenkocd716832009-11-28 22:14:02 +01002664/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2665 * caller must ensure proper cast on it if c is *char_ptr!
2666 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002667/* Values for syntax param */
2668#define BASESYNTAX 0 /* not in quotes */
2669#define DQSYNTAX 1 /* in double quotes */
2670#define SQSYNTAX 2 /* in single quotes */
2671#define ARISYNTAX 3 /* in arithmetic */
2672#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002673
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002674#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002675
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002676static int
2677SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002678{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002679 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002680# if ENABLE_ASH_ALIAS
2681 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002682 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2683 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2684 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2685 11, 3 /* "}~" */
2686 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002687# else
2688 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002689 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2690 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2691 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2692 10, 2 /* "}~" */
2693 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002694# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002695 const char *s;
2696 int indx;
2697
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002698 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002699 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002700# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002702 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002703 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002704# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002706 /* Cast is purely for paranoia here,
2707 * just in case someone passed signed char to us */
2708 if ((unsigned char)c >= CTL_FIRST
2709 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002710 ) {
2711 return CCTL;
2712 }
2713 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002714 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002715 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002716 indx = syntax_index_table[s - spec_symbls];
2717 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002718 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002719}
2720
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002721#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002722
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002723static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002724 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002725 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2735 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2736 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2758 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2759 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2760 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2761 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2762 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2764 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2765 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2766 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2767 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2770 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2772 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2785 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2786 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2817 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2818 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2822 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2850 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2851 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2852 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2853 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2855 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2856 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2857 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2858 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2859 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2860 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2861 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2862 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002981 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002982# if ENABLE_ASH_ALIAS
2983 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2984# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002985};
2986
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002987# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002988
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002989#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002990
Eric Andersen2870d962001-07-02 17:27:21 +00002991
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002992/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002993
Denis Vlasenko131ae172007-02-18 13:00:19 +00002994#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002995
2996#define ALIASINUSE 1
2997#define ALIASDEAD 2
2998
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00002999struct alias {
3000 struct alias *next;
3001 char *name;
3002 char *val;
3003 int flag;
3004};
3005
Denis Vlasenko01631112007-12-16 17:20:38 +00003006
3007static struct alias **atab; // [ATABSIZE];
3008#define INIT_G_alias() do { \
3009 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3010} while (0)
3011
Eric Andersen2870d962001-07-02 17:27:21 +00003012
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003013static struct alias **
3014__lookupalias(const char *name) {
3015 unsigned int hashval;
3016 struct alias **app;
3017 const char *p;
3018 unsigned int ch;
3019
3020 p = name;
3021
3022 ch = (unsigned char)*p;
3023 hashval = ch << 4;
3024 while (ch) {
3025 hashval += ch;
3026 ch = (unsigned char)*++p;
3027 }
3028 app = &atab[hashval % ATABSIZE];
3029
3030 for (; *app; app = &(*app)->next) {
3031 if (strcmp(name, (*app)->name) == 0) {
3032 break;
3033 }
3034 }
3035
3036 return app;
3037}
3038
3039static struct alias *
3040lookupalias(const char *name, int check)
3041{
3042 struct alias *ap = *__lookupalias(name);
3043
3044 if (check && ap && (ap->flag & ALIASINUSE))
3045 return NULL;
3046 return ap;
3047}
3048
3049static struct alias *
3050freealias(struct alias *ap)
3051{
3052 struct alias *next;
3053
3054 if (ap->flag & ALIASINUSE) {
3055 ap->flag |= ALIASDEAD;
3056 return ap;
3057 }
3058
3059 next = ap->next;
3060 free(ap->name);
3061 free(ap->val);
3062 free(ap);
3063 return next;
3064}
Eric Andersencb57d552001-06-28 07:25:16 +00003065
Eric Andersenc470f442003-07-28 09:56:35 +00003066static void
3067setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003068{
3069 struct alias *ap, **app;
3070
3071 app = __lookupalias(name);
3072 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003073 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003074 if (ap) {
3075 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003076 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003077 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003078 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003079 ap->flag &= ~ALIASDEAD;
3080 } else {
3081 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003082 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003083 ap->name = ckstrdup(name);
3084 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003085 /*ap->flag = 0; - ckzalloc did it */
3086 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003087 *app = ap;
3088 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003089 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003090}
3091
Eric Andersenc470f442003-07-28 09:56:35 +00003092static int
3093unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003094{
Eric Andersencb57d552001-06-28 07:25:16 +00003095 struct alias **app;
3096
3097 app = __lookupalias(name);
3098
3099 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003100 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003101 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003102 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003103 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003104 }
3105
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003106 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003107}
3108
Eric Andersenc470f442003-07-28 09:56:35 +00003109static void
3110rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003111{
Eric Andersencb57d552001-06-28 07:25:16 +00003112 struct alias *ap, **app;
3113 int i;
3114
Denis Vlasenkob012b102007-02-19 22:43:01 +00003115 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003116 for (i = 0; i < ATABSIZE; i++) {
3117 app = &atab[i];
3118 for (ap = *app; ap; ap = *app) {
3119 *app = freealias(*app);
3120 if (ap == *app) {
3121 app = &ap->next;
3122 }
3123 }
3124 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003125 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003126}
3127
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003128static void
3129printalias(const struct alias *ap)
3130{
3131 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3132}
3133
Eric Andersencb57d552001-06-28 07:25:16 +00003134/*
3135 * TODO - sort output
3136 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003137static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003138aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003139{
3140 char *n, *v;
3141 int ret = 0;
3142 struct alias *ap;
3143
Denis Vlasenko68404f12008-03-17 09:00:54 +00003144 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003145 int i;
3146
Denis Vlasenko68404f12008-03-17 09:00:54 +00003147 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003148 for (ap = atab[i]; ap; ap = ap->next) {
3149 printalias(ap);
3150 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003151 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003152 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003153 }
3154 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003155 v = strchr(n+1, '=');
3156 if (v == NULL) { /* n+1: funny ksh stuff */
3157 ap = *__lookupalias(n);
3158 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003159 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003160 ret = 1;
3161 } else
3162 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003163 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003164 *v++ = '\0';
3165 setalias(n, v);
3166 }
3167 }
3168
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003169 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003170}
3171
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003172static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003173unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003174{
3175 int i;
3176
3177 while ((i = nextopt("a")) != '\0') {
3178 if (i == 'a') {
3179 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003180 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003181 }
3182 }
3183 for (i = 0; *argptr; argptr++) {
3184 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003185 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003186 i = 1;
3187 }
3188 }
3189
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003190 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003191}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003192
Denis Vlasenko131ae172007-02-18 13:00:19 +00003193#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003194
Eric Andersenc470f442003-07-28 09:56:35 +00003195
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003196/* ============ jobs.c */
3197
3198/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003199#define FORK_FG 0
3200#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003201#define FORK_NOJOB 2
3202
3203/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003204#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3205#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3206#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003207
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003208/*
3209 * A job structure contains information about a job. A job is either a
3210 * single process or a set of processes contained in a pipeline. In the
3211 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3212 * array of pids.
3213 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003214struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003215 pid_t ps_pid; /* process id */
3216 int ps_status; /* last process status from wait() */
3217 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003218};
3219
3220struct job {
3221 struct procstat ps0; /* status of process */
3222 struct procstat *ps; /* status or processes when more than one */
3223#if JOBS
3224 int stopstatus; /* status of a stopped job */
3225#endif
3226 uint32_t
3227 nprocs: 16, /* number of processes */
3228 state: 8,
3229#define JOBRUNNING 0 /* at least one proc running */
3230#define JOBSTOPPED 1 /* all procs are stopped */
3231#define JOBDONE 2 /* all procs are completed */
3232#if JOBS
3233 sigint: 1, /* job was killed by SIGINT */
3234 jobctl: 1, /* job running under job control */
3235#endif
3236 waited: 1, /* true if this entry has been waited for */
3237 used: 1, /* true if this entry is in used */
3238 changed: 1; /* true if status has changed */
3239 struct job *prev_job; /* previous job */
3240};
3241
Denis Vlasenko68404f12008-03-17 09:00:54 +00003242static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003243static int forkshell(struct job *, union node *, int);
3244static int waitforjob(struct job *);
3245
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003246#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003247enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003248#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003250static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003251static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252#endif
3253
3254/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003255 * Ignore a signal.
3256 */
3257static void
3258ignoresig(int signo)
3259{
3260 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3261 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3262 /* No, need to do it */
3263 signal(signo, SIG_IGN);
3264 }
3265 sigmode[signo - 1] = S_HARD_IGN;
3266}
3267
3268/*
3269 * Signal handler. Only one usage site - in setsignal()
3270 */
3271static void
3272onsig(int signo)
3273{
3274 gotsig[signo - 1] = 1;
3275
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003276 if (signo == SIGINT && !trap[SIGINT]) {
3277 if (!suppress_int) {
3278 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003279 raise_interrupt(); /* does not return */
3280 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003281 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003283 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003284 }
3285}
3286
3287/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003288 * Set the signal handler for the specified signal. The routine figures
3289 * out what it should be set to.
3290 */
3291static void
3292setsignal(int signo)
3293{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003294 char *t;
3295 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003296 struct sigaction act;
3297
3298 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003299 new_act = S_DFL;
3300 if (t != NULL) { /* trap for this sig is set */
3301 new_act = S_CATCH;
3302 if (t[0] == '\0') /* trap is "": ignore this sig */
3303 new_act = S_IGN;
3304 }
3305
3306 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003307 switch (signo) {
3308 case SIGINT:
3309 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003310 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003311 break;
3312 case SIGQUIT:
3313#if DEBUG
3314 if (debug)
3315 break;
3316#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003317 /* man bash:
3318 * "In all cases, bash ignores SIGQUIT. Non-builtin
3319 * commands run by bash have signal handlers
3320 * set to the values inherited by the shell
3321 * from its parent". */
3322 new_act = S_IGN;
3323 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003324 case SIGTERM:
3325 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003326 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 break;
3328#if JOBS
3329 case SIGTSTP:
3330 case SIGTTOU:
3331 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003332 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003333 break;
3334#endif
3335 }
3336 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003337//TODO: if !rootshell, we reset SIGQUIT to DFL,
3338//whereas we have to restore it to what shell got on entry
3339//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003340
3341 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003342 cur_act = *t;
3343 if (cur_act == 0) {
3344 /* current setting is not yet known */
3345 if (sigaction(signo, NULL, &act)) {
3346 /* pretend it worked; maybe we should give a warning,
3347 * but other shells don't. We don't alter sigmode,
3348 * so we retry every time.
3349 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003350 return;
3351 }
3352 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003353 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003354 if (mflag
3355 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3356 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003357 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003358 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 }
3360 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003363
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003364 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003365 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003366 case S_CATCH:
3367 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3369 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003370 break;
3371 case S_IGN:
3372 act.sa_handler = SIG_IGN;
3373 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003374 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003375 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003376
3377 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003378}
3379
3380/* mode flags for set_curjob */
3381#define CUR_DELETE 2
3382#define CUR_RUNNING 1
3383#define CUR_STOPPED 0
3384
3385/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003386#define DOWAIT_NONBLOCK WNOHANG
3387#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003388
3389#if JOBS
3390/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003391static int initialpgrp; //references:2
3392static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003393#endif
3394/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003395static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003397static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003399static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003400/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003401static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402
3403static void
3404set_curjob(struct job *jp, unsigned mode)
3405{
3406 struct job *jp1;
3407 struct job **jpp, **curp;
3408
3409 /* first remove from list */
3410 jpp = curp = &curjob;
3411 do {
3412 jp1 = *jpp;
3413 if (jp1 == jp)
3414 break;
3415 jpp = &jp1->prev_job;
3416 } while (1);
3417 *jpp = jp1->prev_job;
3418
3419 /* Then re-insert in correct position */
3420 jpp = curp;
3421 switch (mode) {
3422 default:
3423#if DEBUG
3424 abort();
3425#endif
3426 case CUR_DELETE:
3427 /* job being deleted */
3428 break;
3429 case CUR_RUNNING:
3430 /* newly created job or backgrounded job,
3431 put after all stopped jobs. */
3432 do {
3433 jp1 = *jpp;
3434#if JOBS
3435 if (!jp1 || jp1->state != JOBSTOPPED)
3436#endif
3437 break;
3438 jpp = &jp1->prev_job;
3439 } while (1);
3440 /* FALLTHROUGH */
3441#if JOBS
3442 case CUR_STOPPED:
3443#endif
3444 /* newly stopped job - becomes curjob */
3445 jp->prev_job = *jpp;
3446 *jpp = jp;
3447 break;
3448 }
3449}
3450
3451#if JOBS || DEBUG
3452static int
3453jobno(const struct job *jp)
3454{
3455 return jp - jobtab + 1;
3456}
3457#endif
3458
3459/*
3460 * Convert a job name to a job structure.
3461 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003462#if !JOBS
3463#define getjob(name, getctl) getjob(name)
3464#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003465static struct job *
3466getjob(const char *name, int getctl)
3467{
3468 struct job *jp;
3469 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003470 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003471 unsigned num;
3472 int c;
3473 const char *p;
3474 char *(*match)(const char *, const char *);
3475
3476 jp = curjob;
3477 p = name;
3478 if (!p)
3479 goto currentjob;
3480
3481 if (*p != '%')
3482 goto err;
3483
3484 c = *++p;
3485 if (!c)
3486 goto currentjob;
3487
3488 if (!p[1]) {
3489 if (c == '+' || c == '%') {
3490 currentjob:
3491 err_msg = "No current job";
3492 goto check;
3493 }
3494 if (c == '-') {
3495 if (jp)
3496 jp = jp->prev_job;
3497 err_msg = "No previous job";
3498 check:
3499 if (!jp)
3500 goto err;
3501 goto gotit;
3502 }
3503 }
3504
3505 if (is_number(p)) {
3506 num = atoi(p);
3507 if (num < njobs) {
3508 jp = jobtab + num - 1;
3509 if (jp->used)
3510 goto gotit;
3511 goto err;
3512 }
3513 }
3514
3515 match = prefix;
3516 if (*p == '?') {
3517 match = strstr;
3518 p++;
3519 }
3520
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003521 found = NULL;
3522 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003523 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003524 if (found)
3525 goto err;
3526 found = jp;
3527 err_msg = "%s: ambiguous";
3528 }
3529 jp = jp->prev_job;
3530 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003531 if (!found)
3532 goto err;
3533 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003534
3535 gotit:
3536#if JOBS
3537 err_msg = "job %s not created under job control";
3538 if (getctl && jp->jobctl == 0)
3539 goto err;
3540#endif
3541 return jp;
3542 err:
3543 ash_msg_and_raise_error(err_msg, name);
3544}
3545
3546/*
3547 * Mark a job structure as unused.
3548 */
3549static void
3550freejob(struct job *jp)
3551{
3552 struct procstat *ps;
3553 int i;
3554
3555 INT_OFF;
3556 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003557 if (ps->ps_cmd != nullstr)
3558 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003559 }
3560 if (jp->ps != &jp->ps0)
3561 free(jp->ps);
3562 jp->used = 0;
3563 set_curjob(jp, CUR_DELETE);
3564 INT_ON;
3565}
3566
3567#if JOBS
3568static void
3569xtcsetpgrp(int fd, pid_t pgrp)
3570{
3571 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003572 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003573}
3574
3575/*
3576 * Turn job control on and off.
3577 *
3578 * Note: This code assumes that the third arg to ioctl is a character
3579 * pointer, which is true on Berkeley systems but not System V. Since
3580 * System V doesn't have job control yet, this isn't a problem now.
3581 *
3582 * Called with interrupts off.
3583 */
3584static void
3585setjobctl(int on)
3586{
3587 int fd;
3588 int pgrp;
3589
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003590 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003591 return;
3592 if (on) {
3593 int ofd;
3594 ofd = fd = open(_PATH_TTY, O_RDWR);
3595 if (fd < 0) {
3596 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3597 * That sometimes helps to acquire controlling tty.
3598 * Obviously, a workaround for bugs when someone
3599 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003600 fd = 2;
3601 while (!isatty(fd))
3602 if (--fd < 0)
3603 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003604 }
3605 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003606 if (ofd >= 0)
3607 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003608 if (fd < 0)
3609 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003610 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003611 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003612 do { /* while we are in the background */
3613 pgrp = tcgetpgrp(fd);
3614 if (pgrp < 0) {
3615 out:
3616 ash_msg("can't access tty; job control turned off");
3617 mflag = on = 0;
3618 goto close;
3619 }
3620 if (pgrp == getpgrp())
3621 break;
3622 killpg(0, SIGTTIN);
3623 } while (1);
3624 initialpgrp = pgrp;
3625
3626 setsignal(SIGTSTP);
3627 setsignal(SIGTTOU);
3628 setsignal(SIGTTIN);
3629 pgrp = rootpid;
3630 setpgid(0, pgrp);
3631 xtcsetpgrp(fd, pgrp);
3632 } else {
3633 /* turning job control off */
3634 fd = ttyfd;
3635 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003636 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003637 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003638 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003639 setpgid(0, pgrp);
3640 setsignal(SIGTSTP);
3641 setsignal(SIGTTOU);
3642 setsignal(SIGTTIN);
3643 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003644 if (fd >= 0)
3645 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003646 fd = -1;
3647 }
3648 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003649 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003650}
3651
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003652static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653killcmd(int argc, char **argv)
3654{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003655 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003656 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003657 do {
3658 if (argv[i][0] == '%') {
3659 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003660 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003661 /* Enough space for ' -NNN<nul>' */
3662 argv[i] = alloca(sizeof(int)*3 + 3);
3663 /* kill_main has matching code to expect
3664 * leading space. Needed to not confuse
3665 * negative pids with "kill -SIGNAL_NO" syntax */
3666 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003667 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003668 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003669 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003670 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003671}
3672
3673static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003674showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003675{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003676 struct procstat *ps;
3677 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678
Denys Vlasenko285ad152009-12-04 23:02:27 +01003679 psend = jp->ps + jp->nprocs;
3680 for (ps = jp->ps + 1; ps < psend; ps++)
3681 printf(" | %s", ps->ps_cmd);
3682 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003683 flush_stdout_stderr();
3684}
3685
3686
3687static int
3688restartjob(struct job *jp, int mode)
3689{
3690 struct procstat *ps;
3691 int i;
3692 int status;
3693 pid_t pgid;
3694
3695 INT_OFF;
3696 if (jp->state == JOBDONE)
3697 goto out;
3698 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003699 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003700 if (mode == FORK_FG)
3701 xtcsetpgrp(ttyfd, pgid);
3702 killpg(pgid, SIGCONT);
3703 ps = jp->ps;
3704 i = jp->nprocs;
3705 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003706 if (WIFSTOPPED(ps->ps_status)) {
3707 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003708 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003709 ps++;
3710 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 out:
3712 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3713 INT_ON;
3714 return status;
3715}
3716
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003717static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003718fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003719{
3720 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003721 int mode;
3722 int retval;
3723
3724 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3725 nextopt(nullstr);
3726 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003727 do {
3728 jp = getjob(*argv, 1);
3729 if (mode == FORK_BG) {
3730 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003731 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003732 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003733 out1str(jp->ps[0].ps_cmd);
3734 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003735 retval = restartjob(jp, mode);
3736 } while (*argv && *++argv);
3737 return retval;
3738}
3739#endif
3740
3741static int
3742sprint_status(char *s, int status, int sigonly)
3743{
3744 int col;
3745 int st;
3746
3747 col = 0;
3748 if (!WIFEXITED(status)) {
3749#if JOBS
3750 if (WIFSTOPPED(status))
3751 st = WSTOPSIG(status);
3752 else
3753#endif
3754 st = WTERMSIG(status);
3755 if (sigonly) {
3756 if (st == SIGINT || st == SIGPIPE)
3757 goto out;
3758#if JOBS
3759 if (WIFSTOPPED(status))
3760 goto out;
3761#endif
3762 }
3763 st &= 0x7f;
3764 col = fmtstr(s, 32, strsignal(st));
3765 if (WCOREDUMP(status)) {
3766 col += fmtstr(s + col, 16, " (core dumped)");
3767 }
3768 } else if (!sigonly) {
3769 st = WEXITSTATUS(status);
3770 if (st)
3771 col = fmtstr(s, 16, "Done(%d)", st);
3772 else
3773 col = fmtstr(s, 16, "Done");
3774 }
3775 out:
3776 return col;
3777}
3778
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003779static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003780dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003781{
3782 int pid;
3783 int status;
3784 struct job *jp;
3785 struct job *thisjob;
3786 int state;
3787
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003788 TRACE(("dowait(0x%x) called\n", wait_flags));
3789
3790 /* Do a wait system call. If job control is compiled in, we accept
3791 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3792 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003793 if (doing_jobctl)
3794 wait_flags |= WUNTRACED;
3795 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003796 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3797 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003798 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003799 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003800
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003801 INT_OFF;
3802 thisjob = NULL;
3803 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003804 struct procstat *ps;
3805 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003806 if (jp->state == JOBDONE)
3807 continue;
3808 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003809 ps = jp->ps;
3810 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003811 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003813 TRACE(("Job %d: changing status of proc %d "
3814 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 jobno(jp), pid, ps->ps_status, status));
3816 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003817 thisjob = jp;
3818 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003819 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003820 state = JOBRUNNING;
3821#if JOBS
3822 if (state == JOBRUNNING)
3823 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003824 if (WIFSTOPPED(ps->ps_status)) {
3825 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003826 state = JOBSTOPPED;
3827 }
3828#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003829 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003830 if (thisjob)
3831 goto gotjob;
3832 }
3833#if JOBS
3834 if (!WIFSTOPPED(status))
3835#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003836 jobless--;
3837 goto out;
3838
3839 gotjob:
3840 if (state != JOBRUNNING) {
3841 thisjob->changed = 1;
3842
3843 if (thisjob->state != state) {
3844 TRACE(("Job %d: changing state from %d to %d\n",
3845 jobno(thisjob), thisjob->state, state));
3846 thisjob->state = state;
3847#if JOBS
3848 if (state == JOBSTOPPED) {
3849 set_curjob(thisjob, CUR_STOPPED);
3850 }
3851#endif
3852 }
3853 }
3854
3855 out:
3856 INT_ON;
3857
3858 if (thisjob && thisjob == job) {
3859 char s[48 + 1];
3860 int len;
3861
3862 len = sprint_status(s, status, 1);
3863 if (len) {
3864 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003865 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003866 out2str(s);
3867 }
3868 }
3869 return pid;
3870}
3871
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003872static int
3873blocking_wait_with_raise_on_sig(struct job *job)
3874{
3875 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003876 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003877 raise_exception(EXSIG);
3878 return pid;
3879}
3880
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003881#if JOBS
3882static void
3883showjob(FILE *out, struct job *jp, int mode)
3884{
3885 struct procstat *ps;
3886 struct procstat *psend;
3887 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003888 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003889 char s[80];
3890
3891 ps = jp->ps;
3892
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003893 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003894 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003895 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003896 return;
3897 }
3898
3899 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003900 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003901
3902 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003903 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003905 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003906
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003907 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003908 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
3910 psend = ps + jp->nprocs;
3911
3912 if (jp->state == JOBRUNNING) {
3913 strcpy(s + col, "Running");
3914 col += sizeof("Running") - 1;
3915 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003916 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003917 if (jp->state == JOBSTOPPED)
3918 status = jp->stopstatus;
3919 col += sprint_status(s + col, status, 0);
3920 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003921 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003922
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003923 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3924 * or prints several "PID | <cmdN>" lines,
3925 * depending on SHOW_PIDS bit.
3926 * We do not print status of individual processes
3927 * between PID and <cmdN>. bash does it, but not very well:
3928 * first line shows overall job status, not process status,
3929 * making it impossible to know 1st process status.
3930 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003931 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003932 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003933 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003934 s[0] = '\0';
3935 col = 33;
3936 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003937 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003938 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003939 fprintf(out, "%s%*c%s%s",
3940 s,
3941 33 - col >= 0 ? 33 - col : 0, ' ',
3942 ps == jp->ps ? "" : "| ",
3943 ps->ps_cmd
3944 );
3945 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003946 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003947
3948 jp->changed = 0;
3949
3950 if (jp->state == JOBDONE) {
3951 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3952 freejob(jp);
3953 }
3954}
3955
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003956/*
3957 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3958 * statuses have changed since the last call to showjobs.
3959 */
3960static void
3961showjobs(FILE *out, int mode)
3962{
3963 struct job *jp;
3964
Denys Vlasenko883cea42009-07-11 15:31:59 +02003965 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003966
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003967 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003968 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969 continue;
3970
3971 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003972 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003973 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003974 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003975 }
3976}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003978static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003979jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980{
3981 int mode, m;
3982
3983 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003984 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003985 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003986 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003987 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003988 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003989 }
3990
3991 argv = argptr;
3992 if (*argv) {
3993 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003994 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003995 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003996 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003997 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003998 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003999
4000 return 0;
4001}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002#endif /* JOBS */
4003
Michael Abbott359da5e2009-12-04 23:03:29 +01004004/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005static int
4006getstatus(struct job *job)
4007{
4008 int status;
4009 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004010 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011
Michael Abbott359da5e2009-12-04 23:03:29 +01004012 /* Fetch last member's status */
4013 ps = job->ps + job->nprocs - 1;
4014 status = ps->ps_status;
4015 if (pipefail) {
4016 /* "set -o pipefail" mode: use last _nonzero_ status */
4017 while (status == 0 && --ps >= job->ps)
4018 status = ps->ps_status;
4019 }
4020
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004021 retval = WEXITSTATUS(status);
4022 if (!WIFEXITED(status)) {
4023#if JOBS
4024 retval = WSTOPSIG(status);
4025 if (!WIFSTOPPED(status))
4026#endif
4027 {
4028 /* XXX: limits number of signals */
4029 retval = WTERMSIG(status);
4030#if JOBS
4031 if (retval == SIGINT)
4032 job->sigint = 1;
4033#endif
4034 }
4035 retval += 128;
4036 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004037 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004038 jobno(job), job->nprocs, status, retval));
4039 return retval;
4040}
4041
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004042static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004043waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004044{
4045 struct job *job;
4046 int retval;
4047 struct job *jp;
4048
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004049 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004050 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004051
4052 nextopt(nullstr);
4053 retval = 0;
4054
4055 argv = argptr;
4056 if (!*argv) {
4057 /* wait for all jobs */
4058 for (;;) {
4059 jp = curjob;
4060 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004061 if (!jp) /* no running procs */
4062 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004063 if (jp->state == JOBRUNNING)
4064 break;
4065 jp->waited = 1;
4066 jp = jp->prev_job;
4067 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004068 /* man bash:
4069 * "When bash is waiting for an asynchronous command via
4070 * the wait builtin, the reception of a signal for which a trap
4071 * has been set will cause the wait builtin to return immediately
4072 * with an exit status greater than 128, immediately after which
4073 * the trap is executed."
4074 * Do we do it that way? */
4075 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076 }
4077 }
4078
4079 retval = 127;
4080 do {
4081 if (**argv != '%') {
4082 pid_t pid = number(*argv);
4083 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004084 while (1) {
4085 if (!job)
4086 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004087 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004088 break;
4089 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004090 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004091 } else
4092 job = getjob(*argv, 0);
4093 /* loop until process terminated or stopped */
4094 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004095 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004096 job->waited = 1;
4097 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004098 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004099 } while (*++argv);
4100
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004101 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004102 return retval;
4103}
4104
4105static struct job *
4106growjobtab(void)
4107{
4108 size_t len;
4109 ptrdiff_t offset;
4110 struct job *jp, *jq;
4111
4112 len = njobs * sizeof(*jp);
4113 jq = jobtab;
4114 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4115
4116 offset = (char *)jp - (char *)jq;
4117 if (offset) {
4118 /* Relocate pointers */
4119 size_t l = len;
4120
4121 jq = (struct job *)((char *)jq + l);
4122 while (l) {
4123 l -= sizeof(*jp);
4124 jq--;
4125#define joff(p) ((struct job *)((char *)(p) + l))
4126#define jmove(p) (p) = (void *)((char *)(p) + offset)
4127 if (joff(jp)->ps == &jq->ps0)
4128 jmove(joff(jp)->ps);
4129 if (joff(jp)->prev_job)
4130 jmove(joff(jp)->prev_job);
4131 }
4132 if (curjob)
4133 jmove(curjob);
4134#undef joff
4135#undef jmove
4136 }
4137
4138 njobs += 4;
4139 jobtab = jp;
4140 jp = (struct job *)((char *)jp + len);
4141 jq = jp + 3;
4142 do {
4143 jq->used = 0;
4144 } while (--jq >= jp);
4145 return jp;
4146}
4147
4148/*
4149 * Return a new job structure.
4150 * Called with interrupts off.
4151 */
4152static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004153makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004154{
4155 int i;
4156 struct job *jp;
4157
4158 for (i = njobs, jp = jobtab; ; jp++) {
4159 if (--i < 0) {
4160 jp = growjobtab();
4161 break;
4162 }
4163 if (jp->used == 0)
4164 break;
4165 if (jp->state != JOBDONE || !jp->waited)
4166 continue;
4167#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004168 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004169 continue;
4170#endif
4171 freejob(jp);
4172 break;
4173 }
4174 memset(jp, 0, sizeof(*jp));
4175#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004176 /* jp->jobctl is a bitfield.
4177 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004178 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004179 jp->jobctl = 1;
4180#endif
4181 jp->prev_job = curjob;
4182 curjob = jp;
4183 jp->used = 1;
4184 jp->ps = &jp->ps0;
4185 if (nprocs > 1) {
4186 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4187 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004188 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004189 jobno(jp)));
4190 return jp;
4191}
4192
4193#if JOBS
4194/*
4195 * Return a string identifying a command (to be printed by the
4196 * jobs command).
4197 */
4198static char *cmdnextc;
4199
4200static void
4201cmdputs(const char *s)
4202{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004203 static const char vstype[VSTYPE + 1][3] = {
4204 "", "}", "-", "+", "?", "=",
4205 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004206 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004207 };
4208
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004209 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004210 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004211 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004212 unsigned char c;
4213 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004215
Denys Vlasenko46a14772009-12-10 21:27:13 +01004216 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4218 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004219 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004220 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221 switch (c) {
4222 case CTLESC:
4223 c = *p++;
4224 break;
4225 case CTLVAR:
4226 subtype = *p++;
4227 if ((subtype & VSTYPE) == VSLENGTH)
4228 str = "${#";
4229 else
4230 str = "${";
4231 if (!(subtype & VSQUOTE) == !(quoted & 1))
4232 goto dostr;
4233 quoted ^= 1;
4234 c = '"';
4235 break;
4236 case CTLENDVAR:
4237 str = "\"}" + !(quoted & 1);
4238 quoted >>= 1;
4239 subtype = 0;
4240 goto dostr;
4241 case CTLBACKQ:
4242 str = "$(...)";
4243 goto dostr;
4244 case CTLBACKQ+CTLQUOTE:
4245 str = "\"$(...)\"";
4246 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004247#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004248 case CTLARI:
4249 str = "$((";
4250 goto dostr;
4251 case CTLENDARI:
4252 str = "))";
4253 goto dostr;
4254#endif
4255 case CTLQUOTEMARK:
4256 quoted ^= 1;
4257 c = '"';
4258 break;
4259 case '=':
4260 if (subtype == 0)
4261 break;
4262 if ((subtype & VSTYPE) != VSNORMAL)
4263 quoted <<= 1;
4264 str = vstype[subtype & VSTYPE];
4265 if (subtype & VSNUL)
4266 c = ':';
4267 else
4268 goto checkstr;
4269 break;
4270 case '\'':
4271 case '\\':
4272 case '"':
4273 case '$':
4274 /* These can only happen inside quotes */
4275 cc[0] = c;
4276 str = cc;
4277 c = '\\';
4278 break;
4279 default:
4280 break;
4281 }
4282 USTPUTC(c, nextc);
4283 checkstr:
4284 if (!str)
4285 continue;
4286 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004287 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004288 USTPUTC(c, nextc);
4289 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004290 } /* while *p++ not NUL */
4291
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004292 if (quoted & 1) {
4293 USTPUTC('"', nextc);
4294 }
4295 *nextc = 0;
4296 cmdnextc = nextc;
4297}
4298
4299/* cmdtxt() and cmdlist() call each other */
4300static void cmdtxt(union node *n);
4301
4302static void
4303cmdlist(union node *np, int sep)
4304{
4305 for (; np; np = np->narg.next) {
4306 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004307 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004308 cmdtxt(np);
4309 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004310 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004311 }
4312}
4313
4314static void
4315cmdtxt(union node *n)
4316{
4317 union node *np;
4318 struct nodelist *lp;
4319 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004320
4321 if (!n)
4322 return;
4323 switch (n->type) {
4324 default:
4325#if DEBUG
4326 abort();
4327#endif
4328 case NPIPE:
4329 lp = n->npipe.cmdlist;
4330 for (;;) {
4331 cmdtxt(lp->n);
4332 lp = lp->next;
4333 if (!lp)
4334 break;
4335 cmdputs(" | ");
4336 }
4337 break;
4338 case NSEMI:
4339 p = "; ";
4340 goto binop;
4341 case NAND:
4342 p = " && ";
4343 goto binop;
4344 case NOR:
4345 p = " || ";
4346 binop:
4347 cmdtxt(n->nbinary.ch1);
4348 cmdputs(p);
4349 n = n->nbinary.ch2;
4350 goto donode;
4351 case NREDIR:
4352 case NBACKGND:
4353 n = n->nredir.n;
4354 goto donode;
4355 case NNOT:
4356 cmdputs("!");
4357 n = n->nnot.com;
4358 donode:
4359 cmdtxt(n);
4360 break;
4361 case NIF:
4362 cmdputs("if ");
4363 cmdtxt(n->nif.test);
4364 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004365 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004366 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004367 cmdputs("; else ");
4368 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004369 } else {
4370 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004371 }
4372 p = "; fi";
4373 goto dotail;
4374 case NSUBSHELL:
4375 cmdputs("(");
4376 n = n->nredir.n;
4377 p = ")";
4378 goto dotail;
4379 case NWHILE:
4380 p = "while ";
4381 goto until;
4382 case NUNTIL:
4383 p = "until ";
4384 until:
4385 cmdputs(p);
4386 cmdtxt(n->nbinary.ch1);
4387 n = n->nbinary.ch2;
4388 p = "; done";
4389 dodo:
4390 cmdputs("; do ");
4391 dotail:
4392 cmdtxt(n);
4393 goto dotail2;
4394 case NFOR:
4395 cmdputs("for ");
4396 cmdputs(n->nfor.var);
4397 cmdputs(" in ");
4398 cmdlist(n->nfor.args, 1);
4399 n = n->nfor.body;
4400 p = "; done";
4401 goto dodo;
4402 case NDEFUN:
4403 cmdputs(n->narg.text);
4404 p = "() { ... }";
4405 goto dotail2;
4406 case NCMD:
4407 cmdlist(n->ncmd.args, 1);
4408 cmdlist(n->ncmd.redirect, 0);
4409 break;
4410 case NARG:
4411 p = n->narg.text;
4412 dotail2:
4413 cmdputs(p);
4414 break;
4415 case NHERE:
4416 case NXHERE:
4417 p = "<<...";
4418 goto dotail2;
4419 case NCASE:
4420 cmdputs("case ");
4421 cmdputs(n->ncase.expr->narg.text);
4422 cmdputs(" in ");
4423 for (np = n->ncase.cases; np; np = np->nclist.next) {
4424 cmdtxt(np->nclist.pattern);
4425 cmdputs(") ");
4426 cmdtxt(np->nclist.body);
4427 cmdputs(";; ");
4428 }
4429 p = "esac";
4430 goto dotail2;
4431 case NTO:
4432 p = ">";
4433 goto redir;
4434 case NCLOBBER:
4435 p = ">|";
4436 goto redir;
4437 case NAPPEND:
4438 p = ">>";
4439 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004440#if ENABLE_ASH_BASH_COMPAT
4441 case NTO2:
4442#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004443 case NTOFD:
4444 p = ">&";
4445 goto redir;
4446 case NFROM:
4447 p = "<";
4448 goto redir;
4449 case NFROMFD:
4450 p = "<&";
4451 goto redir;
4452 case NFROMTO:
4453 p = "<>";
4454 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004455 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004456 cmdputs(p);
4457 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004458 cmdputs(utoa(n->ndup.dupfd));
4459 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004460 }
4461 n = n->nfile.fname;
4462 goto donode;
4463 }
4464}
4465
4466static char *
4467commandtext(union node *n)
4468{
4469 char *name;
4470
4471 STARTSTACKSTR(cmdnextc);
4472 cmdtxt(n);
4473 name = stackblock();
4474 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4475 name, cmdnextc, cmdnextc));
4476 return ckstrdup(name);
4477}
4478#endif /* JOBS */
4479
4480/*
4481 * Fork off a subshell. If we are doing job control, give the subshell its
4482 * own process group. Jp is a job structure that the job is to be added to.
4483 * N is the command that will be evaluated by the child. Both jp and n may
4484 * be NULL. The mode parameter can be one of the following:
4485 * FORK_FG - Fork off a foreground process.
4486 * FORK_BG - Fork off a background process.
4487 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4488 * process group even if job control is on.
4489 *
4490 * When job control is turned off, background processes have their standard
4491 * input redirected to /dev/null (except for the second and later processes
4492 * in a pipeline).
4493 *
4494 * Called with interrupts off.
4495 */
4496/*
4497 * Clear traps on a fork.
4498 */
4499static void
4500clear_traps(void)
4501{
4502 char **tp;
4503
4504 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004505 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004506 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004507 if (trap_ptr == trap)
4508 free(*tp);
4509 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004510 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004511 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004512 setsignal(tp - trap);
4513 INT_ON;
4514 }
4515 }
4516}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004517
4518/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004519static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004520
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004521/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004522static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004523forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004524{
4525 int oldlvl;
4526
4527 TRACE(("Child shell %d\n", getpid()));
4528 oldlvl = shlvl;
4529 shlvl++;
4530
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004531 /* man bash: "Non-builtin commands run by bash have signal handlers
4532 * set to the values inherited by the shell from its parent".
4533 * Do we do it correctly? */
4534
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004535 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004536
4537 if (mode == FORK_NOJOB /* is it `xxx` ? */
4538 && n && n->type == NCMD /* is it single cmd? */
4539 /* && n->ncmd.args->type == NARG - always true? */
4540 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4541 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4542 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4543 ) {
4544 TRACE(("Trap hack\n"));
4545 /* Awful hack for `trap` or $(trap).
4546 *
4547 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4548 * contains an example where "trap" is executed in a subshell:
4549 *
4550 * save_traps=$(trap)
4551 * ...
4552 * eval "$save_traps"
4553 *
4554 * Standard does not say that "trap" in subshell shall print
4555 * parent shell's traps. It only says that its output
4556 * must have suitable form, but then, in the above example
4557 * (which is not supposed to be normative), it implies that.
4558 *
4559 * bash (and probably other shell) does implement it
4560 * (traps are reset to defaults, but "trap" still shows them),
4561 * but as a result, "trap" logic is hopelessly messed up:
4562 *
4563 * # trap
4564 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4565 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4566 * # true | trap <--- trap is in subshell - no output (ditto)
4567 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4568 * trap -- 'echo Ho' SIGWINCH
4569 * # echo `(trap)` <--- in subshell in subshell - output
4570 * trap -- 'echo Ho' SIGWINCH
4571 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4572 * trap -- 'echo Ho' SIGWINCH
4573 *
4574 * The rules when to forget and when to not forget traps
4575 * get really complex and nonsensical.
4576 *
4577 * Our solution: ONLY bare $(trap) or `trap` is special.
4578 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004579 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004580 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004581 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004582 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004583 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004584#if JOBS
4585 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004586 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004587 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4588 pid_t pgrp;
4589
4590 if (jp->nprocs == 0)
4591 pgrp = getpid();
4592 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004593 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004594 /* this can fail because we are doing it in the parent also */
4595 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004596 if (mode == FORK_FG)
4597 xtcsetpgrp(ttyfd, pgrp);
4598 setsignal(SIGTSTP);
4599 setsignal(SIGTTOU);
4600 } else
4601#endif
4602 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004603 /* man bash: "When job control is not in effect,
4604 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004605 ignoresig(SIGINT);
4606 ignoresig(SIGQUIT);
4607 if (jp->nprocs == 0) {
4608 close(0);
4609 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004610 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 }
4612 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004613 if (!oldlvl) {
4614 if (iflag) { /* why if iflag only? */
4615 setsignal(SIGINT);
4616 setsignal(SIGTERM);
4617 }
4618 /* man bash:
4619 * "In all cases, bash ignores SIGQUIT. Non-builtin
4620 * commands run by bash have signal handlers
4621 * set to the values inherited by the shell
4622 * from its parent".
4623 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004624 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004625 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004626#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004627 if (n && n->type == NCMD
4628 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4629 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004630 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004631 /* "jobs": we do not want to clear job list for it,
4632 * instead we remove only _its_ own_ job from job list.
4633 * This makes "jobs .... | cat" more useful.
4634 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004635 freejob(curjob);
4636 return;
4637 }
4638#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004639 for (jp = curjob; jp; jp = jp->prev_job)
4640 freejob(jp);
4641 jobless = 0;
4642}
4643
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004644/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004645#if !JOBS
4646#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4647#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004648static void
4649forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4650{
4651 TRACE(("In parent shell: child = %d\n", pid));
4652 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004653 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4654 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004655 jobless++;
4656 return;
4657 }
4658#if JOBS
4659 if (mode != FORK_NOJOB && jp->jobctl) {
4660 int pgrp;
4661
4662 if (jp->nprocs == 0)
4663 pgrp = pid;
4664 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004665 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004666 /* This can fail because we are doing it in the child also */
4667 setpgid(pid, pgrp);
4668 }
4669#endif
4670 if (mode == FORK_BG) {
4671 backgndpid = pid; /* set $! */
4672 set_curjob(jp, CUR_RUNNING);
4673 }
4674 if (jp) {
4675 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004676 ps->ps_pid = pid;
4677 ps->ps_status = -1;
4678 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004679#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004680 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004681 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004682#endif
4683 }
4684}
4685
4686static int
4687forkshell(struct job *jp, union node *n, int mode)
4688{
4689 int pid;
4690
4691 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4692 pid = fork();
4693 if (pid < 0) {
4694 TRACE(("Fork failed, errno=%d", errno));
4695 if (jp)
4696 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004697 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004698 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004699 if (pid == 0) {
4700 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004701 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004702 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004703 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004704 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004705 return pid;
4706}
4707
4708/*
4709 * Wait for job to finish.
4710 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004711 * Under job control we have the problem that while a child process
4712 * is running interrupts generated by the user are sent to the child
4713 * but not to the shell. This means that an infinite loop started by
4714 * an interactive user may be hard to kill. With job control turned off,
4715 * an interactive user may place an interactive program inside a loop.
4716 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004717 * these interrupts to also abort the loop. The approach we take here
4718 * is to have the shell ignore interrupt signals while waiting for a
4719 * foreground process to terminate, and then send itself an interrupt
4720 * signal if the child process was terminated by an interrupt signal.
4721 * Unfortunately, some programs want to do a bit of cleanup and then
4722 * exit on interrupt; unless these processes terminate themselves by
4723 * sending a signal to themselves (instead of calling exit) they will
4724 * confuse this approach.
4725 *
4726 * Called with interrupts off.
4727 */
4728static int
4729waitforjob(struct job *jp)
4730{
4731 int st;
4732
4733 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004734
4735 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004736 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004737 /* In non-interactive shells, we _can_ get
4738 * a keyboard signal here and be EINTRed,
4739 * but we just loop back, waiting for command to complete.
4740 *
4741 * man bash:
4742 * "If bash is waiting for a command to complete and receives
4743 * a signal for which a trap has been set, the trap
4744 * will not be executed until the command completes."
4745 *
4746 * Reality is that even if trap is not set, bash
4747 * will not act on the signal until command completes.
4748 * Try this. sleep5intoff.c:
4749 * #include <signal.h>
4750 * #include <unistd.h>
4751 * int main() {
4752 * sigset_t set;
4753 * sigemptyset(&set);
4754 * sigaddset(&set, SIGINT);
4755 * sigaddset(&set, SIGQUIT);
4756 * sigprocmask(SIG_BLOCK, &set, NULL);
4757 * sleep(5);
4758 * return 0;
4759 * }
4760 * $ bash -c './sleep5intoff; echo hi'
4761 * ^C^C^C^C <--- pressing ^C once a second
4762 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004763 * $ bash -c './sleep5intoff; echo hi'
4764 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4765 * $ _
4766 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004767 dowait(DOWAIT_BLOCK, jp);
4768 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004769 INT_ON;
4770
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004771 st = getstatus(jp);
4772#if JOBS
4773 if (jp->jobctl) {
4774 xtcsetpgrp(ttyfd, rootpid);
4775 /*
4776 * This is truly gross.
4777 * If we're doing job control, then we did a TIOCSPGRP which
4778 * caused us (the shell) to no longer be in the controlling
4779 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4780 * intuit from the subprocess exit status whether a SIGINT
4781 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4782 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004783 if (jp->sigint) /* TODO: do the same with all signals */
4784 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004785 }
4786 if (jp->state == JOBDONE)
4787#endif
4788 freejob(jp);
4789 return st;
4790}
4791
4792/*
4793 * return 1 if there are stopped jobs, otherwise 0
4794 */
4795static int
4796stoppedjobs(void)
4797{
4798 struct job *jp;
4799 int retval;
4800
4801 retval = 0;
4802 if (job_warning)
4803 goto out;
4804 jp = curjob;
4805 if (jp && jp->state == JOBSTOPPED) {
4806 out2str("You have stopped jobs.\n");
4807 job_warning = 2;
4808 retval++;
4809 }
4810 out:
4811 return retval;
4812}
4813
4814
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004815/* ============ redir.c
4816 *
4817 * Code for dealing with input/output redirection.
4818 */
4819
4820#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004821#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004822
4823/*
4824 * Open a file in noclobber mode.
4825 * The code was copied from bash.
4826 */
4827static int
4828noclobberopen(const char *fname)
4829{
4830 int r, fd;
4831 struct stat finfo, finfo2;
4832
4833 /*
4834 * If the file exists and is a regular file, return an error
4835 * immediately.
4836 */
4837 r = stat(fname, &finfo);
4838 if (r == 0 && S_ISREG(finfo.st_mode)) {
4839 errno = EEXIST;
4840 return -1;
4841 }
4842
4843 /*
4844 * If the file was not present (r != 0), make sure we open it
4845 * exclusively so that if it is created before we open it, our open
4846 * will fail. Make sure that we do not truncate an existing file.
4847 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4848 * file was not a regular file, we leave O_EXCL off.
4849 */
4850 if (r != 0)
4851 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4852 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4853
4854 /* If the open failed, return the file descriptor right away. */
4855 if (fd < 0)
4856 return fd;
4857
4858 /*
4859 * OK, the open succeeded, but the file may have been changed from a
4860 * non-regular file to a regular file between the stat and the open.
4861 * We are assuming that the O_EXCL open handles the case where FILENAME
4862 * did not exist and is symlinked to an existing file between the stat
4863 * and open.
4864 */
4865
4866 /*
4867 * If we can open it and fstat the file descriptor, and neither check
4868 * revealed that it was a regular file, and the file has not been
4869 * replaced, return the file descriptor.
4870 */
4871 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4872 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4873 return fd;
4874
4875 /* The file has been replaced. badness. */
4876 close(fd);
4877 errno = EEXIST;
4878 return -1;
4879}
4880
4881/*
4882 * Handle here documents. Normally we fork off a process to write the
4883 * data to a pipe. If the document is short, we can stuff the data in
4884 * the pipe without forking.
4885 */
4886/* openhere needs this forward reference */
4887static void expandhere(union node *arg, int fd);
4888static int
4889openhere(union node *redir)
4890{
4891 int pip[2];
4892 size_t len = 0;
4893
4894 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004895 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004896 if (redir->type == NHERE) {
4897 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004898 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004899 full_write(pip[1], redir->nhere.doc->narg.text, len);
4900 goto out;
4901 }
4902 }
4903 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004904 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004905 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004906 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4907 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4908 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4909 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004910 signal(SIGPIPE, SIG_DFL);
4911 if (redir->type == NHERE)
4912 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004913 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004914 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004915 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004916 }
4917 out:
4918 close(pip[1]);
4919 return pip[0];
4920}
4921
4922static int
4923openredirect(union node *redir)
4924{
4925 char *fname;
4926 int f;
4927
4928 switch (redir->nfile.type) {
4929 case NFROM:
4930 fname = redir->nfile.expfname;
4931 f = open(fname, O_RDONLY);
4932 if (f < 0)
4933 goto eopen;
4934 break;
4935 case NFROMTO:
4936 fname = redir->nfile.expfname;
4937 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4938 if (f < 0)
4939 goto ecreate;
4940 break;
4941 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004942#if ENABLE_ASH_BASH_COMPAT
4943 case NTO2:
4944#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004945 /* Take care of noclobber mode. */
4946 if (Cflag) {
4947 fname = redir->nfile.expfname;
4948 f = noclobberopen(fname);
4949 if (f < 0)
4950 goto ecreate;
4951 break;
4952 }
4953 /* FALLTHROUGH */
4954 case NCLOBBER:
4955 fname = redir->nfile.expfname;
4956 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4957 if (f < 0)
4958 goto ecreate;
4959 break;
4960 case NAPPEND:
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4963 if (f < 0)
4964 goto ecreate;
4965 break;
4966 default:
4967#if DEBUG
4968 abort();
4969#endif
4970 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004971/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004972// case NTOFD:
4973// case NFROMFD:
4974// f = -1;
4975// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004976 case NHERE:
4977 case NXHERE:
4978 f = openhere(redir);
4979 break;
4980 }
4981
4982 return f;
4983 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004984 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004985 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004986 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004987}
4988
4989/*
4990 * Copy a file descriptor to be >= to. Returns -1
4991 * if the source file descriptor is closed, EMPTY if there are no unused
4992 * file descriptors left.
4993 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004994/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4995 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004996enum {
4997 COPYFD_EXACT = (int)~(INT_MAX),
4998 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4999};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005000static int
5001copyfd(int from, int to)
5002{
5003 int newfd;
5004
Denis Vlasenko5a867312008-07-24 19:46:38 +00005005 if (to & COPYFD_EXACT) {
5006 to &= ~COPYFD_EXACT;
5007 /*if (from != to)*/
5008 newfd = dup2(from, to);
5009 } else {
5010 newfd = fcntl(from, F_DUPFD, to);
5011 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005012 if (newfd < 0) {
5013 if (errno == EMFILE)
5014 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005015 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005016 ash_msg_and_raise_error("%d: %m", from);
5017 }
5018 return newfd;
5019}
5020
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005021/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005022struct two_fd_t {
5023 int orig, copy;
5024};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005025struct redirtab {
5026 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005027 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005028 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005029 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005030};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005031#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005032
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005033static int need_to_remember(struct redirtab *rp, int fd)
5034{
5035 int i;
5036
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005037 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005038 return 0;
5039
5040 for (i = 0; i < rp->pair_count; i++) {
5041 if (rp->two_fd[i].orig == fd) {
5042 /* already remembered */
5043 return 0;
5044 }
5045 }
5046 return 1;
5047}
5048
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005049/* "hidden" fd is a fd used to read scripts, or a copy of such */
5050static int is_hidden_fd(struct redirtab *rp, int fd)
5051{
5052 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005053 struct parsefile *pf;
5054
5055 if (fd == -1)
5056 return 0;
5057 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005058 while (pf) {
5059 if (fd == pf->fd) {
5060 return 1;
5061 }
5062 pf = pf->prev;
5063 }
5064 if (!rp)
5065 return 0;
5066 fd |= COPYFD_RESTORE;
5067 for (i = 0; i < rp->pair_count; i++) {
5068 if (rp->two_fd[i].copy == fd) {
5069 return 1;
5070 }
5071 }
5072 return 0;
5073}
5074
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005075/*
5076 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5077 * old file descriptors are stashed away so that the redirection can be
5078 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5079 * standard output, and the standard error if it becomes a duplicate of
5080 * stdout, is saved in memory.
5081 */
5082/* flags passed to redirect */
5083#define REDIR_PUSH 01 /* save previous values of file descriptors */
5084#define REDIR_SAVEFD2 03 /* set preverrout */
5085static void
5086redirect(union node *redir, int flags)
5087{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005088 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005089 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005090 int i;
5091 int fd;
5092 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005093 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005094
Denis Vlasenko01631112007-12-16 17:20:38 +00005095 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005096 if (!redir) {
5097 return;
5098 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005099
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005100 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005101 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005102 INT_OFF;
5103 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005104 union node *tmp = redir;
5105 do {
5106 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005107#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005108 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005109 sv_pos++;
5110#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005111 tmp = tmp->nfile.next;
5112 } while (tmp);
5113 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005114 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005116 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005117 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005118 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005119 while (sv_pos > 0) {
5120 sv_pos--;
5121 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5122 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005123 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005124
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005125 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005126 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005127 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005128 int right_fd = redir->ndup.dupfd;
5129 /* redirect from/to same file descriptor? */
5130 if (right_fd == fd)
5131 continue;
5132 /* echo >&10 and 10 is a fd opened to the sh script? */
5133 if (is_hidden_fd(sv, right_fd)) {
5134 errno = EBADF; /* as if it is closed */
5135 ash_msg_and_raise_error("%d: %m", right_fd);
5136 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005137 newfd = -1;
5138 } else {
5139 newfd = openredirect(redir); /* always >= 0 */
5140 if (fd == newfd) {
5141 /* Descriptor wasn't open before redirect.
5142 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005143 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005144 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005145 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005146 continue;
5147 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005148 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005149#if ENABLE_ASH_BASH_COMPAT
5150 redirect_more:
5151#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005152 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005153 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005154 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005155/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5156 * are closed in popredir() in the child, preventing them from leaking
5157 * into child. (popredir() also cleans up the mess in case of failures)
5158 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005159 if (i == -1) {
5160 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005161 if (i != EBADF) {
5162 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005163 if (newfd >= 0)
5164 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005165 errno = i;
5166 ash_msg_and_raise_error("%d: %m", fd);
5167 /* NOTREACHED */
5168 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005169 /* EBADF: it is not open - good, remember to close it */
5170 remember_to_close:
5171 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005172 } else { /* fd is open, save its copy */
5173 /* "exec fd>&-" should not close fds
5174 * which point to script file(s).
5175 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005176 if (is_hidden_fd(sv, fd))
5177 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005178 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005179 if (fd == 2)
5180 copied_fd2 = i;
5181 sv->two_fd[sv_pos].orig = fd;
5182 sv->two_fd[sv_pos].copy = i;
5183 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005184 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005185 if (newfd < 0) {
5186 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005187 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005188 /* Don't want to trigger debugging */
5189 if (fd != -1)
5190 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005191 } else {
5192 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005193 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005194 } else if (fd != newfd) { /* move newfd to fd */
5195 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005196#if ENABLE_ASH_BASH_COMPAT
5197 if (!(redir->nfile.type == NTO2 && fd == 2))
5198#endif
5199 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005200 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005201#if ENABLE_ASH_BASH_COMPAT
5202 if (redir->nfile.type == NTO2 && fd == 1) {
5203 /* We already redirected it to fd 1, now copy it to 2 */
5204 newfd = 1;
5205 fd = 2;
5206 goto redirect_more;
5207 }
5208#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005209 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005210
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005211 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005212 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5213 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005214}
5215
5216/*
5217 * Undo the effects of the last redirection.
5218 */
5219static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005220popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005221{
5222 struct redirtab *rp;
5223 int i;
5224
Denis Vlasenko01631112007-12-16 17:20:38 +00005225 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005226 return;
5227 INT_OFF;
5228 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005229 for (i = 0; i < rp->pair_count; i++) {
5230 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005231 int copy = rp->two_fd[i].copy;
5232 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005233 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005234 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005235 continue;
5236 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005237 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005238 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005239 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005240 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005241 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005243 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005244 }
5245 }
5246 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005247 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005248 free(rp);
5249 INT_ON;
5250}
5251
5252/*
5253 * Undo all redirections. Called on error or interrupt.
5254 */
5255
5256/*
5257 * Discard all saved file descriptors.
5258 */
5259static void
5260clearredir(int drop)
5261{
5262 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005263 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005264 if (!redirlist)
5265 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005266 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005267 }
5268}
5269
5270static int
5271redirectsafe(union node *redir, int flags)
5272{
5273 int err;
5274 volatile int saveint;
5275 struct jmploc *volatile savehandler = exception_handler;
5276 struct jmploc jmploc;
5277
5278 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005279 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5280 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005281 if (!err) {
5282 exception_handler = &jmploc;
5283 redirect(redir, flags);
5284 }
5285 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005286 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005287 longjmp(exception_handler->loc, 1);
5288 RESTORE_INT(saveint);
5289 return err;
5290}
5291
5292
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005293/* ============ Routines to expand arguments to commands
5294 *
5295 * We have to deal with backquotes, shell variables, and file metacharacters.
5296 */
5297
Mike Frysinger98c52642009-04-02 10:02:37 +00005298#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005299static arith_t
5300ash_arith(const char *s)
5301{
5302 arith_eval_hooks_t math_hooks;
5303 arith_t result;
5304 int errcode = 0;
5305
5306 math_hooks.lookupvar = lookupvar;
5307 math_hooks.setvar = setvar;
5308 math_hooks.endofname = endofname;
5309
5310 INT_OFF;
5311 result = arith(s, &errcode, &math_hooks);
5312 if (errcode < 0) {
5313 if (errcode == -3)
5314 ash_msg_and_raise_error("exponent less than 0");
5315 if (errcode == -2)
5316 ash_msg_and_raise_error("divide by zero");
5317 if (errcode == -5)
5318 ash_msg_and_raise_error("expression recursion loop detected");
5319 raise_error_syntax(s);
5320 }
5321 INT_ON;
5322
5323 return result;
5324}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005325#endif
5326
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005327/*
5328 * expandarg flags
5329 */
5330#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5331#define EXP_TILDE 0x2 /* do normal tilde expansion */
5332#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5333#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5334#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5335#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5336#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5337#define EXP_WORD 0x80 /* expand word in parameter expansion */
5338#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5339/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005340 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005341 */
5342#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5343#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5344#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5345#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5346#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5347
5348/*
5349 * Structure specifying which parts of the string should be searched
5350 * for IFS characters.
5351 */
5352struct ifsregion {
5353 struct ifsregion *next; /* next region in list */
5354 int begoff; /* offset of start of region */
5355 int endoff; /* offset of end of region */
5356 int nulonly; /* search for nul bytes only */
5357};
5358
5359struct arglist {
5360 struct strlist *list;
5361 struct strlist **lastp;
5362};
5363
5364/* output of current string */
5365static char *expdest;
5366/* list of back quote expressions */
5367static struct nodelist *argbackq;
5368/* first struct in list of ifs regions */
5369static struct ifsregion ifsfirst;
5370/* last struct in list */
5371static struct ifsregion *ifslastp;
5372/* holds expanded arg list */
5373static struct arglist exparg;
5374
5375/*
5376 * Our own itoa().
5377 */
5378static int
5379cvtnum(arith_t num)
5380{
5381 int len;
5382
5383 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005384 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005385 STADJUST(len, expdest);
5386 return len;
5387}
5388
5389static size_t
5390esclen(const char *start, const char *p)
5391{
5392 size_t esc = 0;
5393
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005394 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005395 esc++;
5396 }
5397 return esc;
5398}
5399
5400/*
5401 * Remove any CTLESC characters from a string.
5402 */
5403static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005404rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005405{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005406 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005407
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005408 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005409 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005410 unsigned protect_against_glob;
5411 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005412
5413 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005414 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005415 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005416
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005417 q = p;
5418 r = str;
5419 if (flag & RMESCAPE_ALLOC) {
5420 size_t len = p - str;
5421 size_t fulllen = len + strlen(p) + 1;
5422
5423 if (flag & RMESCAPE_GROW) {
5424 r = makestrspace(fulllen, expdest);
5425 } else if (flag & RMESCAPE_HEAP) {
5426 r = ckmalloc(fulllen);
5427 } else {
5428 r = stalloc(fulllen);
5429 }
5430 q = r;
5431 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005432 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 }
5434 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005435
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5437 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005440 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5442// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5443// Note: both inquotes and protect_against_glob only affect whether
5444// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005445 inquotes = ~inquotes;
5446 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005447 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 continue;
5449 }
5450 if (*p == '\\') {
5451 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005452 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005453 goto copy;
5454 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005455 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005456 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005457 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458 *q++ = '\\';
5459 }
5460 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005461 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005462 copy:
5463 *q++ = *p++;
5464 }
5465 *q = '\0';
5466 if (flag & RMESCAPE_GROW) {
5467 expdest = r;
5468 STADJUST(q - r + 1, expdest);
5469 }
5470 return r;
5471}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005472#define pmatch(a, b) !fnmatch((a), (b), 0)
5473
5474/*
5475 * Prepare a pattern for a expmeta (internal glob(3)) call.
5476 *
5477 * Returns an stalloced string.
5478 */
5479static char *
5480preglob(const char *pattern, int quoted, int flag)
5481{
5482 flag |= RMESCAPE_GLOB;
5483 if (quoted) {
5484 flag |= RMESCAPE_QUOTED;
5485 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005486 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005487}
5488
5489/*
5490 * Put a string on the stack.
5491 */
5492static void
5493memtodest(const char *p, size_t len, int syntax, int quotes)
5494{
5495 char *q = expdest;
5496
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005497 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005498
5499 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005500 unsigned char c = *p++;
5501 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005502 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005503 if (quotes) {
5504 int n = SIT(c, syntax);
5505 if (n == CCTL || n == CBACK)
5506 USTPUTC(CTLESC, q);
5507 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005508 USTPUTC(c, q);
5509 }
5510
5511 expdest = q;
5512}
5513
5514static void
5515strtodest(const char *p, int syntax, int quotes)
5516{
5517 memtodest(p, strlen(p), syntax, quotes);
5518}
5519
5520/*
5521 * Record the fact that we have to scan this region of the
5522 * string for IFS characters.
5523 */
5524static void
5525recordregion(int start, int end, int nulonly)
5526{
5527 struct ifsregion *ifsp;
5528
5529 if (ifslastp == NULL) {
5530 ifsp = &ifsfirst;
5531 } else {
5532 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005533 ifsp = ckzalloc(sizeof(*ifsp));
5534 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005535 ifslastp->next = ifsp;
5536 INT_ON;
5537 }
5538 ifslastp = ifsp;
5539 ifslastp->begoff = start;
5540 ifslastp->endoff = end;
5541 ifslastp->nulonly = nulonly;
5542}
5543
5544static void
5545removerecordregions(int endoff)
5546{
5547 if (ifslastp == NULL)
5548 return;
5549
5550 if (ifsfirst.endoff > endoff) {
5551 while (ifsfirst.next != NULL) {
5552 struct ifsregion *ifsp;
5553 INT_OFF;
5554 ifsp = ifsfirst.next->next;
5555 free(ifsfirst.next);
5556 ifsfirst.next = ifsp;
5557 INT_ON;
5558 }
5559 if (ifsfirst.begoff > endoff)
5560 ifslastp = NULL;
5561 else {
5562 ifslastp = &ifsfirst;
5563 ifsfirst.endoff = endoff;
5564 }
5565 return;
5566 }
5567
5568 ifslastp = &ifsfirst;
5569 while (ifslastp->next && ifslastp->next->begoff < endoff)
5570 ifslastp=ifslastp->next;
5571 while (ifslastp->next != NULL) {
5572 struct ifsregion *ifsp;
5573 INT_OFF;
5574 ifsp = ifslastp->next->next;
5575 free(ifslastp->next);
5576 ifslastp->next = ifsp;
5577 INT_ON;
5578 }
5579 if (ifslastp->endoff > endoff)
5580 ifslastp->endoff = endoff;
5581}
5582
5583static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005584exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005585{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005586 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005587 char *name;
5588 struct passwd *pw;
5589 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005590 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005591 int startloc;
5592
5593 name = p + 1;
5594
5595 while ((c = *++p) != '\0') {
5596 switch (c) {
5597 case CTLESC:
5598 return startp;
5599 case CTLQUOTEMARK:
5600 return startp;
5601 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005602 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005603 goto done;
5604 break;
5605 case '/':
5606 case CTLENDVAR:
5607 goto done;
5608 }
5609 }
5610 done:
5611 *p = '\0';
5612 if (*name == '\0') {
5613 home = lookupvar(homestr);
5614 } else {
5615 pw = getpwnam(name);
5616 if (pw == NULL)
5617 goto lose;
5618 home = pw->pw_dir;
5619 }
5620 if (!home || !*home)
5621 goto lose;
5622 *p = c;
5623 startloc = expdest - (char *)stackblock();
5624 strtodest(home, SQSYNTAX, quotes);
5625 recordregion(startloc, expdest - (char *)stackblock(), 0);
5626 return p;
5627 lose:
5628 *p = c;
5629 return startp;
5630}
5631
5632/*
5633 * Execute a command inside back quotes. If it's a builtin command, we
5634 * want to save its output in a block obtained from malloc. Otherwise
5635 * we fork off a subprocess and get the output of the command via a pipe.
5636 * Should be called with interrupts off.
5637 */
5638struct backcmd { /* result of evalbackcmd */
5639 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005640 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005641 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005642 struct job *jp; /* job structure for command */
5643};
5644
5645/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005646static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005647#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005648static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005649
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005650static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005651evalbackcmd(union node *n, struct backcmd *result)
5652{
5653 int saveherefd;
5654
5655 result->fd = -1;
5656 result->buf = NULL;
5657 result->nleft = 0;
5658 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005659 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005660 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005661
5662 saveherefd = herefd;
5663 herefd = -1;
5664
5665 {
5666 int pip[2];
5667 struct job *jp;
5668
5669 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005670 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005671 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005672 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5673 FORCE_INT_ON;
5674 close(pip[0]);
5675 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005676 /*close(1);*/
5677 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678 close(pip[1]);
5679 }
5680 eflag = 0;
5681 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5682 /* NOTREACHED */
5683 }
5684 close(pip[1]);
5685 result->fd = pip[0];
5686 result->jp = jp;
5687 }
5688 herefd = saveherefd;
5689 out:
5690 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5691 result->fd, result->buf, result->nleft, result->jp));
5692}
5693
5694/*
5695 * Expand stuff in backwards quotes.
5696 */
5697static void
5698expbackq(union node *cmd, int quoted, int quotes)
5699{
5700 struct backcmd in;
5701 int i;
5702 char buf[128];
5703 char *p;
5704 char *dest;
5705 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005706 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005707 struct stackmark smark;
5708
5709 INT_OFF;
5710 setstackmark(&smark);
5711 dest = expdest;
5712 startloc = dest - (char *)stackblock();
5713 grabstackstr(dest);
5714 evalbackcmd(cmd, &in);
5715 popstackmark(&smark);
5716
5717 p = in.buf;
5718 i = in.nleft;
5719 if (i == 0)
5720 goto read;
5721 for (;;) {
5722 memtodest(p, i, syntax, quotes);
5723 read:
5724 if (in.fd < 0)
5725 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005726 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005727 TRACE(("expbackq: read returns %d\n", i));
5728 if (i <= 0)
5729 break;
5730 p = buf;
5731 }
5732
Denis Vlasenko60818682007-09-28 22:07:23 +00005733 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005734 if (in.fd >= 0) {
5735 close(in.fd);
5736 back_exitstatus = waitforjob(in.jp);
5737 }
5738 INT_ON;
5739
5740 /* Eat all trailing newlines */
5741 dest = expdest;
5742 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5743 STUNPUTC(dest);
5744 expdest = dest;
5745
5746 if (quoted == 0)
5747 recordregion(startloc, dest - (char *)stackblock(), 0);
5748 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5749 (dest - (char *)stackblock()) - startloc,
5750 (dest - (char *)stackblock()) - startloc,
5751 stackblock() + startloc));
5752}
5753
Mike Frysinger98c52642009-04-02 10:02:37 +00005754#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005755/*
5756 * Expand arithmetic expression. Backup to start of expression,
5757 * evaluate, place result in (backed up) result, adjust string position.
5758 */
5759static void
5760expari(int quotes)
5761{
5762 char *p, *start;
5763 int begoff;
5764 int flag;
5765 int len;
5766
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005767 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005768
5769 /*
5770 * This routine is slightly over-complicated for
5771 * efficiency. Next we scan backwards looking for the
5772 * start of arithmetic.
5773 */
5774 start = stackblock();
5775 p = expdest - 1;
5776 *p = '\0';
5777 p--;
5778 do {
5779 int esc;
5780
Denys Vlasenkocd716832009-11-28 22:14:02 +01005781 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005782 p--;
5783#if DEBUG
5784 if (p < start) {
5785 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5786 }
5787#endif
5788 }
5789
5790 esc = esclen(start, p);
5791 if (!(esc % 2)) {
5792 break;
5793 }
5794
5795 p -= esc + 1;
5796 } while (1);
5797
5798 begoff = p - start;
5799
5800 removerecordregions(begoff);
5801
5802 flag = p[1];
5803
5804 expdest = p;
5805
5806 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005807 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005808
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005809 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005810
5811 if (flag != '"')
5812 recordregion(begoff, begoff + len, 0);
5813}
5814#endif
5815
5816/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005817static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005818
5819/*
5820 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5821 * characters to allow for further processing. Otherwise treat
5822 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005823 *
5824 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5825 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5826 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005827 */
5828static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005829argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005831 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005832 '=',
5833 ':',
5834 CTLQUOTEMARK,
5835 CTLENDVAR,
5836 CTLESC,
5837 CTLVAR,
5838 CTLBACKQ,
5839 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005840#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005841 CTLENDARI,
5842#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005843 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005844 };
5845 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005846 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5847 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005848 int inquotes;
5849 size_t length;
5850 int startloc;
5851
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005852 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005853 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005854 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005855 reject++;
5856 }
5857 inquotes = 0;
5858 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005859 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005860 char *q;
5861
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005862 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 tilde:
5864 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005865 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 q++;
5867 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 }
5870 start:
5871 startloc = expdest - (char *)stackblock();
5872 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005873 unsigned char c;
5874
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005875 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005876 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005877 if (c) {
5878 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005879#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 ) {
5883 /* c == '=' || c == ':' || c == CTLENDARI */
5884 length++;
5885 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005886 }
5887 if (length > 0) {
5888 int newloc;
5889 expdest = stack_nputstr(p, length, expdest);
5890 newloc = expdest - (char *)stackblock();
5891 if (breakall && !inquotes && newloc > startloc) {
5892 recordregion(startloc, newloc, 0);
5893 }
5894 startloc = newloc;
5895 }
5896 p += length + 1;
5897 length = 0;
5898
5899 switch (c) {
5900 case '\0':
5901 goto breakloop;
5902 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005903 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005904 p--;
5905 continue;
5906 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005907 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005908 reject++;
5909 /* fall through */
5910 case ':':
5911 /*
5912 * sort of a hack - expand tildes in variable
5913 * assignments (after the first '=' and after ':'s).
5914 */
5915 if (*--p == '~') {
5916 goto tilde;
5917 }
5918 continue;
5919 }
5920
5921 switch (c) {
5922 case CTLENDVAR: /* ??? */
5923 goto breakloop;
5924 case CTLQUOTEMARK:
5925 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005926 if (!inquotes
5927 && memcmp(p, dolatstr, 4) == 0
5928 && ( p[4] == CTLQUOTEMARK
5929 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5930 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005931 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005932 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005933 goto start;
5934 }
5935 inquotes = !inquotes;
5936 addquote:
5937 if (quotes) {
5938 p--;
5939 length++;
5940 startloc++;
5941 }
5942 break;
5943 case CTLESC:
5944 startloc++;
5945 length++;
5946 goto addquote;
5947 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005948 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005949 goto start;
5950 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005951 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005952 case CTLBACKQ|CTLQUOTE:
5953 expbackq(argbackq->n, c, quotes);
5954 argbackq = argbackq->next;
5955 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005956#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005957 case CTLENDARI:
5958 p--;
5959 expari(quotes);
5960 goto start;
5961#endif
5962 }
5963 }
5964 breakloop:
5965 ;
5966}
5967
5968static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005969scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005970 int zero)
5971{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005972// This commented out code was added by James Simmons <jsimmons@infradead.org>
5973// as part of a larger change when he added support for ${var/a/b}.
5974// However, it broke # and % operators:
5975//
5976//var=ababcdcd
5977// ok bad
5978//echo ${var#ab} abcdcd abcdcd
5979//echo ${var##ab} abcdcd abcdcd
5980//echo ${var#a*b} abcdcd ababcdcd (!)
5981//echo ${var##a*b} cdcd cdcd
5982//echo ${var#?} babcdcd ababcdcd (!)
5983//echo ${var##?} babcdcd babcdcd
5984//echo ${var#*} ababcdcd babcdcd (!)
5985//echo ${var##*}
5986//echo ${var%cd} ababcd ababcd
5987//echo ${var%%cd} ababcd abab (!)
5988//echo ${var%c*d} ababcd ababcd
5989//echo ${var%%c*d} abab ababcdcd (!)
5990//echo ${var%?} ababcdc ababcdc
5991//echo ${var%%?} ababcdc ababcdcd (!)
5992//echo ${var%*} ababcdcd ababcdcd
5993//echo ${var%%*}
5994//
5995// Commenting it back out helped. Remove it completely if it really
5996// is not needed.
5997
5998 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005999 char c;
6000
6001 loc = startp;
6002 loc2 = rmesc;
6003 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006004 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006005 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006006
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006007 c = *loc2;
6008 if (zero) {
6009 *loc2 = '\0';
6010 s = rmesc;
6011 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006012 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006013
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006014// // chop off end if its '*'
6015// full = strrchr(str, '*');
6016// if (full && full != str)
6017// match--;
6018//
6019// // If str starts with '*' replace with s.
6020// if ((*str == '*') && strlen(s) >= match) {
6021// full = xstrdup(s);
6022// strncpy(full+strlen(s)-match+1, str+1, match-1);
6023// } else
6024// full = xstrndup(str, match);
6025// match = strncmp(s, full, strlen(full));
6026// free(full);
6027//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006028 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006029 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006030 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006031 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006032 loc++;
6033 loc++;
6034 loc2++;
6035 } while (c);
6036 return 0;
6037}
6038
6039static char *
6040scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6041 int zero)
6042{
6043 int esc = 0;
6044 char *loc;
6045 char *loc2;
6046
6047 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6048 int match;
6049 char c = *loc2;
6050 const char *s = loc2;
6051 if (zero) {
6052 *loc2 = '\0';
6053 s = rmesc;
6054 }
6055 match = pmatch(str, s);
6056 *loc2 = c;
6057 if (match)
6058 return loc;
6059 loc--;
6060 if (quotes) {
6061 if (--esc < 0) {
6062 esc = esclen(startp, loc);
6063 }
6064 if (esc % 2) {
6065 esc--;
6066 loc--;
6067 }
6068 }
6069 }
6070 return 0;
6071}
6072
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006073static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006074static void
6075varunset(const char *end, const char *var, const char *umsg, int varflags)
6076{
6077 const char *msg;
6078 const char *tail;
6079
6080 tail = nullstr;
6081 msg = "parameter not set";
6082 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006083 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006084 if (varflags & VSNUL)
6085 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006086 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006087 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006088 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006089 }
6090 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6091}
6092
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006093#if ENABLE_ASH_BASH_COMPAT
6094static char *
6095parse_sub_pattern(char *arg, int inquotes)
6096{
6097 char *idx, *repl = NULL;
6098 unsigned char c;
6099
Denis Vlasenko2659c632008-06-14 06:04:59 +00006100 idx = arg;
6101 while (1) {
6102 c = *arg;
6103 if (!c)
6104 break;
6105 if (c == '/') {
6106 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006107 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006108 repl = idx + 1;
6109 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006110 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006111 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006112 *idx++ = c;
6113 if (!inquotes && c == '\\' && arg[1] == '\\')
6114 arg++; /* skip both \\, not just first one */
6115 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006116 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006117 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006118
6119 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006120}
6121#endif /* ENABLE_ASH_BASH_COMPAT */
6122
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006124subevalvar(char *p, char *str, int strloc, int subtype,
6125 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006126{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006127 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006128 char *startp;
6129 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006130 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006131 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6132 IF_ASH_BASH_COMPAT(char null = '\0';)
6133 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006134 int saveherefd = herefd;
6135 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006136 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138
6139 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006140 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6141 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006142 STPUTC('\0', expdest);
6143 herefd = saveherefd;
6144 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006145 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006146
6147 switch (subtype) {
6148 case VSASSIGN:
6149 setvar(str, startp, 0);
6150 amount = startp - expdest;
6151 STADJUST(amount, expdest);
6152 return startp;
6153
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006154#if ENABLE_ASH_BASH_COMPAT
6155 case VSSUBSTR:
6156 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006157 /* Read POS in ${var:POS:LEN} */
6158 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006159 len = str - startp - 1;
6160
6161 /* *loc != '\0', guaranteed by parser */
6162 if (quotes) {
6163 char *ptr;
6164
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006165 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006166 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006167 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006168 len--;
6169 ptr++;
6170 }
6171 }
6172 }
6173 orig_len = len;
6174
6175 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006176 /* ${var::LEN} */
6177 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006179 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006181 while (*loc && *loc != ':') {
6182 /* TODO?
6183 * bash complains on: var=qwe; echo ${var:1a:123}
6184 if (!isdigit(*loc))
6185 ash_msg_and_raise_error(msg_illnum, str);
6186 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006187 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006188 }
6189 if (*loc++ == ':') {
6190 len = number(loc);
6191 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006192 }
6193 if (pos >= orig_len) {
6194 pos = 0;
6195 len = 0;
6196 }
6197 if (len > (orig_len - pos))
6198 len = orig_len - pos;
6199
6200 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006201 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006202 str++;
6203 }
6204 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006205 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006206 *loc++ = *str++;
6207 *loc++ = *str++;
6208 }
6209 *loc = '\0';
6210 amount = loc - expdest;
6211 STADJUST(amount, expdest);
6212 return loc;
6213#endif
6214
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006215 case VSQUESTION:
6216 varunset(p, str, startp, varflags);
6217 /* NOTREACHED */
6218 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006219 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006220
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006221 /* We'll comeback here if we grow the stack while handling
6222 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6223 * stack will need rebasing, and we'll need to remove our work
6224 * areas each time
6225 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006226 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006227
6228 amount = expdest - ((char *)stackblock() + resetloc);
6229 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006230 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006231
6232 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006233 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006234 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006235 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006236 if (rmesc != startp) {
6237 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006238 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006239 }
6240 }
6241 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006242 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006243 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006244 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006245
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006246#if ENABLE_ASH_BASH_COMPAT
6247 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6248 char *idx, *end, *restart_detect;
6249
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006250 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6252 if (!repl)
6253 repl = &null;
6254 }
6255
6256 /* If there's no pattern to match, return the expansion unmolested */
6257 if (*str == '\0')
6258 return 0;
6259
6260 len = 0;
6261 idx = startp;
6262 end = str - 1;
6263 while (idx < end) {
6264 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6265 if (!loc) {
6266 /* No match, advance */
6267 restart_detect = stackblock();
6268 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006269 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 idx++;
6271 len++;
6272 STPUTC(*idx, expdest);
6273 }
6274 if (stackblock() != restart_detect)
6275 goto restart;
6276 idx++;
6277 len++;
6278 rmesc++;
6279 continue;
6280 }
6281
6282 if (subtype == VSREPLACEALL) {
6283 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006284 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006285 idx++;
6286 idx++;
6287 rmesc++;
6288 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006289 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006290 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006291 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006292
6293 for (loc = repl; *loc; loc++) {
6294 restart_detect = stackblock();
6295 STPUTC(*loc, expdest);
6296 if (stackblock() != restart_detect)
6297 goto restart;
6298 len++;
6299 }
6300
6301 if (subtype == VSREPLACE) {
6302 while (*idx) {
6303 restart_detect = stackblock();
6304 STPUTC(*idx, expdest);
6305 if (stackblock() != restart_detect)
6306 goto restart;
6307 len++;
6308 idx++;
6309 }
6310 break;
6311 }
6312 }
6313
6314 /* We've put the replaced text into a buffer at workloc, now
6315 * move it to the right place and adjust the stack.
6316 */
6317 startp = stackblock() + startloc;
6318 STPUTC('\0', expdest);
6319 memmove(startp, stackblock() + workloc, len);
6320 startp[len++] = '\0';
6321 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6322 STADJUST(-amount, expdest);
6323 return startp;
6324 }
6325#endif /* ENABLE_ASH_BASH_COMPAT */
6326
6327 subtype -= VSTRIMRIGHT;
6328#if DEBUG
6329 if (subtype < 0 || subtype > 7)
6330 abort();
6331#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006332 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6333 zero = subtype >> 1;
6334 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6335 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6336
6337 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6338 if (loc) {
6339 if (zero) {
6340 memmove(startp, loc, str - loc);
6341 loc = startp + (str - loc) - 1;
6342 }
6343 *loc = '\0';
6344 amount = loc - expdest;
6345 STADJUST(amount, expdest);
6346 }
6347 return loc;
6348}
6349
6350/*
6351 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006352 * name parameter (examples):
6353 * ash -c 'echo $1' name:'1='
6354 * ash -c 'echo $qwe' name:'qwe='
6355 * ash -c 'echo $$' name:'$='
6356 * ash -c 'echo ${$}' name:'$='
6357 * ash -c 'echo ${$##q}' name:'$=q'
6358 * ash -c 'echo ${#$}' name:'$='
6359 * note: examples with bad shell syntax:
6360 * ash -c 'echo ${#$1}' name:'$=1'
6361 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006362 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006363static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006364varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006365{
Mike Frysinger98c52642009-04-02 10:02:37 +00006366 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006367 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006368 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006369 int sepq = 0;
6370 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006371 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006372 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006373 int quoted = varflags & VSQUOTE;
6374 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006375
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006376 switch (*name) {
6377 case '$':
6378 num = rootpid;
6379 goto numvar;
6380 case '?':
6381 num = exitstatus;
6382 goto numvar;
6383 case '#':
6384 num = shellparam.nparam;
6385 goto numvar;
6386 case '!':
6387 num = backgndpid;
6388 if (num == 0)
6389 return -1;
6390 numvar:
6391 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006392 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006394 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006395 for (i = NOPTS - 1; i >= 0; i--) {
6396 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006397 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006398 len++;
6399 }
6400 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006401 check_1char_name:
6402#if 0
6403 /* handles cases similar to ${#$1} */
6404 if (name[2] != '\0')
6405 raise_error_syntax("bad substitution");
6406#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006407 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006408 case '@': {
6409 char **ap;
6410 int sep;
6411
6412 if (quoted && (flags & EXP_FULL)) {
6413 /* note: this is not meant as PEOF value */
6414 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006416 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006417 /* fall through */
6418 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006419 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006420 i = SIT(sep, syntax);
6421 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006422 sepq = 1;
6423 param:
6424 ap = shellparam.p;
6425 if (!ap)
6426 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006427 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006428 size_t partlen;
6429
6430 partlen = strlen(p);
6431 len += partlen;
6432
6433 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6434 memtodest(p, partlen, syntax, quotes);
6435
6436 if (*ap && sep) {
6437 char *q;
6438
6439 len++;
6440 if (subtype == VSPLUS || subtype == VSLENGTH) {
6441 continue;
6442 }
6443 q = expdest;
6444 if (sepq)
6445 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006446 /* note: may put NUL despite sep != 0
6447 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006448 STPUTC(sep, q);
6449 expdest = q;
6450 }
6451 }
6452 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006453 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006454 case '0':
6455 case '1':
6456 case '2':
6457 case '3':
6458 case '4':
6459 case '5':
6460 case '6':
6461 case '7':
6462 case '8':
6463 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006464 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006465 if (num < 0 || num > shellparam.nparam)
6466 return -1;
6467 p = num ? shellparam.p[num - 1] : arg0;
6468 goto value;
6469 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006470 /* NB: name has form "VAR=..." */
6471
6472 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6473 * which should be considered before we check variables. */
6474 if (var_str_list) {
6475 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6476 p = NULL;
6477 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006478 char *str, *eq;
6479 str = var_str_list->text;
6480 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006481 if (!eq) /* stop at first non-assignment */
6482 break;
6483 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006484 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006485 && strncmp(str, name, name_len) == 0
6486 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006487 p = eq;
6488 /* goto value; - WRONG! */
6489 /* think "A=1 A=2 B=$A" */
6490 }
6491 var_str_list = var_str_list->next;
6492 } while (var_str_list);
6493 if (p)
6494 goto value;
6495 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006496 p = lookupvar(name);
6497 value:
6498 if (!p)
6499 return -1;
6500
6501 len = strlen(p);
6502 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6503 memtodest(p, len, syntax, quotes);
6504 return len;
6505 }
6506
6507 if (subtype == VSPLUS || subtype == VSLENGTH)
6508 STADJUST(-len, expdest);
6509 return len;
6510}
6511
6512/*
6513 * Expand a variable, and return a pointer to the next character in the
6514 * input string.
6515 */
6516static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006517evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006518{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006519 char varflags;
6520 char subtype;
6521 char quoted;
6522 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 char *var;
6524 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006525 int startloc;
6526 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006527
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006528 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529 subtype = varflags & VSTYPE;
6530 quoted = varflags & VSQUOTE;
6531 var = p;
6532 easy = (!quoted || (*var == '@' && shellparam.nparam));
6533 startloc = expdest - (char *)stackblock();
6534 p = strchr(p, '=') + 1;
6535
6536 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006537 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006538 if (varflags & VSNUL)
6539 varlen--;
6540
6541 if (subtype == VSPLUS) {
6542 varlen = -1 - varlen;
6543 goto vsplus;
6544 }
6545
6546 if (subtype == VSMINUS) {
6547 vsplus:
6548 if (varlen < 0) {
6549 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006550 p, flags | EXP_TILDE |
6551 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006552 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006553 );
6554 goto end;
6555 }
6556 if (easy)
6557 goto record;
6558 goto end;
6559 }
6560
6561 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6562 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006563 if (subevalvar(p, var, /* strloc: */ 0,
6564 subtype, startloc, varflags,
6565 /* quotes: */ 0,
6566 var_str_list)
6567 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006568 varflags &= ~VSNUL;
6569 /*
6570 * Remove any recorded regions beyond
6571 * start of variable
6572 */
6573 removerecordregions(startloc);
6574 goto again;
6575 }
6576 goto end;
6577 }
6578 if (easy)
6579 goto record;
6580 goto end;
6581 }
6582
6583 if (varlen < 0 && uflag)
6584 varunset(p, var, 0, 0);
6585
6586 if (subtype == VSLENGTH) {
6587 cvtnum(varlen > 0 ? varlen : 0);
6588 goto record;
6589 }
6590
6591 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006592 if (easy)
6593 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594 goto end;
6595 }
6596
6597#if DEBUG
6598 switch (subtype) {
6599 case VSTRIMLEFT:
6600 case VSTRIMLEFTMAX:
6601 case VSTRIMRIGHT:
6602 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006603#if ENABLE_ASH_BASH_COMPAT
6604 case VSSUBSTR:
6605 case VSREPLACE:
6606 case VSREPLACEALL:
6607#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006608 break;
6609 default:
6610 abort();
6611 }
6612#endif
6613
6614 if (varlen >= 0) {
6615 /*
6616 * Terminate the string and start recording the pattern
6617 * right after it
6618 */
6619 STPUTC('\0', expdest);
6620 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006621 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6622 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006623//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006624 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006625 var_str_list)
6626 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006627 int amount = expdest - (
6628 (char *)stackblock() + patloc - 1
6629 );
6630 STADJUST(-amount, expdest);
6631 }
6632 /* Remove any recorded regions beyond start of variable */
6633 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006634 record:
6635 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006636 }
6637
6638 end:
6639 if (subtype != VSNORMAL) { /* skip to end of alternative */
6640 int nesting = 1;
6641 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006642 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 if (c == CTLESC)
6644 p++;
6645 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6646 if (varlen >= 0)
6647 argbackq = argbackq->next;
6648 } else if (c == CTLVAR) {
6649 if ((*p++ & VSTYPE) != VSNORMAL)
6650 nesting++;
6651 } else if (c == CTLENDVAR) {
6652 if (--nesting == 0)
6653 break;
6654 }
6655 }
6656 }
6657 return p;
6658}
6659
6660/*
6661 * Break the argument string into pieces based upon IFS and add the
6662 * strings to the argument list. The regions of the string to be
6663 * searched for IFS characters have been stored by recordregion.
6664 */
6665static void
6666ifsbreakup(char *string, struct arglist *arglist)
6667{
6668 struct ifsregion *ifsp;
6669 struct strlist *sp;
6670 char *start;
6671 char *p;
6672 char *q;
6673 const char *ifs, *realifs;
6674 int ifsspc;
6675 int nulonly;
6676
6677 start = string;
6678 if (ifslastp != NULL) {
6679 ifsspc = 0;
6680 nulonly = 0;
6681 realifs = ifsset() ? ifsval() : defifs;
6682 ifsp = &ifsfirst;
6683 do {
6684 p = string + ifsp->begoff;
6685 nulonly = ifsp->nulonly;
6686 ifs = nulonly ? nullstr : realifs;
6687 ifsspc = 0;
6688 while (p < string + ifsp->endoff) {
6689 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006690 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006691 p++;
6692 if (!strchr(ifs, *p)) {
6693 p++;
6694 continue;
6695 }
6696 if (!nulonly)
6697 ifsspc = (strchr(defifs, *p) != NULL);
6698 /* Ignore IFS whitespace at start */
6699 if (q == start && ifsspc) {
6700 p++;
6701 start = p;
6702 continue;
6703 }
6704 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006705 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006706 sp->text = start;
6707 *arglist->lastp = sp;
6708 arglist->lastp = &sp->next;
6709 p++;
6710 if (!nulonly) {
6711 for (;;) {
6712 if (p >= string + ifsp->endoff) {
6713 break;
6714 }
6715 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006716 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006717 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006718 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006719 p = q;
6720 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006721 }
6722 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006723 if (ifsspc) {
6724 p++;
6725 ifsspc = 0;
6726 } else {
6727 p = q;
6728 break;
6729 }
6730 } else
6731 p++;
6732 }
6733 }
6734 start = p;
6735 } /* while */
6736 ifsp = ifsp->next;
6737 } while (ifsp != NULL);
6738 if (nulonly)
6739 goto add;
6740 }
6741
6742 if (!*start)
6743 return;
6744
6745 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006746 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006747 sp->text = start;
6748 *arglist->lastp = sp;
6749 arglist->lastp = &sp->next;
6750}
6751
6752static void
6753ifsfree(void)
6754{
6755 struct ifsregion *p;
6756
6757 INT_OFF;
6758 p = ifsfirst.next;
6759 do {
6760 struct ifsregion *ifsp;
6761 ifsp = p->next;
6762 free(p);
6763 p = ifsp;
6764 } while (p);
6765 ifslastp = NULL;
6766 ifsfirst.next = NULL;
6767 INT_ON;
6768}
6769
6770/*
6771 * Add a file name to the list.
6772 */
6773static void
6774addfname(const char *name)
6775{
6776 struct strlist *sp;
6777
Denis Vlasenko597906c2008-02-20 16:38:54 +00006778 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006779 sp->text = ststrdup(name);
6780 *exparg.lastp = sp;
6781 exparg.lastp = &sp->next;
6782}
6783
6784static char *expdir;
6785
6786/*
6787 * Do metacharacter (i.e. *, ?, [...]) expansion.
6788 */
6789static void
6790expmeta(char *enddir, char *name)
6791{
6792 char *p;
6793 const char *cp;
6794 char *start;
6795 char *endname;
6796 int metaflag;
6797 struct stat statb;
6798 DIR *dirp;
6799 struct dirent *dp;
6800 int atend;
6801 int matchdot;
6802
6803 metaflag = 0;
6804 start = name;
6805 for (p = name; *p; p++) {
6806 if (*p == '*' || *p == '?')
6807 metaflag = 1;
6808 else if (*p == '[') {
6809 char *q = p + 1;
6810 if (*q == '!')
6811 q++;
6812 for (;;) {
6813 if (*q == '\\')
6814 q++;
6815 if (*q == '/' || *q == '\0')
6816 break;
6817 if (*++q == ']') {
6818 metaflag = 1;
6819 break;
6820 }
6821 }
6822 } else if (*p == '\\')
6823 p++;
6824 else if (*p == '/') {
6825 if (metaflag)
6826 goto out;
6827 start = p + 1;
6828 }
6829 }
6830 out:
6831 if (metaflag == 0) { /* we've reached the end of the file name */
6832 if (enddir != expdir)
6833 metaflag++;
6834 p = name;
6835 do {
6836 if (*p == '\\')
6837 p++;
6838 *enddir++ = *p;
6839 } while (*p++);
6840 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6841 addfname(expdir);
6842 return;
6843 }
6844 endname = p;
6845 if (name < start) {
6846 p = name;
6847 do {
6848 if (*p == '\\')
6849 p++;
6850 *enddir++ = *p++;
6851 } while (p < start);
6852 }
6853 if (enddir == expdir) {
6854 cp = ".";
6855 } else if (enddir == expdir + 1 && *expdir == '/') {
6856 cp = "/";
6857 } else {
6858 cp = expdir;
6859 enddir[-1] = '\0';
6860 }
6861 dirp = opendir(cp);
6862 if (dirp == NULL)
6863 return;
6864 if (enddir != expdir)
6865 enddir[-1] = '/';
6866 if (*endname == 0) {
6867 atend = 1;
6868 } else {
6869 atend = 0;
6870 *endname++ = '\0';
6871 }
6872 matchdot = 0;
6873 p = start;
6874 if (*p == '\\')
6875 p++;
6876 if (*p == '.')
6877 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006878 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006879 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006880 continue;
6881 if (pmatch(start, dp->d_name)) {
6882 if (atend) {
6883 strcpy(enddir, dp->d_name);
6884 addfname(expdir);
6885 } else {
6886 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6887 continue;
6888 p[-1] = '/';
6889 expmeta(p, endname);
6890 }
6891 }
6892 }
6893 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006894 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006895 endname[-1] = '/';
6896}
6897
6898static struct strlist *
6899msort(struct strlist *list, int len)
6900{
6901 struct strlist *p, *q = NULL;
6902 struct strlist **lpp;
6903 int half;
6904 int n;
6905
6906 if (len <= 1)
6907 return list;
6908 half = len >> 1;
6909 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006910 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006911 q = p;
6912 p = p->next;
6913 }
6914 q->next = NULL; /* terminate first half of list */
6915 q = msort(list, half); /* sort first half of list */
6916 p = msort(p, len - half); /* sort second half */
6917 lpp = &list;
6918 for (;;) {
6919#if ENABLE_LOCALE_SUPPORT
6920 if (strcoll(p->text, q->text) < 0)
6921#else
6922 if (strcmp(p->text, q->text) < 0)
6923#endif
6924 {
6925 *lpp = p;
6926 lpp = &p->next;
6927 p = *lpp;
6928 if (p == NULL) {
6929 *lpp = q;
6930 break;
6931 }
6932 } else {
6933 *lpp = q;
6934 lpp = &q->next;
6935 q = *lpp;
6936 if (q == NULL) {
6937 *lpp = p;
6938 break;
6939 }
6940 }
6941 }
6942 return list;
6943}
6944
6945/*
6946 * Sort the results of file name expansion. It calculates the number of
6947 * strings to sort and then calls msort (short for merge sort) to do the
6948 * work.
6949 */
6950static struct strlist *
6951expsort(struct strlist *str)
6952{
6953 int len;
6954 struct strlist *sp;
6955
6956 len = 0;
6957 for (sp = str; sp; sp = sp->next)
6958 len++;
6959 return msort(str, len);
6960}
6961
6962static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006963expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006964{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006965 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006966 '*', '?', '[', 0
6967 };
6968 /* TODO - EXP_REDIR */
6969
6970 while (str) {
6971 struct strlist **savelastp;
6972 struct strlist *sp;
6973 char *p;
6974
6975 if (fflag)
6976 goto nometa;
6977 if (!strpbrk(str->text, metachars))
6978 goto nometa;
6979 savelastp = exparg.lastp;
6980
6981 INT_OFF;
6982 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6983 {
6984 int i = strlen(str->text);
6985 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6986 }
6987
6988 expmeta(expdir, p);
6989 free(expdir);
6990 if (p != str->text)
6991 free(p);
6992 INT_ON;
6993 if (exparg.lastp == savelastp) {
6994 /*
6995 * no matches
6996 */
6997 nometa:
6998 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006999 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007000 exparg.lastp = &str->next;
7001 } else {
7002 *exparg.lastp = NULL;
7003 *savelastp = sp = expsort(*savelastp);
7004 while (sp->next != NULL)
7005 sp = sp->next;
7006 exparg.lastp = &sp->next;
7007 }
7008 str = str->next;
7009 }
7010}
7011
7012/*
7013 * Perform variable substitution and command substitution on an argument,
7014 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7015 * perform splitting and file name expansion. When arglist is NULL, perform
7016 * here document expansion.
7017 */
7018static void
7019expandarg(union node *arg, struct arglist *arglist, int flag)
7020{
7021 struct strlist *sp;
7022 char *p;
7023
7024 argbackq = arg->narg.backquote;
7025 STARTSTACKSTR(expdest);
7026 ifsfirst.next = NULL;
7027 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007028 argstr(arg->narg.text, flag,
7029 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007030 p = _STPUTC('\0', expdest);
7031 expdest = p - 1;
7032 if (arglist == NULL) {
7033 return; /* here document expanded */
7034 }
7035 p = grabstackstr(p);
7036 exparg.lastp = &exparg.list;
7037 /*
7038 * TODO - EXP_REDIR
7039 */
7040 if (flag & EXP_FULL) {
7041 ifsbreakup(p, &exparg);
7042 *exparg.lastp = NULL;
7043 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007044 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007045 } else {
7046 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007047 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007048 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007049 sp->text = p;
7050 *exparg.lastp = sp;
7051 exparg.lastp = &sp->next;
7052 }
7053 if (ifsfirst.next)
7054 ifsfree();
7055 *exparg.lastp = NULL;
7056 if (exparg.list) {
7057 *arglist->lastp = exparg.list;
7058 arglist->lastp = exparg.lastp;
7059 }
7060}
7061
7062/*
7063 * Expand shell variables and backquotes inside a here document.
7064 */
7065static void
7066expandhere(union node *arg, int fd)
7067{
7068 herefd = fd;
7069 expandarg(arg, (struct arglist *)NULL, 0);
7070 full_write(fd, stackblock(), expdest - (char *)stackblock());
7071}
7072
7073/*
7074 * Returns true if the pattern matches the string.
7075 */
7076static int
7077patmatch(char *pattern, const char *string)
7078{
7079 return pmatch(preglob(pattern, 0, 0), string);
7080}
7081
7082/*
7083 * See if a pattern matches in a case statement.
7084 */
7085static int
7086casematch(union node *pattern, char *val)
7087{
7088 struct stackmark smark;
7089 int result;
7090
7091 setstackmark(&smark);
7092 argbackq = pattern->narg.backquote;
7093 STARTSTACKSTR(expdest);
7094 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007095 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7096 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007097 STACKSTRNUL(expdest);
7098 result = patmatch(stackblock(), val);
7099 popstackmark(&smark);
7100 return result;
7101}
7102
7103
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007104/* ============ find_command */
7105
7106struct builtincmd {
7107 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007108 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007109 /* unsigned flags; */
7110};
7111#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007112/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007113 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007114#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007115#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007116
7117struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007118 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007119 union param {
7120 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007121 /* index >= 0 for commands without path (slashes) */
7122 /* (TODO: what exactly does the value mean? PATH position?) */
7123 /* index == -1 for commands with slashes */
7124 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125 const struct builtincmd *cmd;
7126 struct funcnode *func;
7127 } u;
7128};
7129/* values of cmdtype */
7130#define CMDUNKNOWN -1 /* no entry in table for command */
7131#define CMDNORMAL 0 /* command is an executable program */
7132#define CMDFUNCTION 1 /* command is a shell function */
7133#define CMDBUILTIN 2 /* command is a shell builtin */
7134
7135/* action to find_command() */
7136#define DO_ERR 0x01 /* prints errors */
7137#define DO_ABS 0x02 /* checks absolute paths */
7138#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7139#define DO_ALTPATH 0x08 /* using alternate path */
7140#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7141
7142static void find_command(char *, struct cmdentry *, int, const char *);
7143
7144
7145/* ============ Hashing commands */
7146
7147/*
7148 * When commands are first encountered, they are entered in a hash table.
7149 * This ensures that a full path search will not have to be done for them
7150 * on each invocation.
7151 *
7152 * We should investigate converting to a linear search, even though that
7153 * would make the command name "hash" a misnomer.
7154 */
7155
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007156struct tblentry {
7157 struct tblentry *next; /* next entry in hash chain */
7158 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007159 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007160 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007161 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162};
7163
Denis Vlasenko01631112007-12-16 17:20:38 +00007164static struct tblentry **cmdtable;
7165#define INIT_G_cmdtable() do { \
7166 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7167} while (0)
7168
7169static int builtinloc = -1; /* index in path of %builtin, or -1 */
7170
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171
7172static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007173tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174{
7175 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007177#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007178 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007179 if (APPLET_IS_NOEXEC(applet_no)) {
7180 while (*envp)
7181 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007182 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007183 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007184 /* re-exec ourselves with the new arguments */
7185 execve(bb_busybox_exec_path, argv, envp);
7186 /* If they called chroot or otherwise made the binary no longer
7187 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007188 }
7189#endif
7190
7191 repeat:
7192#ifdef SYSV
7193 do {
7194 execve(cmd, argv, envp);
7195 } while (errno == EINTR);
7196#else
7197 execve(cmd, argv, envp);
7198#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007199 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007200 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007201 return;
7202 }
7203 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007204 char **ap;
7205 char **new;
7206
7207 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007208 continue;
7209 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007210 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007211 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007212 ap += 2;
7213 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007214 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007215 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007216 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007217 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007218 goto repeat;
7219 }
7220}
7221
7222/*
7223 * Exec a program. Never returns. If you change this routine, you may
7224 * have to change the find_command routine as well.
7225 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007226static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007227static void
7228shellexec(char **argv, const char *path, int idx)
7229{
7230 char *cmdname;
7231 int e;
7232 char **envp;
7233 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007234#if ENABLE_FEATURE_SH_STANDALONE
7235 int applet_no = -1;
7236#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007238 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007239 envp = listvars(VEXPORT, VUNSET, 0);
7240 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007241#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007242 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243#endif
7244 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007245 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246 e = errno;
7247 } else {
7248 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007249 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007250 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007251 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007252 if (errno != ENOENT && errno != ENOTDIR)
7253 e = errno;
7254 }
7255 stunalloc(cmdname);
7256 }
7257 }
7258
7259 /* Map to POSIX errors */
7260 switch (e) {
7261 case EACCES:
7262 exerrno = 126;
7263 break;
7264 case ENOENT:
7265 exerrno = 127;
7266 break;
7267 default:
7268 exerrno = 2;
7269 break;
7270 }
7271 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007272 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7273 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007274 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7275 /* NOTREACHED */
7276}
7277
7278static void
7279printentry(struct tblentry *cmdp)
7280{
7281 int idx;
7282 const char *path;
7283 char *name;
7284
7285 idx = cmdp->param.index;
7286 path = pathval();
7287 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007288 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007289 stunalloc(name);
7290 } while (--idx >= 0);
7291 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7292}
7293
7294/*
7295 * Clear out command entries. The argument specifies the first entry in
7296 * PATH which has changed.
7297 */
7298static void
7299clearcmdentry(int firstchange)
7300{
7301 struct tblentry **tblp;
7302 struct tblentry **pp;
7303 struct tblentry *cmdp;
7304
7305 INT_OFF;
7306 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7307 pp = tblp;
7308 while ((cmdp = *pp) != NULL) {
7309 if ((cmdp->cmdtype == CMDNORMAL &&
7310 cmdp->param.index >= firstchange)
7311 || (cmdp->cmdtype == CMDBUILTIN &&
7312 builtinloc >= firstchange)
7313 ) {
7314 *pp = cmdp->next;
7315 free(cmdp);
7316 } else {
7317 pp = &cmdp->next;
7318 }
7319 }
7320 }
7321 INT_ON;
7322}
7323
7324/*
7325 * Locate a command in the command hash table. If "add" is nonzero,
7326 * add the command to the table if it is not already present. The
7327 * variable "lastcmdentry" is set to point to the address of the link
7328 * pointing to the entry, so that delete_cmd_entry can delete the
7329 * entry.
7330 *
7331 * Interrupts must be off if called with add != 0.
7332 */
7333static struct tblentry **lastcmdentry;
7334
7335static struct tblentry *
7336cmdlookup(const char *name, int add)
7337{
7338 unsigned int hashval;
7339 const char *p;
7340 struct tblentry *cmdp;
7341 struct tblentry **pp;
7342
7343 p = name;
7344 hashval = (unsigned char)*p << 4;
7345 while (*p)
7346 hashval += (unsigned char)*p++;
7347 hashval &= 0x7FFF;
7348 pp = &cmdtable[hashval % CMDTABLESIZE];
7349 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7350 if (strcmp(cmdp->cmdname, name) == 0)
7351 break;
7352 pp = &cmdp->next;
7353 }
7354 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007355 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7356 + strlen(name)
7357 /* + 1 - already done because
7358 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007359 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007360 cmdp->cmdtype = CMDUNKNOWN;
7361 strcpy(cmdp->cmdname, name);
7362 }
7363 lastcmdentry = pp;
7364 return cmdp;
7365}
7366
7367/*
7368 * Delete the command entry returned on the last lookup.
7369 */
7370static void
7371delete_cmd_entry(void)
7372{
7373 struct tblentry *cmdp;
7374
7375 INT_OFF;
7376 cmdp = *lastcmdentry;
7377 *lastcmdentry = cmdp->next;
7378 if (cmdp->cmdtype == CMDFUNCTION)
7379 freefunc(cmdp->param.func);
7380 free(cmdp);
7381 INT_ON;
7382}
7383
7384/*
7385 * Add a new command entry, replacing any existing command entry for
7386 * the same name - except special builtins.
7387 */
7388static void
7389addcmdentry(char *name, struct cmdentry *entry)
7390{
7391 struct tblentry *cmdp;
7392
7393 cmdp = cmdlookup(name, 1);
7394 if (cmdp->cmdtype == CMDFUNCTION) {
7395 freefunc(cmdp->param.func);
7396 }
7397 cmdp->cmdtype = entry->cmdtype;
7398 cmdp->param = entry->u;
7399 cmdp->rehash = 0;
7400}
7401
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007402static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007403hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007404{
7405 struct tblentry **pp;
7406 struct tblentry *cmdp;
7407 int c;
7408 struct cmdentry entry;
7409 char *name;
7410
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007411 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007412 clearcmdentry(0);
7413 return 0;
7414 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007415
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007416 if (*argptr == NULL) {
7417 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7418 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7419 if (cmdp->cmdtype == CMDNORMAL)
7420 printentry(cmdp);
7421 }
7422 }
7423 return 0;
7424 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007425
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007426 c = 0;
7427 while ((name = *argptr) != NULL) {
7428 cmdp = cmdlookup(name, 0);
7429 if (cmdp != NULL
7430 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007431 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7432 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007433 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007434 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007435 find_command(name, &entry, DO_ERR, pathval());
7436 if (entry.cmdtype == CMDUNKNOWN)
7437 c = 1;
7438 argptr++;
7439 }
7440 return c;
7441}
7442
7443/*
7444 * Called when a cd is done. Marks all commands so the next time they
7445 * are executed they will be rehashed.
7446 */
7447static void
7448hashcd(void)
7449{
7450 struct tblentry **pp;
7451 struct tblentry *cmdp;
7452
7453 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7454 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007455 if (cmdp->cmdtype == CMDNORMAL
7456 || (cmdp->cmdtype == CMDBUILTIN
7457 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7458 && builtinloc > 0)
7459 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007460 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007461 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007462 }
7463 }
7464}
7465
7466/*
7467 * Fix command hash table when PATH changed.
7468 * Called before PATH is changed. The argument is the new value of PATH;
7469 * pathval() still returns the old value at this point.
7470 * Called with interrupts off.
7471 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007472static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007473changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007474{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007475 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007476 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007477 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007478 int idx_bltin;
7479
7480 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007481 firstchange = 9999; /* assume no change */
7482 idx = 0;
7483 idx_bltin = -1;
7484 for (;;) {
7485 if (*old != *new) {
7486 firstchange = idx;
7487 if ((*old == '\0' && *new == ':')
7488 || (*old == ':' && *new == '\0'))
7489 firstchange++;
7490 old = new; /* ignore subsequent differences */
7491 }
7492 if (*new == '\0')
7493 break;
7494 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7495 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007496 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007498 new++, old++;
7499 }
7500 if (builtinloc < 0 && idx_bltin >= 0)
7501 builtinloc = idx_bltin; /* zap builtins */
7502 if (builtinloc >= 0 && idx_bltin < 0)
7503 firstchange = 0;
7504 clearcmdentry(firstchange);
7505 builtinloc = idx_bltin;
7506}
7507
7508#define TEOF 0
7509#define TNL 1
7510#define TREDIR 2
7511#define TWORD 3
7512#define TSEMI 4
7513#define TBACKGND 5
7514#define TAND 6
7515#define TOR 7
7516#define TPIPE 8
7517#define TLP 9
7518#define TRP 10
7519#define TENDCASE 11
7520#define TENDBQUOTE 12
7521#define TNOT 13
7522#define TCASE 14
7523#define TDO 15
7524#define TDONE 16
7525#define TELIF 17
7526#define TELSE 18
7527#define TESAC 19
7528#define TFI 20
7529#define TFOR 21
7530#define TIF 22
7531#define TIN 23
7532#define TTHEN 24
7533#define TUNTIL 25
7534#define TWHILE 26
7535#define TBEGIN 27
7536#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007537typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007538
7539/* first char is indicating which tokens mark the end of a list */
7540static const char *const tokname_array[] = {
7541 "\1end of file",
7542 "\0newline",
7543 "\0redirection",
7544 "\0word",
7545 "\0;",
7546 "\0&",
7547 "\0&&",
7548 "\0||",
7549 "\0|",
7550 "\0(",
7551 "\1)",
7552 "\1;;",
7553 "\1`",
7554#define KWDOFFSET 13
7555 /* the following are keywords */
7556 "\0!",
7557 "\0case",
7558 "\1do",
7559 "\1done",
7560 "\1elif",
7561 "\1else",
7562 "\1esac",
7563 "\1fi",
7564 "\0for",
7565 "\0if",
7566 "\0in",
7567 "\1then",
7568 "\0until",
7569 "\0while",
7570 "\0{",
7571 "\1}",
7572};
7573
7574static const char *
7575tokname(int tok)
7576{
7577 static char buf[16];
7578
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007579//try this:
7580//if (tok < TSEMI) return tokname_array[tok] + 1;
7581//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7582//return buf;
7583
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007584 if (tok >= TSEMI)
7585 buf[0] = '"';
7586 sprintf(buf + (tok >= TSEMI), "%s%c",
7587 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7588 return buf;
7589}
7590
7591/* Wrapper around strcmp for qsort/bsearch/... */
7592static int
7593pstrcmp(const void *a, const void *b)
7594{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007595 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007596}
7597
7598static const char *const *
7599findkwd(const char *s)
7600{
7601 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007602 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7603 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007604}
7605
7606/*
7607 * Locate and print what a word is...
7608 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007609static int
7610describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007611{
7612 struct cmdentry entry;
7613 struct tblentry *cmdp;
7614#if ENABLE_ASH_ALIAS
7615 const struct alias *ap;
7616#endif
7617 const char *path = pathval();
7618
7619 if (describe_command_verbose) {
7620 out1str(command);
7621 }
7622
7623 /* First look at the keywords */
7624 if (findkwd(command)) {
7625 out1str(describe_command_verbose ? " is a shell keyword" : command);
7626 goto out;
7627 }
7628
7629#if ENABLE_ASH_ALIAS
7630 /* Then look at the aliases */
7631 ap = lookupalias(command, 0);
7632 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007633 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634 out1str("alias ");
7635 printalias(ap);
7636 return 0;
7637 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007638 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007639 goto out;
7640 }
7641#endif
7642 /* Then check if it is a tracked alias */
7643 cmdp = cmdlookup(command, 0);
7644 if (cmdp != NULL) {
7645 entry.cmdtype = cmdp->cmdtype;
7646 entry.u = cmdp->param;
7647 } else {
7648 /* Finally use brute force */
7649 find_command(command, &entry, DO_ABS, path);
7650 }
7651
7652 switch (entry.cmdtype) {
7653 case CMDNORMAL: {
7654 int j = entry.u.index;
7655 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007656 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657 p = command;
7658 } else {
7659 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007660 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007661 stunalloc(p);
7662 } while (--j >= 0);
7663 }
7664 if (describe_command_verbose) {
7665 out1fmt(" is%s %s",
7666 (cmdp ? " a tracked alias for" : nullstr), p
7667 );
7668 } else {
7669 out1str(p);
7670 }
7671 break;
7672 }
7673
7674 case CMDFUNCTION:
7675 if (describe_command_verbose) {
7676 out1str(" is a shell function");
7677 } else {
7678 out1str(command);
7679 }
7680 break;
7681
7682 case CMDBUILTIN:
7683 if (describe_command_verbose) {
7684 out1fmt(" is a %sshell builtin",
7685 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7686 "special " : nullstr
7687 );
7688 } else {
7689 out1str(command);
7690 }
7691 break;
7692
7693 default:
7694 if (describe_command_verbose) {
7695 out1str(": not found\n");
7696 }
7697 return 127;
7698 }
7699 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007700 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007701 return 0;
7702}
7703
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007704static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007705typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007706{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007707 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007708 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007709 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007710
Denis Vlasenko46846e22007-05-20 13:08:31 +00007711 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007712 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007713 i++;
7714 verbose = 0;
7715 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007716 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007717 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007718 }
7719 return err;
7720}
7721
7722#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007723static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007724commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007725{
7726 int c;
7727 enum {
7728 VERIFY_BRIEF = 1,
7729 VERIFY_VERBOSE = 2,
7730 } verify = 0;
7731
7732 while ((c = nextopt("pvV")) != '\0')
7733 if (c == 'V')
7734 verify |= VERIFY_VERBOSE;
7735 else if (c == 'v')
7736 verify |= VERIFY_BRIEF;
7737#if DEBUG
7738 else if (c != 'p')
7739 abort();
7740#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007741 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7742 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007743 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007744 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007745
7746 return 0;
7747}
7748#endif
7749
7750
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007751/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007752
Denis Vlasenko340299a2008-11-21 10:36:36 +00007753static int funcblocksize; /* size of structures in function */
7754static int funcstringsize; /* size of strings in node */
7755static void *funcblock; /* block to allocate function from */
7756static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007757
Eric Andersencb57d552001-06-28 07:25:16 +00007758/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007759#define EV_EXIT 01 /* exit after evaluating tree */
7760#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007761#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007762
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007763static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007764 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7765 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7766 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7767 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7768 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7769 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7770 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7771 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7772 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7773 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7774 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7775 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7776 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7777 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7778 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7779 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7780 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007781#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007782 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007783#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007784 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7785 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7786 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7787 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7788 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7789 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7790 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7791 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7792 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007793};
7794
7795static void calcsize(union node *n);
7796
7797static void
7798sizenodelist(struct nodelist *lp)
7799{
7800 while (lp) {
7801 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7802 calcsize(lp->n);
7803 lp = lp->next;
7804 }
7805}
7806
7807static void
7808calcsize(union node *n)
7809{
7810 if (n == NULL)
7811 return;
7812 funcblocksize += nodesize[n->type];
7813 switch (n->type) {
7814 case NCMD:
7815 calcsize(n->ncmd.redirect);
7816 calcsize(n->ncmd.args);
7817 calcsize(n->ncmd.assign);
7818 break;
7819 case NPIPE:
7820 sizenodelist(n->npipe.cmdlist);
7821 break;
7822 case NREDIR:
7823 case NBACKGND:
7824 case NSUBSHELL:
7825 calcsize(n->nredir.redirect);
7826 calcsize(n->nredir.n);
7827 break;
7828 case NAND:
7829 case NOR:
7830 case NSEMI:
7831 case NWHILE:
7832 case NUNTIL:
7833 calcsize(n->nbinary.ch2);
7834 calcsize(n->nbinary.ch1);
7835 break;
7836 case NIF:
7837 calcsize(n->nif.elsepart);
7838 calcsize(n->nif.ifpart);
7839 calcsize(n->nif.test);
7840 break;
7841 case NFOR:
7842 funcstringsize += strlen(n->nfor.var) + 1;
7843 calcsize(n->nfor.body);
7844 calcsize(n->nfor.args);
7845 break;
7846 case NCASE:
7847 calcsize(n->ncase.cases);
7848 calcsize(n->ncase.expr);
7849 break;
7850 case NCLIST:
7851 calcsize(n->nclist.body);
7852 calcsize(n->nclist.pattern);
7853 calcsize(n->nclist.next);
7854 break;
7855 case NDEFUN:
7856 case NARG:
7857 sizenodelist(n->narg.backquote);
7858 funcstringsize += strlen(n->narg.text) + 1;
7859 calcsize(n->narg.next);
7860 break;
7861 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007862#if ENABLE_ASH_BASH_COMPAT
7863 case NTO2:
7864#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007865 case NCLOBBER:
7866 case NFROM:
7867 case NFROMTO:
7868 case NAPPEND:
7869 calcsize(n->nfile.fname);
7870 calcsize(n->nfile.next);
7871 break;
7872 case NTOFD:
7873 case NFROMFD:
7874 calcsize(n->ndup.vname);
7875 calcsize(n->ndup.next);
7876 break;
7877 case NHERE:
7878 case NXHERE:
7879 calcsize(n->nhere.doc);
7880 calcsize(n->nhere.next);
7881 break;
7882 case NNOT:
7883 calcsize(n->nnot.com);
7884 break;
7885 };
7886}
7887
7888static char *
7889nodeckstrdup(char *s)
7890{
7891 char *rtn = funcstring;
7892
7893 strcpy(funcstring, s);
7894 funcstring += strlen(s) + 1;
7895 return rtn;
7896}
7897
7898static union node *copynode(union node *);
7899
7900static struct nodelist *
7901copynodelist(struct nodelist *lp)
7902{
7903 struct nodelist *start;
7904 struct nodelist **lpp;
7905
7906 lpp = &start;
7907 while (lp) {
7908 *lpp = funcblock;
7909 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7910 (*lpp)->n = copynode(lp->n);
7911 lp = lp->next;
7912 lpp = &(*lpp)->next;
7913 }
7914 *lpp = NULL;
7915 return start;
7916}
7917
7918static union node *
7919copynode(union node *n)
7920{
7921 union node *new;
7922
7923 if (n == NULL)
7924 return NULL;
7925 new = funcblock;
7926 funcblock = (char *) funcblock + nodesize[n->type];
7927
7928 switch (n->type) {
7929 case NCMD:
7930 new->ncmd.redirect = copynode(n->ncmd.redirect);
7931 new->ncmd.args = copynode(n->ncmd.args);
7932 new->ncmd.assign = copynode(n->ncmd.assign);
7933 break;
7934 case NPIPE:
7935 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007936 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007937 break;
7938 case NREDIR:
7939 case NBACKGND:
7940 case NSUBSHELL:
7941 new->nredir.redirect = copynode(n->nredir.redirect);
7942 new->nredir.n = copynode(n->nredir.n);
7943 break;
7944 case NAND:
7945 case NOR:
7946 case NSEMI:
7947 case NWHILE:
7948 case NUNTIL:
7949 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7950 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7951 break;
7952 case NIF:
7953 new->nif.elsepart = copynode(n->nif.elsepart);
7954 new->nif.ifpart = copynode(n->nif.ifpart);
7955 new->nif.test = copynode(n->nif.test);
7956 break;
7957 case NFOR:
7958 new->nfor.var = nodeckstrdup(n->nfor.var);
7959 new->nfor.body = copynode(n->nfor.body);
7960 new->nfor.args = copynode(n->nfor.args);
7961 break;
7962 case NCASE:
7963 new->ncase.cases = copynode(n->ncase.cases);
7964 new->ncase.expr = copynode(n->ncase.expr);
7965 break;
7966 case NCLIST:
7967 new->nclist.body = copynode(n->nclist.body);
7968 new->nclist.pattern = copynode(n->nclist.pattern);
7969 new->nclist.next = copynode(n->nclist.next);
7970 break;
7971 case NDEFUN:
7972 case NARG:
7973 new->narg.backquote = copynodelist(n->narg.backquote);
7974 new->narg.text = nodeckstrdup(n->narg.text);
7975 new->narg.next = copynode(n->narg.next);
7976 break;
7977 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007978#if ENABLE_ASH_BASH_COMPAT
7979 case NTO2:
7980#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007981 case NCLOBBER:
7982 case NFROM:
7983 case NFROMTO:
7984 case NAPPEND:
7985 new->nfile.fname = copynode(n->nfile.fname);
7986 new->nfile.fd = n->nfile.fd;
7987 new->nfile.next = copynode(n->nfile.next);
7988 break;
7989 case NTOFD:
7990 case NFROMFD:
7991 new->ndup.vname = copynode(n->ndup.vname);
7992 new->ndup.dupfd = n->ndup.dupfd;
7993 new->ndup.fd = n->ndup.fd;
7994 new->ndup.next = copynode(n->ndup.next);
7995 break;
7996 case NHERE:
7997 case NXHERE:
7998 new->nhere.doc = copynode(n->nhere.doc);
7999 new->nhere.fd = n->nhere.fd;
8000 new->nhere.next = copynode(n->nhere.next);
8001 break;
8002 case NNOT:
8003 new->nnot.com = copynode(n->nnot.com);
8004 break;
8005 };
8006 new->type = n->type;
8007 return new;
8008}
8009
8010/*
8011 * Make a copy of a parse tree.
8012 */
8013static struct funcnode *
8014copyfunc(union node *n)
8015{
8016 struct funcnode *f;
8017 size_t blocksize;
8018
8019 funcblocksize = offsetof(struct funcnode, n);
8020 funcstringsize = 0;
8021 calcsize(n);
8022 blocksize = funcblocksize;
8023 f = ckmalloc(blocksize + funcstringsize);
8024 funcblock = (char *) f + offsetof(struct funcnode, n);
8025 funcstring = (char *) f + blocksize;
8026 copynode(n);
8027 f->count = 0;
8028 return f;
8029}
8030
8031/*
8032 * Define a shell function.
8033 */
8034static void
8035defun(char *name, union node *func)
8036{
8037 struct cmdentry entry;
8038
8039 INT_OFF;
8040 entry.cmdtype = CMDFUNCTION;
8041 entry.u.func = copyfunc(func);
8042 addcmdentry(name, &entry);
8043 INT_ON;
8044}
8045
Denis Vlasenko4b875702009-03-19 13:30:04 +00008046/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008047#define SKIPBREAK (1 << 0)
8048#define SKIPCONT (1 << 1)
8049#define SKIPFUNC (1 << 2)
8050#define SKIPFILE (1 << 3)
8051#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008052static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008053static int skipcount; /* number of levels to skip */
8054static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008055static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008056
Denis Vlasenko4b875702009-03-19 13:30:04 +00008057/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008058static int evalstring(char *s, int mask);
8059
Denis Vlasenko4b875702009-03-19 13:30:04 +00008060/* Called to execute a trap.
8061 * Single callsite - at the end of evaltree().
8062 * If we return non-zero, exaltree raises EXEXIT exception.
8063 *
8064 * Perhaps we should avoid entering new trap handlers
8065 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008066 */
8067static int
8068dotrap(void)
8069{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008070 uint8_t *g;
8071 int sig;
8072 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008073
8074 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008075 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008076 xbarrier();
8077
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008078 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008079 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8080 int want_exexit;
8081 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008082
Denis Vlasenko4b875702009-03-19 13:30:04 +00008083 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008084 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008085 t = trap[sig];
8086 /* non-trapped SIGINT is handled separately by raise_interrupt,
8087 * don't upset it by resetting gotsig[SIGINT-1] */
8088 if (sig == SIGINT && !t)
8089 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008090
8091 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008092 *g = 0;
8093 if (!t)
8094 continue;
8095 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008096 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008097 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008098 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008099 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008100 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008101 }
8102
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008103 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008104 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008105}
8106
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008107/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008108static void evalloop(union node *, int);
8109static void evalfor(union node *, int);
8110static void evalcase(union node *, int);
8111static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008112static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008113static void evalpipe(union node *, int);
8114static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008115static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008116static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008117
Eric Andersen62483552001-07-10 06:09:16 +00008118/*
Eric Andersenc470f442003-07-28 09:56:35 +00008119 * Evaluate a parse tree. The value is left in the global variable
8120 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008121 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008122static void
Eric Andersenc470f442003-07-28 09:56:35 +00008123evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008124{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008125 struct jmploc *volatile savehandler = exception_handler;
8126 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008127 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008128 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008129 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008130 int int_level;
8131
8132 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008133
Eric Andersenc470f442003-07-28 09:56:35 +00008134 if (n == NULL) {
8135 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008137 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008138 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008139
8140 exception_handler = &jmploc;
8141 {
8142 int err = setjmp(jmploc.loc);
8143 if (err) {
8144 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008145 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008146 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8147 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008148 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008149 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008150 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008151 TRACE(("exception %d in evaltree, propagating err=%d\n",
8152 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008153 exception_handler = savehandler;
8154 longjmp(exception_handler->loc, err);
8155 }
8156 }
8157
Eric Andersenc470f442003-07-28 09:56:35 +00008158 switch (n->type) {
8159 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008160#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008161 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008162 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008163 break;
8164#endif
8165 case NNOT:
8166 evaltree(n->nnot.com, EV_TESTED);
8167 status = !exitstatus;
8168 goto setstatus;
8169 case NREDIR:
8170 expredir(n->nredir.redirect);
8171 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8172 if (!status) {
8173 evaltree(n->nredir.n, flags & EV_TESTED);
8174 status = exitstatus;
8175 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008176 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008177 goto setstatus;
8178 case NCMD:
8179 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008180 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008181 if (eflag && !(flags & EV_TESTED))
8182 checkexit = ~0;
8183 goto calleval;
8184 case NFOR:
8185 evalfn = evalfor;
8186 goto calleval;
8187 case NWHILE:
8188 case NUNTIL:
8189 evalfn = evalloop;
8190 goto calleval;
8191 case NSUBSHELL:
8192 case NBACKGND:
8193 evalfn = evalsubshell;
8194 goto calleval;
8195 case NPIPE:
8196 evalfn = evalpipe;
8197 goto checkexit;
8198 case NCASE:
8199 evalfn = evalcase;
8200 goto calleval;
8201 case NAND:
8202 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008203 case NSEMI: {
8204
Eric Andersenc470f442003-07-28 09:56:35 +00008205#if NAND + 1 != NOR
8206#error NAND + 1 != NOR
8207#endif
8208#if NOR + 1 != NSEMI
8209#error NOR + 1 != NSEMI
8210#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008211 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008212 evaltree(
8213 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008214 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008215 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008216 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008217 break;
8218 if (!evalskip) {
8219 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008220 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008221 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008222 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008223 evalfn(n, flags);
8224 break;
8225 }
8226 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008227 }
Eric Andersenc470f442003-07-28 09:56:35 +00008228 case NIF:
8229 evaltree(n->nif.test, EV_TESTED);
8230 if (evalskip)
8231 break;
8232 if (exitstatus == 0) {
8233 n = n->nif.ifpart;
8234 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008235 }
8236 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008237 n = n->nif.elsepart;
8238 goto evaln;
8239 }
8240 goto success;
8241 case NDEFUN:
8242 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008243 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008244 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008245 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008246 exitstatus = status;
8247 break;
8248 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008249
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008250 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008251 exception_handler = savehandler;
8252 out1:
8253 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008254 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008255 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008256 goto exexit;
8257
8258 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008259 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008260 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008261 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008262
8263 RESTORE_INT(int_level);
8264 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008265}
8266
Eric Andersenc470f442003-07-28 09:56:35 +00008267#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8268static
8269#endif
8270void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8271
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008272static void
Eric Andersenc470f442003-07-28 09:56:35 +00008273evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008274{
8275 int status;
8276
8277 loopnest++;
8278 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008279 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008280 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008281 int i;
8282
Eric Andersencb57d552001-06-28 07:25:16 +00008283 evaltree(n->nbinary.ch1, EV_TESTED);
8284 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008285 skipping:
8286 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008287 evalskip = 0;
8288 continue;
8289 }
8290 if (evalskip == SKIPBREAK && --skipcount <= 0)
8291 evalskip = 0;
8292 break;
8293 }
Eric Andersenc470f442003-07-28 09:56:35 +00008294 i = exitstatus;
8295 if (n->type != NWHILE)
8296 i = !i;
8297 if (i != 0)
8298 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008299 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008300 status = exitstatus;
8301 if (evalskip)
8302 goto skipping;
8303 }
8304 loopnest--;
8305 exitstatus = status;
8306}
8307
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008308static void
Eric Andersenc470f442003-07-28 09:56:35 +00008309evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008310{
8311 struct arglist arglist;
8312 union node *argp;
8313 struct strlist *sp;
8314 struct stackmark smark;
8315
8316 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008317 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008318 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008319 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008320 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008321 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008322 if (evalskip)
8323 goto out;
8324 }
8325 *arglist.lastp = NULL;
8326
8327 exitstatus = 0;
8328 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008329 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008330 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008331 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008332 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008333 if (evalskip) {
8334 if (evalskip == SKIPCONT && --skipcount <= 0) {
8335 evalskip = 0;
8336 continue;
8337 }
8338 if (evalskip == SKIPBREAK && --skipcount <= 0)
8339 evalskip = 0;
8340 break;
8341 }
8342 }
8343 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008344 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008345 popstackmark(&smark);
8346}
8347
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008348static void
Eric Andersenc470f442003-07-28 09:56:35 +00008349evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008350{
8351 union node *cp;
8352 union node *patp;
8353 struct arglist arglist;
8354 struct stackmark smark;
8355
8356 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008357 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008358 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008359 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008360 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008361 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8362 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008363 if (casematch(patp, arglist.list->text)) {
8364 if (evalskip == 0) {
8365 evaltree(cp->nclist.body, flags);
8366 }
8367 goto out;
8368 }
8369 }
8370 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008371 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008372 popstackmark(&smark);
8373}
8374
Eric Andersenc470f442003-07-28 09:56:35 +00008375/*
8376 * Kick off a subshell to evaluate a tree.
8377 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008378static void
Eric Andersenc470f442003-07-28 09:56:35 +00008379evalsubshell(union node *n, int flags)
8380{
8381 struct job *jp;
8382 int backgnd = (n->type == NBACKGND);
8383 int status;
8384
8385 expredir(n->nredir.redirect);
8386 if (!backgnd && flags & EV_EXIT && !trap[0])
8387 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008388 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008389 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008390 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008391 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008392 flags |= EV_EXIT;
8393 if (backgnd)
8394 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008395 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008396 redirect(n->nredir.redirect, 0);
8397 evaltreenr(n->nredir.n, flags);
8398 /* never returns */
8399 }
8400 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008401 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008402 status = waitforjob(jp);
8403 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008404 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008405}
8406
Eric Andersenc470f442003-07-28 09:56:35 +00008407/*
8408 * Compute the names of the files in a redirection list.
8409 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008410static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008411static void
8412expredir(union node *n)
8413{
8414 union node *redir;
8415
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008416 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008417 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008418
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008419 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008420 fn.lastp = &fn.list;
8421 switch (redir->type) {
8422 case NFROMTO:
8423 case NFROM:
8424 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008425#if ENABLE_ASH_BASH_COMPAT
8426 case NTO2:
8427#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008428 case NCLOBBER:
8429 case NAPPEND:
8430 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008431#if ENABLE_ASH_BASH_COMPAT
8432 store_expfname:
8433#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008434 redir->nfile.expfname = fn.list->text;
8435 break;
8436 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008437 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008438 if (redir->ndup.vname) {
8439 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008440 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008441 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008442#if ENABLE_ASH_BASH_COMPAT
8443//FIXME: we used expandarg with different args!
8444 if (!isdigit_str9(fn.list->text)) {
8445 /* >&file, not >&fd */
8446 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8447 ash_msg_and_raise_error("redir error");
8448 redir->type = NTO2;
8449 goto store_expfname;
8450 }
8451#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008452 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008453 }
8454 break;
8455 }
8456 }
8457}
8458
Eric Andersencb57d552001-06-28 07:25:16 +00008459/*
Eric Andersencb57d552001-06-28 07:25:16 +00008460 * Evaluate a pipeline. All the processes in the pipeline are children
8461 * of the process creating the pipeline. (This differs from some versions
8462 * of the shell, which make the last process in a pipeline the parent
8463 * of all the rest.)
8464 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008465static void
Eric Andersenc470f442003-07-28 09:56:35 +00008466evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008467{
8468 struct job *jp;
8469 struct nodelist *lp;
8470 int pipelen;
8471 int prevfd;
8472 int pip[2];
8473
Eric Andersenc470f442003-07-28 09:56:35 +00008474 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008475 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008476 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008477 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008478 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008479 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008480 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008481 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008482 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008483 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008484 pip[1] = -1;
8485 if (lp->next) {
8486 if (pipe(pip) < 0) {
8487 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008488 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008489 }
8490 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008491 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008492 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008493 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008494 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008495 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008496 if (prevfd > 0) {
8497 dup2(prevfd, 0);
8498 close(prevfd);
8499 }
8500 if (pip[1] > 1) {
8501 dup2(pip[1], 1);
8502 close(pip[1]);
8503 }
Eric Andersenc470f442003-07-28 09:56:35 +00008504 evaltreenr(lp->n, flags);
8505 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008506 }
8507 if (prevfd >= 0)
8508 close(prevfd);
8509 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008510 /* Don't want to trigger debugging */
8511 if (pip[1] != -1)
8512 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008513 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008514 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008515 exitstatus = waitforjob(jp);
8516 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008517 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008518 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008519}
8520
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008521/*
8522 * Controls whether the shell is interactive or not.
8523 */
8524static void
8525setinteractive(int on)
8526{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008527 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008528
8529 if (++on == is_interactive)
8530 return;
8531 is_interactive = on;
8532 setsignal(SIGINT);
8533 setsignal(SIGQUIT);
8534 setsignal(SIGTERM);
8535#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8536 if (is_interactive > 1) {
8537 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008538 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008539
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008540 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008541 /* note: ash and hush share this string */
8542 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008543 "Enter 'help' for a list of built-in commands."
8544 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008545 bb_banner,
8546 "built-in shell (ash)"
8547 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008548 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008549 }
8550 }
8551#endif
8552}
8553
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008554static void
8555optschanged(void)
8556{
8557#if DEBUG
8558 opentrace();
8559#endif
8560 setinteractive(iflag);
8561 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008562#if ENABLE_FEATURE_EDITING_VI
8563 if (viflag)
8564 line_input_state->flags |= VI_MODE;
8565 else
8566 line_input_state->flags &= ~VI_MODE;
8567#else
8568 viflag = 0; /* forcibly keep the option off */
8569#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008570}
8571
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008572static struct localvar *localvars;
8573
8574/*
8575 * Called after a function returns.
8576 * Interrupts must be off.
8577 */
8578static void
8579poplocalvars(void)
8580{
8581 struct localvar *lvp;
8582 struct var *vp;
8583
8584 while ((lvp = localvars) != NULL) {
8585 localvars = lvp->next;
8586 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008587 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008588 if (vp == NULL) { /* $- saved */
8589 memcpy(optlist, lvp->text, sizeof(optlist));
8590 free((char*)lvp->text);
8591 optschanged();
8592 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8593 unsetvar(vp->text);
8594 } else {
8595 if (vp->func)
8596 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8597 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8598 free((char*)vp->text);
8599 vp->flags = lvp->flags;
8600 vp->text = lvp->text;
8601 }
8602 free(lvp);
8603 }
8604}
8605
8606static int
8607evalfun(struct funcnode *func, int argc, char **argv, int flags)
8608{
8609 volatile struct shparam saveparam;
8610 struct localvar *volatile savelocalvars;
8611 struct jmploc *volatile savehandler;
8612 struct jmploc jmploc;
8613 int e;
8614
8615 saveparam = shellparam;
8616 savelocalvars = localvars;
8617 e = setjmp(jmploc.loc);
8618 if (e) {
8619 goto funcdone;
8620 }
8621 INT_OFF;
8622 savehandler = exception_handler;
8623 exception_handler = &jmploc;
8624 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008625 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008626 func->count++;
8627 funcnest++;
8628 INT_ON;
8629 shellparam.nparam = argc - 1;
8630 shellparam.p = argv + 1;
8631#if ENABLE_ASH_GETOPTS
8632 shellparam.optind = 1;
8633 shellparam.optoff = -1;
8634#endif
8635 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008636 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008637 INT_OFF;
8638 funcnest--;
8639 freefunc(func);
8640 poplocalvars();
8641 localvars = savelocalvars;
8642 freeparam(&shellparam);
8643 shellparam = saveparam;
8644 exception_handler = savehandler;
8645 INT_ON;
8646 evalskip &= ~SKIPFUNC;
8647 return e;
8648}
8649
Denis Vlasenko131ae172007-02-18 13:00:19 +00008650#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008651static char **
8652parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008653{
8654 char *cp, c;
8655
8656 for (;;) {
8657 cp = *++argv;
8658 if (!cp)
8659 return 0;
8660 if (*cp++ != '-')
8661 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008662 c = *cp++;
8663 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008664 break;
8665 if (c == '-' && !*cp) {
8666 argv++;
8667 break;
8668 }
8669 do {
8670 switch (c) {
8671 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008672 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008673 break;
8674 default:
8675 /* run 'typecmd' for other options */
8676 return 0;
8677 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008678 c = *cp++;
8679 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008680 }
8681 return argv;
8682}
8683#endif
8684
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008685/*
8686 * Make a variable a local variable. When a variable is made local, it's
8687 * value and flags are saved in a localvar structure. The saved values
8688 * will be restored when the shell function returns. We handle the name
8689 * "-" as a special case.
8690 */
8691static void
8692mklocal(char *name)
8693{
8694 struct localvar *lvp;
8695 struct var **vpp;
8696 struct var *vp;
8697
8698 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008699 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008700 if (LONE_DASH(name)) {
8701 char *p;
8702 p = ckmalloc(sizeof(optlist));
8703 lvp->text = memcpy(p, optlist, sizeof(optlist));
8704 vp = NULL;
8705 } else {
8706 char *eq;
8707
8708 vpp = hashvar(name);
8709 vp = *findvar(vpp, name);
8710 eq = strchr(name, '=');
8711 if (vp == NULL) {
8712 if (eq)
8713 setvareq(name, VSTRFIXED);
8714 else
8715 setvar(name, NULL, VSTRFIXED);
8716 vp = *vpp; /* the new variable */
8717 lvp->flags = VUNSET;
8718 } else {
8719 lvp->text = vp->text;
8720 lvp->flags = vp->flags;
8721 vp->flags |= VSTRFIXED|VTEXTFIXED;
8722 if (eq)
8723 setvareq(name, 0);
8724 }
8725 }
8726 lvp->vp = vp;
8727 lvp->next = localvars;
8728 localvars = lvp;
8729 INT_ON;
8730}
8731
8732/*
8733 * The "local" command.
8734 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008735static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008736localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008737{
8738 char *name;
8739
8740 argv = argptr;
8741 while ((name = *argv++) != NULL) {
8742 mklocal(name);
8743 }
8744 return 0;
8745}
8746
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008747static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008748falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008749{
8750 return 1;
8751}
8752
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008753static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008754truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008755{
8756 return 0;
8757}
8758
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008759static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008760execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008761{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008762 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008763 iflag = 0; /* exit on error */
8764 mflag = 0;
8765 optschanged();
8766 shellexec(argv + 1, pathval(), 0);
8767 }
8768 return 0;
8769}
8770
8771/*
8772 * The return command.
8773 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008774static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008775returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008776{
8777 /*
8778 * If called outside a function, do what ksh does;
8779 * skip the rest of the file.
8780 */
8781 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8782 return argv[1] ? number(argv[1]) : exitstatus;
8783}
8784
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008785/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008786static int breakcmd(int, char **) FAST_FUNC;
8787static int dotcmd(int, char **) FAST_FUNC;
8788static int evalcmd(int, char **) FAST_FUNC;
8789static int exitcmd(int, char **) FAST_FUNC;
8790static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008791#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008792static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008793#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008794#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008795static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008796#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008797#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008798static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008799#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008800static int readcmd(int, char **) FAST_FUNC;
8801static int setcmd(int, char **) FAST_FUNC;
8802static int shiftcmd(int, char **) FAST_FUNC;
8803static int timescmd(int, char **) FAST_FUNC;
8804static int trapcmd(int, char **) FAST_FUNC;
8805static int umaskcmd(int, char **) FAST_FUNC;
8806static int unsetcmd(int, char **) FAST_FUNC;
8807static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008808
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008809#define BUILTIN_NOSPEC "0"
8810#define BUILTIN_SPECIAL "1"
8811#define BUILTIN_REGULAR "2"
8812#define BUILTIN_SPEC_REG "3"
8813#define BUILTIN_ASSIGN "4"
8814#define BUILTIN_SPEC_ASSG "5"
8815#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008816#define BUILTIN_SPEC_REG_ASSG "7"
8817
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008818/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008819#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008820static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008821#endif
8822#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008823static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008824#endif
8825#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008826static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008827#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008828
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008829/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008830static const struct builtincmd builtintab[] = {
8831 { BUILTIN_SPEC_REG ".", dotcmd },
8832 { BUILTIN_SPEC_REG ":", truecmd },
8833#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008834 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008835#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008836 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008837#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008838#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008839#if ENABLE_ASH_ALIAS
8840 { BUILTIN_REG_ASSG "alias", aliascmd },
8841#endif
8842#if JOBS
8843 { BUILTIN_REGULAR "bg", fg_bgcmd },
8844#endif
8845 { BUILTIN_SPEC_REG "break", breakcmd },
8846 { BUILTIN_REGULAR "cd", cdcmd },
8847 { BUILTIN_NOSPEC "chdir", cdcmd },
8848#if ENABLE_ASH_CMDCMD
8849 { BUILTIN_REGULAR "command", commandcmd },
8850#endif
8851 { BUILTIN_SPEC_REG "continue", breakcmd },
8852#if ENABLE_ASH_BUILTIN_ECHO
8853 { BUILTIN_REGULAR "echo", echocmd },
8854#endif
8855 { BUILTIN_SPEC_REG "eval", evalcmd },
8856 { BUILTIN_SPEC_REG "exec", execcmd },
8857 { BUILTIN_SPEC_REG "exit", exitcmd },
8858 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8859 { BUILTIN_REGULAR "false", falsecmd },
8860#if JOBS
8861 { BUILTIN_REGULAR "fg", fg_bgcmd },
8862#endif
8863#if ENABLE_ASH_GETOPTS
8864 { BUILTIN_REGULAR "getopts", getoptscmd },
8865#endif
8866 { BUILTIN_NOSPEC "hash", hashcmd },
8867#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8868 { BUILTIN_NOSPEC "help", helpcmd },
8869#endif
8870#if JOBS
8871 { BUILTIN_REGULAR "jobs", jobscmd },
8872 { BUILTIN_REGULAR "kill", killcmd },
8873#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008874#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008875 { BUILTIN_NOSPEC "let", letcmd },
8876#endif
8877 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008878#if ENABLE_ASH_BUILTIN_PRINTF
8879 { BUILTIN_REGULAR "printf", printfcmd },
8880#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008881 { BUILTIN_NOSPEC "pwd", pwdcmd },
8882 { BUILTIN_REGULAR "read", readcmd },
8883 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8884 { BUILTIN_SPEC_REG "return", returncmd },
8885 { BUILTIN_SPEC_REG "set", setcmd },
8886 { BUILTIN_SPEC_REG "shift", shiftcmd },
8887 { BUILTIN_SPEC_REG "source", dotcmd },
8888#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008889 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008890#endif
8891 { BUILTIN_SPEC_REG "times", timescmd },
8892 { BUILTIN_SPEC_REG "trap", trapcmd },
8893 { BUILTIN_REGULAR "true", truecmd },
8894 { BUILTIN_NOSPEC "type", typecmd },
8895 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8896 { BUILTIN_REGULAR "umask", umaskcmd },
8897#if ENABLE_ASH_ALIAS
8898 { BUILTIN_REGULAR "unalias", unaliascmd },
8899#endif
8900 { BUILTIN_SPEC_REG "unset", unsetcmd },
8901 { BUILTIN_REGULAR "wait", waitcmd },
8902};
8903
Denis Vlasenko80591b02008-03-25 07:49:43 +00008904/* Should match the above table! */
8905#define COMMANDCMD (builtintab + \
8906 2 + \
8907 1 * ENABLE_ASH_BUILTIN_TEST + \
8908 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8909 1 * ENABLE_ASH_ALIAS + \
8910 1 * ENABLE_ASH_JOB_CONTROL + \
8911 3)
8912#define EXECCMD (builtintab + \
8913 2 + \
8914 1 * ENABLE_ASH_BUILTIN_TEST + \
8915 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8916 1 * ENABLE_ASH_ALIAS + \
8917 1 * ENABLE_ASH_JOB_CONTROL + \
8918 3 + \
8919 1 * ENABLE_ASH_CMDCMD + \
8920 1 + \
8921 ENABLE_ASH_BUILTIN_ECHO + \
8922 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008923
8924/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008925 * Search the table of builtin commands.
8926 */
8927static struct builtincmd *
8928find_builtin(const char *name)
8929{
8930 struct builtincmd *bp;
8931
8932 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008933 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008934 pstrcmp
8935 );
8936 return bp;
8937}
8938
8939/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008940 * Execute a simple command.
8941 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008942static int
8943isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008944{
8945 const char *q = endofname(p);
8946 if (p == q)
8947 return 0;
8948 return *q == '=';
8949}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008950static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008951bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008952{
8953 /* Preserve exitstatus of a previous possible redirection
8954 * as POSIX mandates */
8955 return back_exitstatus;
8956}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008957static void
Eric Andersenc470f442003-07-28 09:56:35 +00008958evalcommand(union node *cmd, int flags)
8959{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008960 static const struct builtincmd null_bltin = {
8961 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008962 };
Eric Andersenc470f442003-07-28 09:56:35 +00008963 struct stackmark smark;
8964 union node *argp;
8965 struct arglist arglist;
8966 struct arglist varlist;
8967 char **argv;
8968 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008969 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008970 struct cmdentry cmdentry;
8971 struct job *jp;
8972 char *lastarg;
8973 const char *path;
8974 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008975 int status;
8976 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008977 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008978 smallint cmd_is_exec;
8979 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008980
8981 /* First expand the arguments. */
8982 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8983 setstackmark(&smark);
8984 back_exitstatus = 0;
8985
8986 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008987 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008988 varlist.lastp = &varlist.list;
8989 *varlist.lastp = NULL;
8990 arglist.lastp = &arglist.list;
8991 *arglist.lastp = NULL;
8992
8993 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008994 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008995 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8996 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8997 }
8998
Eric Andersenc470f442003-07-28 09:56:35 +00008999 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9000 struct strlist **spp;
9001
9002 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009003 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009004 expandarg(argp, &arglist, EXP_VARTILDE);
9005 else
9006 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9007
Eric Andersenc470f442003-07-28 09:56:35 +00009008 for (sp = *spp; sp; sp = sp->next)
9009 argc++;
9010 }
9011
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009012 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009013 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009014 TRACE(("evalcommand arg: %s\n", sp->text));
9015 *nargv++ = sp->text;
9016 }
9017 *nargv = NULL;
9018
9019 lastarg = NULL;
9020 if (iflag && funcnest == 0 && argc > 0)
9021 lastarg = nargv[-1];
9022
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009023 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009024 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009025 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009026
9027 path = vpath.text;
9028 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9029 struct strlist **spp;
9030 char *p;
9031
9032 spp = varlist.lastp;
9033 expandarg(argp, &varlist, EXP_VARTILDE);
9034
9035 /*
9036 * Modify the command lookup path, if a PATH= assignment
9037 * is present
9038 */
9039 p = (*spp)->text;
9040 if (varequal(p, path))
9041 path = p;
9042 }
9043
9044 /* Print the command if xflag is set. */
9045 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009046 int n;
9047 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009048
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009049 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009050 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009051
9052 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009053 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009054 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009055 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009056 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009057 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009058 p--;
9059 }
9060 }
9061 sp = arglist.list;
9062 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009063 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009064 }
9065
9066 cmd_is_exec = 0;
9067 spclbltin = -1;
9068
9069 /* Now locate the command. */
9070 if (argc) {
9071 const char *oldpath;
9072 int cmd_flag = DO_ERR;
9073
9074 path += 5;
9075 oldpath = path;
9076 for (;;) {
9077 find_command(argv[0], &cmdentry, cmd_flag, path);
9078 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009079 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009080 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009081 goto bail;
9082 }
9083
9084 /* implement bltin and command here */
9085 if (cmdentry.cmdtype != CMDBUILTIN)
9086 break;
9087 if (spclbltin < 0)
9088 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9089 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009090 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009091#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009092 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009093 path = oldpath;
9094 nargv = parse_command_args(argv, &path);
9095 if (!nargv)
9096 break;
9097 argc -= nargv - argv;
9098 argv = nargv;
9099 cmd_flag |= DO_NOFUNC;
9100 } else
9101#endif
9102 break;
9103 }
9104 }
9105
9106 if (status) {
9107 /* We have a redirection error. */
9108 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009109 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009110 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009111 exitstatus = status;
9112 goto out;
9113 }
9114
9115 /* Execute the command. */
9116 switch (cmdentry.cmdtype) {
9117 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009118
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009119#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009120/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9121 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009122 {
9123 /* find_command() encodes applet_no as (-2 - applet_no) */
9124 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009125 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009126 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009127 /* run <applet>_main() */
9128 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009129 break;
9130 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009131 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009132#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009133 /* Fork off a child process if necessary. */
9134 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009135 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009136 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009137 if (forkshell(jp, cmd, FORK_FG) != 0) {
9138 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009139 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009140 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009141 break;
9142 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009143 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009144 }
9145 listsetvar(varlist.list, VEXPORT|VSTACK);
9146 shellexec(argv, path, cmdentry.u.index);
9147 /* NOTREACHED */
9148
9149 case CMDBUILTIN:
9150 cmdenviron = varlist.list;
9151 if (cmdenviron) {
9152 struct strlist *list = cmdenviron;
9153 int i = VNOSET;
9154 if (spclbltin > 0 || argc == 0) {
9155 i = 0;
9156 if (cmd_is_exec && argc > 1)
9157 i = VEXPORT;
9158 }
9159 listsetvar(list, i);
9160 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009161 /* Tight loop with builtins only:
9162 * "while kill -0 $child; do true; done"
9163 * will never exit even if $child died, unless we do this
9164 * to reap the zombie and make kill detect that it's gone: */
9165 dowait(DOWAIT_NONBLOCK, NULL);
9166
Eric Andersenc470f442003-07-28 09:56:35 +00009167 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9168 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009169 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009170 if (i == EXEXIT)
9171 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009172 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009173 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009174 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009175 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009176 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009177 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009178 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009179 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009180 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009181 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009182 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009183 }
9184 break;
9185
9186 case CMDFUNCTION:
9187 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009188 /* See above for the rationale */
9189 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009190 if (evalfun(cmdentry.u.func, argc, argv, flags))
9191 goto raise;
9192 break;
9193 }
9194
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009195 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009196 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009197 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009198 /* dsl: I think this is intended to be used to support
9199 * '_' in 'vi' command mode during line editing...
9200 * However I implemented that within libedit itself.
9201 */
9202 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009203 }
Eric Andersenc470f442003-07-28 09:56:35 +00009204 popstackmark(&smark);
9205}
9206
9207static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009208evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9209{
Eric Andersenc470f442003-07-28 09:56:35 +00009210 char *volatile savecmdname;
9211 struct jmploc *volatile savehandler;
9212 struct jmploc jmploc;
9213 int i;
9214
9215 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009216 i = setjmp(jmploc.loc);
9217 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009218 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009219 savehandler = exception_handler;
9220 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009221 commandname = argv[0];
9222 argptr = argv + 1;
9223 optptr = NULL; /* initialize nextopt */
9224 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009225 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009226 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009227 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009228 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009229 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009230 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009231
9232 return i;
9233}
9234
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009235static int
9236goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009237{
9238 return !*endofname(p);
9239}
9240
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009241
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009242/*
9243 * Search for a command. This is called before we fork so that the
9244 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009245 * the child. The check for "goodname" is an overly conservative
9246 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009247 */
Eric Andersenc470f442003-07-28 09:56:35 +00009248static void
9249prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009250{
9251 struct cmdentry entry;
9252
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009253 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9254 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009255}
9256
Eric Andersencb57d552001-06-28 07:25:16 +00009257
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009258/* ============ Builtin commands
9259 *
9260 * Builtin commands whose functions are closely tied to evaluation
9261 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009262 */
9263
9264/*
Eric Andersencb57d552001-06-28 07:25:16 +00009265 * Handle break and continue commands. Break, continue, and return are
9266 * all handled by setting the evalskip flag. The evaluation routines
9267 * above all check this flag, and if it is set they start skipping
9268 * commands rather than executing them. The variable skipcount is
9269 * the number of loops to break/continue, or the number of function
9270 * levels to return. (The latter is always 1.) It should probably
9271 * be an error to break out of more loops than exist, but it isn't
9272 * in the standard shell so we don't make it one here.
9273 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009274static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009275breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009276{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009277 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009278
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009279 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009280 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009281 if (n > loopnest)
9282 n = loopnest;
9283 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009284 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009285 skipcount = n;
9286 }
9287 return 0;
9288}
9289
Eric Andersenc470f442003-07-28 09:56:35 +00009290
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009291/* ============ input.c
9292 *
Eric Andersen90898442003-08-06 11:20:52 +00009293 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009294 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009295
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009296enum {
9297 INPUT_PUSH_FILE = 1,
9298 INPUT_NOFILE_OK = 2,
9299};
Eric Andersencb57d552001-06-28 07:25:16 +00009300
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009301static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009302/* values of checkkwd variable */
9303#define CHKALIAS 0x1
9304#define CHKKWD 0x2
9305#define CHKNL 0x4
9306
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009307/*
9308 * Push a string back onto the input at this current parsefile level.
9309 * We handle aliases this way.
9310 */
9311#if !ENABLE_ASH_ALIAS
9312#define pushstring(s, ap) pushstring(s)
9313#endif
9314static void
9315pushstring(char *s, struct alias *ap)
9316{
9317 struct strpush *sp;
9318 int len;
9319
9320 len = strlen(s);
9321 INT_OFF;
9322 if (g_parsefile->strpush) {
9323 sp = ckzalloc(sizeof(*sp));
9324 sp->prev = g_parsefile->strpush;
9325 } else {
9326 sp = &(g_parsefile->basestrpush);
9327 }
9328 g_parsefile->strpush = sp;
9329 sp->prev_string = g_parsefile->next_to_pgetc;
9330 sp->prev_left_in_line = g_parsefile->left_in_line;
9331#if ENABLE_ASH_ALIAS
9332 sp->ap = ap;
9333 if (ap) {
9334 ap->flag |= ALIASINUSE;
9335 sp->string = s;
9336 }
9337#endif
9338 g_parsefile->next_to_pgetc = s;
9339 g_parsefile->left_in_line = len;
9340 INT_ON;
9341}
9342
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009343static void
9344popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009345{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009346 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009347
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009348 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009349#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009350 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009351 if (g_parsefile->next_to_pgetc[-1] == ' '
9352 || g_parsefile->next_to_pgetc[-1] == '\t'
9353 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009354 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009355 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009356 if (sp->string != sp->ap->val) {
9357 free(sp->string);
9358 }
9359 sp->ap->flag &= ~ALIASINUSE;
9360 if (sp->ap->flag & ALIASDEAD) {
9361 unalias(sp->ap->name);
9362 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009363 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009364#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009365 g_parsefile->next_to_pgetc = sp->prev_string;
9366 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009367 g_parsefile->strpush = sp->prev;
9368 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009369 free(sp);
9370 INT_ON;
9371}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009372
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009373//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9374//it peeks whether it is &>, and then pushes back both chars.
9375//This function needs to save last *next_to_pgetc to buf[0]
9376//to make two pungetc() reliable. Currently,
9377// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009378static int
9379preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009380{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009381 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009382 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009383
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009384 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009385#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009386 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009387 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009388 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009389 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009390#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009391 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009392#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009393 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9394 if (nr == 0) {
9395 /* Ctrl+C pressed */
9396 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009397 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009398 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009399 raise(SIGINT);
9400 return 1;
9401 }
Eric Andersenc470f442003-07-28 09:56:35 +00009402 goto retry;
9403 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009404 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009405 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009406 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009407 }
Eric Andersencb57d552001-06-28 07:25:16 +00009408 }
9409#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009410 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009411#endif
9412
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009413#if 0
9414/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009415 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009416 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009417 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009418 if (flags >= 0 && (flags & O_NONBLOCK)) {
9419 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009420 if (fcntl(0, F_SETFL, flags) >= 0) {
9421 out2str("sh: turning off NDELAY mode\n");
9422 goto retry;
9423 }
9424 }
9425 }
9426 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009427#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009428 return nr;
9429}
9430
9431/*
9432 * Refill the input buffer and return the next input character:
9433 *
9434 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009435 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9436 * or we are reading from a string so we can't refill the buffer,
9437 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009438 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009439 * 4) Process input up to the next newline, deleting nul characters.
9440 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009441//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9442#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009443static int
Eric Andersenc470f442003-07-28 09:56:35 +00009444preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009445{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009446 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009447 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009448
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009449 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009450#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009451 if (g_parsefile->left_in_line == -1
9452 && g_parsefile->strpush->ap
9453 && g_parsefile->next_to_pgetc[-1] != ' '
9454 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009455 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009456 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009457 return PEOA;
9458 }
Eric Andersen2870d962001-07-02 17:27:21 +00009459#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009460 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009461 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009462 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9463 g_parsefile->left_in_line,
9464 g_parsefile->next_to_pgetc,
9465 g_parsefile->next_to_pgetc);
9466 if (--g_parsefile->left_in_line >= 0)
9467 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009468 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009469 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009470 * "pgetc" needs refilling.
9471 */
9472
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009473 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009474 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009475 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009476 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009477 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009478 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009479 /* even in failure keep left_in_line and next_to_pgetc
9480 * in lock step, for correct multi-layer pungetc.
9481 * left_in_line was decremented before preadbuffer(),
9482 * must inc next_to_pgetc: */
9483 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009484 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009485 }
Eric Andersencb57d552001-06-28 07:25:16 +00009486
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009487 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009488 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009489 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009490 again:
9491 more = preadfd();
9492 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009493 /* don't try reading again */
9494 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009495 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009497 return PEOF;
9498 }
9499 }
9500
Denis Vlasenko727752d2008-11-28 03:41:47 +00009501 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009502 * Set g_parsefile->left_in_line
9503 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009504 * NUL chars are deleted.
9505 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009506 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009507 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009508 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009509
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009510 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009511
Denis Vlasenko727752d2008-11-28 03:41:47 +00009512 c = *q;
9513 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009514 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009515 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009516 q++;
9517 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009518 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009519 break;
9520 }
Eric Andersencb57d552001-06-28 07:25:16 +00009521 }
9522
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009523 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9525 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009526 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009527 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009528 }
9529 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009530 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009531
Eric Andersencb57d552001-06-28 07:25:16 +00009532 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009533 char save = *q;
9534 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009536 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009537 }
9538
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009539 pgetc_debug("preadbuffer at %d:%p'%s'",
9540 g_parsefile->left_in_line,
9541 g_parsefile->next_to_pgetc,
9542 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009543 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009544}
9545
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009546#define pgetc_as_macro() \
9547 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009548 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009549 : preadbuffer() \
9550 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009551
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009552static int
9553pgetc(void)
9554{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 pgetc_debug("pgetc_fast at %d:%p'%s'",
9556 g_parsefile->left_in_line,
9557 g_parsefile->next_to_pgetc,
9558 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009559 return pgetc_as_macro();
9560}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009561
9562#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009563# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009564#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009565# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009566#endif
9567
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009568#if ENABLE_ASH_ALIAS
9569static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009570pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009571{
9572 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009573 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009574 pgetc_debug("pgetc_fast at %d:%p'%s'",
9575 g_parsefile->left_in_line,
9576 g_parsefile->next_to_pgetc,
9577 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009578 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009579 } while (c == PEOA);
9580 return c;
9581}
9582#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009583# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009584#endif
9585
9586/*
9587 * Read a line from the script.
9588 */
9589static char *
9590pfgets(char *line, int len)
9591{
9592 char *p = line;
9593 int nleft = len;
9594 int c;
9595
9596 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009597 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009598 if (c == PEOF) {
9599 if (p == line)
9600 return NULL;
9601 break;
9602 }
9603 *p++ = c;
9604 if (c == '\n')
9605 break;
9606 }
9607 *p = '\0';
9608 return line;
9609}
9610
Eric Andersenc470f442003-07-28 09:56:35 +00009611/*
9612 * Undo the last call to pgetc. Only one character may be pushed back.
9613 * PEOF may be pushed back.
9614 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009615static void
Eric Andersenc470f442003-07-28 09:56:35 +00009616pungetc(void)
9617{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009618 g_parsefile->left_in_line++;
9619 g_parsefile->next_to_pgetc--;
9620 pgetc_debug("pushed back to %d:%p'%s'",
9621 g_parsefile->left_in_line,
9622 g_parsefile->next_to_pgetc,
9623 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009624}
9625
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009626/*
9627 * To handle the "." command, a stack of input files is used. Pushfile
9628 * adds a new entry to the stack and popfile restores the previous level.
9629 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009630static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009631pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009632{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009633 struct parsefile *pf;
9634
Denis Vlasenko597906c2008-02-20 16:38:54 +00009635 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009636 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009637 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009638 /*pf->strpush = NULL; - ckzalloc did it */
9639 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009640 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641}
9642
9643static void
9644popfile(void)
9645{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009646 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009647
Denis Vlasenkob012b102007-02-19 22:43:01 +00009648 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009649 if (pf->fd >= 0)
9650 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009651 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009652 while (pf->strpush)
9653 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009654 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009655 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009656 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009657}
9658
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009659/*
9660 * Return to top level.
9661 */
9662static void
9663popallfiles(void)
9664{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009665 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009666 popfile();
9667}
9668
9669/*
9670 * Close the file(s) that the shell is reading commands from. Called
9671 * after a fork is done.
9672 */
9673static void
9674closescript(void)
9675{
9676 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009677 if (g_parsefile->fd > 0) {
9678 close(g_parsefile->fd);
9679 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009680 }
9681}
9682
9683/*
9684 * Like setinputfile, but takes an open file descriptor. Call this with
9685 * interrupts off.
9686 */
9687static void
9688setinputfd(int fd, int push)
9689{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009690 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009691 if (push) {
9692 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009693 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009694 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009695 g_parsefile->fd = fd;
9696 if (g_parsefile->buf == NULL)
9697 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009698 g_parsefile->left_in_buffer = 0;
9699 g_parsefile->left_in_line = 0;
9700 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009701}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009702
Eric Andersenc470f442003-07-28 09:56:35 +00009703/*
9704 * Set the input to take input from a file. If push is set, push the
9705 * old input onto the stack first.
9706 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009707static int
9708setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009709{
9710 int fd;
9711 int fd2;
9712
Denis Vlasenkob012b102007-02-19 22:43:01 +00009713 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009714 fd = open(fname, O_RDONLY);
9715 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009716 if (flags & INPUT_NOFILE_OK)
9717 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009718 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009719 }
Eric Andersenc470f442003-07-28 09:56:35 +00009720 if (fd < 10) {
9721 fd2 = copyfd(fd, 10);
9722 close(fd);
9723 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009724 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009725 fd = fd2;
9726 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009727 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009728 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009729 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009730 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009731}
9732
Eric Andersencb57d552001-06-28 07:25:16 +00009733/*
9734 * Like setinputfile, but takes input from a string.
9735 */
Eric Andersenc470f442003-07-28 09:56:35 +00009736static void
9737setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009738{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009739 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009740 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009741 g_parsefile->next_to_pgetc = string;
9742 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009743 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009744 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009745 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009746}
9747
9748
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009749/* ============ mail.c
9750 *
9751 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009752 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009753
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009754#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009755
Eric Andersencb57d552001-06-28 07:25:16 +00009756#define MAXMBOXES 10
9757
Eric Andersenc470f442003-07-28 09:56:35 +00009758/* times of mailboxes */
9759static time_t mailtime[MAXMBOXES];
9760/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009761static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009762
Eric Andersencb57d552001-06-28 07:25:16 +00009763/*
Eric Andersenc470f442003-07-28 09:56:35 +00009764 * Print appropriate message(s) if mail has arrived.
9765 * If mail_var_path_changed is set,
9766 * then the value of MAIL has mail_var_path_changed,
9767 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009768 */
Eric Andersenc470f442003-07-28 09:56:35 +00009769static void
9770chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009771{
Eric Andersencb57d552001-06-28 07:25:16 +00009772 const char *mpath;
9773 char *p;
9774 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009775 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009776 struct stackmark smark;
9777 struct stat statb;
9778
Eric Andersencb57d552001-06-28 07:25:16 +00009779 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009780 mpath = mpathset() ? mpathval() : mailval();
9781 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009782 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009783 if (p == NULL)
9784 break;
9785 if (*p == '\0')
9786 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009787 for (q = p; *q; q++)
9788 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009789#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009790 if (q[-1] != '/')
9791 abort();
9792#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009793 q[-1] = '\0'; /* delete trailing '/' */
9794 if (stat(p, &statb) < 0) {
9795 *mtp = 0;
9796 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009797 }
Eric Andersenc470f442003-07-28 09:56:35 +00009798 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9799 fprintf(
9800 stderr, snlfmt,
9801 pathopt ? pathopt : "you have mail"
9802 );
9803 }
9804 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009805 }
Eric Andersenc470f442003-07-28 09:56:35 +00009806 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009807 popstackmark(&smark);
9808}
Eric Andersencb57d552001-06-28 07:25:16 +00009809
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009810static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009811changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009812{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009813 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009814}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009815
Denis Vlasenko131ae172007-02-18 13:00:19 +00009816#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009817
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009818
9819/* ============ ??? */
9820
Eric Andersencb57d552001-06-28 07:25:16 +00009821/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009822 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009823 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009824static void
9825setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009826{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009827 char **newparam;
9828 char **ap;
9829 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009830
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009831 for (nparam = 0; argv[nparam]; nparam++)
9832 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009833 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9834 while (*argv) {
9835 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009836 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009837 *ap = NULL;
9838 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009839 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009840 shellparam.nparam = nparam;
9841 shellparam.p = newparam;
9842#if ENABLE_ASH_GETOPTS
9843 shellparam.optind = 1;
9844 shellparam.optoff = -1;
9845#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009846}
9847
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009848/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009849 * Process shell options. The global variable argptr contains a pointer
9850 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009851 *
9852 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9853 * For a non-interactive shell, an error condition encountered
9854 * by a special built-in ... shall cause the shell to write a diagnostic message
9855 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009856 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009857 * ...
9858 * Utility syntax error (option or operand error) Shall exit
9859 * ...
9860 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9861 * we see that bash does not do that (set "finishes" with error code 1 instead,
9862 * and shell continues), and people rely on this behavior!
9863 * Testcase:
9864 * set -o barfoo 2>/dev/null
9865 * echo $?
9866 *
9867 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009868 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009869static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009870plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009871{
9872 int i;
9873
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009874 if (name) {
9875 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009876 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009877 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009878 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009879 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009880 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009881 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009882 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009883 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009884 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009885 if (val) {
9886 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9887 } else {
9888 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9889 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009890 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009891 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009892}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009893static void
9894setoption(int flag, int val)
9895{
9896 int i;
9897
9898 for (i = 0; i < NOPTS; i++) {
9899 if (optletters(i) == flag) {
9900 optlist[i] = val;
9901 return;
9902 }
9903 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009904 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009905 /* NOTREACHED */
9906}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009907static int
Eric Andersenc470f442003-07-28 09:56:35 +00009908options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009909{
9910 char *p;
9911 int val;
9912 int c;
9913
9914 if (cmdline)
9915 minusc = NULL;
9916 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009917 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009918 if (c != '-' && c != '+')
9919 break;
9920 argptr++;
9921 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009922 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009923 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009924 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009925 if (!cmdline) {
9926 /* "-" means turn off -x and -v */
9927 if (p[0] == '\0')
9928 xflag = vflag = 0;
9929 /* "--" means reset params */
9930 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009931 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009932 }
Eric Andersenc470f442003-07-28 09:56:35 +00009933 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009934 }
Eric Andersencb57d552001-06-28 07:25:16 +00009935 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009936 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009937 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009938 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009939 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009940 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009941 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009942 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009943 /* it already printed err message */
9944 return 1; /* error */
9945 }
Eric Andersencb57d552001-06-28 07:25:16 +00009946 if (*argptr)
9947 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009948 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9949 isloginsh = 1;
9950 /* bash does not accept +-login, we also won't */
9951 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009952 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009953 isloginsh = 1;
9954 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009955 } else {
9956 setoption(c, val);
9957 }
9958 }
9959 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009960 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009961}
9962
Eric Andersencb57d552001-06-28 07:25:16 +00009963/*
Eric Andersencb57d552001-06-28 07:25:16 +00009964 * The shift builtin command.
9965 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009966static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009967shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009968{
9969 int n;
9970 char **ap1, **ap2;
9971
9972 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009973 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009974 n = number(argv[1]);
9975 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009976 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009977 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009978 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009979 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009980 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009981 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009982 }
9983 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009984 while ((*ap2++ = *ap1++) != NULL)
9985 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009986#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009987 shellparam.optind = 1;
9988 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009989#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009990 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009991 return 0;
9992}
9993
Eric Andersencb57d552001-06-28 07:25:16 +00009994/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009995 * POSIX requires that 'set' (but not export or readonly) output the
9996 * variables in lexicographic order - by the locale's collating order (sigh).
9997 * Maybe we could keep them in an ordered balanced binary tree
9998 * instead of hashed lists.
9999 * For now just roll 'em through qsort for printing...
10000 */
10001static int
10002showvars(const char *sep_prefix, int on, int off)
10003{
10004 const char *sep;
10005 char **ep, **epend;
10006
10007 ep = listvars(on, off, &epend);
10008 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10009
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010010 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010011
10012 for (; ep < epend; ep++) {
10013 const char *p;
10014 const char *q;
10015
10016 p = strchrnul(*ep, '=');
10017 q = nullstr;
10018 if (*p)
10019 q = single_quote(++p);
10020 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10021 }
10022 return 0;
10023}
10024
10025/*
Eric Andersencb57d552001-06-28 07:25:16 +000010026 * The set command builtin.
10027 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010028static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010029setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010030{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010031 int retval;
10032
Denis Vlasenko68404f12008-03-17 09:00:54 +000010033 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010034 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010035 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010036 retval = 1;
10037 if (!options(0)) { /* if no parse error... */
10038 retval = 0;
10039 optschanged();
10040 if (*argptr != NULL) {
10041 setparam(argptr);
10042 }
Eric Andersencb57d552001-06-28 07:25:16 +000010043 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010044 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010045 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010046}
10047
Denis Vlasenko131ae172007-02-18 13:00:19 +000010048#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010049static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010050change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010051{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010052 uint32_t t;
10053
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010054 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010055 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010056 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010057 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010058 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010059 vrandom.flags &= ~VNOFUNC;
10060 } else {
10061 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010062 t = strtoul(value, NULL, 10);
10063 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010064 }
Eric Andersenef02f822004-03-11 13:34:24 +000010065}
Eric Andersen16767e22004-03-16 05:14:10 +000010066#endif
10067
Denis Vlasenko131ae172007-02-18 13:00:19 +000010068#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010069static int
Eric Andersenc470f442003-07-28 09:56:35 +000010070getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010071{
10072 char *p, *q;
10073 char c = '?';
10074 int done = 0;
10075 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010076 char s[12];
10077 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010078
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010079 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010080 return 1;
10081 optnext = optfirst + *param_optind - 1;
10082
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010083 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010084 p = NULL;
10085 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010086 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010087 if (p == NULL || *p == '\0') {
10088 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010089 p = *optnext;
10090 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010091 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010092 p = NULL;
10093 done = 1;
10094 goto out;
10095 }
10096 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010097 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010098 goto atend;
10099 }
10100
10101 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010102 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010103 if (*q == '\0') {
10104 if (optstr[0] == ':') {
10105 s[0] = c;
10106 s[1] = '\0';
10107 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010108 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010109 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010110 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010111 }
10112 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010113 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010114 }
10115 if (*++q == ':')
10116 q++;
10117 }
10118
10119 if (*++q == ':') {
10120 if (*p == '\0' && (p = *optnext) == NULL) {
10121 if (optstr[0] == ':') {
10122 s[0] = c;
10123 s[1] = '\0';
10124 err |= setvarsafe("OPTARG", s, 0);
10125 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010126 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010127 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010128 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010129 c = '?';
10130 }
Eric Andersenc470f442003-07-28 09:56:35 +000010131 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010132 }
10133
10134 if (p == *optnext)
10135 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010136 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010137 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010138 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010139 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010140 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010141 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010142 *param_optind = optnext - optfirst + 1;
10143 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010144 err |= setvarsafe("OPTIND", s, VNOFUNC);
10145 s[0] = c;
10146 s[1] = '\0';
10147 err |= setvarsafe(optvar, s, 0);
10148 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010149 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010150 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010151 flush_stdout_stderr();
10152 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010153 }
10154 return done;
10155}
Eric Andersenc470f442003-07-28 09:56:35 +000010156
10157/*
10158 * The getopts builtin. Shellparam.optnext points to the next argument
10159 * to be processed. Shellparam.optptr points to the next character to
10160 * be processed in the current argument. If shellparam.optnext is NULL,
10161 * then it's the first time getopts has been called.
10162 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010163static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010164getoptscmd(int argc, char **argv)
10165{
10166 char **optbase;
10167
10168 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010169 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010170 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010171 optbase = shellparam.p;
10172 if (shellparam.optind > shellparam.nparam + 1) {
10173 shellparam.optind = 1;
10174 shellparam.optoff = -1;
10175 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010176 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010177 optbase = &argv[3];
10178 if (shellparam.optind > argc - 2) {
10179 shellparam.optind = 1;
10180 shellparam.optoff = -1;
10181 }
10182 }
10183
10184 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010185 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010186}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010187#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010188
Eric Andersencb57d552001-06-28 07:25:16 +000010189
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010190/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010191
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010192struct heredoc {
10193 struct heredoc *next; /* next here document in list */
10194 union node *here; /* redirection node */
10195 char *eofmark; /* string indicating end of input */
10196 smallint striptabs; /* if set, strip leading tabs */
10197};
10198
10199static smallint tokpushback; /* last token pushed back */
10200static smallint parsebackquote; /* nonzero if we are inside backquotes */
10201static smallint quoteflag; /* set if (part of) last token was quoted */
10202static token_id_t lasttoken; /* last token read (integer id Txxx) */
10203static struct heredoc *heredoclist; /* list of here documents to read */
10204static char *wordtext; /* text of last word returned by readtoken */
10205static struct nodelist *backquotelist;
10206static union node *redirnode;
10207static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010208
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010209/*
10210 * Called when an unexpected token is read during the parse. The argument
10211 * is the token that is expected, or -1 if more than one type of token can
10212 * occur at this point.
10213 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010214static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010215static void
10216raise_error_unexpected_syntax(int token)
10217{
10218 char msg[64];
10219 int l;
10220
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010221 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010222 if (token >= 0)
10223 sprintf(msg + l, " (expecting %s)", tokname(token));
10224 raise_error_syntax(msg);
10225 /* NOTREACHED */
10226}
Eric Andersencb57d552001-06-28 07:25:16 +000010227
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010228#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010229
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010230/* parsing is heavily cross-recursive, need these forward decls */
10231static union node *andor(void);
10232static union node *pipeline(void);
10233static union node *parse_command(void);
10234static void parseheredoc(void);
10235static char peektoken(void);
10236static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010237
Eric Andersenc470f442003-07-28 09:56:35 +000010238static union node *
10239list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010240{
10241 union node *n1, *n2, *n3;
10242 int tok;
10243
Eric Andersenc470f442003-07-28 09:56:35 +000010244 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10245 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010246 return NULL;
10247 n1 = NULL;
10248 for (;;) {
10249 n2 = andor();
10250 tok = readtoken();
10251 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010252 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010253 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010254 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010255 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010256 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010257 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010258 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010259 n2 = n3;
10260 }
10261 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010262 }
10263 }
10264 if (n1 == NULL) {
10265 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010266 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010267 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010268 n3->type = NSEMI;
10269 n3->nbinary.ch1 = n1;
10270 n3->nbinary.ch2 = n2;
10271 n1 = n3;
10272 }
10273 switch (tok) {
10274 case TBACKGND:
10275 case TSEMI:
10276 tok = readtoken();
10277 /* fall through */
10278 case TNL:
10279 if (tok == TNL) {
10280 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010281 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010282 return n1;
10283 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010284 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010285 }
Eric Andersenc470f442003-07-28 09:56:35 +000010286 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010287 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010288 return n1;
10289 break;
10290 case TEOF:
10291 if (heredoclist)
10292 parseheredoc();
10293 else
Eric Andersenc470f442003-07-28 09:56:35 +000010294 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010295 return n1;
10296 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010297 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010298 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010299 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010300 return n1;
10301 }
10302 }
10303}
10304
Eric Andersenc470f442003-07-28 09:56:35 +000010305static union node *
10306andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010307{
Eric Andersencb57d552001-06-28 07:25:16 +000010308 union node *n1, *n2, *n3;
10309 int t;
10310
Eric Andersencb57d552001-06-28 07:25:16 +000010311 n1 = pipeline();
10312 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010313 t = readtoken();
10314 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010315 t = NAND;
10316 } else if (t == TOR) {
10317 t = NOR;
10318 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010319 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010320 return n1;
10321 }
Eric Andersenc470f442003-07-28 09:56:35 +000010322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010323 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010324 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010325 n3->type = t;
10326 n3->nbinary.ch1 = n1;
10327 n3->nbinary.ch2 = n2;
10328 n1 = n3;
10329 }
10330}
10331
Eric Andersenc470f442003-07-28 09:56:35 +000010332static union node *
10333pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010334{
Eric Andersencb57d552001-06-28 07:25:16 +000010335 union node *n1, *n2, *pipenode;
10336 struct nodelist *lp, *prev;
10337 int negate;
10338
10339 negate = 0;
10340 TRACE(("pipeline: entered\n"));
10341 if (readtoken() == TNOT) {
10342 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010343 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010344 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010345 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010346 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010347 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010348 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010349 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010350 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010351 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010352 pipenode->npipe.cmdlist = lp;
10353 lp->n = n1;
10354 do {
10355 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010356 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010357 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010358 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010359 prev->next = lp;
10360 } while (readtoken() == TPIPE);
10361 lp->next = NULL;
10362 n1 = pipenode;
10363 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010364 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010365 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010366 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010367 n2->type = NNOT;
10368 n2->nnot.com = n1;
10369 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010370 }
10371 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010372}
10373
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010374static union node *
10375makename(void)
10376{
10377 union node *n;
10378
Denis Vlasenko597906c2008-02-20 16:38:54 +000010379 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010380 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010381 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010382 n->narg.text = wordtext;
10383 n->narg.backquote = backquotelist;
10384 return n;
10385}
10386
10387static void
10388fixredir(union node *n, const char *text, int err)
10389{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010390 int fd;
10391
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010392 TRACE(("Fix redir %s %d\n", text, err));
10393 if (!err)
10394 n->ndup.vname = NULL;
10395
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010396 fd = bb_strtou(text, NULL, 10);
10397 if (!errno && fd >= 0)
10398 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010399 else if (LONE_DASH(text))
10400 n->ndup.dupfd = -1;
10401 else {
10402 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010403 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010404 n->ndup.vname = makename();
10405 }
10406}
10407
10408/*
10409 * Returns true if the text contains nothing to expand (no dollar signs
10410 * or backquotes).
10411 */
10412static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010413noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010415 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416
Denys Vlasenkocd716832009-11-28 22:14:02 +010010417 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010418 if (c == CTLQUOTEMARK)
10419 continue;
10420 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010421 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010422 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010423 return 0;
10424 }
10425 return 1;
10426}
10427
10428static void
10429parsefname(void)
10430{
10431 union node *n = redirnode;
10432
10433 if (readtoken() != TWORD)
10434 raise_error_unexpected_syntax(-1);
10435 if (n->type == NHERE) {
10436 struct heredoc *here = heredoc;
10437 struct heredoc *p;
10438 int i;
10439
10440 if (quoteflag == 0)
10441 n->type = NXHERE;
10442 TRACE(("Here document %d\n", n->type));
10443 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010444 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010445 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010446 here->eofmark = wordtext;
10447 here->next = NULL;
10448 if (heredoclist == NULL)
10449 heredoclist = here;
10450 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010451 for (p = heredoclist; p->next; p = p->next)
10452 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010453 p->next = here;
10454 }
10455 } else if (n->type == NTOFD || n->type == NFROMFD) {
10456 fixredir(n, wordtext, 0);
10457 } else {
10458 n->nfile.fname = makename();
10459 }
10460}
Eric Andersencb57d552001-06-28 07:25:16 +000010461
Eric Andersenc470f442003-07-28 09:56:35 +000010462static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010463simplecmd(void)
10464{
10465 union node *args, **app;
10466 union node *n = NULL;
10467 union node *vars, **vpp;
10468 union node **rpp, *redir;
10469 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010470#if ENABLE_ASH_BASH_COMPAT
10471 smallint double_brackets_flag = 0;
10472#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010473
10474 args = NULL;
10475 app = &args;
10476 vars = NULL;
10477 vpp = &vars;
10478 redir = NULL;
10479 rpp = &redir;
10480
10481 savecheckkwd = CHKALIAS;
10482 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010483 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010485 t = readtoken();
10486 switch (t) {
10487#if ENABLE_ASH_BASH_COMPAT
10488 case TAND: /* "&&" */
10489 case TOR: /* "||" */
10490 if (!double_brackets_flag) {
10491 tokpushback = 1;
10492 goto out;
10493 }
10494 wordtext = (char *) (t == TAND ? "-a" : "-o");
10495#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010496 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010497 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010498 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010499 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010500 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010501#if ENABLE_ASH_BASH_COMPAT
10502 if (strcmp("[[", wordtext) == 0)
10503 double_brackets_flag = 1;
10504 else if (strcmp("]]", wordtext) == 0)
10505 double_brackets_flag = 0;
10506#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010507 n->narg.backquote = backquotelist;
10508 if (savecheckkwd && isassignment(wordtext)) {
10509 *vpp = n;
10510 vpp = &n->narg.next;
10511 } else {
10512 *app = n;
10513 app = &n->narg.next;
10514 savecheckkwd = 0;
10515 }
10516 break;
10517 case TREDIR:
10518 *rpp = n = redirnode;
10519 rpp = &n->nfile.next;
10520 parsefname(); /* read name of redirection file */
10521 break;
10522 case TLP:
10523 if (args && app == &args->narg.next
10524 && !vars && !redir
10525 ) {
10526 struct builtincmd *bcmd;
10527 const char *name;
10528
10529 /* We have a function */
10530 if (readtoken() != TRP)
10531 raise_error_unexpected_syntax(TRP);
10532 name = n->narg.text;
10533 if (!goodname(name)
10534 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10535 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010536 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010537 }
10538 n->type = NDEFUN;
10539 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10540 n->narg.next = parse_command();
10541 return n;
10542 }
10543 /* fall through */
10544 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010545 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010546 goto out;
10547 }
10548 }
10549 out:
10550 *app = NULL;
10551 *vpp = NULL;
10552 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010553 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010554 n->type = NCMD;
10555 n->ncmd.args = args;
10556 n->ncmd.assign = vars;
10557 n->ncmd.redirect = redir;
10558 return n;
10559}
10560
10561static union node *
10562parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010563{
Eric Andersencb57d552001-06-28 07:25:16 +000010564 union node *n1, *n2;
10565 union node *ap, **app;
10566 union node *cp, **cpp;
10567 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010568 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010569 int t;
10570
10571 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010572 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010573
Eric Andersencb57d552001-06-28 07:25:16 +000010574 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010575 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010576 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010577 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010578 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010579 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010580 n1->type = NIF;
10581 n1->nif.test = list(0);
10582 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010583 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010584 n1->nif.ifpart = list(0);
10585 n2 = n1;
10586 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010587 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010588 n2 = n2->nif.elsepart;
10589 n2->type = NIF;
10590 n2->nif.test = list(0);
10591 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010592 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010593 n2->nif.ifpart = list(0);
10594 }
10595 if (lasttoken == TELSE)
10596 n2->nif.elsepart = list(0);
10597 else {
10598 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010599 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010600 }
Eric Andersenc470f442003-07-28 09:56:35 +000010601 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010602 break;
10603 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010604 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010605 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010606 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010607 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010608 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010609 got = readtoken();
10610 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010611 TRACE(("expecting DO got %s %s\n", tokname(got),
10612 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010613 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010614 }
10615 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010616 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010617 break;
10618 }
10619 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010620 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010621 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010622 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010623 n1->type = NFOR;
10624 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010625 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010626 if (readtoken() == TIN) {
10627 app = &ap;
10628 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010629 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010630 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010631 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010632 n2->narg.text = wordtext;
10633 n2->narg.backquote = backquotelist;
10634 *app = n2;
10635 app = &n2->narg.next;
10636 }
10637 *app = NULL;
10638 n1->nfor.args = ap;
10639 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010640 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010641 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010642 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010643 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010644 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010645 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010646 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010647 n1->nfor.args = n2;
10648 /*
10649 * Newline or semicolon here is optional (but note
10650 * that the original Bourne shell only allowed NL).
10651 */
10652 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010653 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010654 }
Eric Andersenc470f442003-07-28 09:56:35 +000010655 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010656 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010657 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010658 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010659 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010660 break;
10661 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010662 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010663 n1->type = NCASE;
10664 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010665 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010666 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010667 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010668 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010669 n2->narg.text = wordtext;
10670 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010671 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010672 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010673 } while (readtoken() == TNL);
10674 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010675 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010676 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010677 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010678 checkkwd = CHKNL | CHKKWD;
10679 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010680 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010681 if (lasttoken == TLP)
10682 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010683 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010684 cp->type = NCLIST;
10685 app = &cp->nclist.pattern;
10686 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010687 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010688 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010689 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010690 ap->narg.text = wordtext;
10691 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010692 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010693 break;
10694 app = &ap->narg.next;
10695 readtoken();
10696 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010697 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010698 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010699 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010700 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010701
Eric Andersenc470f442003-07-28 09:56:35 +000010702 cpp = &cp->nclist.next;
10703
10704 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010705 t = readtoken();
10706 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010707 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010708 raise_error_unexpected_syntax(TENDCASE);
10709 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010710 }
Eric Andersenc470f442003-07-28 09:56:35 +000010711 }
Eric Andersencb57d552001-06-28 07:25:16 +000010712 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010713 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010714 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010715 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010716 n1->type = NSUBSHELL;
10717 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010718 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010719 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010720 break;
10721 case TBEGIN:
10722 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010723 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010724 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010725 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010726 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010727 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010728 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010729 }
10730
Eric Andersenc470f442003-07-28 09:56:35 +000010731 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010732 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010733
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010734 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010735 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010736 checkkwd = CHKKWD | CHKALIAS;
10737 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010738 while (readtoken() == TREDIR) {
10739 *rpp = n2 = redirnode;
10740 rpp = &n2->nfile.next;
10741 parsefname();
10742 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010743 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010744 *rpp = NULL;
10745 if (redir) {
10746 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010747 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010748 n2->type = NREDIR;
10749 n2->nredir.n = n1;
10750 n1 = n2;
10751 }
10752 n1->nredir.redirect = redir;
10753 }
Eric Andersencb57d552001-06-28 07:25:16 +000010754 return n1;
10755}
10756
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010757#if ENABLE_ASH_BASH_COMPAT
10758static int decode_dollar_squote(void)
10759{
10760 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10761 int c, cnt;
10762 char *p;
10763 char buf[4];
10764
10765 c = pgetc();
10766 p = strchr(C_escapes, c);
10767 if (p) {
10768 buf[0] = c;
10769 p = buf;
10770 cnt = 3;
10771 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10772 do {
10773 c = pgetc();
10774 *++p = c;
10775 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10776 pungetc();
10777 } else if (c == 'x') { /* \xHH */
10778 do {
10779 c = pgetc();
10780 *++p = c;
10781 } while (isxdigit(c) && --cnt);
10782 pungetc();
10783 if (cnt == 3) { /* \x but next char is "bad" */
10784 c = 'x';
10785 goto unrecognized;
10786 }
10787 } else { /* simple seq like \\ or \t */
10788 p++;
10789 }
10790 *p = '\0';
10791 p = buf;
10792 c = bb_process_escape_sequence((void*)&p);
10793 } else { /* unrecognized "\z": print both chars unless ' or " */
10794 if (c != '\'' && c != '"') {
10795 unrecognized:
10796 c |= 0x100; /* "please encode \, then me" */
10797 }
10798 }
10799 return c;
10800}
10801#endif
10802
Eric Andersencb57d552001-06-28 07:25:16 +000010803/*
10804 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10805 * is not NULL, read a here document. In the latter case, eofmark is the
10806 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010807 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010808 * is the first character of the input token or document.
10809 *
10810 * Because C does not have internal subroutines, I have simulated them
10811 * using goto's to implement the subroutine linkage. The following macros
10812 * will run code that appears at the end of readtoken1.
10813 */
Eric Andersen2870d962001-07-02 17:27:21 +000010814#define CHECKEND() {goto checkend; checkend_return:;}
10815#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10816#define PARSESUB() {goto parsesub; parsesub_return:;}
10817#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10818#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10819#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010820static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010821readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010822{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010823 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010824 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010825 char *out;
10826 int len;
10827 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010828 struct nodelist *bqlist;
10829 smallint quotef;
10830 smallint dblquote;
10831 smallint oldstyle;
10832 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010833#if ENABLE_ASH_EXPAND_PRMT
10834 smallint pssyntax; /* we are expanding a prompt string */
10835#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010836 int varnest; /* levels of variables expansion */
10837 int arinest; /* levels of arithmetic expansion */
10838 int parenlevel; /* levels of parens in arithmetic */
10839 int dqvarnest; /* levels of variables expansion within double quotes */
10840
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010841 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010842
Eric Andersencb57d552001-06-28 07:25:16 +000010843#if __GNUC__
10844 /* Avoid longjmp clobbering */
10845 (void) &out;
10846 (void) &quotef;
10847 (void) &dblquote;
10848 (void) &varnest;
10849 (void) &arinest;
10850 (void) &parenlevel;
10851 (void) &dqvarnest;
10852 (void) &oldstyle;
10853 (void) &prevsyntax;
10854 (void) &syntax;
10855#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010856 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010857 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010858 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010859 oldstyle = 0;
10860 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010861#if ENABLE_ASH_EXPAND_PRMT
10862 pssyntax = (syntax == PSSYNTAX);
10863 if (pssyntax)
10864 syntax = DQSYNTAX;
10865#endif
10866 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010867 varnest = 0;
10868 arinest = 0;
10869 parenlevel = 0;
10870 dqvarnest = 0;
10871
10872 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010873 loop:
10874 /* For each line, until end of word */
10875 {
Eric Andersenc470f442003-07-28 09:56:35 +000010876 CHECKEND(); /* set c to PEOF if at end of here document */
10877 for (;;) { /* until end of line or end of word */
10878 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010879 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010880 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010881 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010882 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010883 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010884 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010885 if (doprompt)
10886 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010887 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010888 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010889 case CWORD:
10890 USTPUTC(c, out);
10891 break;
10892 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010893 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010894 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010895#if ENABLE_ASH_BASH_COMPAT
10896 if (c == '\\' && bash_dollar_squote) {
10897 c = decode_dollar_squote();
10898 if (c & 0x100) {
10899 USTPUTC('\\', out);
10900 c = (unsigned char)c;
10901 }
10902 }
10903#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010904 USTPUTC(c, out);
10905 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010906 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010907 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010908 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010909 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010910 USTPUTC('\\', out);
10911 pungetc();
10912 } else if (c == '\n') {
10913 if (doprompt)
10914 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010915 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010916#if ENABLE_ASH_EXPAND_PRMT
10917 if (c == '$' && pssyntax) {
10918 USTPUTC(CTLESC, out);
10919 USTPUTC('\\', out);
10920 }
10921#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010922 if (dblquote && c != '\\'
10923 && c != '`' && c != '$'
10924 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010925 ) {
10926 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010927 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010928 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010929 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010930 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010931 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010932 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010933 }
10934 break;
10935 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010936 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010937 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010938 if (eofmark == NULL) {
10939 USTPUTC(CTLQUOTEMARK, out);
10940 }
Eric Andersencb57d552001-06-28 07:25:16 +000010941 break;
10942 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010943 syntax = DQSYNTAX;
10944 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010945 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010946 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010947 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010948 if (eofmark != NULL && arinest == 0
10949 && varnest == 0
10950 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010951 USTPUTC(c, out);
10952 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010953 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010954 syntax = BASESYNTAX;
10955 dblquote = 0;
10956 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010957 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010958 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010959 }
10960 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010961 case CVAR: /* '$' */
10962 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010963 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010964 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010965 if (varnest > 0) {
10966 varnest--;
10967 if (dqvarnest > 0) {
10968 dqvarnest--;
10969 }
10970 USTPUTC(CTLENDVAR, out);
10971 } else {
10972 USTPUTC(c, out);
10973 }
10974 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010975#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010976 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010977 parenlevel++;
10978 USTPUTC(c, out);
10979 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010980 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010981 if (parenlevel > 0) {
10982 USTPUTC(c, out);
10983 --parenlevel;
10984 } else {
10985 if (pgetc() == ')') {
10986 if (--arinest == 0) {
10987 USTPUTC(CTLENDARI, out);
10988 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010989 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010990 } else
10991 USTPUTC(')', out);
10992 } else {
10993 /*
10994 * unbalanced parens
10995 * (don't 2nd guess - no error)
10996 */
10997 pungetc();
10998 USTPUTC(')', out);
10999 }
11000 }
11001 break;
11002#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011003 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011004 PARSEBACKQOLD();
11005 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011006 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011007 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011008 case CIGN:
11009 break;
11010 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011011 if (varnest == 0) {
11012#if ENABLE_ASH_BASH_COMPAT
11013 if (c == '&') {
11014 if (pgetc() == '>')
11015 c = 0x100 + '>'; /* flag &> */
11016 pungetc();
11017 }
11018#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011019 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011020 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011021 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011022 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011023
Eric Andersencb57d552001-06-28 07:25:16 +000011024 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011025 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011026 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011027 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011028 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011029#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011030 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011031 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011032#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011033 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011034 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011035 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011036 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011037 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011038 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011039 }
11040 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011041 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011042 out = stackblock();
11043 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011044 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011045 && quotef == 0
11046 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011047 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011048 PARSEREDIR(); /* passed as params: out, c */
11049 lasttoken = TREDIR;
11050 return lasttoken;
11051 }
11052 /* else: non-number X seen, interpret it
11053 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011054 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011055 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011056 }
11057 quoteflag = quotef;
11058 backquotelist = bqlist;
11059 grabstackblock(len);
11060 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011061 lasttoken = TWORD;
11062 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011063/* end of readtoken routine */
11064
Eric Andersencb57d552001-06-28 07:25:16 +000011065/*
11066 * Check to see whether we are at the end of the here document. When this
11067 * is called, c is set to the first character of the next input line. If
11068 * we are at the end of the here document, this routine sets the c to PEOF.
11069 */
Eric Andersenc470f442003-07-28 09:56:35 +000011070checkend: {
11071 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011072#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011073 if (c == PEOA)
11074 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011075#endif
11076 if (striptabs) {
11077 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011078 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011079 }
Eric Andersenc470f442003-07-28 09:56:35 +000011080 }
11081 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011082 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011083 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011084
Eric Andersenc470f442003-07-28 09:56:35 +000011085 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011086 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11087 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011088 if (*p == '\n' && *q == '\0') {
11089 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011090 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011091 needprompt = doprompt;
11092 } else {
11093 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011094 }
11095 }
11096 }
11097 }
Eric Andersenc470f442003-07-28 09:56:35 +000011098 goto checkend_return;
11099}
Eric Andersencb57d552001-06-28 07:25:16 +000011100
Eric Andersencb57d552001-06-28 07:25:16 +000011101/*
11102 * Parse a redirection operator. The variable "out" points to a string
11103 * specifying the fd to be redirected. The variable "c" contains the
11104 * first character of the redirection operator.
11105 */
Eric Andersenc470f442003-07-28 09:56:35 +000011106parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011107 /* out is already checked to be a valid number or "" */
11108 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011109 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011110
Denis Vlasenko597906c2008-02-20 16:38:54 +000011111 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011112 if (c == '>') {
11113 np->nfile.fd = 1;
11114 c = pgetc();
11115 if (c == '>')
11116 np->type = NAPPEND;
11117 else if (c == '|')
11118 np->type = NCLOBBER;
11119 else if (c == '&')
11120 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011121 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011122 else {
11123 np->type = NTO;
11124 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011125 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011126 }
11127#if ENABLE_ASH_BASH_COMPAT
11128 else if (c == 0x100 + '>') { /* this flags &> redirection */
11129 np->nfile.fd = 1;
11130 pgetc(); /* this is '>', no need to check */
11131 np->type = NTO2;
11132 }
11133#endif
11134 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011135 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011136 c = pgetc();
11137 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011138 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011139 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011140 np = stzalloc(sizeof(struct nhere));
11141 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011142 }
11143 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011144 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011145 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011146 c = pgetc();
11147 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011148 heredoc->striptabs = 1;
11149 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011150 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011151 pungetc();
11152 }
11153 break;
11154
11155 case '&':
11156 np->type = NFROMFD;
11157 break;
11158
11159 case '>':
11160 np->type = NFROMTO;
11161 break;
11162
11163 default:
11164 np->type = NFROM;
11165 pungetc();
11166 break;
11167 }
Eric Andersencb57d552001-06-28 07:25:16 +000011168 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011169 if (fd >= 0)
11170 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011171 redirnode = np;
11172 goto parseredir_return;
11173}
Eric Andersencb57d552001-06-28 07:25:16 +000011174
Eric Andersencb57d552001-06-28 07:25:16 +000011175/*
11176 * Parse a substitution. At this point, we have read the dollar sign
11177 * and nothing else.
11178 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011179
11180/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11181 * (assuming ascii char codes, as the original implementation did) */
11182#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011183 (((unsigned)(c) - 33 < 32) \
11184 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011185parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011186 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011187 int typeloc;
11188 int flags;
11189 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011190 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011191
Eric Andersenc470f442003-07-28 09:56:35 +000011192 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011193 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011194 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011195 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011196#if ENABLE_ASH_BASH_COMPAT
11197 if (c == '\'')
11198 bash_dollar_squote = 1;
11199 else
11200#endif
11201 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011202 pungetc();
11203 } else if (c == '(') { /* $(command) or $((arith)) */
11204 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011205#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011206 PARSEARITH();
11207#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011208 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011209#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011210 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011211 pungetc();
11212 PARSEBACKQNEW();
11213 }
11214 } else {
11215 USTPUTC(CTLVAR, out);
11216 typeloc = out - (char *)stackblock();
11217 USTPUTC(VSNORMAL, out);
11218 subtype = VSNORMAL;
11219 if (c == '{') {
11220 c = pgetc();
11221 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011222 c = pgetc();
11223 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011224 c = '#';
11225 else
11226 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011227 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011228 subtype = 0;
11229 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011230 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011231 do {
11232 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011233 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011234 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011235 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011236 do {
11237 STPUTC(c, out);
11238 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011239 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011240 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011241 USTPUTC(c, out);
11242 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011243 } else {
11244 badsub:
11245 raise_error_syntax("bad substitution");
11246 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011247 if (c != '}' && subtype == VSLENGTH)
11248 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011249
Eric Andersenc470f442003-07-28 09:56:35 +000011250 STPUTC('=', out);
11251 flags = 0;
11252 if (subtype == 0) {
11253 switch (c) {
11254 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011255 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011256#if ENABLE_ASH_BASH_COMPAT
11257 if (c == ':' || c == '$' || isdigit(c)) {
11258 pungetc();
11259 subtype = VSSUBSTR;
11260 break;
11261 }
11262#endif
11263 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011264 /*FALLTHROUGH*/
11265 default:
11266 p = strchr(types, c);
11267 if (p == NULL)
11268 goto badsub;
11269 subtype = p - types + VSNORMAL;
11270 break;
11271 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011272 case '#': {
11273 int cc = c;
11274 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11275 c = pgetc();
11276 if (c == cc)
11277 subtype++;
11278 else
11279 pungetc();
11280 break;
11281 }
11282#if ENABLE_ASH_BASH_COMPAT
11283 case '/':
11284 subtype = VSREPLACE;
11285 c = pgetc();
11286 if (c == '/')
11287 subtype++; /* VSREPLACEALL */
11288 else
11289 pungetc();
11290 break;
11291#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011292 }
Eric Andersenc470f442003-07-28 09:56:35 +000011293 } else {
11294 pungetc();
11295 }
11296 if (dblquote || arinest)
11297 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011298 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011299 if (subtype != VSNORMAL) {
11300 varnest++;
11301 if (dblquote || arinest) {
11302 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011303 }
11304 }
11305 }
Eric Andersenc470f442003-07-28 09:56:35 +000011306 goto parsesub_return;
11307}
Eric Andersencb57d552001-06-28 07:25:16 +000011308
Eric Andersencb57d552001-06-28 07:25:16 +000011309/*
11310 * Called to parse command substitutions. Newstyle is set if the command
11311 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11312 * list of commands (passed by reference), and savelen is the number of
11313 * characters on the top of the stack which must be preserved.
11314 */
Eric Andersenc470f442003-07-28 09:56:35 +000011315parsebackq: {
11316 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011317 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011318 union node *n;
11319 char *volatile str;
11320 struct jmploc jmploc;
11321 struct jmploc *volatile savehandler;
11322 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011323 smallint saveprompt = 0;
11324
Eric Andersencb57d552001-06-28 07:25:16 +000011325#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011326 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011327#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011328 savepbq = parsebackquote;
11329 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011330 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011331 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011332 exception_handler = savehandler;
11333 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011334 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011335 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011336 str = NULL;
11337 savelen = out - (char *)stackblock();
11338 if (savelen > 0) {
11339 str = ckmalloc(savelen);
11340 memcpy(str, stackblock(), savelen);
11341 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011342 savehandler = exception_handler;
11343 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011344 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011345 if (oldstyle) {
11346 /* We must read until the closing backquote, giving special
11347 treatment to some slashes, and then push the string and
11348 reread it as input, interpreting it normally. */
11349 char *pout;
11350 int pc;
11351 size_t psavelen;
11352 char *pstr;
11353
11354
11355 STARTSTACKSTR(pout);
11356 for (;;) {
11357 if (needprompt) {
11358 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011359 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011360 pc = pgetc();
11361 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011362 case '`':
11363 goto done;
11364
11365 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011366 pc = pgetc();
11367 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011368 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011369 if (doprompt)
11370 setprompt(2);
11371 /*
11372 * If eating a newline, avoid putting
11373 * the newline into the new character
11374 * stream (via the STPUTC after the
11375 * switch).
11376 */
11377 continue;
11378 }
11379 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011380 && (!dblquote || pc != '"')
11381 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011382 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011383 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011384 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011385 break;
11386 }
11387 /* fall through */
11388
11389 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011390 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011391 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011392 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011393
11394 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011395 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011396 needprompt = doprompt;
11397 break;
11398
11399 default:
11400 break;
11401 }
11402 STPUTC(pc, pout);
11403 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011404 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011405 STPUTC('\0', pout);
11406 psavelen = pout - (char *)stackblock();
11407 if (psavelen > 0) {
11408 pstr = grabstackstr(pout);
11409 setinputstring(pstr);
11410 }
11411 }
11412 nlpp = &bqlist;
11413 while (*nlpp)
11414 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011415 *nlpp = stzalloc(sizeof(**nlpp));
11416 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011417 parsebackquote = oldstyle;
11418
11419 if (oldstyle) {
11420 saveprompt = doprompt;
11421 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011422 }
11423
Eric Andersenc470f442003-07-28 09:56:35 +000011424 n = list(2);
11425
11426 if (oldstyle)
11427 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011428 else if (readtoken() != TRP)
11429 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011430
11431 (*nlpp)->n = n;
11432 if (oldstyle) {
11433 /*
11434 * Start reading from old file again, ignoring any pushed back
11435 * tokens left from the backquote parsing
11436 */
11437 popfile();
11438 tokpushback = 0;
11439 }
11440 while (stackblocksize() <= savelen)
11441 growstackblock();
11442 STARTSTACKSTR(out);
11443 if (str) {
11444 memcpy(out, str, savelen);
11445 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011446 INT_OFF;
11447 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011448 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011449 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011450 }
11451 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011452 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011453 if (arinest || dblquote)
11454 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11455 else
11456 USTPUTC(CTLBACKQ, out);
11457 if (oldstyle)
11458 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011459 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011460}
11461
Mike Frysinger98c52642009-04-02 10:02:37 +000011462#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011463/*
11464 * Parse an arithmetic expansion (indicate start of one and set state)
11465 */
Eric Andersenc470f442003-07-28 09:56:35 +000011466parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011467 if (++arinest == 1) {
11468 prevsyntax = syntax;
11469 syntax = ARISYNTAX;
11470 USTPUTC(CTLARI, out);
11471 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011472 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011473 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011474 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011475 } else {
11476 /*
11477 * we collapse embedded arithmetic expansion to
11478 * parenthesis, which should be equivalent
11479 */
11480 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011481 }
Eric Andersenc470f442003-07-28 09:56:35 +000011482 goto parsearith_return;
11483}
11484#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011485
Eric Andersenc470f442003-07-28 09:56:35 +000011486} /* end of readtoken */
11487
Eric Andersencb57d552001-06-28 07:25:16 +000011488/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011489 * Read the next input token.
11490 * If the token is a word, we set backquotelist to the list of cmds in
11491 * backquotes. We set quoteflag to true if any part of the word was
11492 * quoted.
11493 * If the token is TREDIR, then we set redirnode to a structure containing
11494 * the redirection.
11495 * In all cases, the variable startlinno is set to the number of the line
11496 * on which the token starts.
11497 *
11498 * [Change comment: here documents and internal procedures]
11499 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11500 * word parsing code into a separate routine. In this case, readtoken
11501 * doesn't need to have any internal procedures, but parseword does.
11502 * We could also make parseoperator in essence the main routine, and
11503 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011504 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011505#define NEW_xxreadtoken
11506#ifdef NEW_xxreadtoken
11507/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011508static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011509 '\n', '(', ')', /* singles */
11510 '&', '|', ';', /* doubles */
11511 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011512};
Eric Andersencb57d552001-06-28 07:25:16 +000011513
Denis Vlasenko834dee72008-10-07 09:18:30 +000011514#define xxreadtoken_singles 3
11515#define xxreadtoken_doubles 3
11516
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011517static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011518 TNL, TLP, TRP, /* only single occurrence allowed */
11519 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11520 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011521 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011522};
11523
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011524static int
11525xxreadtoken(void)
11526{
11527 int c;
11528
11529 if (tokpushback) {
11530 tokpushback = 0;
11531 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011532 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011533 if (needprompt) {
11534 setprompt(2);
11535 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011536 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011537 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011538 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011539 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011540 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011541
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011542 if (c == '#') {
11543 while ((c = pgetc()) != '\n' && c != PEOF)
11544 continue;
11545 pungetc();
11546 } else if (c == '\\') {
11547 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011548 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011549 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011550 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011551 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011552 if (doprompt)
11553 setprompt(2);
11554 } else {
11555 const char *p;
11556
11557 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11558 if (c != PEOF) {
11559 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011560 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011561 needprompt = doprompt;
11562 }
11563
11564 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011565 if (p == NULL)
11566 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011567
Denis Vlasenko834dee72008-10-07 09:18:30 +000011568 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11569 int cc = pgetc();
11570 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011571 p += xxreadtoken_doubles + 1;
11572 } else {
11573 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011574#if ENABLE_ASH_BASH_COMPAT
11575 if (c == '&' && cc == '>') /* &> */
11576 break; /* return readtoken1(...) */
11577#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011578 }
11579 }
11580 }
11581 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11582 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011583 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011584 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011585
11586 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011587}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011588#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589#define RETURN(token) return lasttoken = token
11590static int
11591xxreadtoken(void)
11592{
11593 int c;
11594
11595 if (tokpushback) {
11596 tokpushback = 0;
11597 return lasttoken;
11598 }
11599 if (needprompt) {
11600 setprompt(2);
11601 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011602 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011603 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011604 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011605 switch (c) {
11606 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011607 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011608 continue;
11609 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011610 while ((c = pgetc()) != '\n' && c != PEOF)
11611 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011612 pungetc();
11613 continue;
11614 case '\\':
11615 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011616 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011617 if (doprompt)
11618 setprompt(2);
11619 continue;
11620 }
11621 pungetc();
11622 goto breakloop;
11623 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011624 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011625 needprompt = doprompt;
11626 RETURN(TNL);
11627 case PEOF:
11628 RETURN(TEOF);
11629 case '&':
11630 if (pgetc() == '&')
11631 RETURN(TAND);
11632 pungetc();
11633 RETURN(TBACKGND);
11634 case '|':
11635 if (pgetc() == '|')
11636 RETURN(TOR);
11637 pungetc();
11638 RETURN(TPIPE);
11639 case ';':
11640 if (pgetc() == ';')
11641 RETURN(TENDCASE);
11642 pungetc();
11643 RETURN(TSEMI);
11644 case '(':
11645 RETURN(TLP);
11646 case ')':
11647 RETURN(TRP);
11648 default:
11649 goto breakloop;
11650 }
11651 }
11652 breakloop:
11653 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11654#undef RETURN
11655}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011656#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011657
11658static int
11659readtoken(void)
11660{
11661 int t;
11662#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011663 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011664#endif
11665
11666#if ENABLE_ASH_ALIAS
11667 top:
11668#endif
11669
11670 t = xxreadtoken();
11671
11672 /*
11673 * eat newlines
11674 */
11675 if (checkkwd & CHKNL) {
11676 while (t == TNL) {
11677 parseheredoc();
11678 t = xxreadtoken();
11679 }
11680 }
11681
11682 if (t != TWORD || quoteflag) {
11683 goto out;
11684 }
11685
11686 /*
11687 * check for keywords
11688 */
11689 if (checkkwd & CHKKWD) {
11690 const char *const *pp;
11691
11692 pp = findkwd(wordtext);
11693 if (pp) {
11694 lasttoken = t = pp - tokname_array;
11695 TRACE(("keyword %s recognized\n", tokname(t)));
11696 goto out;
11697 }
11698 }
11699
11700 if (checkkwd & CHKALIAS) {
11701#if ENABLE_ASH_ALIAS
11702 struct alias *ap;
11703 ap = lookupalias(wordtext, 1);
11704 if (ap != NULL) {
11705 if (*ap->val) {
11706 pushstring(ap->val, ap);
11707 }
11708 goto top;
11709 }
11710#endif
11711 }
11712 out:
11713 checkkwd = 0;
11714#if DEBUG
11715 if (!alreadyseen)
11716 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11717 else
11718 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11719#endif
11720 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011721}
11722
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011723static char
11724peektoken(void)
11725{
11726 int t;
11727
11728 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011729 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011730 return tokname_array[t][0];
11731}
Eric Andersencb57d552001-06-28 07:25:16 +000011732
11733/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011734 * Read and parse a command. Returns NODE_EOF on end of file.
11735 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011736 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011737static union node *
11738parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011739{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011740 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011741
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011742 tokpushback = 0;
11743 doprompt = interact;
11744 if (doprompt)
11745 setprompt(doprompt);
11746 needprompt = 0;
11747 t = readtoken();
11748 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011749 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011750 if (t == TNL)
11751 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011752 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011753 return list(1);
11754}
11755
11756/*
11757 * Input any here documents.
11758 */
11759static void
11760parseheredoc(void)
11761{
11762 struct heredoc *here;
11763 union node *n;
11764
11765 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011766 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011767
11768 while (here) {
11769 if (needprompt) {
11770 setprompt(2);
11771 }
11772 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11773 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011774 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011775 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011776 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011777 n->narg.text = wordtext;
11778 n->narg.backquote = backquotelist;
11779 here->here->nhere.doc = n;
11780 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011781 }
Eric Andersencb57d552001-06-28 07:25:16 +000011782}
11783
11784
11785/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011786 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011787 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011788#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011789static const char *
11790expandstr(const char *ps)
11791{
11792 union node n;
11793
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011794 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11795 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011796 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011797 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011798 popfile();
11799
11800 n.narg.type = NARG;
11801 n.narg.next = NULL;
11802 n.narg.text = wordtext;
11803 n.narg.backquote = backquotelist;
11804
11805 expandarg(&n, NULL, 0);
11806 return stackblock();
11807}
11808#endif
11809
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011810/*
11811 * Execute a command or commands contained in a string.
11812 */
11813static int
11814evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011815{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011816 union node *n;
11817 struct stackmark smark;
11818 int skip;
11819
11820 setinputstring(s);
11821 setstackmark(&smark);
11822
11823 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011824 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011825 evaltree(n, 0);
11826 popstackmark(&smark);
11827 skip = evalskip;
11828 if (skip)
11829 break;
11830 }
11831 popfile();
11832
11833 skip &= mask;
11834 evalskip = skip;
11835 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011836}
11837
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011838/*
11839 * The eval command.
11840 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011841static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011842evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011843{
11844 char *p;
11845 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011846
Denis Vlasenko68404f12008-03-17 09:00:54 +000011847 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011848 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011849 argv += 2;
11850 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011851 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011852 for (;;) {
11853 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011854 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011855 if (p == NULL)
11856 break;
11857 STPUTC(' ', concat);
11858 }
11859 STPUTC('\0', concat);
11860 p = grabstackstr(concat);
11861 }
11862 evalstring(p, ~SKIPEVAL);
11863
11864 }
11865 return exitstatus;
11866}
11867
11868/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011869 * Read and execute commands.
11870 * "Top" is nonzero for the top level command loop;
11871 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011872 */
11873static int
11874cmdloop(int top)
11875{
11876 union node *n;
11877 struct stackmark smark;
11878 int inter;
11879 int numeof = 0;
11880
11881 TRACE(("cmdloop(%d) called\n", top));
11882 for (;;) {
11883 int skip;
11884
11885 setstackmark(&smark);
11886#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011887 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011888 showjobs(stderr, SHOW_CHANGED);
11889#endif
11890 inter = 0;
11891 if (iflag && top) {
11892 inter++;
11893#if ENABLE_ASH_MAIL
11894 chkmail();
11895#endif
11896 }
11897 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011898#if DEBUG
11899 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011900 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011901#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011902 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011903 if (!top || numeof >= 50)
11904 break;
11905 if (!stoppedjobs()) {
11906 if (!Iflag)
11907 break;
11908 out2str("\nUse \"exit\" to leave shell.\n");
11909 }
11910 numeof++;
11911 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011912 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11913 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011914 numeof = 0;
11915 evaltree(n, 0);
11916 }
11917 popstackmark(&smark);
11918 skip = evalskip;
11919
11920 if (skip) {
11921 evalskip = 0;
11922 return skip & SKIPEVAL;
11923 }
11924 }
11925 return 0;
11926}
11927
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011928/*
11929 * Take commands from a file. To be compatible we should do a path
11930 * search for the file, which is necessary to find sub-commands.
11931 */
11932static char *
11933find_dot_file(char *name)
11934{
11935 char *fullname;
11936 const char *path = pathval();
11937 struct stat statb;
11938
11939 /* don't try this for absolute or relative paths */
11940 if (strchr(name, '/'))
11941 return name;
11942
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011943 /* IIRC standards do not say whether . is to be searched.
11944 * And it is even smaller this way, making it unconditional for now:
11945 */
11946 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11947 fullname = name;
11948 goto try_cur_dir;
11949 }
11950
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011951 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011952 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011953 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11954 /*
11955 * Don't bother freeing here, since it will
11956 * be freed by the caller.
11957 */
11958 return fullname;
11959 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011960 if (fullname != name)
11961 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011962 }
11963
11964 /* not found in the PATH */
11965 ash_msg_and_raise_error("%s: not found", name);
11966 /* NOTREACHED */
11967}
11968
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011969static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011970dotcmd(int argc, char **argv)
11971{
11972 struct strlist *sp;
11973 volatile struct shparam saveparam;
11974 int status = 0;
11975
11976 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011977 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011978
Denis Vlasenko68404f12008-03-17 09:00:54 +000011979 if (argv[1]) { /* That's what SVR2 does */
11980 char *fullname = find_dot_file(argv[1]);
11981 argv += 2;
11982 argc -= 2;
11983 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011984 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011985 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011986 shellparam.nparam = argc;
11987 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011988 };
11989
11990 setinputfile(fullname, INPUT_PUSH_FILE);
11991 commandname = fullname;
11992 cmdloop(0);
11993 popfile();
11994
Denis Vlasenko68404f12008-03-17 09:00:54 +000011995 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011996 freeparam(&shellparam);
11997 shellparam = saveparam;
11998 };
11999 status = exitstatus;
12000 }
12001 return status;
12002}
12003
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012004static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012005exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012006{
12007 if (stoppedjobs())
12008 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012009 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012010 exitstatus = number(argv[1]);
12011 raise_exception(EXEXIT);
12012 /* NOTREACHED */
12013}
12014
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012015/*
12016 * Read a file containing shell functions.
12017 */
12018static void
12019readcmdfile(char *name)
12020{
12021 setinputfile(name, INPUT_PUSH_FILE);
12022 cmdloop(0);
12023 popfile();
12024}
12025
12026
Denis Vlasenkocc571512007-02-23 21:10:35 +000012027/* ============ find_command inplementation */
12028
12029/*
12030 * Resolve a command name. If you change this routine, you may have to
12031 * change the shellexec routine as well.
12032 */
12033static void
12034find_command(char *name, struct cmdentry *entry, int act, const char *path)
12035{
12036 struct tblentry *cmdp;
12037 int idx;
12038 int prev;
12039 char *fullname;
12040 struct stat statb;
12041 int e;
12042 int updatetbl;
12043 struct builtincmd *bcmd;
12044
12045 /* If name contains a slash, don't use PATH or hash table */
12046 if (strchr(name, '/') != NULL) {
12047 entry->u.index = -1;
12048 if (act & DO_ABS) {
12049 while (stat(name, &statb) < 0) {
12050#ifdef SYSV
12051 if (errno == EINTR)
12052 continue;
12053#endif
12054 entry->cmdtype = CMDUNKNOWN;
12055 return;
12056 }
12057 }
12058 entry->cmdtype = CMDNORMAL;
12059 return;
12060 }
12061
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012062/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012063
12064 updatetbl = (path == pathval());
12065 if (!updatetbl) {
12066 act |= DO_ALTPATH;
12067 if (strstr(path, "%builtin") != NULL)
12068 act |= DO_ALTBLTIN;
12069 }
12070
12071 /* If name is in the table, check answer will be ok */
12072 cmdp = cmdlookup(name, 0);
12073 if (cmdp != NULL) {
12074 int bit;
12075
12076 switch (cmdp->cmdtype) {
12077 default:
12078#if DEBUG
12079 abort();
12080#endif
12081 case CMDNORMAL:
12082 bit = DO_ALTPATH;
12083 break;
12084 case CMDFUNCTION:
12085 bit = DO_NOFUNC;
12086 break;
12087 case CMDBUILTIN:
12088 bit = DO_ALTBLTIN;
12089 break;
12090 }
12091 if (act & bit) {
12092 updatetbl = 0;
12093 cmdp = NULL;
12094 } else if (cmdp->rehash == 0)
12095 /* if not invalidated by cd, we're done */
12096 goto success;
12097 }
12098
12099 /* If %builtin not in path, check for builtin next */
12100 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012101 if (bcmd) {
12102 if (IS_BUILTIN_REGULAR(bcmd))
12103 goto builtin_success;
12104 if (act & DO_ALTPATH) {
12105 if (!(act & DO_ALTBLTIN))
12106 goto builtin_success;
12107 } else if (builtinloc <= 0) {
12108 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012109 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012110 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012111
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012112#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012113 {
12114 int applet_no = find_applet_by_name(name);
12115 if (applet_no >= 0) {
12116 entry->cmdtype = CMDNORMAL;
12117 entry->u.index = -2 - applet_no;
12118 return;
12119 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012120 }
12121#endif
12122
Denis Vlasenkocc571512007-02-23 21:10:35 +000012123 /* We have to search path. */
12124 prev = -1; /* where to start */
12125 if (cmdp && cmdp->rehash) { /* doing a rehash */
12126 if (cmdp->cmdtype == CMDBUILTIN)
12127 prev = builtinloc;
12128 else
12129 prev = cmdp->param.index;
12130 }
12131
12132 e = ENOENT;
12133 idx = -1;
12134 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012135 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012136 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012137 /* NB: code below will still use fullname
12138 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012139 idx++;
12140 if (pathopt) {
12141 if (prefix(pathopt, "builtin")) {
12142 if (bcmd)
12143 goto builtin_success;
12144 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012145 }
12146 if ((act & DO_NOFUNC)
12147 || !prefix(pathopt, "func")
12148 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012149 continue;
12150 }
12151 }
12152 /* if rehash, don't redo absolute path names */
12153 if (fullname[0] == '/' && idx <= prev) {
12154 if (idx < prev)
12155 continue;
12156 TRACE(("searchexec \"%s\": no change\n", name));
12157 goto success;
12158 }
12159 while (stat(fullname, &statb) < 0) {
12160#ifdef SYSV
12161 if (errno == EINTR)
12162 continue;
12163#endif
12164 if (errno != ENOENT && errno != ENOTDIR)
12165 e = errno;
12166 goto loop;
12167 }
12168 e = EACCES; /* if we fail, this will be the error */
12169 if (!S_ISREG(statb.st_mode))
12170 continue;
12171 if (pathopt) { /* this is a %func directory */
12172 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012173 /* NB: stalloc will return space pointed by fullname
12174 * (because we don't have any intervening allocations
12175 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012176 readcmdfile(fullname);
12177 cmdp = cmdlookup(name, 0);
12178 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12179 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12180 stunalloc(fullname);
12181 goto success;
12182 }
12183 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12184 if (!updatetbl) {
12185 entry->cmdtype = CMDNORMAL;
12186 entry->u.index = idx;
12187 return;
12188 }
12189 INT_OFF;
12190 cmdp = cmdlookup(name, 1);
12191 cmdp->cmdtype = CMDNORMAL;
12192 cmdp->param.index = idx;
12193 INT_ON;
12194 goto success;
12195 }
12196
12197 /* We failed. If there was an entry for this command, delete it */
12198 if (cmdp && updatetbl)
12199 delete_cmd_entry();
12200 if (act & DO_ERR)
12201 ash_msg("%s: %s", name, errmsg(e, "not found"));
12202 entry->cmdtype = CMDUNKNOWN;
12203 return;
12204
12205 builtin_success:
12206 if (!updatetbl) {
12207 entry->cmdtype = CMDBUILTIN;
12208 entry->u.cmd = bcmd;
12209 return;
12210 }
12211 INT_OFF;
12212 cmdp = cmdlookup(name, 1);
12213 cmdp->cmdtype = CMDBUILTIN;
12214 cmdp->param.cmd = bcmd;
12215 INT_ON;
12216 success:
12217 cmdp->rehash = 0;
12218 entry->cmdtype = cmdp->cmdtype;
12219 entry->u = cmdp->param;
12220}
12221
12222
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012223/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012224
Eric Andersencb57d552001-06-28 07:25:16 +000012225/*
Eric Andersencb57d552001-06-28 07:25:16 +000012226 * The trap builtin.
12227 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012228static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012229trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012230{
12231 char *action;
12232 char **ap;
12233 int signo;
12234
Eric Andersenc470f442003-07-28 09:56:35 +000012235 nextopt(nullstr);
12236 ap = argptr;
12237 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012238 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012239 char *tr = trap_ptr[signo];
12240 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012241 /* note: bash adds "SIG", but only if invoked
12242 * as "bash". If called as "sh", or if set -o posix,
12243 * then it prints short signal names.
12244 * We are printing short names: */
12245 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012246 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012247 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012248 /* trap_ptr != trap only if we are in special-cased `trap` code.
12249 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012250 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012251 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012252 }
12253 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012254 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012255 if (trap_ptr != trap) {
12256 free(trap_ptr);
12257 trap_ptr = trap;
12258 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012259 */
Eric Andersencb57d552001-06-28 07:25:16 +000012260 return 0;
12261 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012262
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012263 action = NULL;
12264 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012265 action = *ap++;
12266 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012267 signo = get_signum(*ap);
12268 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012269 ash_msg_and_raise_error("%s: bad trap", *ap);
12270 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012271 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012272 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012273 action = NULL;
12274 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012275 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012276 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012277 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012278 trap[signo] = action;
12279 if (signo != 0)
12280 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012281 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012282 ap++;
12283 }
12284 return 0;
12285}
12286
Eric Andersenc470f442003-07-28 09:56:35 +000012287
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012288/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012289
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012290#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012291/*
12292 * Lists available builtins
12293 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012294static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012295helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012296{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012297 unsigned col;
12298 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012299
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012300 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012301 "Built-in commands:\n"
12302 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012303 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012304 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012305 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012306 if (col > 60) {
12307 out1fmt("\n");
12308 col = 0;
12309 }
12310 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012311#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012312 {
12313 const char *a = applet_names;
12314 while (*a) {
12315 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12316 if (col > 60) {
12317 out1fmt("\n");
12318 col = 0;
12319 }
12320 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012321 }
12322 }
12323#endif
12324 out1fmt("\n\n");
12325 return EXIT_SUCCESS;
12326}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012327#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012328
Eric Andersencb57d552001-06-28 07:25:16 +000012329/*
Eric Andersencb57d552001-06-28 07:25:16 +000012330 * The export and readonly commands.
12331 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012332static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012333exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012334{
12335 struct var *vp;
12336 char *name;
12337 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012338 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012339 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012340
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012341 if (nextopt("p") != 'p') {
12342 aptr = argptr;
12343 name = *aptr;
12344 if (name) {
12345 do {
12346 p = strchr(name, '=');
12347 if (p != NULL) {
12348 p++;
12349 } else {
12350 vp = *findvar(hashvar(name), name);
12351 if (vp) {
12352 vp->flags |= flag;
12353 continue;
12354 }
Eric Andersencb57d552001-06-28 07:25:16 +000012355 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012356 setvar(name, p, flag);
12357 } while ((name = *++aptr) != NULL);
12358 return 0;
12359 }
Eric Andersencb57d552001-06-28 07:25:16 +000012360 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012361 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012362 return 0;
12363}
12364
Eric Andersencb57d552001-06-28 07:25:16 +000012365/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012366 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012367 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012368static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012369unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012370{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012371 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012372
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012373 cmdp = cmdlookup(name, 0);
12374 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12375 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012376}
12377
Eric Andersencb57d552001-06-28 07:25:16 +000012378/*
Eric Andersencb57d552001-06-28 07:25:16 +000012379 * The unset builtin command. We unset the function before we unset the
12380 * variable to allow a function to be unset when there is a readonly variable
12381 * with the same name.
12382 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012383static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012384unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012385{
12386 char **ap;
12387 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012388 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012389 int ret = 0;
12390
12391 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012392 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012393 }
Eric Andersencb57d552001-06-28 07:25:16 +000012394
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012395 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012396 if (flag != 'f') {
12397 i = unsetvar(*ap);
12398 ret |= i;
12399 if (!(i & 2))
12400 continue;
12401 }
12402 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012403 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012404 }
Eric Andersenc470f442003-07-28 09:56:35 +000012405 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012406}
12407
12408
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012409/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012410
Eric Andersenc470f442003-07-28 09:56:35 +000012411#include <sys/times.h>
12412
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012413static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012414 ' ', offsetof(struct tms, tms_utime),
12415 '\n', offsetof(struct tms, tms_stime),
12416 ' ', offsetof(struct tms, tms_cutime),
12417 '\n', offsetof(struct tms, tms_cstime),
12418 0
12419};
Eric Andersencb57d552001-06-28 07:25:16 +000012420
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012421static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012422timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012423{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012424 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012425 const unsigned char *p;
12426 struct tms buf;
12427
12428 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012429 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012430
12431 p = timescmd_str;
12432 do {
12433 t = *(clock_t *)(((char *) &buf) + p[1]);
12434 s = t / clk_tck;
12435 out1fmt("%ldm%ld.%.3lds%c",
12436 s/60, s%60,
12437 ((t - s * clk_tck) * 1000) / clk_tck,
12438 p[0]);
12439 } while (*(p += 2));
12440
Eric Andersencb57d552001-06-28 07:25:16 +000012441 return 0;
12442}
12443
Mike Frysinger98c52642009-04-02 10:02:37 +000012444#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012445/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012446 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12447 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012448 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012449 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012450 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012451static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012452letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012453{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012454 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012455
Denis Vlasenko68404f12008-03-17 09:00:54 +000012456 argv++;
12457 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012458 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012459 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012460 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012461 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012462
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012463 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012464}
Mike Frysinger98c52642009-04-02 10:02:37 +000012465#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012466
Eric Andersenc470f442003-07-28 09:56:35 +000012467
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012468/* ============ miscbltin.c
12469 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012470 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012471 */
12472
12473#undef rflag
12474
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012475#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012476typedef enum __rlimit_resource rlim_t;
12477#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012478
Eric Andersenc470f442003-07-28 09:56:35 +000012479/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012480 * The read builtin. Options:
12481 * -r Do not interpret '\' specially
12482 * -s Turn off echo (tty only)
12483 * -n NCHARS Read NCHARS max
12484 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12485 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12486 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012487 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012488 * TODO: bash also has:
12489 * -a ARRAY Read into array[0],[1],etc
12490 * -d DELIM End on DELIM char, not newline
12491 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012492 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012493static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012494readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012495{
Denys Vlasenko73067272010-01-12 22:11:24 +010012496 char *opt_n = NULL;
12497 char *opt_p = NULL;
12498 char *opt_t = NULL;
12499 char *opt_u = NULL;
12500 int read_flags = 0;
12501 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012502 int i;
12503
Denys Vlasenko73067272010-01-12 22:11:24 +010012504 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012505 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012506 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012507 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012508 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012509 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012510 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012511 break;
12512 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012513 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012514 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012515 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012516 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012517 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012518 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012519 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012520 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012521 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012522 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012523 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012524 default:
12525 break;
12526 }
Eric Andersenc470f442003-07-28 09:56:35 +000012527 }
Paul Fox02eb9342005-09-07 16:56:02 +000012528
Denys Vlasenko73067272010-01-12 22:11:24 +010012529 r = builtin_read(setvar,
12530 argptr,
12531 bltinlookup("IFS"), /* can be NULL */
12532 read_flags,
12533 opt_n,
12534 opt_p,
12535 opt_t,
12536 opt_u
12537 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012538
Denys Vlasenko73067272010-01-12 22:11:24 +010012539 if ((uintptr_t)r > 1)
12540 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012541
Denys Vlasenko73067272010-01-12 22:11:24 +010012542 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012543}
12544
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012545static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012546umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012547{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012548 static const char permuser[3] ALIGN1 = "ugo";
12549 static const char permmode[3] ALIGN1 = "rwx";
12550 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012551 S_IRUSR, S_IWUSR, S_IXUSR,
12552 S_IRGRP, S_IWGRP, S_IXGRP,
12553 S_IROTH, S_IWOTH, S_IXOTH
12554 };
12555
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012556 /* TODO: use bb_parse_mode() instead */
12557
Eric Andersenc470f442003-07-28 09:56:35 +000012558 char *ap;
12559 mode_t mask;
12560 int i;
12561 int symbolic_mode = 0;
12562
12563 while (nextopt("S") != '\0') {
12564 symbolic_mode = 1;
12565 }
12566
Denis Vlasenkob012b102007-02-19 22:43:01 +000012567 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012568 mask = umask(0);
12569 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012570 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012571
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012572 ap = *argptr;
12573 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012574 if (symbolic_mode) {
12575 char buf[18];
12576 char *p = buf;
12577
12578 for (i = 0; i < 3; i++) {
12579 int j;
12580
12581 *p++ = permuser[i];
12582 *p++ = '=';
12583 for (j = 0; j < 3; j++) {
12584 if ((mask & permmask[3 * i + j]) == 0) {
12585 *p++ = permmode[j];
12586 }
12587 }
12588 *p++ = ',';
12589 }
12590 *--p = 0;
12591 puts(buf);
12592 } else {
12593 out1fmt("%.4o\n", mask);
12594 }
12595 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012596 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012597 mask = 0;
12598 do {
12599 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012600 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012601 mask = (mask << 3) + (*ap - '0');
12602 } while (*++ap != '\0');
12603 umask(mask);
12604 } else {
12605 mask = ~mask & 0777;
12606 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012607 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012608 }
12609 umask(~mask & 0777);
12610 }
12611 }
12612 return 0;
12613}
12614
12615/*
12616 * ulimit builtin
12617 *
12618 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12619 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12620 * ash by J.T. Conklin.
12621 *
12622 * Public domain.
12623 */
Eric Andersenc470f442003-07-28 09:56:35 +000012624struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012625 uint8_t cmd; /* RLIMIT_xxx fit into it */
12626 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012627 char option;
12628};
12629
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012630static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012631#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012632 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012633#endif
12634#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012635 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012636#endif
12637#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012638 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012639#endif
12640#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012641 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012642#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012643#ifdef RLIMIT_CORE
12644 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012645#endif
12646#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012647 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012648#endif
12649#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012650 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012651#endif
12652#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012653 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012654#endif
12655#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012656 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012657#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012658#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012659 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012660#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012661#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012662 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012663#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012664};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012665static const char limits_name[] =
12666#ifdef RLIMIT_CPU
12667 "time(seconds)" "\0"
12668#endif
12669#ifdef RLIMIT_FSIZE
12670 "file(blocks)" "\0"
12671#endif
12672#ifdef RLIMIT_DATA
12673 "data(kb)" "\0"
12674#endif
12675#ifdef RLIMIT_STACK
12676 "stack(kb)" "\0"
12677#endif
12678#ifdef RLIMIT_CORE
12679 "coredump(blocks)" "\0"
12680#endif
12681#ifdef RLIMIT_RSS
12682 "memory(kb)" "\0"
12683#endif
12684#ifdef RLIMIT_MEMLOCK
12685 "locked memory(kb)" "\0"
12686#endif
12687#ifdef RLIMIT_NPROC
12688 "process" "\0"
12689#endif
12690#ifdef RLIMIT_NOFILE
12691 "nofiles" "\0"
12692#endif
12693#ifdef RLIMIT_AS
12694 "vmemory(kb)" "\0"
12695#endif
12696#ifdef RLIMIT_LOCKS
12697 "locks" "\0"
12698#endif
12699;
Eric Andersenc470f442003-07-28 09:56:35 +000012700
Glenn L McGrath76620622004-01-13 10:19:37 +000012701enum limtype { SOFT = 0x1, HARD = 0x2 };
12702
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012703static void
12704printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012705 const struct limits *l)
12706{
12707 rlim_t val;
12708
12709 val = limit->rlim_max;
12710 if (how & SOFT)
12711 val = limit->rlim_cur;
12712
12713 if (val == RLIM_INFINITY)
12714 out1fmt("unlimited\n");
12715 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012716 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012717 out1fmt("%lld\n", (long long) val);
12718 }
12719}
12720
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012721static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012722ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012723{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012724 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012725 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012726 const struct limits *l;
12727 int set, all = 0;
12728 int optc, what;
12729 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012730
12731 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012732 while ((optc = nextopt("HSa"
12733#ifdef RLIMIT_CPU
12734 "t"
12735#endif
12736#ifdef RLIMIT_FSIZE
12737 "f"
12738#endif
12739#ifdef RLIMIT_DATA
12740 "d"
12741#endif
12742#ifdef RLIMIT_STACK
12743 "s"
12744#endif
12745#ifdef RLIMIT_CORE
12746 "c"
12747#endif
12748#ifdef RLIMIT_RSS
12749 "m"
12750#endif
12751#ifdef RLIMIT_MEMLOCK
12752 "l"
12753#endif
12754#ifdef RLIMIT_NPROC
12755 "p"
12756#endif
12757#ifdef RLIMIT_NOFILE
12758 "n"
12759#endif
12760#ifdef RLIMIT_AS
12761 "v"
12762#endif
12763#ifdef RLIMIT_LOCKS
12764 "w"
12765#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012766 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012767 switch (optc) {
12768 case 'H':
12769 how = HARD;
12770 break;
12771 case 'S':
12772 how = SOFT;
12773 break;
12774 case 'a':
12775 all = 1;
12776 break;
12777 default:
12778 what = optc;
12779 }
12780
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012781 for (l = limits_tbl; l->option != what; l++)
12782 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012783
12784 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012785 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012786 if (set) {
12787 char *p = *argptr;
12788
12789 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012790 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012791 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012792 val = RLIM_INFINITY;
12793 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012794 if (sizeof(val) == sizeof(int))
12795 val = bb_strtou(p, NULL, 10);
12796 else if (sizeof(val) == sizeof(long))
12797 val = bb_strtoul(p, NULL, 10);
12798 else
12799 val = bb_strtoull(p, NULL, 10);
12800 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012801 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012802 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012803 }
12804 }
12805 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012806 const char *lname = limits_name;
12807 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012808 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012809 out1fmt("%-20s ", lname);
12810 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012811 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012812 }
12813 return 0;
12814 }
12815
12816 getrlimit(l->cmd, &limit);
12817 if (set) {
12818 if (how & HARD)
12819 limit.rlim_max = val;
12820 if (how & SOFT)
12821 limit.rlim_cur = val;
12822 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012823 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012824 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012825 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012826 }
12827 return 0;
12828}
12829
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012830/* ============ main() and helpers */
12831
12832/*
12833 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012834 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012835static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012836static void
12837exitshell(void)
12838{
12839 struct jmploc loc;
12840 char *p;
12841 int status;
12842
12843 status = exitstatus;
12844 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12845 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012846 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012847/* dash bug: it just does _exit(exitstatus) here
12848 * but we have to do setjobctl(0) first!
12849 * (bug is still not fixed in dash-0.5.3 - if you run dash
12850 * under Midnight Commander, on exit from dash MC is backgrounded) */
12851 status = exitstatus;
12852 goto out;
12853 }
12854 exception_handler = &loc;
12855 p = trap[0];
12856 if (p) {
12857 trap[0] = NULL;
12858 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012859 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012860 }
12861 flush_stdout_stderr();
12862 out:
12863 setjobctl(0);
12864 _exit(status);
12865 /* NOTREACHED */
12866}
12867
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012868static void
12869init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012870{
12871 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012872 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012873
12874 /* from trap.c: */
12875 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012876 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12877 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12878 */
12879 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012880
12881 /* from var.c: */
12882 {
12883 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012884 const char *p;
12885 struct stat st1, st2;
12886
12887 initvar();
12888 for (envp = environ; envp && *envp; envp++) {
12889 if (strchr(*envp, '=')) {
12890 setvareq(*envp, VEXPORT|VTEXTFIXED);
12891 }
12892 }
12893
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012894 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012895
12896 p = lookupvar("PWD");
12897 if (p)
12898 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12899 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12900 p = '\0';
12901 setpwd(p, 0);
12902 }
12903}
12904
12905/*
12906 * Process the shell command line arguments.
12907 */
12908static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012909procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012910{
12911 int i;
12912 const char *xminusc;
12913 char **xargv;
12914
12915 xargv = argv;
12916 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012917 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012918 xargv++;
12919 for (i = 0; i < NOPTS; i++)
12920 optlist[i] = 2;
12921 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012922 if (options(1)) {
12923 /* it already printed err message */
12924 raise_exception(EXERROR);
12925 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012926 xargv = argptr;
12927 xminusc = minusc;
12928 if (*xargv == NULL) {
12929 if (xminusc)
12930 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12931 sflag = 1;
12932 }
12933 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12934 iflag = 1;
12935 if (mflag == 2)
12936 mflag = iflag;
12937 for (i = 0; i < NOPTS; i++)
12938 if (optlist[i] == 2)
12939 optlist[i] = 0;
12940#if DEBUG == 2
12941 debug = 1;
12942#endif
12943 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12944 if (xminusc) {
12945 minusc = *xargv++;
12946 if (*xargv)
12947 goto setarg0;
12948 } else if (!sflag) {
12949 setinputfile(*xargv, 0);
12950 setarg0:
12951 arg0 = *xargv++;
12952 commandname = arg0;
12953 }
12954
12955 shellparam.p = xargv;
12956#if ENABLE_ASH_GETOPTS
12957 shellparam.optind = 1;
12958 shellparam.optoff = -1;
12959#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012960 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012961 while (*xargv) {
12962 shellparam.nparam++;
12963 xargv++;
12964 }
12965 optschanged();
12966}
12967
12968/*
12969 * Read /etc/profile or .profile.
12970 */
12971static void
12972read_profile(const char *name)
12973{
12974 int skip;
12975
12976 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12977 return;
12978 skip = cmdloop(0);
12979 popfile();
12980 if (skip)
12981 exitshell();
12982}
12983
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012984/*
12985 * This routine is called when an error or an interrupt occurs in an
12986 * interactive shell and control is returned to the main command loop.
12987 */
12988static void
12989reset(void)
12990{
12991 /* from eval.c: */
12992 evalskip = 0;
12993 loopnest = 0;
12994 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012995 g_parsefile->left_in_buffer = 0;
12996 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012997 popallfiles();
12998 /* from parser.c: */
12999 tokpushback = 0;
13000 checkkwd = 0;
13001 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013002 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013003}
13004
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013005#if PROFILE
13006static short profile_buf[16384];
13007extern int etext();
13008#endif
13009
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013010/*
13011 * Main routine. We initialize things, parse the arguments, execute
13012 * profiles if we're a login shell, and then call cmdloop to execute
13013 * commands. The setjmp call sets up the location to jump to when an
13014 * exception occurs. When an exception occurs the variable "state"
13015 * is used to figure out how far we had gotten.
13016 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013017int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013018int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013019{
Mike Frysinger98c52642009-04-02 10:02:37 +000013020 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013021 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013022 struct jmploc jmploc;
13023 struct stackmark smark;
13024
Denis Vlasenko01631112007-12-16 17:20:38 +000013025 /* Initialize global data */
13026 INIT_G_misc();
13027 INIT_G_memstack();
13028 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013029#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013030 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013031#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013032 INIT_G_cmdtable();
13033
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013034#if PROFILE
13035 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13036#endif
13037
13038#if ENABLE_FEATURE_EDITING
13039 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13040#endif
13041 state = 0;
13042 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013043 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013044 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013045
13046 reset();
13047
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013048 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013049 if (e == EXERROR)
13050 exitstatus = 2;
13051 s = state;
13052 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13053 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013054 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013055 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013056
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013057 popstackmark(&smark);
13058 FORCE_INT_ON; /* enable interrupts */
13059 if (s == 1)
13060 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013061 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013062 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013063 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013064 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013065 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013066 }
13067 exception_handler = &jmploc;
13068#if DEBUG
13069 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013070 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013071 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013072#endif
13073 rootpid = getpid();
13074
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013075 init();
13076 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013077 procargs(argv);
13078
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013079#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13080 if (iflag) {
13081 const char *hp = lookupvar("HISTFILE");
13082
13083 if (hp == NULL) {
13084 hp = lookupvar("HOME");
13085 if (hp != NULL) {
13086 char *defhp = concat_path_file(hp, ".ash_history");
13087 setvar("HISTFILE", defhp, 0);
13088 free(defhp);
13089 }
13090 }
13091 }
13092#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013093 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013094 isloginsh = 1;
13095 if (isloginsh) {
13096 state = 1;
13097 read_profile("/etc/profile");
13098 state1:
13099 state = 2;
13100 read_profile(".profile");
13101 }
13102 state2:
13103 state = 3;
13104 if (
13105#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013106 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013107#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013108 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013109 ) {
13110 shinit = lookupvar("ENV");
13111 if (shinit != NULL && *shinit != '\0') {
13112 read_profile(shinit);
13113 }
13114 }
13115 state3:
13116 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013117 if (minusc) {
13118 /* evalstring pushes parsefile stack.
13119 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013120 * is one of stacked source fds.
13121 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013122 if (!sflag)
13123 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013124 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013125 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013126
13127 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013128#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013129 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013130 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013131 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013132 line_input_state->hist_file = hp;
13133 }
13134#endif
13135 state4: /* XXX ??? - why isn't this before the "if" statement */
13136 cmdloop(1);
13137 }
13138#if PROFILE
13139 monitor(0);
13140#endif
13141#ifdef GPROF
13142 {
13143 extern void _mcleanup(void);
13144 _mcleanup();
13145 }
13146#endif
13147 exitshell();
13148 /* NOTREACHED */
13149}
13150
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013151
Eric Andersendf82f612001-06-28 07:46:40 +000013152/*-
13153 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013154 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013155 *
13156 * This code is derived from software contributed to Berkeley by
13157 * Kenneth Almquist.
13158 *
13159 * Redistribution and use in source and binary forms, with or without
13160 * modification, are permitted provided that the following conditions
13161 * are met:
13162 * 1. Redistributions of source code must retain the above copyright
13163 * notice, this list of conditions and the following disclaimer.
13164 * 2. Redistributions in binary form must reproduce the above copyright
13165 * notice, this list of conditions and the following disclaimer in the
13166 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013167 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013168 * may be used to endorse or promote products derived from this software
13169 * without specific prior written permission.
13170 *
13171 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13172 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13173 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13174 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13175 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13176 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13177 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13178 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13179 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13180 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13181 * SUCH DAMAGE.
13182 */