blob: cfd8154ef8e8abd9a2baa3b2ac4c2b1daef169b3 [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 Vlasenko1aa7e472007-11-28 06:49:03 +000039#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000040#include <paths.h>
41#include <setjmp.h>
42#include <fnmatch.h>
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020043#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010044
45#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000046#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020047#if ENABLE_ASH_RANDOM_SUPPORT
48# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020049#else
50# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020051#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000052
Denys Vlasenko1fcbff22010-06-26 02:40:08 +020053#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +010054#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000055/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020056# undef CONFIG_FEATURE_SH_STANDALONE
57# undef ENABLE_FEATURE_SH_STANDALONE
58# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010059# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020060# define ENABLE_FEATURE_SH_STANDALONE 0
61# define IF_FEATURE_SH_STANDALONE(...)
62# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000063#endif
64
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000065#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000066# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000067#endif
68
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010069#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000070# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000071#endif
72
Denis Vlasenkob012b102007-02-19 22:43:01 +000073
Denis Vlasenko01631112007-12-16 17:20:38 +000074/* ============ Hash table sizes. Configurable. */
75
76#define VTABSIZE 39
77#define ATABSIZE 39
78#define CMDTABLESIZE 31 /* should be prime */
79
80
Denis Vlasenkob012b102007-02-19 22:43:01 +000081/* ============ Shell options */
82
83static const char *const optletters_optnames[] = {
84 "e" "errexit",
85 "f" "noglob",
86 "I" "ignoreeof",
87 "i" "interactive",
88 "m" "monitor",
89 "n" "noexec",
90 "s" "stdin",
91 "x" "xtrace",
92 "v" "verbose",
93 "C" "noclobber",
94 "a" "allexport",
95 "b" "notify",
96 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +010097 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +010098#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +010099 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100100#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000101#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000102 ,"\0" "nolog"
103 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000104#endif
105};
106
Denys Vlasenko285ad152009-12-04 23:02:27 +0100107#define optletters(n) optletters_optnames[n][0]
108#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000110enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111
Eric Andersenc470f442003-07-28 09:56:35 +0000112
Denis Vlasenkob012b102007-02-19 22:43:01 +0000113/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000114
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200115#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000116
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000117/*
Eric Andersenc470f442003-07-28 09:56:35 +0000118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000120 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000121 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
125 */
Eric Andersenc470f442003-07-28 09:56:35 +0000126struct jmploc {
127 jmp_buf loc;
128};
Denis Vlasenko01631112007-12-16 17:20:38 +0000129
130struct globals_misc {
131 /* pid of main shell */
132 int rootpid;
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
134 int shlvl;
135#define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
137
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
140
141 char *arg0; /* value of $0 */
142
143 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000144
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200145 volatile int suppress_int; /* counter */
146 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000147 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200148 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000149 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000150 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000151#define EXINT 0 /* SIGINT received */
152#define EXERROR 1 /* a generic error */
153#define EXSHELLPROC 2 /* execute a shell procedure */
154#define EXEXEC 3 /* command execution failed */
155#define EXEXIT 4 /* exit the shell */
156#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000157
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000159 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000160
161 char optlist[NOPTS];
162#define eflag optlist[0]
163#define fflag optlist[1]
164#define Iflag optlist[2]
165#define iflag optlist[3]
166#define mflag optlist[4]
167#define nflag optlist[5]
168#define sflag optlist[6]
169#define xflag optlist[7]
170#define vflag optlist[8]
171#define Cflag optlist[9]
172#define aflag optlist[10]
173#define bflag optlist[11]
174#define uflag optlist[12]
175#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100176#if ENABLE_ASH_BASH_COMPAT
177# define pipefail optlist[14]
178#else
179# define pipefail 0
180#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000181#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100182# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
183# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000184#endif
185
186 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000187 /*
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000191 */
192 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000193#define S_DFL 1 /* default signal handling (SIG_DFL) */
194#define S_CATCH 2 /* signal is caught */
195#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000196#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000197
Denis Vlasenko01631112007-12-16 17:20:38 +0000198 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200200 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000201 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200202 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000203
204 /* Rarely referenced stuff */
205#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200206 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000207#endif
208 pid_t backgndpid; /* pid of last background process */
209 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000210};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000211extern struct globals_misc *const ash_ptr_to_globals_misc;
212#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000213#define rootpid (G_misc.rootpid )
214#define shlvl (G_misc.shlvl )
215#define minusc (G_misc.minusc )
216#define curdir (G_misc.curdir )
217#define physdir (G_misc.physdir )
218#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000219#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000220#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200221#define suppress_int (G_misc.suppress_int )
222#define pending_int (G_misc.pending_int )
223#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000224#define isloginsh (G_misc.isloginsh )
225#define nullstr (G_misc.nullstr )
226#define optlist (G_misc.optlist )
227#define sigmode (G_misc.sigmode )
228#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200229#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000230#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200231#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200232#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000233#define backgndpid (G_misc.backgndpid )
234#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000235#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000236 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
237 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000238 curdir = nullstr; \
239 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200240 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000241} while (0)
242
243
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000244/* ============ DEBUG */
245#if DEBUG
246static void trace_printf(const char *fmt, ...);
247static void trace_vprintf(const char *fmt, va_list va);
248# define TRACE(param) trace_printf param
249# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000250# define close(fd) do { \
251 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000252 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200253 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000254 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000255} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000256#else
257# define TRACE(param)
258# define TRACEV(param)
259#endif
260
261
Denis Vlasenko559691a2008-10-05 18:39:31 +0000262/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000263#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
264
Denis Vlasenko559691a2008-10-05 18:39:31 +0000265static int isdigit_str9(const char *str)
266{
267 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
268 while (--maxlen && isdigit(*str))
269 str++;
270 return (*str == '\0');
271}
Denis Vlasenko01631112007-12-16 17:20:38 +0000272
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200273static const char *var_end(const char *var)
274{
275 while (*var)
276 if (*var++ == '=')
277 break;
278 return var;
279}
280
Denis Vlasenko559691a2008-10-05 18:39:31 +0000281
282/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000283/*
Eric Andersen2870d962001-07-02 17:27:21 +0000284 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000285 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000286 * much more efficient and portable. (But hacking the kernel is so much
287 * more fun than worrying about efficiency and portability. :-))
288 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000289#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200290 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000291 xbarrier(); \
292} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000293
294/*
295 * Called to raise an exception. Since C doesn't include exceptions, we
296 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000297 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000299static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300static void
301raise_exception(int e)
302{
303#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000304 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000305 abort();
306#endif
307 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000308 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000309 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000310}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000311#if DEBUG
312#define raise_exception(e) do { \
313 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
314 raise_exception(e); \
315} while (0)
316#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317
318/*
319 * Called from trap.c when a SIGINT is received. (If the user specifies
320 * that SIGINT is to be trapped or ignored using the trap builtin, then
321 * this routine is not called.) Suppressint is nonzero when interrupts
322 * are held using the INT_OFF macro. (The test for iflag is just
323 * defensive programming.)
324 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000325static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000326static void
327raise_interrupt(void)
328{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000329 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000330
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200331 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000332 /* Signal is not automatically unmasked after it is raised,
333 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000334 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200335 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000336
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
339 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000340 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000341 signal(SIGINT, SIG_DFL);
342 raise(SIGINT);
343 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000344 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000346 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000347 /* NOTREACHED */
348}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000349#if DEBUG
350#define raise_interrupt() do { \
351 TRACE(("raising interrupt on line %d\n", __LINE__)); \
352 raise_interrupt(); \
353} while (0)
354#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000356static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000357int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000358{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000359 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200360 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361 raise_interrupt();
362 }
363}
364#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000365static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000366force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000367{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000368 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200369 suppress_int = 0;
370 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000371 raise_interrupt();
372}
373#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000374
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200375#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000377#define RESTORE_INT(v) do { \
378 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200379 suppress_int = (v); \
380 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000381 raise_interrupt(); \
382} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000383
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000384
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000385/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000386
Eric Andersenc470f442003-07-28 09:56:35 +0000387static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000388outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000389{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390 INT_OFF;
391 fputs(p, file);
392 INT_ON;
393}
394
395static void
396flush_stdout_stderr(void)
397{
398 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100399 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000400 INT_ON;
401}
402
403static void
404outcslow(int c, FILE *dest)
405{
406 INT_OFF;
407 putc(c, dest);
408 fflush(dest);
409 INT_ON;
410}
411
412static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
413static int
414out1fmt(const char *fmt, ...)
415{
416 va_list ap;
417 int r;
418
419 INT_OFF;
420 va_start(ap, fmt);
421 r = vprintf(fmt, ap);
422 va_end(ap);
423 INT_ON;
424 return r;
425}
426
427static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
428static int
429fmtstr(char *outbuf, size_t length, const char *fmt, ...)
430{
431 va_list ap;
432 int ret;
433
434 va_start(ap, fmt);
435 INT_OFF;
436 ret = vsnprintf(outbuf, length, fmt, ap);
437 va_end(ap);
438 INT_ON;
439 return ret;
440}
441
442static void
443out1str(const char *p)
444{
445 outstr(p, stdout);
446}
447
448static void
449out2str(const char *p)
450{
451 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100452 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000453}
454
455
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000456/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000457
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000458/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100459#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200460#define CTLESC ((unsigned char)'\201') /* escape next character */
461#define CTLVAR ((unsigned char)'\202') /* variable defn */
462#define CTLENDVAR ((unsigned char)'\203')
463#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000464#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
465/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200466#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
467#define CTLENDARI ((unsigned char)'\207')
468#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100469#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000470
471/* variable substitution byte (follows CTLVAR) */
472#define VSTYPE 0x0f /* type of variable substitution */
473#define VSNUL 0x10 /* colon--treat the empty string as unset */
474#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475
476/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000477#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478#define VSMINUS 0x2 /* ${var-text} */
479#define VSPLUS 0x3 /* ${var+text} */
480#define VSQUESTION 0x4 /* ${var?message} */
481#define VSASSIGN 0x5 /* ${var=text} */
482#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484#define VSTRIMLEFT 0x8 /* ${var#pattern} */
485#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486#define VSLENGTH 0xa /* ${#var} */
487#if ENABLE_ASH_BASH_COMPAT
488#define VSSUBSTR 0xc /* ${var:position:length} */
489#define VSREPLACE 0xd /* ${var/pattern/replacement} */
490#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000492
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000493static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
495};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000496
Denis Vlasenko559691a2008-10-05 18:39:31 +0000497#define NCMD 0
498#define NPIPE 1
499#define NREDIR 2
500#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000501#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000502#define NAND 5
503#define NOR 6
504#define NSEMI 7
505#define NIF 8
506#define NWHILE 9
507#define NUNTIL 10
508#define NFOR 11
509#define NCASE 12
510#define NCLIST 13
511#define NDEFUN 14
512#define NARG 15
513#define NTO 16
514#if ENABLE_ASH_BASH_COMPAT
515#define NTO2 17
516#endif
517#define NCLOBBER 18
518#define NFROM 19
519#define NFROMTO 20
520#define NAPPEND 21
521#define NTOFD 22
522#define NFROMFD 23
523#define NHERE 24
524#define NXHERE 25
525#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000526#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000527
528union node;
529
530struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000531 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000532 union node *assign;
533 union node *args;
534 union node *redirect;
535};
536
537struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000538 smallint type;
539 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 struct nodelist *cmdlist;
541};
542
543struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000544 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000545 union node *n;
546 union node *redirect;
547};
548
549struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000550 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000551 union node *ch1;
552 union node *ch2;
553};
554
555struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000556 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000557 union node *test;
558 union node *ifpart;
559 union node *elsepart;
560};
561
562struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000563 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000564 union node *args;
565 union node *body;
566 char *var;
567};
568
569struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000570 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000571 union node *expr;
572 union node *cases;
573};
574
575struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000576 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000577 union node *next;
578 union node *pattern;
579 union node *body;
580};
581
582struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000583 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584 union node *next;
585 char *text;
586 struct nodelist *backquote;
587};
588
Denis Vlasenko559691a2008-10-05 18:39:31 +0000589/* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
592 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000594 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000595 union node *next;
596 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *fname;
599 char *expfname;
600};
601
602struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000603 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000604 union node *next;
605 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 int dupfd;
607 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000608 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609};
610
611struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000612 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000613 union node *next;
614 int fd;
615 union node *doc;
616};
617
618struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 union node *com;
621};
622
623union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000624 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000625 struct ncmd ncmd;
626 struct npipe npipe;
627 struct nredir nredir;
628 struct nbinary nbinary;
629 struct nif nif;
630 struct nfor nfor;
631 struct ncase ncase;
632 struct nclist nclist;
633 struct narg narg;
634 struct nfile nfile;
635 struct ndup ndup;
636 struct nhere nhere;
637 struct nnot nnot;
638};
639
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200640/*
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
643 */
644#define NODE_EOF ((union node *) -1L)
645
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000646struct nodelist {
647 struct nodelist *next;
648 union node *n;
649};
650
651struct funcnode {
652 int count;
653 union node n;
654};
655
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000656/*
657 * Free a parse tree.
658 */
659static void
660freefunc(struct funcnode *f)
661{
662 if (f && --f->count < 0)
663 free(f);
664}
665
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000666
667/* ============ Debugging output */
668
669#if DEBUG
670
671static FILE *tracefile;
672
673static void
674trace_printf(const char *fmt, ...)
675{
676 va_list va;
677
678 if (debug != 1)
679 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000680 if (DEBUG_TIME)
681 fprintf(tracefile, "%u ", (int) time(NULL));
682 if (DEBUG_PID)
683 fprintf(tracefile, "[%u] ", (int) getpid());
684 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000686 va_start(va, fmt);
687 vfprintf(tracefile, fmt, va);
688 va_end(va);
689}
690
691static void
692trace_vprintf(const char *fmt, va_list va)
693{
694 if (debug != 1)
695 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000696 if (DEBUG_TIME)
697 fprintf(tracefile, "%u ", (int) time(NULL));
698 if (DEBUG_PID)
699 fprintf(tracefile, "[%u] ", (int) getpid());
700 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000702 vfprintf(tracefile, fmt, va);
703}
704
705static void
706trace_puts(const char *s)
707{
708 if (debug != 1)
709 return;
710 fputs(s, tracefile);
711}
712
713static void
714trace_puts_quoted(char *s)
715{
716 char *p;
717 char c;
718
719 if (debug != 1)
720 return;
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100723 switch ((unsigned char)*p) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '\"': c = '\"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000734 backslash:
735 putc('\\', tracefile);
736 putc(c, tracefile);
737 break;
738 default:
739 if (*p >= ' ' && *p <= '~')
740 putc(*p, tracefile);
741 else {
742 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100743 putc((*p >> 6) & 03, tracefile);
744 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000745 putc(*p & 07, tracefile);
746 }
747 break;
748 }
749 }
750 putc('"', tracefile);
751}
752
753static void
754trace_puts_args(char **ap)
755{
756 if (debug != 1)
757 return;
758 if (!*ap)
759 return;
760 while (1) {
761 trace_puts_quoted(*ap);
762 if (!*++ap) {
763 putc('\n', tracefile);
764 break;
765 }
766 putc(' ', tracefile);
767 }
768}
769
770static void
771opentrace(void)
772{
773 char s[100];
774#ifdef O_APPEND
775 int flags;
776#endif
777
778 if (debug != 1) {
779 if (tracefile)
780 fflush(tracefile);
781 /* leave open because libedit might be using it */
782 return;
783 }
784 strcpy(s, "./trace");
785 if (tracefile) {
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
788 debug = 0;
789 return;
790 }
791 } else {
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
795 debug = 0;
796 return;
797 }
798 }
799#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000800 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000801 if (flags >= 0)
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
803#endif
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
806}
807
808static void
809indent(int amount, char *pfx, FILE *fp)
810{
811 int i;
812
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
815 fputs(pfx, fp);
816 putc('\t', fp);
817 }
818}
819
820/* little circular references here... */
821static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822
823static void
824sharg(union node *arg, FILE *fp)
825{
826 char *p;
827 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100828 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000829
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
832 abort();
833 }
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100836 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837 case CTLESC:
838 putc(*++p, fp);
839 break;
840 case CTLVAR:
841 putc('$', fp);
842 putc('{', fp);
843 subtype = *++p;
844 if (subtype == VSLENGTH)
845 putc('#', fp);
846
847 while (*p != '=')
848 putc(*p++, fp);
849
850 if (subtype & VSNUL)
851 putc(':', fp);
852
853 switch (subtype & VSTYPE) {
854 case VSNORMAL:
855 putc('}', fp);
856 break;
857 case VSMINUS:
858 putc('-', fp);
859 break;
860 case VSPLUS:
861 putc('+', fp);
862 break;
863 case VSQUESTION:
864 putc('?', fp);
865 break;
866 case VSASSIGN:
867 putc('=', fp);
868 break;
869 case VSTRIMLEFT:
870 putc('#', fp);
871 break;
872 case VSTRIMLEFTMAX:
873 putc('#', fp);
874 putc('#', fp);
875 break;
876 case VSTRIMRIGHT:
877 putc('%', fp);
878 break;
879 case VSTRIMRIGHTMAX:
880 putc('%', fp);
881 putc('%', fp);
882 break;
883 case VSLENGTH:
884 break;
885 default:
886 out1fmt("<subtype %d>", subtype);
887 }
888 break;
889 case CTLENDVAR:
890 putc('}', fp);
891 break;
892 case CTLBACKQ:
893 case CTLBACKQ|CTLQUOTE:
894 putc('$', fp);
895 putc('(', fp);
896 shtree(bqlist->n, -1, NULL, fp);
897 putc(')', fp);
898 break;
899 default:
900 putc(*p, fp);
901 break;
902 }
903 }
904}
905
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200906static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000907shcmd(union node *cmd, FILE *fp)
908{
909 union node *np;
910 int first;
911 const char *s;
912 int dftfd;
913
914 first = 1;
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000916 if (!first)
917 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000918 sharg(np, fp);
919 first = 0;
920 }
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000922 if (!first)
923 putc(' ', fp);
924 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000925 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000929#if ENABLE_ASH_BASH_COMPAT
930 case NTO2:
931#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000933 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000937 }
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
940 fputs(s, fp);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
943 } else {
944 sharg(np->nfile.fname, fp);
945 }
946 first = 0;
947 }
948}
949
950static void
951shtree(union node *n, int ind, char *pfx, FILE *fp)
952{
953 struct nodelist *lp;
954 const char *s;
955
956 if (n == NULL)
957 return;
958
959 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200960
961 if (n == NODE_EOF) {
962 fputs("<EOF>", fp);
963 return;
964 }
965
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000966 switch (n->type) {
967 case NSEMI:
968 s = "; ";
969 goto binop;
970 case NAND:
971 s = " && ";
972 goto binop;
973 case NOR:
974 s = " || ";
975 binop:
976 shtree(n->nbinary.ch1, ind, NULL, fp);
977 /* if (ind < 0) */
978 fputs(s, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
980 break;
981 case NCMD:
982 shcmd(n, fp);
983 if (ind >= 0)
984 putc('\n', fp);
985 break;
986 case NPIPE:
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200988 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989 if (lp->next)
990 fputs(" | ", fp);
991 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000992 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000993 fputs(" &", fp);
994 if (ind >= 0)
995 putc('\n', fp);
996 break;
997 default:
998 fprintf(fp, "<node type %d>", n->type);
999 if (ind >= 0)
1000 putc('\n', fp);
1001 break;
1002 }
1003}
1004
1005static void
1006showtree(union node *n)
1007{
1008 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001009 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010}
1011
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001012#endif /* DEBUG */
1013
1014
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001015/* ============ Parser data */
1016
1017/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001020struct strlist {
1021 struct strlist *next;
1022 char *text;
1023};
1024
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001025struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001026
Denis Vlasenkob012b102007-02-19 22:43:01 +00001027struct strpush {
1028 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001029 char *prev_string;
1030 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001031#if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1033#endif
1034 char *string; /* remember the string since it may change */
1035};
1036
1037struct parsefile {
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001040 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1047};
1048
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001049static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001050static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051static int startlinno; /* line # where last token started */
1052static char *commandname; /* currently executing command */
1053static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001054static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001055
1056
1057/* ============ Message printing */
1058
1059static void
1060ash_vmsg(const char *msg, va_list ap)
1061{
1062 fprintf(stderr, "%s: ", arg0);
1063 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001066 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001068 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001071}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072
1073/*
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1077 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001078static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001079static void
1080ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001081{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082#if DEBUG
1083 if (msg) {
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1085 TRACEV((msg, ap));
1086 TRACE(("\") pid=%d\n", getpid()));
1087 } else
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1089 if (msg)
1090#endif
1091 ash_vmsg(msg, ap);
1092
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1095 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001096}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001098static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001099static void
1100ash_msg_and_raise_error(const char *msg, ...)
1101{
1102 va_list ap;
1103
1104 va_start(ap, msg);
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1106 /* NOTREACHED */
1107 va_end(ap);
1108}
1109
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001110static void raise_error_syntax(const char *) NORETURN;
1111static void
1112raise_error_syntax(const char *msg)
1113{
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1115 /* NOTREACHED */
1116}
1117
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001118static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001119static void
1120ash_msg_and_raise(int cond, const char *msg, ...)
1121{
1122 va_list ap;
1123
1124 va_start(ap, msg);
1125 ash_vmsg_and_raise(cond, msg, ap);
1126 /* NOTREACHED */
1127 va_end(ap);
1128}
1129
1130/*
1131 * error/warning routines for external builtins
1132 */
1133static void
1134ash_msg(const char *fmt, ...)
1135{
1136 va_list ap;
1137
1138 va_start(ap, fmt);
1139 ash_vmsg(fmt, ap);
1140 va_end(ap);
1141}
1142
1143/*
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1147 */
1148static const char *
1149errmsg(int e, const char *em)
1150{
1151 if (e == ENOENT || e == ENOTDIR) {
1152 return em;
1153 }
1154 return strerror(e);
1155}
1156
1157
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001158/* ============ Memory allocation */
1159
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001160#if 0
1161/* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1165 */
1166static void *
1167ckrealloc(void * p, size_t nbytes)
1168{
1169 p = realloc(p, nbytes);
1170 if (!p)
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1172 return p;
1173}
1174
1175static void *
1176ckmalloc(size_t nbytes)
1177{
1178 return ckrealloc(NULL, nbytes);
1179}
1180
1181static void *
1182ckzalloc(size_t nbytes)
1183{
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1185}
1186
1187static char *
1188ckstrdup(const char *s)
1189{
1190 char *p = strdup(s);
1191 if (!p)
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1193 return p;
1194}
1195#else
1196/* Using bbox equivalents. They exit if out of memory */
1197# define ckrealloc xrealloc
1198# define ckmalloc xmalloc
1199# define ckzalloc xzalloc
1200# define ckstrdup xstrdup
1201#endif
1202
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001203/*
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1206 */
1207#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1208enum {
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001214 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001215};
1216
1217struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1220};
1221
1222struct stackmark {
1223 struct stack_block *stackp;
1224 char *stacknxt;
1225 size_t stacknleft;
1226 struct stackmark *marknext;
1227};
1228
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001229
Denis Vlasenko01631112007-12-16 17:20:38 +00001230struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1238};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001239extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001241#define g_stackp (G_memstack.g_stackp )
1242#define markp (G_memstack.markp )
1243#define g_stacknxt (G_memstack.g_stacknxt )
1244#define sstrend (G_memstack.sstrend )
1245#define g_stacknleft (G_memstack.g_stacknleft)
1246#define herefd (G_memstack.herefd )
1247#define stackbase (G_memstack.stackbase )
1248#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1250 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1255 herefd = -1; \
1256} while (0)
1257
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001258
Denis Vlasenko01631112007-12-16 17:20:38 +00001259#define stackblock() ((void *)g_stacknxt)
1260#define stackblocksize() g_stacknleft
1261
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001262/*
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1266 *
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1268 * well.
1269 */
1270static void *
1271stalloc(size_t nbytes)
1272{
1273 char *p;
1274 size_t aligned;
1275
1276 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001277 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001278 size_t len;
1279 size_t blocksize;
1280 struct stack_block *sp;
1281
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1288 INT_OFF;
1289 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1294 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001295 INT_ON;
1296 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001297 p = g_stacknxt;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300 return p;
1301}
1302
Denis Vlasenko597906c2008-02-20 16:38:54 +00001303static void *
1304stzalloc(size_t nbytes)
1305{
1306 return memset(stalloc(nbytes), 0, nbytes);
1307}
1308
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001309static void
1310stunalloc(void *p)
1311{
1312#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001314 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001315 abort();
1316 }
1317#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001318 g_stacknleft += g_stacknxt - (char *)p;
1319 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001320}
1321
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001322/*
1323 * Like strdup but works with the ash stack.
1324 */
1325static char *
1326ststrdup(const char *p)
1327{
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1330}
1331
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001332static void
1333setstackmark(struct stackmark *mark)
1334{
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338 mark->marknext = markp;
1339 markp = mark;
1340}
1341
1342static void
1343popstackmark(struct stackmark *mark)
1344{
1345 struct stack_block *sp;
1346
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001347 if (!mark->stackp)
1348 return;
1349
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350 INT_OFF;
1351 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001352 while (g_stackp != mark->stackp) {
1353 sp = g_stackp;
1354 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001355 free(sp);
1356 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001359 sstrend = mark->stacknxt + mark->stacknleft;
1360 INT_ON;
1361}
1362
1363/*
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1371 */
1372static void
1373growstackblock(void)
1374{
1375 size_t newlen;
1376
Denis Vlasenko01631112007-12-16 17:20:38 +00001377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1380 if (newlen < 128)
1381 newlen += 128;
1382
Denis Vlasenko01631112007-12-16 17:20:38 +00001383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1388 size_t grosslen;
1389
1390 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 oldstackp = g_stackp;
1392 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001397 g_stackp = sp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 sstrend = sp->space + newlen;
1401
1402 /*
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1405 */
1406 xmark = markp;
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001411 xmark = xmark->marknext;
1412 }
1413 INT_ON;
1414 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001416 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001417 char *p = stalloc(newlen);
1418
1419 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001422 }
1423}
1424
1425static void
1426grabstackblock(size_t len)
1427{
1428 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001429 g_stacknxt += len;
1430 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001431}
1432
1433/*
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1445 *
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1449 */
1450static void *
1451growstackstr(void)
1452{
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1457 }
1458 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001459 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001460}
1461
1462/*
1463 * Called from CHECKSTRSPACE.
1464 */
1465static char *
1466makestrspace(size_t newlen, char *p)
1467{
Denis Vlasenko01631112007-12-16 17:20:38 +00001468 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001469 size_t size = stackblocksize();
1470
1471 for (;;) {
1472 size_t nleft;
1473
1474 size = stackblocksize();
1475 nleft = size - len;
1476 if (nleft >= newlen)
1477 break;
1478 growstackblock();
1479 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001480 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001481}
1482
1483static char *
1484stack_nputstr(const char *s, size_t n, char *p)
1485{
1486 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001487 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001488 return p;
1489}
1490
1491static char *
1492stack_putstr(const char *s, char *p)
1493{
1494 return stack_nputstr(s, strlen(s), p);
1495}
1496
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001497static char *
1498_STPUTC(int c, char *p)
1499{
1500 if (p == sstrend)
1501 p = growstackstr();
1502 *p++ = c;
1503 return p;
1504}
1505
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001506#define STARTSTACKSTR(p) ((p) = stackblock())
1507#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001508#define CHECKSTRSPACE(n, p) do { \
1509 char *q = (p); \
1510 size_t l = (n); \
1511 size_t m = sstrend - q; \
1512 if (l > m) \
1513 (p) = makestrspace(l, q); \
1514} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001515#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1519 *(p) = '\0'; \
1520} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001521#define STUNPUTC(p) (--(p))
1522#define STTOPC(p) ((p)[-1])
1523#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001524
1525#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001526#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001527#define stackstrend() ((void *)sstrend)
1528
1529
1530/* ============ String helpers */
1531
1532/*
1533 * prefix -- see if pfx is a prefix of string.
1534 */
1535static char *
1536prefix(const char *string, const char *pfx)
1537{
1538 while (*pfx) {
1539 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001540 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001541 }
1542 return (char *) string;
1543}
1544
1545/*
1546 * Check for a valid number. This should be elsewhere.
1547 */
1548static int
1549is_number(const char *p)
1550{
1551 do {
1552 if (!isdigit(*p))
1553 return 0;
1554 } while (*++p != '\0');
1555 return 1;
1556}
1557
1558/*
1559 * Convert a string of digits to an integer, printing an error message on
1560 * failure.
1561 */
1562static int
1563number(const char *s)
1564{
1565 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001566 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001567 return atoi(s);
1568}
1569
1570/*
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1573 */
1574static char *
1575single_quote(const char *s)
1576{
1577 char *p;
1578
1579 STARTSTACKSTR(p);
1580
1581 do {
1582 char *q;
1583 size_t len;
1584
1585 len = strchrnul(s, '\'') - s;
1586
1587 q = p = makestrspace(len + 3, p);
1588
1589 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001590 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001591 *q++ = '\'';
1592 s += len;
1593
1594 STADJUST(q - p, p);
1595
Denys Vlasenkocd716832009-11-28 22:14:02 +01001596 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001597 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001598 len = 0;
1599 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001600
1601 q = p = makestrspace(len + 3, p);
1602
1603 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001604 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001606
1607 STADJUST(q - p, p);
1608 } while (*s);
1609
Denys Vlasenkocd716832009-11-28 22:14:02 +01001610 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001611
1612 return stackblock();
1613}
1614
1615
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001616/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001617
1618static char **argptr; /* argument list for builtin commands */
1619static char *optionarg; /* set by nextopt (like getopt) */
1620static char *optptr; /* used by nextopt */
1621
1622/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001626 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001631 */
1632static int
1633nextopt(const char *optstring)
1634{
1635 char *p;
1636 const char *q;
1637 char c;
1638
1639 p = optptr;
1640 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 if (p == NULL)
1644 return '\0';
1645 if (*p != '-')
1646 return '\0';
1647 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 return '\0';
1649 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001656 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001658 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 if (*++q == ':')
1660 q++;
1661 }
1662 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001663 if (*p == '\0') {
1664 p = *argptr++;
1665 if (p == NULL)
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1667 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001668 optionarg = p;
1669 p = NULL;
1670 }
1671 optptr = p;
1672 return c;
1673}
1674
1675
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001676/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001677
Denis Vlasenko01631112007-12-16 17:20:38 +00001678/*
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1681 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001682struct shparam {
1683 int nparam; /* # of positional parameters (without $0) */
1684#if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1687#endif
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1690};
1691
1692/*
1693 * Free the list of positional parameters.
1694 */
1695static void
1696freeparam(volatile struct shparam *param)
1697{
Denis Vlasenko01631112007-12-16 17:20:38 +00001698 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001699 char **ap, **ap1;
1700 ap = ap1 = param->p;
1701 while (*ap)
1702 free(*ap++);
1703 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001704 }
1705}
1706
1707#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001708static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001709#endif
1710
1711struct var {
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001714 const char *var_text; /* name=value */
1715 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001716 /* the variable gets set/unset */
1717};
1718
1719struct localvar {
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1724};
1725
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726/* flags */
1727#define VEXPORT 0x01 /* variable is exported */
1728#define VREADONLY 0x02 /* variable cannot be modified */
1729#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730#define VTEXTFIXED 0x08 /* text is statically allocated */
1731#define VSTACK 0x10 /* text is allocated on the stack */
1732#define VUNSET 0x20 /* the variable is not set */
1733#define VNOFUNC 0x40 /* don't call the callback function */
1734#define VNOSET 0x80 /* do not set variable - just readonly test */
1735#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001736#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001737# define VDYNAMIC 0x200 /* dynamic variable */
1738#else
1739# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#endif
1741
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001742
Denis Vlasenko01631112007-12-16 17:20:38 +00001743/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001744#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001745static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001746change_lc_all(const char *value)
1747{
1748 if (value && *value != '\0')
1749 setlocale(LC_ALL, value);
1750}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001751static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001752change_lc_ctype(const char *value)
1753{
1754 if (value && *value != '\0')
1755 setlocale(LC_CTYPE, value);
1756}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001757#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001758#if ENABLE_ASH_MAIL
1759static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001760static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001764static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#endif
1766
Denis Vlasenko01631112007-12-16 17:20:38 +00001767static const struct {
1768 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001769 const char *var_text;
1770 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001771} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1778 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001782 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#endif
1784#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001785 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#endif
1791#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001792 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794};
1795
Denis Vlasenko0b769642008-07-24 07:54:57 +00001796struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001797
1798struct globals_var {
1799 struct shparam shellparam; /* $@ current positional parameters */
1800 struct redirtab *redirlist;
1801 int g_nullredirs;
1802 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1803 struct var *vartab[VTABSIZE];
1804 struct var varinit[ARRAY_SIZE(varinit_data)];
1805};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001806extern struct globals_var *const ash_ptr_to_globals_var;
1807#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001808#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001809//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001810#define g_nullredirs (G_var.g_nullredirs )
1811#define preverrout_fd (G_var.preverrout_fd)
1812#define vartab (G_var.vartab )
1813#define varinit (G_var.varinit )
1814#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001815 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001816 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001818 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001819 varinit[i].flags = varinit_data[i].flags; \
1820 varinit[i].var_text = varinit_data[i].var_text; \
1821 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001822 } \
1823} while (0)
1824
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001825#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001826#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827# define vmail (&vifs)[1]
1828# define vmpath (&vmail)[1]
1829# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001830#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001831# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833#define vps1 (&vpath)[1]
1834#define vps2 (&vps1)[1]
1835#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001836#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001837# define voptind (&vps4)[1]
1838# if ENABLE_ASH_RANDOM_SUPPORT
1839# define vrandom (&voptind)[1]
1840# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842# if ENABLE_ASH_RANDOM_SUPPORT
1843# define vrandom (&vps4)[1]
1844# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846
1847/*
1848 * The following macros access the values of the above variables.
1849 * They have to skip over the name. They return the null string
1850 * for unset variables.
1851 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001852#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001853#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001854#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001855# define mailval() (vmail.var_text + 5)
1856# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001857# define mpathset() ((vmpath.flags & VUNSET) == 0)
1858#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001859#define pathval() (vpath.var_text + 5)
1860#define ps1val() (vps1.var_text + 4)
1861#define ps2val() (vps2.var_text + 4)
1862#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001863#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001864# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001866
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1869#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870
Denis Vlasenko01631112007-12-16 17:20:38 +00001871#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001872static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001873getoptsreset(const char *value)
1874{
1875 shellparam.optind = number(value);
1876 shellparam.optoff = -1;
1877}
1878#endif
1879
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001880/*
1881 * Return of a legal variable name (a letter or underscore followed by zero or
1882 * more letters, underscores, and digits).
1883 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001884static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001885endofname(const char *name)
1886{
1887 char *p;
1888
1889 p = (char *) name;
1890 if (!is_name(*p))
1891 return p;
1892 while (*++p) {
1893 if (!is_in_name(*p))
1894 break;
1895 }
1896 return p;
1897}
1898
1899/*
1900 * Compares two strings up to the first = or '\0'. The first
1901 * string must be terminated by '='; the second may be terminated by
1902 * either '=' or '\0'.
1903 */
1904static int
1905varcmp(const char *p, const char *q)
1906{
1907 int c, d;
1908
1909 while ((c = *p) == (d = *q)) {
1910 if (!c || c == '=')
1911 goto out;
1912 p++;
1913 q++;
1914 }
1915 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001916 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001917 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001918 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001919 out:
1920 return c - d;
1921}
1922
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001923/*
1924 * Find the appropriate entry in the hash table from the name.
1925 */
1926static struct var **
1927hashvar(const char *p)
1928{
1929 unsigned hashval;
1930
1931 hashval = ((unsigned char) *p) << 4;
1932 while (*p && *p != '=')
1933 hashval += (unsigned char) *p++;
1934 return &vartab[hashval % VTABSIZE];
1935}
1936
1937static int
1938vpcmp(const void *a, const void *b)
1939{
1940 return varcmp(*(const char **)a, *(const char **)b);
1941}
1942
1943/*
1944 * This routine initializes the builtin variables.
1945 */
1946static void
1947initvar(void)
1948{
1949 struct var *vp;
1950 struct var *end;
1951 struct var **vpp;
1952
1953 /*
1954 * PS1 depends on uid
1955 */
1956#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001957 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001958#else
1959 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001960 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001961#endif
1962 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001963 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001964 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001965 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966 vp->next = *vpp;
1967 *vpp = vp;
1968 } while (++vp < end);
1969}
1970
1971static struct var **
1972findvar(struct var **vpp, const char *name)
1973{
1974 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001975 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001976 break;
1977 }
1978 }
1979 return vpp;
1980}
1981
1982/*
1983 * Find the value of a variable. Returns NULL if not set.
1984 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001985static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001986lookupvar(const char *name)
1987{
1988 struct var *v;
1989
1990 v = *findvar(hashvar(name), name);
1991 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001992#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001993 /*
1994 * Dynamic variables are implemented roughly the same way they are
1995 * in bash. Namely, they're "special" so long as they aren't unset.
1996 * As soon as they're unset, they're no longer dynamic, and dynamic
1997 * lookup will no longer happen at that point. -- PFM.
1998 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001999 if (v->flags & VDYNAMIC)
2000 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001#endif
2002 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002003 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002004 }
2005 return NULL;
2006}
2007
2008/*
2009 * Search the environment of a builtin command.
2010 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002011static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002012bltinlookup(const char *name)
2013{
2014 struct strlist *sp;
2015
2016 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002017 if (varcmp(sp->text, name) == 0)
2018 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002019 }
2020 return lookupvar(name);
2021}
2022
2023/*
2024 * Same as setvar except that the variable and value are passed in
2025 * the first argument as name=value. Since the first argument will
2026 * be actually stored in the table, it should not be a string that
2027 * will go away.
2028 * Called with interrupts off.
2029 */
2030static void
2031setvareq(char *s, int flags)
2032{
2033 struct var *vp, **vpp;
2034
2035 vpp = hashvar(s);
2036 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2037 vp = *findvar(vpp, s);
2038 if (vp) {
2039 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2040 const char *n;
2041
2042 if (flags & VNOSAVE)
2043 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002044 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002045 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2046 }
2047
2048 if (flags & VNOSET)
2049 return;
2050
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002051 if (vp->var_func && !(flags & VNOFUNC))
2052 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002053
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002054 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2055 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002056
2057 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2058 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002059 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002060 if (flags & VNOSET)
2061 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002062 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002063 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002064 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002065 *vpp = vp;
2066 }
2067 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2068 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002069 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002070 vp->flags = flags;
2071}
2072
2073/*
2074 * Set the value of a variable. The flags argument is ored with the
2075 * flags of the variable. If val is NULL, the variable is unset.
2076 */
2077static void
2078setvar(const char *name, const char *val, int flags)
2079{
2080 char *p, *q;
2081 size_t namelen;
2082 char *nameeq;
2083 size_t vallen;
2084
2085 q = endofname(name);
2086 p = strchrnul(q, '=');
2087 namelen = p - name;
2088 if (!namelen || p != q)
2089 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2090 vallen = 0;
2091 if (val == NULL) {
2092 flags |= VUNSET;
2093 } else {
2094 vallen = strlen(val);
2095 }
2096 INT_OFF;
2097 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002098 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002099 if (val) {
2100 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002101 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002102 }
2103 *p = '\0';
2104 setvareq(nameeq, flags | VNOSAVE);
2105 INT_ON;
2106}
2107
Denys Vlasenko03dad222010-01-12 23:29:57 +01002108static void FAST_FUNC
2109setvar2(const char *name, const char *val)
2110{
2111 setvar(name, val, 0);
2112}
2113
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002114#if ENABLE_ASH_GETOPTS
2115/*
2116 * Safe version of setvar, returns 1 on success 0 on failure.
2117 */
2118static int
2119setvarsafe(const char *name, const char *val, int flags)
2120{
2121 int err;
2122 volatile int saveint;
2123 struct jmploc *volatile savehandler = exception_handler;
2124 struct jmploc jmploc;
2125
2126 SAVE_INT(saveint);
2127 if (setjmp(jmploc.loc))
2128 err = 1;
2129 else {
2130 exception_handler = &jmploc;
2131 setvar(name, val, flags);
2132 err = 0;
2133 }
2134 exception_handler = savehandler;
2135 RESTORE_INT(saveint);
2136 return err;
2137}
2138#endif
2139
2140/*
2141 * Unset the specified variable.
2142 */
2143static int
2144unsetvar(const char *s)
2145{
2146 struct var **vpp;
2147 struct var *vp;
2148 int retval;
2149
2150 vpp = findvar(hashvar(s), s);
2151 vp = *vpp;
2152 retval = 2;
2153 if (vp) {
2154 int flags = vp->flags;
2155
2156 retval = 1;
2157 if (flags & VREADONLY)
2158 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002159#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002160 vp->flags &= ~VDYNAMIC;
2161#endif
2162 if (flags & VUNSET)
2163 goto ok;
2164 if ((flags & VSTRFIXED) == 0) {
2165 INT_OFF;
2166 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002167 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002168 *vpp = vp->next;
2169 free(vp);
2170 INT_ON;
2171 } else {
2172 setvar(s, 0, 0);
2173 vp->flags &= ~VEXPORT;
2174 }
2175 ok:
2176 retval = 0;
2177 }
2178 out:
2179 return retval;
2180}
2181
2182/*
2183 * Process a linked list of variable assignments.
2184 */
2185static void
2186listsetvar(struct strlist *list_set_var, int flags)
2187{
2188 struct strlist *lp = list_set_var;
2189
2190 if (!lp)
2191 return;
2192 INT_OFF;
2193 do {
2194 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002195 lp = lp->next;
2196 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002197 INT_ON;
2198}
2199
2200/*
2201 * Generate a list of variables satisfying the given conditions.
2202 */
2203static char **
2204listvars(int on, int off, char ***end)
2205{
2206 struct var **vpp;
2207 struct var *vp;
2208 char **ep;
2209 int mask;
2210
2211 STARTSTACKSTR(ep);
2212 vpp = vartab;
2213 mask = on | off;
2214 do {
2215 for (vp = *vpp; vp; vp = vp->next) {
2216 if ((vp->flags & mask) == on) {
2217 if (ep == stackstrend())
2218 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002219 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002220 }
2221 }
2222 } while (++vpp < vartab + VTABSIZE);
2223 if (ep == stackstrend())
2224 ep = growstackstr();
2225 if (end)
2226 *end = ep;
2227 *ep++ = NULL;
2228 return grabstackstr(ep);
2229}
2230
2231
2232/* ============ Path search helper
2233 *
2234 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002235 * of the path before the first call; path_advance will update
2236 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002237 * the possible path expansions in sequence. If an option (indicated by
2238 * a percent sign) appears in the path entry then the global variable
2239 * pathopt will be set to point to it; otherwise pathopt will be set to
2240 * NULL.
2241 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002242static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002243
2244static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002245path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246{
2247 const char *p;
2248 char *q;
2249 const char *start;
2250 size_t len;
2251
2252 if (*path == NULL)
2253 return NULL;
2254 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002255 for (p = start; *p && *p != ':' && *p != '%'; p++)
2256 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002257 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2258 while (stackblocksize() < len)
2259 growstackblock();
2260 q = stackblock();
2261 if (p != start) {
2262 memcpy(q, start, p - start);
2263 q += p - start;
2264 *q++ = '/';
2265 }
2266 strcpy(q, name);
2267 pathopt = NULL;
2268 if (*p == '%') {
2269 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002270 while (*p && *p != ':')
2271 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002272 }
2273 if (*p == ':')
2274 *path = p + 1;
2275 else
2276 *path = NULL;
2277 return stalloc(len);
2278}
2279
2280
2281/* ============ Prompt */
2282
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002283static smallint doprompt; /* if set, prompt the user */
2284static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002285
2286#if ENABLE_FEATURE_EDITING
2287static line_input_t *line_input_state;
2288static const char *cmdedit_prompt;
2289static void
2290putprompt(const char *s)
2291{
2292 if (ENABLE_ASH_EXPAND_PRMT) {
2293 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002294 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002295 return;
2296 }
2297 cmdedit_prompt = s;
2298}
2299#else
2300static void
2301putprompt(const char *s)
2302{
2303 out2str(s);
2304}
2305#endif
2306
2307#if ENABLE_ASH_EXPAND_PRMT
2308/* expandstr() needs parsing machinery, so it is far away ahead... */
2309static const char *expandstr(const char *ps);
2310#else
2311#define expandstr(s) s
2312#endif
2313
2314static void
2315setprompt(int whichprompt)
2316{
2317 const char *prompt;
2318#if ENABLE_ASH_EXPAND_PRMT
2319 struct stackmark smark;
2320#endif
2321
2322 needprompt = 0;
2323
2324 switch (whichprompt) {
2325 case 1:
2326 prompt = ps1val();
2327 break;
2328 case 2:
2329 prompt = ps2val();
2330 break;
2331 default: /* 0 */
2332 prompt = nullstr;
2333 }
2334#if ENABLE_ASH_EXPAND_PRMT
2335 setstackmark(&smark);
2336 stalloc(stackblocksize());
2337#endif
2338 putprompt(expandstr(prompt));
2339#if ENABLE_ASH_EXPAND_PRMT
2340 popstackmark(&smark);
2341#endif
2342}
2343
2344
2345/* ============ The cd and pwd commands */
2346
2347#define CD_PHYSICAL 1
2348#define CD_PRINT 2
2349
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002350static int
2351cdopt(void)
2352{
2353 int flags = 0;
2354 int i, j;
2355
2356 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002357 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002358 if (i != j) {
2359 flags ^= CD_PHYSICAL;
2360 j = i;
2361 }
2362 }
2363
2364 return flags;
2365}
2366
2367/*
2368 * Update curdir (the name of the current directory) in response to a
2369 * cd command.
2370 */
2371static const char *
2372updatepwd(const char *dir)
2373{
2374 char *new;
2375 char *p;
2376 char *cdcomppath;
2377 const char *lim;
2378
2379 cdcomppath = ststrdup(dir);
2380 STARTSTACKSTR(new);
2381 if (*dir != '/') {
2382 if (curdir == nullstr)
2383 return 0;
2384 new = stack_putstr(curdir, new);
2385 }
2386 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002387 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002388 if (*dir != '/') {
2389 if (new[-1] != '/')
2390 USTPUTC('/', new);
2391 if (new > lim && *lim == '/')
2392 lim++;
2393 } else {
2394 USTPUTC('/', new);
2395 cdcomppath++;
2396 if (dir[1] == '/' && dir[2] != '/') {
2397 USTPUTC('/', new);
2398 cdcomppath++;
2399 lim++;
2400 }
2401 }
2402 p = strtok(cdcomppath, "/");
2403 while (p) {
2404 switch (*p) {
2405 case '.':
2406 if (p[1] == '.' && p[2] == '\0') {
2407 while (new > lim) {
2408 STUNPUTC(new);
2409 if (new[-1] == '/')
2410 break;
2411 }
2412 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002413 }
2414 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002415 break;
2416 /* fall through */
2417 default:
2418 new = stack_putstr(p, new);
2419 USTPUTC('/', new);
2420 }
2421 p = strtok(0, "/");
2422 }
2423 if (new > lim)
2424 STUNPUTC(new);
2425 *new = 0;
2426 return stackblock();
2427}
2428
2429/*
2430 * Find out what the current directory is. If we already know the current
2431 * directory, this routine returns immediately.
2432 */
2433static char *
2434getpwd(void)
2435{
Denis Vlasenko01631112007-12-16 17:20:38 +00002436 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002437 return dir ? dir : nullstr;
2438}
2439
2440static void
2441setpwd(const char *val, int setold)
2442{
2443 char *oldcur, *dir;
2444
2445 oldcur = dir = curdir;
2446
2447 if (setold) {
2448 setvar("OLDPWD", oldcur, VEXPORT);
2449 }
2450 INT_OFF;
2451 if (physdir != nullstr) {
2452 if (physdir != oldcur)
2453 free(physdir);
2454 physdir = nullstr;
2455 }
2456 if (oldcur == val || !val) {
2457 char *s = getpwd();
2458 physdir = s;
2459 if (!val)
2460 dir = s;
2461 } else
2462 dir = ckstrdup(val);
2463 if (oldcur != dir && oldcur != nullstr) {
2464 free(oldcur);
2465 }
2466 curdir = dir;
2467 INT_ON;
2468 setvar("PWD", dir, VEXPORT);
2469}
2470
2471static void hashcd(void);
2472
2473/*
2474 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2475 * know that the current directory has changed.
2476 */
2477static int
2478docd(const char *dest, int flags)
2479{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002480 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002481 int err;
2482
2483 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2484
2485 INT_OFF;
2486 if (!(flags & CD_PHYSICAL)) {
2487 dir = updatepwd(dest);
2488 if (dir)
2489 dest = dir;
2490 }
2491 err = chdir(dest);
2492 if (err)
2493 goto out;
2494 setpwd(dir, 1);
2495 hashcd();
2496 out:
2497 INT_ON;
2498 return err;
2499}
2500
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002501static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002502cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002503{
2504 const char *dest;
2505 const char *path;
2506 const char *p;
2507 char c;
2508 struct stat statb;
2509 int flags;
2510
2511 flags = cdopt();
2512 dest = *argptr;
2513 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002514 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002515 else if (LONE_DASH(dest)) {
2516 dest = bltinlookup("OLDPWD");
2517 flags |= CD_PRINT;
2518 }
2519 if (!dest)
2520 dest = nullstr;
2521 if (*dest == '/')
2522 goto step7;
2523 if (*dest == '.') {
2524 c = dest[1];
2525 dotdot:
2526 switch (c) {
2527 case '\0':
2528 case '/':
2529 goto step6;
2530 case '.':
2531 c = dest[2];
2532 if (c != '.')
2533 goto dotdot;
2534 }
2535 }
2536 if (!*dest)
2537 dest = ".";
2538 path = bltinlookup("CDPATH");
2539 if (!path) {
2540 step6:
2541 step7:
2542 p = dest;
2543 goto docd;
2544 }
2545 do {
2546 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002547 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002548 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2549 if (c && c != ':')
2550 flags |= CD_PRINT;
2551 docd:
2552 if (!docd(p, flags))
2553 goto out;
2554 break;
2555 }
2556 } while (path);
2557 ash_msg_and_raise_error("can't cd to %s", dest);
2558 /* NOTREACHED */
2559 out:
2560 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002561 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002562 return 0;
2563}
2564
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002565static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002566pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002567{
2568 int flags;
2569 const char *dir = curdir;
2570
2571 flags = cdopt();
2572 if (flags) {
2573 if (physdir == nullstr)
2574 setpwd(dir, 0);
2575 dir = physdir;
2576 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002577 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002578 return 0;
2579}
2580
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002581
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002582/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002583
Denis Vlasenko834dee72008-10-07 09:18:30 +00002584
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002585#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002586
Eric Andersenc470f442003-07-28 09:56:35 +00002587/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002588#define CWORD 0 /* character is nothing special */
2589#define CNL 1 /* newline character */
2590#define CBACK 2 /* a backslash character */
2591#define CSQUOTE 3 /* single quote */
2592#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002593#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002594#define CBQUOTE 6 /* backwards single quote */
2595#define CVAR 7 /* a dollar sign */
2596#define CENDVAR 8 /* a '}' character */
2597#define CLP 9 /* a left paren in arithmetic */
2598#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002599#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002600#define CCTL 12 /* like CWORD, except it must be escaped */
2601#define CSPCL 13 /* these terminate a word */
2602#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002603
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002604#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002605#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002606# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002607#endif
2608
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002609#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002610
Mike Frysinger98c52642009-04-02 10:02:37 +00002611#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002612# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002613#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002614# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002615#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002616static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002617#if ENABLE_ASH_ALIAS
2618 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2619#endif
2620 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2621 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2622 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2623 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2624 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2625 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2626 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2628 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2629 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2630 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002631#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002632 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2633 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2634 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2635#endif
2636#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002637};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002638/* Constants below must match table above */
2639enum {
2640#if ENABLE_ASH_ALIAS
2641 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2642#endif
2643 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2644 CNL_CNL_CNL_CNL , /* 2 */
2645 CWORD_CCTL_CCTL_CWORD , /* 3 */
2646 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2647 CVAR_CVAR_CWORD_CVAR , /* 5 */
2648 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2649 CSPCL_CWORD_CWORD_CLP , /* 7 */
2650 CSPCL_CWORD_CWORD_CRP , /* 8 */
2651 CBACK_CBACK_CCTL_CBACK , /* 9 */
2652 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2653 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2654 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2655 CWORD_CWORD_CWORD_CWORD , /* 13 */
2656 CCTL_CCTL_CCTL_CCTL , /* 14 */
2657};
Eric Andersen2870d962001-07-02 17:27:21 +00002658
Denys Vlasenkocd716832009-11-28 22:14:02 +01002659/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2660 * caller must ensure proper cast on it if c is *char_ptr!
2661 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002662/* Values for syntax param */
2663#define BASESYNTAX 0 /* not in quotes */
2664#define DQSYNTAX 1 /* in double quotes */
2665#define SQSYNTAX 2 /* in single quotes */
2666#define ARISYNTAX 3 /* in arithmetic */
2667#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002668
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002669#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002670
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002671static int
2672SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002673{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002674 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002675# if ENABLE_ASH_ALIAS
2676 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002677 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2678 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2679 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2680 11, 3 /* "}~" */
2681 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002682# else
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002684 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2685 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2686 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2687 10, 2 /* "}~" */
2688 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002689# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002690 const char *s;
2691 int indx;
2692
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002693 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002694 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002695# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002696 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002697 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002698 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002699# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002700 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 /* Cast is purely for paranoia here,
2702 * just in case someone passed signed char to us */
2703 if ((unsigned char)c >= CTL_FIRST
2704 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 ) {
2706 return CCTL;
2707 }
2708 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002710 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002711 indx = syntax_index_table[s - spec_symbls];
2712 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002713 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002714}
2715
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002716#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002717
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002718static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002719 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002720 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2730 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2731 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2753 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2754 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2755 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2756 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2757 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2758 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2759 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2760 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2761 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2762 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2765 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2766 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2767 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2770 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2779 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2780 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2781 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2782 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2812 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2813 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2814 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2817 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2845 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2846 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2847 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2848 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2850 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2851 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2852 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2853 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2854 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2855 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2856 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2857 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002976 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002977# if ENABLE_ASH_ALIAS
2978 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2979# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002980};
2981
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002982# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002983
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002984#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002985
Eric Andersen2870d962001-07-02 17:27:21 +00002986
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002987/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002988
Denis Vlasenko131ae172007-02-18 13:00:19 +00002989#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002990
2991#define ALIASINUSE 1
2992#define ALIASDEAD 2
2993
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00002994struct alias {
2995 struct alias *next;
2996 char *name;
2997 char *val;
2998 int flag;
2999};
3000
Denis Vlasenko01631112007-12-16 17:20:38 +00003001
3002static struct alias **atab; // [ATABSIZE];
3003#define INIT_G_alias() do { \
3004 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3005} while (0)
3006
Eric Andersen2870d962001-07-02 17:27:21 +00003007
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003008static struct alias **
3009__lookupalias(const char *name) {
3010 unsigned int hashval;
3011 struct alias **app;
3012 const char *p;
3013 unsigned int ch;
3014
3015 p = name;
3016
3017 ch = (unsigned char)*p;
3018 hashval = ch << 4;
3019 while (ch) {
3020 hashval += ch;
3021 ch = (unsigned char)*++p;
3022 }
3023 app = &atab[hashval % ATABSIZE];
3024
3025 for (; *app; app = &(*app)->next) {
3026 if (strcmp(name, (*app)->name) == 0) {
3027 break;
3028 }
3029 }
3030
3031 return app;
3032}
3033
3034static struct alias *
3035lookupalias(const char *name, int check)
3036{
3037 struct alias *ap = *__lookupalias(name);
3038
3039 if (check && ap && (ap->flag & ALIASINUSE))
3040 return NULL;
3041 return ap;
3042}
3043
3044static struct alias *
3045freealias(struct alias *ap)
3046{
3047 struct alias *next;
3048
3049 if (ap->flag & ALIASINUSE) {
3050 ap->flag |= ALIASDEAD;
3051 return ap;
3052 }
3053
3054 next = ap->next;
3055 free(ap->name);
3056 free(ap->val);
3057 free(ap);
3058 return next;
3059}
Eric Andersencb57d552001-06-28 07:25:16 +00003060
Eric Andersenc470f442003-07-28 09:56:35 +00003061static void
3062setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003063{
3064 struct alias *ap, **app;
3065
3066 app = __lookupalias(name);
3067 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003068 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003069 if (ap) {
3070 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003071 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003072 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003073 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003074 ap->flag &= ~ALIASDEAD;
3075 } else {
3076 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003077 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003078 ap->name = ckstrdup(name);
3079 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003080 /*ap->flag = 0; - ckzalloc did it */
3081 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003082 *app = ap;
3083 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003084 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003085}
3086
Eric Andersenc470f442003-07-28 09:56:35 +00003087static int
3088unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003089{
Eric Andersencb57d552001-06-28 07:25:16 +00003090 struct alias **app;
3091
3092 app = __lookupalias(name);
3093
3094 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003095 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003096 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003097 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003098 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003099 }
3100
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003101 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003102}
3103
Eric Andersenc470f442003-07-28 09:56:35 +00003104static void
3105rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003106{
Eric Andersencb57d552001-06-28 07:25:16 +00003107 struct alias *ap, **app;
3108 int i;
3109
Denis Vlasenkob012b102007-02-19 22:43:01 +00003110 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003111 for (i = 0; i < ATABSIZE; i++) {
3112 app = &atab[i];
3113 for (ap = *app; ap; ap = *app) {
3114 *app = freealias(*app);
3115 if (ap == *app) {
3116 app = &ap->next;
3117 }
3118 }
3119 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003120 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003121}
3122
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003123static void
3124printalias(const struct alias *ap)
3125{
3126 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3127}
3128
Eric Andersencb57d552001-06-28 07:25:16 +00003129/*
3130 * TODO - sort output
3131 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003132static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003133aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003134{
3135 char *n, *v;
3136 int ret = 0;
3137 struct alias *ap;
3138
Denis Vlasenko68404f12008-03-17 09:00:54 +00003139 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003140 int i;
3141
Denis Vlasenko68404f12008-03-17 09:00:54 +00003142 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003143 for (ap = atab[i]; ap; ap = ap->next) {
3144 printalias(ap);
3145 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003146 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003147 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003148 }
3149 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003150 v = strchr(n+1, '=');
3151 if (v == NULL) { /* n+1: funny ksh stuff */
3152 ap = *__lookupalias(n);
3153 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003154 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003155 ret = 1;
3156 } else
3157 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003158 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003159 *v++ = '\0';
3160 setalias(n, v);
3161 }
3162 }
3163
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003164 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003165}
3166
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003167static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003168unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003169{
3170 int i;
3171
3172 while ((i = nextopt("a")) != '\0') {
3173 if (i == 'a') {
3174 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003175 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003176 }
3177 }
3178 for (i = 0; *argptr; argptr++) {
3179 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003180 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003181 i = 1;
3182 }
3183 }
3184
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003185 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003186}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003187
Denis Vlasenko131ae172007-02-18 13:00:19 +00003188#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003189
Eric Andersenc470f442003-07-28 09:56:35 +00003190
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003191/* ============ jobs.c */
3192
3193/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003194#define FORK_FG 0
3195#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003196#define FORK_NOJOB 2
3197
3198/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003199#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3200#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3201#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003202
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003203/*
3204 * A job structure contains information about a job. A job is either a
3205 * single process or a set of processes contained in a pipeline. In the
3206 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3207 * array of pids.
3208 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003209struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003210 pid_t ps_pid; /* process id */
3211 int ps_status; /* last process status from wait() */
3212 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003213};
3214
3215struct job {
3216 struct procstat ps0; /* status of process */
3217 struct procstat *ps; /* status or processes when more than one */
3218#if JOBS
3219 int stopstatus; /* status of a stopped job */
3220#endif
3221 uint32_t
3222 nprocs: 16, /* number of processes */
3223 state: 8,
3224#define JOBRUNNING 0 /* at least one proc running */
3225#define JOBSTOPPED 1 /* all procs are stopped */
3226#define JOBDONE 2 /* all procs are completed */
3227#if JOBS
3228 sigint: 1, /* job was killed by SIGINT */
3229 jobctl: 1, /* job running under job control */
3230#endif
3231 waited: 1, /* true if this entry has been waited for */
3232 used: 1, /* true if this entry is in used */
3233 changed: 1; /* true if status has changed */
3234 struct job *prev_job; /* previous job */
3235};
3236
Denis Vlasenko68404f12008-03-17 09:00:54 +00003237static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003238static int forkshell(struct job *, union node *, int);
3239static int waitforjob(struct job *);
3240
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003241#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003242enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003243#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003244#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003245static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003247#endif
3248
3249/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003250 * Ignore a signal.
3251 */
3252static void
3253ignoresig(int signo)
3254{
3255 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3256 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3257 /* No, need to do it */
3258 signal(signo, SIG_IGN);
3259 }
3260 sigmode[signo - 1] = S_HARD_IGN;
3261}
3262
3263/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003264 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003265 */
3266static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003267signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003268{
3269 gotsig[signo - 1] = 1;
3270
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003271 if (signo == SIGINT && !trap[SIGINT]) {
3272 if (!suppress_int) {
3273 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003274 raise_interrupt(); /* does not return */
3275 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003276 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003277 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003278 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003279 }
3280}
3281
3282/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003283 * Set the signal handler for the specified signal. The routine figures
3284 * out what it should be set to.
3285 */
3286static void
3287setsignal(int signo)
3288{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003289 char *t;
3290 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291 struct sigaction act;
3292
3293 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003294 new_act = S_DFL;
3295 if (t != NULL) { /* trap for this sig is set */
3296 new_act = S_CATCH;
3297 if (t[0] == '\0') /* trap is "": ignore this sig */
3298 new_act = S_IGN;
3299 }
3300
3301 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003302 switch (signo) {
3303 case SIGINT:
3304 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003305 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003306 break;
3307 case SIGQUIT:
3308#if DEBUG
3309 if (debug)
3310 break;
3311#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003312 /* man bash:
3313 * "In all cases, bash ignores SIGQUIT. Non-builtin
3314 * commands run by bash have signal handlers
3315 * set to the values inherited by the shell
3316 * from its parent". */
3317 new_act = S_IGN;
3318 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003319 case SIGTERM:
3320 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003321 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003322 break;
3323#if JOBS
3324 case SIGTSTP:
3325 case SIGTTOU:
3326 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003327 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003328 break;
3329#endif
3330 }
3331 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003332//TODO: if !rootshell, we reset SIGQUIT to DFL,
3333//whereas we have to restore it to what shell got on entry
3334//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003335
3336 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003337 cur_act = *t;
3338 if (cur_act == 0) {
3339 /* current setting is not yet known */
3340 if (sigaction(signo, NULL, &act)) {
3341 /* pretend it worked; maybe we should give a warning,
3342 * but other shells don't. We don't alter sigmode,
3343 * so we retry every time.
3344 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003345 return;
3346 }
3347 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003348 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003349 if (mflag
3350 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3351 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003352 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003353 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003354 }
3355 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003356 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003358
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003359 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003361 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003362 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003363 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3364 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 break;
3366 case S_IGN:
3367 act.sa_handler = SIG_IGN;
3368 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003370 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371
3372 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003373}
3374
3375/* mode flags for set_curjob */
3376#define CUR_DELETE 2
3377#define CUR_RUNNING 1
3378#define CUR_STOPPED 0
3379
3380/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003381#define DOWAIT_NONBLOCK WNOHANG
3382#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003383
3384#if JOBS
3385/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003386static int initialpgrp; //references:2
3387static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003388#endif
3389/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003390static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003392static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003393/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003395/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003396static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397
3398static void
3399set_curjob(struct job *jp, unsigned mode)
3400{
3401 struct job *jp1;
3402 struct job **jpp, **curp;
3403
3404 /* first remove from list */
3405 jpp = curp = &curjob;
3406 do {
3407 jp1 = *jpp;
3408 if (jp1 == jp)
3409 break;
3410 jpp = &jp1->prev_job;
3411 } while (1);
3412 *jpp = jp1->prev_job;
3413
3414 /* Then re-insert in correct position */
3415 jpp = curp;
3416 switch (mode) {
3417 default:
3418#if DEBUG
3419 abort();
3420#endif
3421 case CUR_DELETE:
3422 /* job being deleted */
3423 break;
3424 case CUR_RUNNING:
3425 /* newly created job or backgrounded job,
3426 put after all stopped jobs. */
3427 do {
3428 jp1 = *jpp;
3429#if JOBS
3430 if (!jp1 || jp1->state != JOBSTOPPED)
3431#endif
3432 break;
3433 jpp = &jp1->prev_job;
3434 } while (1);
3435 /* FALLTHROUGH */
3436#if JOBS
3437 case CUR_STOPPED:
3438#endif
3439 /* newly stopped job - becomes curjob */
3440 jp->prev_job = *jpp;
3441 *jpp = jp;
3442 break;
3443 }
3444}
3445
3446#if JOBS || DEBUG
3447static int
3448jobno(const struct job *jp)
3449{
3450 return jp - jobtab + 1;
3451}
3452#endif
3453
3454/*
3455 * Convert a job name to a job structure.
3456 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003457#if !JOBS
3458#define getjob(name, getctl) getjob(name)
3459#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003460static struct job *
3461getjob(const char *name, int getctl)
3462{
3463 struct job *jp;
3464 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003465 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003466 unsigned num;
3467 int c;
3468 const char *p;
3469 char *(*match)(const char *, const char *);
3470
3471 jp = curjob;
3472 p = name;
3473 if (!p)
3474 goto currentjob;
3475
3476 if (*p != '%')
3477 goto err;
3478
3479 c = *++p;
3480 if (!c)
3481 goto currentjob;
3482
3483 if (!p[1]) {
3484 if (c == '+' || c == '%') {
3485 currentjob:
3486 err_msg = "No current job";
3487 goto check;
3488 }
3489 if (c == '-') {
3490 if (jp)
3491 jp = jp->prev_job;
3492 err_msg = "No previous job";
3493 check:
3494 if (!jp)
3495 goto err;
3496 goto gotit;
3497 }
3498 }
3499
3500 if (is_number(p)) {
3501 num = atoi(p);
3502 if (num < njobs) {
3503 jp = jobtab + num - 1;
3504 if (jp->used)
3505 goto gotit;
3506 goto err;
3507 }
3508 }
3509
3510 match = prefix;
3511 if (*p == '?') {
3512 match = strstr;
3513 p++;
3514 }
3515
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003516 found = NULL;
3517 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003518 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003519 if (found)
3520 goto err;
3521 found = jp;
3522 err_msg = "%s: ambiguous";
3523 }
3524 jp = jp->prev_job;
3525 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003526 if (!found)
3527 goto err;
3528 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003529
3530 gotit:
3531#if JOBS
3532 err_msg = "job %s not created under job control";
3533 if (getctl && jp->jobctl == 0)
3534 goto err;
3535#endif
3536 return jp;
3537 err:
3538 ash_msg_and_raise_error(err_msg, name);
3539}
3540
3541/*
3542 * Mark a job structure as unused.
3543 */
3544static void
3545freejob(struct job *jp)
3546{
3547 struct procstat *ps;
3548 int i;
3549
3550 INT_OFF;
3551 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003552 if (ps->ps_cmd != nullstr)
3553 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003554 }
3555 if (jp->ps != &jp->ps0)
3556 free(jp->ps);
3557 jp->used = 0;
3558 set_curjob(jp, CUR_DELETE);
3559 INT_ON;
3560}
3561
3562#if JOBS
3563static void
3564xtcsetpgrp(int fd, pid_t pgrp)
3565{
3566 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003567 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003568}
3569
3570/*
3571 * Turn job control on and off.
3572 *
3573 * Note: This code assumes that the third arg to ioctl is a character
3574 * pointer, which is true on Berkeley systems but not System V. Since
3575 * System V doesn't have job control yet, this isn't a problem now.
3576 *
3577 * Called with interrupts off.
3578 */
3579static void
3580setjobctl(int on)
3581{
3582 int fd;
3583 int pgrp;
3584
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003585 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003586 return;
3587 if (on) {
3588 int ofd;
3589 ofd = fd = open(_PATH_TTY, O_RDWR);
3590 if (fd < 0) {
3591 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3592 * That sometimes helps to acquire controlling tty.
3593 * Obviously, a workaround for bugs when someone
3594 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003595 fd = 2;
3596 while (!isatty(fd))
3597 if (--fd < 0)
3598 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003599 }
3600 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003601 if (ofd >= 0)
3602 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003603 if (fd < 0)
3604 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003605 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003606 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003607 do { /* while we are in the background */
3608 pgrp = tcgetpgrp(fd);
3609 if (pgrp < 0) {
3610 out:
3611 ash_msg("can't access tty; job control turned off");
3612 mflag = on = 0;
3613 goto close;
3614 }
3615 if (pgrp == getpgrp())
3616 break;
3617 killpg(0, SIGTTIN);
3618 } while (1);
3619 initialpgrp = pgrp;
3620
3621 setsignal(SIGTSTP);
3622 setsignal(SIGTTOU);
3623 setsignal(SIGTTIN);
3624 pgrp = rootpid;
3625 setpgid(0, pgrp);
3626 xtcsetpgrp(fd, pgrp);
3627 } else {
3628 /* turning job control off */
3629 fd = ttyfd;
3630 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003631 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003632 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003633 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003634 setpgid(0, pgrp);
3635 setsignal(SIGTSTP);
3636 setsignal(SIGTTOU);
3637 setsignal(SIGTTIN);
3638 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003639 if (fd >= 0)
3640 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003641 fd = -1;
3642 }
3643 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003644 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003645}
3646
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003647static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003648killcmd(int argc, char **argv)
3649{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003650 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003651 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003652 do {
3653 if (argv[i][0] == '%') {
3654 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003655 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003656 /* Enough space for ' -NNN<nul>' */
3657 argv[i] = alloca(sizeof(int)*3 + 3);
3658 /* kill_main has matching code to expect
3659 * leading space. Needed to not confuse
3660 * negative pids with "kill -SIGNAL_NO" syntax */
3661 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003662 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003663 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003664 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003665 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003666}
3667
3668static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003669showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003670{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003671 struct procstat *ps;
3672 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673
Denys Vlasenko285ad152009-12-04 23:02:27 +01003674 psend = jp->ps + jp->nprocs;
3675 for (ps = jp->ps + 1; ps < psend; ps++)
3676 printf(" | %s", ps->ps_cmd);
3677 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678 flush_stdout_stderr();
3679}
3680
3681
3682static int
3683restartjob(struct job *jp, int mode)
3684{
3685 struct procstat *ps;
3686 int i;
3687 int status;
3688 pid_t pgid;
3689
3690 INT_OFF;
3691 if (jp->state == JOBDONE)
3692 goto out;
3693 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003694 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003695 if (mode == FORK_FG)
3696 xtcsetpgrp(ttyfd, pgid);
3697 killpg(pgid, SIGCONT);
3698 ps = jp->ps;
3699 i = jp->nprocs;
3700 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003701 if (WIFSTOPPED(ps->ps_status)) {
3702 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003704 ps++;
3705 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003706 out:
3707 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3708 INT_ON;
3709 return status;
3710}
3711
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003712static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003713fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714{
3715 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003716 int mode;
3717 int retval;
3718
3719 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3720 nextopt(nullstr);
3721 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003722 do {
3723 jp = getjob(*argv, 1);
3724 if (mode == FORK_BG) {
3725 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003726 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003727 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003728 out1str(jp->ps[0].ps_cmd);
3729 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 retval = restartjob(jp, mode);
3731 } while (*argv && *++argv);
3732 return retval;
3733}
3734#endif
3735
3736static int
3737sprint_status(char *s, int status, int sigonly)
3738{
3739 int col;
3740 int st;
3741
3742 col = 0;
3743 if (!WIFEXITED(status)) {
3744#if JOBS
3745 if (WIFSTOPPED(status))
3746 st = WSTOPSIG(status);
3747 else
3748#endif
3749 st = WTERMSIG(status);
3750 if (sigonly) {
3751 if (st == SIGINT || st == SIGPIPE)
3752 goto out;
3753#if JOBS
3754 if (WIFSTOPPED(status))
3755 goto out;
3756#endif
3757 }
3758 st &= 0x7f;
3759 col = fmtstr(s, 32, strsignal(st));
3760 if (WCOREDUMP(status)) {
3761 col += fmtstr(s + col, 16, " (core dumped)");
3762 }
3763 } else if (!sigonly) {
3764 st = WEXITSTATUS(status);
3765 if (st)
3766 col = fmtstr(s, 16, "Done(%d)", st);
3767 else
3768 col = fmtstr(s, 16, "Done");
3769 }
3770 out:
3771 return col;
3772}
3773
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003774static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003775dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003776{
3777 int pid;
3778 int status;
3779 struct job *jp;
3780 struct job *thisjob;
3781 int state;
3782
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003783 TRACE(("dowait(0x%x) called\n", wait_flags));
3784
3785 /* Do a wait system call. If job control is compiled in, we accept
3786 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3787 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003788 if (doing_jobctl)
3789 wait_flags |= WUNTRACED;
3790 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003791 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3792 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003793 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003794 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003795
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003796 INT_OFF;
3797 thisjob = NULL;
3798 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003799 struct procstat *ps;
3800 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003801 if (jp->state == JOBDONE)
3802 continue;
3803 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003804 ps = jp->ps;
3805 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003806 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003808 TRACE(("Job %d: changing status of proc %d "
3809 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003810 jobno(jp), pid, ps->ps_status, status));
3811 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003812 thisjob = jp;
3813 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003814 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815 state = JOBRUNNING;
3816#if JOBS
3817 if (state == JOBRUNNING)
3818 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003819 if (WIFSTOPPED(ps->ps_status)) {
3820 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003821 state = JOBSTOPPED;
3822 }
3823#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003824 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003825 if (thisjob)
3826 goto gotjob;
3827 }
3828#if JOBS
3829 if (!WIFSTOPPED(status))
3830#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003831 jobless--;
3832 goto out;
3833
3834 gotjob:
3835 if (state != JOBRUNNING) {
3836 thisjob->changed = 1;
3837
3838 if (thisjob->state != state) {
3839 TRACE(("Job %d: changing state from %d to %d\n",
3840 jobno(thisjob), thisjob->state, state));
3841 thisjob->state = state;
3842#if JOBS
3843 if (state == JOBSTOPPED) {
3844 set_curjob(thisjob, CUR_STOPPED);
3845 }
3846#endif
3847 }
3848 }
3849
3850 out:
3851 INT_ON;
3852
3853 if (thisjob && thisjob == job) {
3854 char s[48 + 1];
3855 int len;
3856
3857 len = sprint_status(s, status, 1);
3858 if (len) {
3859 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003860 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003861 out2str(s);
3862 }
3863 }
3864 return pid;
3865}
3866
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003867static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003868blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003869{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003870 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003871 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003872 raise_exception(EXSIG);
3873 return pid;
3874}
3875
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003876#if JOBS
3877static void
3878showjob(FILE *out, struct job *jp, int mode)
3879{
3880 struct procstat *ps;
3881 struct procstat *psend;
3882 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003883 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884 char s[80];
3885
3886 ps = jp->ps;
3887
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003888 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003889 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003890 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003891 return;
3892 }
3893
3894 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003895 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003896
3897 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003898 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003900 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003901
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003902 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003903 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
3905 psend = ps + jp->nprocs;
3906
3907 if (jp->state == JOBRUNNING) {
3908 strcpy(s + col, "Running");
3909 col += sizeof("Running") - 1;
3910 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003911 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912 if (jp->state == JOBSTOPPED)
3913 status = jp->stopstatus;
3914 col += sprint_status(s + col, status, 0);
3915 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003916 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003917
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003918 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3919 * or prints several "PID | <cmdN>" lines,
3920 * depending on SHOW_PIDS bit.
3921 * We do not print status of individual processes
3922 * between PID and <cmdN>. bash does it, but not very well:
3923 * first line shows overall job status, not process status,
3924 * making it impossible to know 1st process status.
3925 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003926 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003927 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003928 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003929 s[0] = '\0';
3930 col = 33;
3931 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003932 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003933 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003934 fprintf(out, "%s%*c%s%s",
3935 s,
3936 33 - col >= 0 ? 33 - col : 0, ' ',
3937 ps == jp->ps ? "" : "| ",
3938 ps->ps_cmd
3939 );
3940 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003941 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003942
3943 jp->changed = 0;
3944
3945 if (jp->state == JOBDONE) {
3946 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3947 freejob(jp);
3948 }
3949}
3950
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003951/*
3952 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3953 * statuses have changed since the last call to showjobs.
3954 */
3955static void
3956showjobs(FILE *out, int mode)
3957{
3958 struct job *jp;
3959
Denys Vlasenko883cea42009-07-11 15:31:59 +02003960 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003961
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003962 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003963 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003964 continue;
3965
3966 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003967 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003968 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003969 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003970 }
3971}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003972
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003973static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003974jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975{
3976 int mode, m;
3977
3978 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003979 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003981 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003982 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003983 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003984 }
3985
3986 argv = argptr;
3987 if (*argv) {
3988 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003990 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003991 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003993 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003994
3995 return 0;
3996}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003997#endif /* JOBS */
3998
Michael Abbott359da5e2009-12-04 23:03:29 +01003999/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004000static int
4001getstatus(struct job *job)
4002{
4003 int status;
4004 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004005 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006
Michael Abbott359da5e2009-12-04 23:03:29 +01004007 /* Fetch last member's status */
4008 ps = job->ps + job->nprocs - 1;
4009 status = ps->ps_status;
4010 if (pipefail) {
4011 /* "set -o pipefail" mode: use last _nonzero_ status */
4012 while (status == 0 && --ps >= job->ps)
4013 status = ps->ps_status;
4014 }
4015
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004016 retval = WEXITSTATUS(status);
4017 if (!WIFEXITED(status)) {
4018#if JOBS
4019 retval = WSTOPSIG(status);
4020 if (!WIFSTOPPED(status))
4021#endif
4022 {
4023 /* XXX: limits number of signals */
4024 retval = WTERMSIG(status);
4025#if JOBS
4026 if (retval == SIGINT)
4027 job->sigint = 1;
4028#endif
4029 }
4030 retval += 128;
4031 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004032 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004033 jobno(job), job->nprocs, status, retval));
4034 return retval;
4035}
4036
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004037static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004038waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004039{
4040 struct job *job;
4041 int retval;
4042 struct job *jp;
4043
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004044 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004045 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004046
4047 nextopt(nullstr);
4048 retval = 0;
4049
4050 argv = argptr;
4051 if (!*argv) {
4052 /* wait for all jobs */
4053 for (;;) {
4054 jp = curjob;
4055 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004056 if (!jp) /* no running procs */
4057 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004058 if (jp->state == JOBRUNNING)
4059 break;
4060 jp->waited = 1;
4061 jp = jp->prev_job;
4062 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004063 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004064 /* man bash:
4065 * "When bash is waiting for an asynchronous command via
4066 * the wait builtin, the reception of a signal for which a trap
4067 * has been set will cause the wait builtin to return immediately
4068 * with an exit status greater than 128, immediately after which
4069 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004070 *
4071 * blocking_wait_with_raise_on_sig raises signal handlers
4072 * if it gets no pid (pid < 0). However,
4073 * if child sends us a signal *and immediately exits*,
4074 * blocking_wait_with_raise_on_sig gets pid > 0
4075 * and does not handle pending_sig. Check this case: */
4076 if (pending_sig)
4077 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004078 }
4079 }
4080
4081 retval = 127;
4082 do {
4083 if (**argv != '%') {
4084 pid_t pid = number(*argv);
4085 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004086 while (1) {
4087 if (!job)
4088 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004089 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004090 break;
4091 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004092 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004093 } else
4094 job = getjob(*argv, 0);
4095 /* loop until process terminated or stopped */
4096 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004097 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 job->waited = 1;
4099 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004100 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004101 } while (*++argv);
4102
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004103 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004104 return retval;
4105}
4106
4107static struct job *
4108growjobtab(void)
4109{
4110 size_t len;
4111 ptrdiff_t offset;
4112 struct job *jp, *jq;
4113
4114 len = njobs * sizeof(*jp);
4115 jq = jobtab;
4116 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4117
4118 offset = (char *)jp - (char *)jq;
4119 if (offset) {
4120 /* Relocate pointers */
4121 size_t l = len;
4122
4123 jq = (struct job *)((char *)jq + l);
4124 while (l) {
4125 l -= sizeof(*jp);
4126 jq--;
4127#define joff(p) ((struct job *)((char *)(p) + l))
4128#define jmove(p) (p) = (void *)((char *)(p) + offset)
4129 if (joff(jp)->ps == &jq->ps0)
4130 jmove(joff(jp)->ps);
4131 if (joff(jp)->prev_job)
4132 jmove(joff(jp)->prev_job);
4133 }
4134 if (curjob)
4135 jmove(curjob);
4136#undef joff
4137#undef jmove
4138 }
4139
4140 njobs += 4;
4141 jobtab = jp;
4142 jp = (struct job *)((char *)jp + len);
4143 jq = jp + 3;
4144 do {
4145 jq->used = 0;
4146 } while (--jq >= jp);
4147 return jp;
4148}
4149
4150/*
4151 * Return a new job structure.
4152 * Called with interrupts off.
4153 */
4154static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004155makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004156{
4157 int i;
4158 struct job *jp;
4159
4160 for (i = njobs, jp = jobtab; ; jp++) {
4161 if (--i < 0) {
4162 jp = growjobtab();
4163 break;
4164 }
4165 if (jp->used == 0)
4166 break;
4167 if (jp->state != JOBDONE || !jp->waited)
4168 continue;
4169#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004170 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004171 continue;
4172#endif
4173 freejob(jp);
4174 break;
4175 }
4176 memset(jp, 0, sizeof(*jp));
4177#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004178 /* jp->jobctl is a bitfield.
4179 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004180 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004181 jp->jobctl = 1;
4182#endif
4183 jp->prev_job = curjob;
4184 curjob = jp;
4185 jp->used = 1;
4186 jp->ps = &jp->ps0;
4187 if (nprocs > 1) {
4188 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4189 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004190 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004191 jobno(jp)));
4192 return jp;
4193}
4194
4195#if JOBS
4196/*
4197 * Return a string identifying a command (to be printed by the
4198 * jobs command).
4199 */
4200static char *cmdnextc;
4201
4202static void
4203cmdputs(const char *s)
4204{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004205 static const char vstype[VSTYPE + 1][3] = {
4206 "", "}", "-", "+", "?", "=",
4207 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004208 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004209 };
4210
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004211 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004212 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004213 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004214 unsigned char c;
4215 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004216 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217
Denys Vlasenko46a14772009-12-10 21:27:13 +01004218 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004219 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4220 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004221 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004222 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223 switch (c) {
4224 case CTLESC:
4225 c = *p++;
4226 break;
4227 case CTLVAR:
4228 subtype = *p++;
4229 if ((subtype & VSTYPE) == VSLENGTH)
4230 str = "${#";
4231 else
4232 str = "${";
4233 if (!(subtype & VSQUOTE) == !(quoted & 1))
4234 goto dostr;
4235 quoted ^= 1;
4236 c = '"';
4237 break;
4238 case CTLENDVAR:
4239 str = "\"}" + !(quoted & 1);
4240 quoted >>= 1;
4241 subtype = 0;
4242 goto dostr;
4243 case CTLBACKQ:
4244 str = "$(...)";
4245 goto dostr;
4246 case CTLBACKQ+CTLQUOTE:
4247 str = "\"$(...)\"";
4248 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004249#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004250 case CTLARI:
4251 str = "$((";
4252 goto dostr;
4253 case CTLENDARI:
4254 str = "))";
4255 goto dostr;
4256#endif
4257 case CTLQUOTEMARK:
4258 quoted ^= 1;
4259 c = '"';
4260 break;
4261 case '=':
4262 if (subtype == 0)
4263 break;
4264 if ((subtype & VSTYPE) != VSNORMAL)
4265 quoted <<= 1;
4266 str = vstype[subtype & VSTYPE];
4267 if (subtype & VSNUL)
4268 c = ':';
4269 else
4270 goto checkstr;
4271 break;
4272 case '\'':
4273 case '\\':
4274 case '"':
4275 case '$':
4276 /* These can only happen inside quotes */
4277 cc[0] = c;
4278 str = cc;
4279 c = '\\';
4280 break;
4281 default:
4282 break;
4283 }
4284 USTPUTC(c, nextc);
4285 checkstr:
4286 if (!str)
4287 continue;
4288 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004289 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004290 USTPUTC(c, nextc);
4291 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004292 } /* while *p++ not NUL */
4293
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004294 if (quoted & 1) {
4295 USTPUTC('"', nextc);
4296 }
4297 *nextc = 0;
4298 cmdnextc = nextc;
4299}
4300
4301/* cmdtxt() and cmdlist() call each other */
4302static void cmdtxt(union node *n);
4303
4304static void
4305cmdlist(union node *np, int sep)
4306{
4307 for (; np; np = np->narg.next) {
4308 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004309 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004310 cmdtxt(np);
4311 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004312 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004313 }
4314}
4315
4316static void
4317cmdtxt(union node *n)
4318{
4319 union node *np;
4320 struct nodelist *lp;
4321 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004322
4323 if (!n)
4324 return;
4325 switch (n->type) {
4326 default:
4327#if DEBUG
4328 abort();
4329#endif
4330 case NPIPE:
4331 lp = n->npipe.cmdlist;
4332 for (;;) {
4333 cmdtxt(lp->n);
4334 lp = lp->next;
4335 if (!lp)
4336 break;
4337 cmdputs(" | ");
4338 }
4339 break;
4340 case NSEMI:
4341 p = "; ";
4342 goto binop;
4343 case NAND:
4344 p = " && ";
4345 goto binop;
4346 case NOR:
4347 p = " || ";
4348 binop:
4349 cmdtxt(n->nbinary.ch1);
4350 cmdputs(p);
4351 n = n->nbinary.ch2;
4352 goto donode;
4353 case NREDIR:
4354 case NBACKGND:
4355 n = n->nredir.n;
4356 goto donode;
4357 case NNOT:
4358 cmdputs("!");
4359 n = n->nnot.com;
4360 donode:
4361 cmdtxt(n);
4362 break;
4363 case NIF:
4364 cmdputs("if ");
4365 cmdtxt(n->nif.test);
4366 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004367 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004368 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004369 cmdputs("; else ");
4370 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004371 } else {
4372 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004373 }
4374 p = "; fi";
4375 goto dotail;
4376 case NSUBSHELL:
4377 cmdputs("(");
4378 n = n->nredir.n;
4379 p = ")";
4380 goto dotail;
4381 case NWHILE:
4382 p = "while ";
4383 goto until;
4384 case NUNTIL:
4385 p = "until ";
4386 until:
4387 cmdputs(p);
4388 cmdtxt(n->nbinary.ch1);
4389 n = n->nbinary.ch2;
4390 p = "; done";
4391 dodo:
4392 cmdputs("; do ");
4393 dotail:
4394 cmdtxt(n);
4395 goto dotail2;
4396 case NFOR:
4397 cmdputs("for ");
4398 cmdputs(n->nfor.var);
4399 cmdputs(" in ");
4400 cmdlist(n->nfor.args, 1);
4401 n = n->nfor.body;
4402 p = "; done";
4403 goto dodo;
4404 case NDEFUN:
4405 cmdputs(n->narg.text);
4406 p = "() { ... }";
4407 goto dotail2;
4408 case NCMD:
4409 cmdlist(n->ncmd.args, 1);
4410 cmdlist(n->ncmd.redirect, 0);
4411 break;
4412 case NARG:
4413 p = n->narg.text;
4414 dotail2:
4415 cmdputs(p);
4416 break;
4417 case NHERE:
4418 case NXHERE:
4419 p = "<<...";
4420 goto dotail2;
4421 case NCASE:
4422 cmdputs("case ");
4423 cmdputs(n->ncase.expr->narg.text);
4424 cmdputs(" in ");
4425 for (np = n->ncase.cases; np; np = np->nclist.next) {
4426 cmdtxt(np->nclist.pattern);
4427 cmdputs(") ");
4428 cmdtxt(np->nclist.body);
4429 cmdputs(";; ");
4430 }
4431 p = "esac";
4432 goto dotail2;
4433 case NTO:
4434 p = ">";
4435 goto redir;
4436 case NCLOBBER:
4437 p = ">|";
4438 goto redir;
4439 case NAPPEND:
4440 p = ">>";
4441 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004442#if ENABLE_ASH_BASH_COMPAT
4443 case NTO2:
4444#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004445 case NTOFD:
4446 p = ">&";
4447 goto redir;
4448 case NFROM:
4449 p = "<";
4450 goto redir;
4451 case NFROMFD:
4452 p = "<&";
4453 goto redir;
4454 case NFROMTO:
4455 p = "<>";
4456 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004457 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004458 cmdputs(p);
4459 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004460 cmdputs(utoa(n->ndup.dupfd));
4461 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004462 }
4463 n = n->nfile.fname;
4464 goto donode;
4465 }
4466}
4467
4468static char *
4469commandtext(union node *n)
4470{
4471 char *name;
4472
4473 STARTSTACKSTR(cmdnextc);
4474 cmdtxt(n);
4475 name = stackblock();
4476 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4477 name, cmdnextc, cmdnextc));
4478 return ckstrdup(name);
4479}
4480#endif /* JOBS */
4481
4482/*
4483 * Fork off a subshell. If we are doing job control, give the subshell its
4484 * own process group. Jp is a job structure that the job is to be added to.
4485 * N is the command that will be evaluated by the child. Both jp and n may
4486 * be NULL. The mode parameter can be one of the following:
4487 * FORK_FG - Fork off a foreground process.
4488 * FORK_BG - Fork off a background process.
4489 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4490 * process group even if job control is on.
4491 *
4492 * When job control is turned off, background processes have their standard
4493 * input redirected to /dev/null (except for the second and later processes
4494 * in a pipeline).
4495 *
4496 * Called with interrupts off.
4497 */
4498/*
4499 * Clear traps on a fork.
4500 */
4501static void
4502clear_traps(void)
4503{
4504 char **tp;
4505
4506 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004507 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004508 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004509 if (trap_ptr == trap)
4510 free(*tp);
4511 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004512 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004513 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004514 setsignal(tp - trap);
4515 INT_ON;
4516 }
4517 }
4518}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004519
4520/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004521static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004522
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004523/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004524static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004525forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004526{
4527 int oldlvl;
4528
4529 TRACE(("Child shell %d\n", getpid()));
4530 oldlvl = shlvl;
4531 shlvl++;
4532
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004533 /* man bash: "Non-builtin commands run by bash have signal handlers
4534 * set to the values inherited by the shell from its parent".
4535 * Do we do it correctly? */
4536
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004537 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004538
4539 if (mode == FORK_NOJOB /* is it `xxx` ? */
4540 && n && n->type == NCMD /* is it single cmd? */
4541 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004542 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004543 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4544 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4545 ) {
4546 TRACE(("Trap hack\n"));
4547 /* Awful hack for `trap` or $(trap).
4548 *
4549 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4550 * contains an example where "trap" is executed in a subshell:
4551 *
4552 * save_traps=$(trap)
4553 * ...
4554 * eval "$save_traps"
4555 *
4556 * Standard does not say that "trap" in subshell shall print
4557 * parent shell's traps. It only says that its output
4558 * must have suitable form, but then, in the above example
4559 * (which is not supposed to be normative), it implies that.
4560 *
4561 * bash (and probably other shell) does implement it
4562 * (traps are reset to defaults, but "trap" still shows them),
4563 * but as a result, "trap" logic is hopelessly messed up:
4564 *
4565 * # trap
4566 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4567 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4568 * # true | trap <--- trap is in subshell - no output (ditto)
4569 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4570 * trap -- 'echo Ho' SIGWINCH
4571 * # echo `(trap)` <--- in subshell in subshell - output
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4574 * trap -- 'echo Ho' SIGWINCH
4575 *
4576 * The rules when to forget and when to not forget traps
4577 * get really complex and nonsensical.
4578 *
4579 * Our solution: ONLY bare $(trap) or `trap` is special.
4580 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004581 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004582 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004583 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004584 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004585 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004586#if JOBS
4587 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004588 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004589 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4590 pid_t pgrp;
4591
4592 if (jp->nprocs == 0)
4593 pgrp = getpid();
4594 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004595 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004596 /* this can fail because we are doing it in the parent also */
4597 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004598 if (mode == FORK_FG)
4599 xtcsetpgrp(ttyfd, pgrp);
4600 setsignal(SIGTSTP);
4601 setsignal(SIGTTOU);
4602 } else
4603#endif
4604 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004605 /* man bash: "When job control is not in effect,
4606 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004607 ignoresig(SIGINT);
4608 ignoresig(SIGQUIT);
4609 if (jp->nprocs == 0) {
4610 close(0);
4611 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004612 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004613 }
4614 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004615 if (!oldlvl) {
4616 if (iflag) { /* why if iflag only? */
4617 setsignal(SIGINT);
4618 setsignal(SIGTERM);
4619 }
4620 /* man bash:
4621 * "In all cases, bash ignores SIGQUIT. Non-builtin
4622 * commands run by bash have signal handlers
4623 * set to the values inherited by the shell
4624 * from its parent".
4625 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004626 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004628#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004629 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004630 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004631 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004632 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004633 /* "jobs": we do not want to clear job list for it,
4634 * instead we remove only _its_ own_ job from job list.
4635 * This makes "jobs .... | cat" more useful.
4636 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004637 freejob(curjob);
4638 return;
4639 }
4640#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004641 for (jp = curjob; jp; jp = jp->prev_job)
4642 freejob(jp);
4643 jobless = 0;
4644}
4645
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004646/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004647#if !JOBS
4648#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4649#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004650static void
4651forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4652{
4653 TRACE(("In parent shell: child = %d\n", pid));
4654 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004655 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4656 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004657 jobless++;
4658 return;
4659 }
4660#if JOBS
4661 if (mode != FORK_NOJOB && jp->jobctl) {
4662 int pgrp;
4663
4664 if (jp->nprocs == 0)
4665 pgrp = pid;
4666 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004667 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004668 /* This can fail because we are doing it in the child also */
4669 setpgid(pid, pgrp);
4670 }
4671#endif
4672 if (mode == FORK_BG) {
4673 backgndpid = pid; /* set $! */
4674 set_curjob(jp, CUR_RUNNING);
4675 }
4676 if (jp) {
4677 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004678 ps->ps_pid = pid;
4679 ps->ps_status = -1;
4680 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004681#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004682 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004683 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004684#endif
4685 }
4686}
4687
4688static int
4689forkshell(struct job *jp, union node *n, int mode)
4690{
4691 int pid;
4692
4693 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4694 pid = fork();
4695 if (pid < 0) {
4696 TRACE(("Fork failed, errno=%d", errno));
4697 if (jp)
4698 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004699 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004700 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004701 if (pid == 0) {
4702 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004703 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004704 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004705 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004706 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004707 return pid;
4708}
4709
4710/*
4711 * Wait for job to finish.
4712 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004713 * Under job control we have the problem that while a child process
4714 * is running interrupts generated by the user are sent to the child
4715 * but not to the shell. This means that an infinite loop started by
4716 * an interactive user may be hard to kill. With job control turned off,
4717 * an interactive user may place an interactive program inside a loop.
4718 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004719 * these interrupts to also abort the loop. The approach we take here
4720 * is to have the shell ignore interrupt signals while waiting for a
4721 * foreground process to terminate, and then send itself an interrupt
4722 * signal if the child process was terminated by an interrupt signal.
4723 * Unfortunately, some programs want to do a bit of cleanup and then
4724 * exit on interrupt; unless these processes terminate themselves by
4725 * sending a signal to themselves (instead of calling exit) they will
4726 * confuse this approach.
4727 *
4728 * Called with interrupts off.
4729 */
4730static int
4731waitforjob(struct job *jp)
4732{
4733 int st;
4734
4735 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004736
4737 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004738 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004739 /* In non-interactive shells, we _can_ get
4740 * a keyboard signal here and be EINTRed,
4741 * but we just loop back, waiting for command to complete.
4742 *
4743 * man bash:
4744 * "If bash is waiting for a command to complete and receives
4745 * a signal for which a trap has been set, the trap
4746 * will not be executed until the command completes."
4747 *
4748 * Reality is that even if trap is not set, bash
4749 * will not act on the signal until command completes.
4750 * Try this. sleep5intoff.c:
4751 * #include <signal.h>
4752 * #include <unistd.h>
4753 * int main() {
4754 * sigset_t set;
4755 * sigemptyset(&set);
4756 * sigaddset(&set, SIGINT);
4757 * sigaddset(&set, SIGQUIT);
4758 * sigprocmask(SIG_BLOCK, &set, NULL);
4759 * sleep(5);
4760 * return 0;
4761 * }
4762 * $ bash -c './sleep5intoff; echo hi'
4763 * ^C^C^C^C <--- pressing ^C once a second
4764 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004765 * $ bash -c './sleep5intoff; echo hi'
4766 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4767 * $ _
4768 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004769 dowait(DOWAIT_BLOCK, jp);
4770 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004771 INT_ON;
4772
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004773 st = getstatus(jp);
4774#if JOBS
4775 if (jp->jobctl) {
4776 xtcsetpgrp(ttyfd, rootpid);
4777 /*
4778 * This is truly gross.
4779 * If we're doing job control, then we did a TIOCSPGRP which
4780 * caused us (the shell) to no longer be in the controlling
4781 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4782 * intuit from the subprocess exit status whether a SIGINT
4783 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4784 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004785 if (jp->sigint) /* TODO: do the same with all signals */
4786 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004787 }
4788 if (jp->state == JOBDONE)
4789#endif
4790 freejob(jp);
4791 return st;
4792}
4793
4794/*
4795 * return 1 if there are stopped jobs, otherwise 0
4796 */
4797static int
4798stoppedjobs(void)
4799{
4800 struct job *jp;
4801 int retval;
4802
4803 retval = 0;
4804 if (job_warning)
4805 goto out;
4806 jp = curjob;
4807 if (jp && jp->state == JOBSTOPPED) {
4808 out2str("You have stopped jobs.\n");
4809 job_warning = 2;
4810 retval++;
4811 }
4812 out:
4813 return retval;
4814}
4815
4816
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004817/* ============ redir.c
4818 *
4819 * Code for dealing with input/output redirection.
4820 */
4821
4822#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004823#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004824
4825/*
4826 * Open a file in noclobber mode.
4827 * The code was copied from bash.
4828 */
4829static int
4830noclobberopen(const char *fname)
4831{
4832 int r, fd;
4833 struct stat finfo, finfo2;
4834
4835 /*
4836 * If the file exists and is a regular file, return an error
4837 * immediately.
4838 */
4839 r = stat(fname, &finfo);
4840 if (r == 0 && S_ISREG(finfo.st_mode)) {
4841 errno = EEXIST;
4842 return -1;
4843 }
4844
4845 /*
4846 * If the file was not present (r != 0), make sure we open it
4847 * exclusively so that if it is created before we open it, our open
4848 * will fail. Make sure that we do not truncate an existing file.
4849 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4850 * file was not a regular file, we leave O_EXCL off.
4851 */
4852 if (r != 0)
4853 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4854 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4855
4856 /* If the open failed, return the file descriptor right away. */
4857 if (fd < 0)
4858 return fd;
4859
4860 /*
4861 * OK, the open succeeded, but the file may have been changed from a
4862 * non-regular file to a regular file between the stat and the open.
4863 * We are assuming that the O_EXCL open handles the case where FILENAME
4864 * did not exist and is symlinked to an existing file between the stat
4865 * and open.
4866 */
4867
4868 /*
4869 * If we can open it and fstat the file descriptor, and neither check
4870 * revealed that it was a regular file, and the file has not been
4871 * replaced, return the file descriptor.
4872 */
4873 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4874 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4875 return fd;
4876
4877 /* The file has been replaced. badness. */
4878 close(fd);
4879 errno = EEXIST;
4880 return -1;
4881}
4882
4883/*
4884 * Handle here documents. Normally we fork off a process to write the
4885 * data to a pipe. If the document is short, we can stuff the data in
4886 * the pipe without forking.
4887 */
4888/* openhere needs this forward reference */
4889static void expandhere(union node *arg, int fd);
4890static int
4891openhere(union node *redir)
4892{
4893 int pip[2];
4894 size_t len = 0;
4895
4896 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004897 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004898 if (redir->type == NHERE) {
4899 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004900 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004901 full_write(pip[1], redir->nhere.doc->narg.text, len);
4902 goto out;
4903 }
4904 }
4905 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004906 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004907 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004908 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4909 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4910 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4911 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004912 signal(SIGPIPE, SIG_DFL);
4913 if (redir->type == NHERE)
4914 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004915 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004916 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004917 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004918 }
4919 out:
4920 close(pip[1]);
4921 return pip[0];
4922}
4923
4924static int
4925openredirect(union node *redir)
4926{
4927 char *fname;
4928 int f;
4929
4930 switch (redir->nfile.type) {
4931 case NFROM:
4932 fname = redir->nfile.expfname;
4933 f = open(fname, O_RDONLY);
4934 if (f < 0)
4935 goto eopen;
4936 break;
4937 case NFROMTO:
4938 fname = redir->nfile.expfname;
Andreas Bühmannda75f442010-06-24 04:32:37 +02004939 f = open(fname, O_RDWR|O_CREAT, 0666);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004940 if (f < 0)
4941 goto ecreate;
4942 break;
4943 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004944#if ENABLE_ASH_BASH_COMPAT
4945 case NTO2:
4946#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004947 /* Take care of noclobber mode. */
4948 if (Cflag) {
4949 fname = redir->nfile.expfname;
4950 f = noclobberopen(fname);
4951 if (f < 0)
4952 goto ecreate;
4953 break;
4954 }
4955 /* FALLTHROUGH */
4956 case NCLOBBER:
4957 fname = redir->nfile.expfname;
4958 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4959 if (f < 0)
4960 goto ecreate;
4961 break;
4962 case NAPPEND:
4963 fname = redir->nfile.expfname;
4964 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4965 if (f < 0)
4966 goto ecreate;
4967 break;
4968 default:
4969#if DEBUG
4970 abort();
4971#endif
4972 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004973/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004974// case NTOFD:
4975// case NFROMFD:
4976// f = -1;
4977// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004978 case NHERE:
4979 case NXHERE:
4980 f = openhere(redir);
4981 break;
4982 }
4983
4984 return f;
4985 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004986 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004987 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004988 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004989}
4990
4991/*
4992 * Copy a file descriptor to be >= to. Returns -1
4993 * if the source file descriptor is closed, EMPTY if there are no unused
4994 * file descriptors left.
4995 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004996/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4997 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004998enum {
4999 COPYFD_EXACT = (int)~(INT_MAX),
5000 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5001};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005002static int
5003copyfd(int from, int to)
5004{
5005 int newfd;
5006
Denis Vlasenko5a867312008-07-24 19:46:38 +00005007 if (to & COPYFD_EXACT) {
5008 to &= ~COPYFD_EXACT;
5009 /*if (from != to)*/
5010 newfd = dup2(from, to);
5011 } else {
5012 newfd = fcntl(from, F_DUPFD, to);
5013 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005014 if (newfd < 0) {
5015 if (errno == EMFILE)
5016 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005017 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005018 ash_msg_and_raise_error("%d: %m", from);
5019 }
5020 return newfd;
5021}
5022
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005023/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005024struct two_fd_t {
5025 int orig, copy;
5026};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005027struct redirtab {
5028 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005029 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005030 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005031 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005032};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005033#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005034
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005035static int need_to_remember(struct redirtab *rp, int fd)
5036{
5037 int i;
5038
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005039 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005040 return 0;
5041
5042 for (i = 0; i < rp->pair_count; i++) {
5043 if (rp->two_fd[i].orig == fd) {
5044 /* already remembered */
5045 return 0;
5046 }
5047 }
5048 return 1;
5049}
5050
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005051/* "hidden" fd is a fd used to read scripts, or a copy of such */
5052static int is_hidden_fd(struct redirtab *rp, int fd)
5053{
5054 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005055 struct parsefile *pf;
5056
5057 if (fd == -1)
5058 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005059 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005060 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005061 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005062 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005063 * $ ash # running ash interactively
5064 * $ . ./script.sh
5065 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005066 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005067 * it's still ok to use it: "read" builtin uses it,
5068 * why should we cripple "exec" builtin?
5069 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005070 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005071 return 1;
5072 }
5073 pf = pf->prev;
5074 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005075
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005076 if (!rp)
5077 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005078 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005079 fd |= COPYFD_RESTORE;
5080 for (i = 0; i < rp->pair_count; i++) {
5081 if (rp->two_fd[i].copy == fd) {
5082 return 1;
5083 }
5084 }
5085 return 0;
5086}
5087
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005088/*
5089 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5090 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005091 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005092 */
5093/* flags passed to redirect */
5094#define REDIR_PUSH 01 /* save previous values of file descriptors */
5095#define REDIR_SAVEFD2 03 /* set preverrout */
5096static void
5097redirect(union node *redir, int flags)
5098{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005100 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005101 int i;
5102 int fd;
5103 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005104 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005105
Denis Vlasenko01631112007-12-16 17:20:38 +00005106 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 if (!redir) {
5108 return;
5109 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005111 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005112 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005113 INT_OFF;
5114 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 union node *tmp = redir;
5116 do {
5117 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005118#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005119 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005120 sv_pos++;
5121#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 tmp = tmp->nfile.next;
5123 } while (tmp);
5124 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005125 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005126 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005127 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005128 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005129 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 while (sv_pos > 0) {
5131 sv_pos--;
5132 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5133 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005134 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005135
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005136 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005137 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005138 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005139 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005140 right_fd = redir->ndup.dupfd;
5141 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005142 /* redirect from/to same file descriptor? */
5143 if (right_fd == fd)
5144 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005145 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005146 if (is_hidden_fd(sv, right_fd)) {
5147 errno = EBADF; /* as if it is closed */
5148 ash_msg_and_raise_error("%d: %m", right_fd);
5149 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005150 newfd = -1;
5151 } else {
5152 newfd = openredirect(redir); /* always >= 0 */
5153 if (fd == newfd) {
5154 /* Descriptor wasn't open before redirect.
5155 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005156 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005157 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005158 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005159 continue;
5160 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005161 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005162#if ENABLE_ASH_BASH_COMPAT
5163 redirect_more:
5164#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005165 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005166 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005167 /* Careful to not accidentally "save"
5168 * to the same fd as right side fd in N>&M */
5169 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5170 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005171/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5172 * are closed in popredir() in the child, preventing them from leaking
5173 * into child. (popredir() also cleans up the mess in case of failures)
5174 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005175 if (i == -1) {
5176 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005177 if (i != EBADF) {
5178 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005179 if (newfd >= 0)
5180 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 errno = i;
5182 ash_msg_and_raise_error("%d: %m", fd);
5183 /* NOTREACHED */
5184 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005185 /* EBADF: it is not open - good, remember to close it */
5186 remember_to_close:
5187 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005188 } else { /* fd is open, save its copy */
5189 /* "exec fd>&-" should not close fds
5190 * which point to script file(s).
5191 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005192 if (is_hidden_fd(sv, fd))
5193 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005194 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005195 if (fd == 2)
5196 copied_fd2 = i;
5197 sv->two_fd[sv_pos].orig = fd;
5198 sv->two_fd[sv_pos].copy = i;
5199 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005200 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005201 if (newfd < 0) {
5202 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005203 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005204 /* Don't want to trigger debugging */
5205 if (fd != -1)
5206 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005207 } else {
5208 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005209 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005210 } else if (fd != newfd) { /* move newfd to fd */
5211 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005212#if ENABLE_ASH_BASH_COMPAT
5213 if (!(redir->nfile.type == NTO2 && fd == 2))
5214#endif
5215 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005216 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005217#if ENABLE_ASH_BASH_COMPAT
5218 if (redir->nfile.type == NTO2 && fd == 1) {
5219 /* We already redirected it to fd 1, now copy it to 2 */
5220 newfd = 1;
5221 fd = 2;
5222 goto redirect_more;
5223 }
5224#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005225 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005226
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005227 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005228 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5229 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005230}
5231
5232/*
5233 * Undo the effects of the last redirection.
5234 */
5235static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005236popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005237{
5238 struct redirtab *rp;
5239 int i;
5240
Denis Vlasenko01631112007-12-16 17:20:38 +00005241 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 return;
5243 INT_OFF;
5244 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005245 for (i = 0; i < rp->pair_count; i++) {
5246 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005247 int copy = rp->two_fd[i].copy;
5248 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005249 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005250 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005251 continue;
5252 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005253 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005254 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005255 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005256 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005257 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005258 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005259 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005260 }
5261 }
5262 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005263 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005264 free(rp);
5265 INT_ON;
5266}
5267
5268/*
5269 * Undo all redirections. Called on error or interrupt.
5270 */
5271
5272/*
5273 * Discard all saved file descriptors.
5274 */
5275static void
5276clearredir(int drop)
5277{
5278 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005279 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005280 if (!redirlist)
5281 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005282 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005283 }
5284}
5285
5286static int
5287redirectsafe(union node *redir, int flags)
5288{
5289 int err;
5290 volatile int saveint;
5291 struct jmploc *volatile savehandler = exception_handler;
5292 struct jmploc jmploc;
5293
5294 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005295 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5296 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005297 if (!err) {
5298 exception_handler = &jmploc;
5299 redirect(redir, flags);
5300 }
5301 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005302 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005303 longjmp(exception_handler->loc, 1);
5304 RESTORE_INT(saveint);
5305 return err;
5306}
5307
5308
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005309/* ============ Routines to expand arguments to commands
5310 *
5311 * We have to deal with backquotes, shell variables, and file metacharacters.
5312 */
5313
Mike Frysinger98c52642009-04-02 10:02:37 +00005314#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005315static arith_t
5316ash_arith(const char *s)
5317{
5318 arith_eval_hooks_t math_hooks;
5319 arith_t result;
5320 int errcode = 0;
5321
5322 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005323 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005324 math_hooks.endofname = endofname;
5325
5326 INT_OFF;
5327 result = arith(s, &errcode, &math_hooks);
5328 if (errcode < 0) {
5329 if (errcode == -3)
5330 ash_msg_and_raise_error("exponent less than 0");
5331 if (errcode == -2)
5332 ash_msg_and_raise_error("divide by zero");
5333 if (errcode == -5)
5334 ash_msg_and_raise_error("expression recursion loop detected");
5335 raise_error_syntax(s);
5336 }
5337 INT_ON;
5338
5339 return result;
5340}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005341#endif
5342
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005343/*
5344 * expandarg flags
5345 */
5346#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5347#define EXP_TILDE 0x2 /* do normal tilde expansion */
5348#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5349#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5350#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5351#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5352#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5353#define EXP_WORD 0x80 /* expand word in parameter expansion */
5354#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5355/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005356 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005357 */
5358#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5359#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5360#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5361#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5362#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5363
5364/*
5365 * Structure specifying which parts of the string should be searched
5366 * for IFS characters.
5367 */
5368struct ifsregion {
5369 struct ifsregion *next; /* next region in list */
5370 int begoff; /* offset of start of region */
5371 int endoff; /* offset of end of region */
5372 int nulonly; /* search for nul bytes only */
5373};
5374
5375struct arglist {
5376 struct strlist *list;
5377 struct strlist **lastp;
5378};
5379
5380/* output of current string */
5381static char *expdest;
5382/* list of back quote expressions */
5383static struct nodelist *argbackq;
5384/* first struct in list of ifs regions */
5385static struct ifsregion ifsfirst;
5386/* last struct in list */
5387static struct ifsregion *ifslastp;
5388/* holds expanded arg list */
5389static struct arglist exparg;
5390
5391/*
5392 * Our own itoa().
5393 */
5394static int
5395cvtnum(arith_t num)
5396{
5397 int len;
5398
5399 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005400 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005401 STADJUST(len, expdest);
5402 return len;
5403}
5404
5405static size_t
5406esclen(const char *start, const char *p)
5407{
5408 size_t esc = 0;
5409
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005410 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411 esc++;
5412 }
5413 return esc;
5414}
5415
5416/*
5417 * Remove any CTLESC characters from a string.
5418 */
5419static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005420rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005421{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005422 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005423
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005424 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005425 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005426 unsigned protect_against_glob;
5427 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005428
5429 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005430 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005431 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005432
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 q = p;
5434 r = str;
5435 if (flag & RMESCAPE_ALLOC) {
5436 size_t len = p - str;
5437 size_t fulllen = len + strlen(p) + 1;
5438
5439 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005440 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005441 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005442 /* p and str may be invalidated by makestrspace */
5443 str = (char *)stackblock() + strloc;
5444 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005445 } else if (flag & RMESCAPE_HEAP) {
5446 r = ckmalloc(fulllen);
5447 } else {
5448 r = stalloc(fulllen);
5449 }
5450 q = r;
5451 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005452 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005453 }
5454 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005455
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005456 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5457 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005458 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005459 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005460 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005461// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5462// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5463// Note: both inquotes and protect_against_glob only affect whether
5464// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005465 inquotes = ~inquotes;
5466 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005467 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 continue;
5469 }
5470 if (*p == '\\') {
5471 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005472 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005473 goto copy;
5474 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005475 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005476 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005477 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005478 *q++ = '\\';
5479 }
5480 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005481 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005482 copy:
5483 *q++ = *p++;
5484 }
5485 *q = '\0';
5486 if (flag & RMESCAPE_GROW) {
5487 expdest = r;
5488 STADJUST(q - r + 1, expdest);
5489 }
5490 return r;
5491}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005492#define pmatch(a, b) !fnmatch((a), (b), 0)
5493
5494/*
5495 * Prepare a pattern for a expmeta (internal glob(3)) call.
5496 *
5497 * Returns an stalloced string.
5498 */
5499static char *
5500preglob(const char *pattern, int quoted, int flag)
5501{
5502 flag |= RMESCAPE_GLOB;
5503 if (quoted) {
5504 flag |= RMESCAPE_QUOTED;
5505 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005506 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005507}
5508
5509/*
5510 * Put a string on the stack.
5511 */
5512static void
5513memtodest(const char *p, size_t len, int syntax, int quotes)
5514{
5515 char *q = expdest;
5516
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005517 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005518
5519 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005520 unsigned char c = *p++;
5521 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005522 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005523 if (quotes) {
5524 int n = SIT(c, syntax);
5525 if (n == CCTL || n == CBACK)
5526 USTPUTC(CTLESC, q);
5527 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005528 USTPUTC(c, q);
5529 }
5530
5531 expdest = q;
5532}
5533
5534static void
5535strtodest(const char *p, int syntax, int quotes)
5536{
5537 memtodest(p, strlen(p), syntax, quotes);
5538}
5539
5540/*
5541 * Record the fact that we have to scan this region of the
5542 * string for IFS characters.
5543 */
5544static void
5545recordregion(int start, int end, int nulonly)
5546{
5547 struct ifsregion *ifsp;
5548
5549 if (ifslastp == NULL) {
5550 ifsp = &ifsfirst;
5551 } else {
5552 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005553 ifsp = ckzalloc(sizeof(*ifsp));
5554 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005555 ifslastp->next = ifsp;
5556 INT_ON;
5557 }
5558 ifslastp = ifsp;
5559 ifslastp->begoff = start;
5560 ifslastp->endoff = end;
5561 ifslastp->nulonly = nulonly;
5562}
5563
5564static void
5565removerecordregions(int endoff)
5566{
5567 if (ifslastp == NULL)
5568 return;
5569
5570 if (ifsfirst.endoff > endoff) {
5571 while (ifsfirst.next != NULL) {
5572 struct ifsregion *ifsp;
5573 INT_OFF;
5574 ifsp = ifsfirst.next->next;
5575 free(ifsfirst.next);
5576 ifsfirst.next = ifsp;
5577 INT_ON;
5578 }
5579 if (ifsfirst.begoff > endoff)
5580 ifslastp = NULL;
5581 else {
5582 ifslastp = &ifsfirst;
5583 ifsfirst.endoff = endoff;
5584 }
5585 return;
5586 }
5587
5588 ifslastp = &ifsfirst;
5589 while (ifslastp->next && ifslastp->next->begoff < endoff)
5590 ifslastp=ifslastp->next;
5591 while (ifslastp->next != NULL) {
5592 struct ifsregion *ifsp;
5593 INT_OFF;
5594 ifsp = ifslastp->next->next;
5595 free(ifslastp->next);
5596 ifslastp->next = ifsp;
5597 INT_ON;
5598 }
5599 if (ifslastp->endoff > endoff)
5600 ifslastp->endoff = endoff;
5601}
5602
5603static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005604exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005605{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005606 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607 char *name;
5608 struct passwd *pw;
5609 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005610 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005611 int startloc;
5612
5613 name = p + 1;
5614
5615 while ((c = *++p) != '\0') {
5616 switch (c) {
5617 case CTLESC:
5618 return startp;
5619 case CTLQUOTEMARK:
5620 return startp;
5621 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005622 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005623 goto done;
5624 break;
5625 case '/':
5626 case CTLENDVAR:
5627 goto done;
5628 }
5629 }
5630 done:
5631 *p = '\0';
5632 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005633 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005634 } else {
5635 pw = getpwnam(name);
5636 if (pw == NULL)
5637 goto lose;
5638 home = pw->pw_dir;
5639 }
5640 if (!home || !*home)
5641 goto lose;
5642 *p = c;
5643 startloc = expdest - (char *)stackblock();
5644 strtodest(home, SQSYNTAX, quotes);
5645 recordregion(startloc, expdest - (char *)stackblock(), 0);
5646 return p;
5647 lose:
5648 *p = c;
5649 return startp;
5650}
5651
5652/*
5653 * Execute a command inside back quotes. If it's a builtin command, we
5654 * want to save its output in a block obtained from malloc. Otherwise
5655 * we fork off a subprocess and get the output of the command via a pipe.
5656 * Should be called with interrupts off.
5657 */
5658struct backcmd { /* result of evalbackcmd */
5659 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005660 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005661 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662 struct job *jp; /* job structure for command */
5663};
5664
5665/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005666static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005667#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005668static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005670static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671evalbackcmd(union node *n, struct backcmd *result)
5672{
5673 int saveherefd;
5674
5675 result->fd = -1;
5676 result->buf = NULL;
5677 result->nleft = 0;
5678 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005679 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005680 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005681
5682 saveherefd = herefd;
5683 herefd = -1;
5684
5685 {
5686 int pip[2];
5687 struct job *jp;
5688
5689 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005690 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005691 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005692 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5693 FORCE_INT_ON;
5694 close(pip[0]);
5695 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005696 /*close(1);*/
5697 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005698 close(pip[1]);
5699 }
5700 eflag = 0;
5701 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5702 /* NOTREACHED */
5703 }
5704 close(pip[1]);
5705 result->fd = pip[0];
5706 result->jp = jp;
5707 }
5708 herefd = saveherefd;
5709 out:
5710 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5711 result->fd, result->buf, result->nleft, result->jp));
5712}
5713
5714/*
5715 * Expand stuff in backwards quotes.
5716 */
5717static void
5718expbackq(union node *cmd, int quoted, int quotes)
5719{
5720 struct backcmd in;
5721 int i;
5722 char buf[128];
5723 char *p;
5724 char *dest;
5725 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005726 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005727 struct stackmark smark;
5728
5729 INT_OFF;
5730 setstackmark(&smark);
5731 dest = expdest;
5732 startloc = dest - (char *)stackblock();
5733 grabstackstr(dest);
5734 evalbackcmd(cmd, &in);
5735 popstackmark(&smark);
5736
5737 p = in.buf;
5738 i = in.nleft;
5739 if (i == 0)
5740 goto read;
5741 for (;;) {
5742 memtodest(p, i, syntax, quotes);
5743 read:
5744 if (in.fd < 0)
5745 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005746 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005747 TRACE(("expbackq: read returns %d\n", i));
5748 if (i <= 0)
5749 break;
5750 p = buf;
5751 }
5752
Denis Vlasenko60818682007-09-28 22:07:23 +00005753 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005754 if (in.fd >= 0) {
5755 close(in.fd);
5756 back_exitstatus = waitforjob(in.jp);
5757 }
5758 INT_ON;
5759
5760 /* Eat all trailing newlines */
5761 dest = expdest;
5762 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5763 STUNPUTC(dest);
5764 expdest = dest;
5765
5766 if (quoted == 0)
5767 recordregion(startloc, dest - (char *)stackblock(), 0);
5768 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5769 (dest - (char *)stackblock()) - startloc,
5770 (dest - (char *)stackblock()) - startloc,
5771 stackblock() + startloc));
5772}
5773
Mike Frysinger98c52642009-04-02 10:02:37 +00005774#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005775/*
5776 * Expand arithmetic expression. Backup to start of expression,
5777 * evaluate, place result in (backed up) result, adjust string position.
5778 */
5779static void
5780expari(int quotes)
5781{
5782 char *p, *start;
5783 int begoff;
5784 int flag;
5785 int len;
5786
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005787 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005788
5789 /*
5790 * This routine is slightly over-complicated for
5791 * efficiency. Next we scan backwards looking for the
5792 * start of arithmetic.
5793 */
5794 start = stackblock();
5795 p = expdest - 1;
5796 *p = '\0';
5797 p--;
5798 do {
5799 int esc;
5800
Denys Vlasenkocd716832009-11-28 22:14:02 +01005801 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005802 p--;
5803#if DEBUG
5804 if (p < start) {
5805 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5806 }
5807#endif
5808 }
5809
5810 esc = esclen(start, p);
5811 if (!(esc % 2)) {
5812 break;
5813 }
5814
5815 p -= esc + 1;
5816 } while (1);
5817
5818 begoff = p - start;
5819
5820 removerecordregions(begoff);
5821
5822 flag = p[1];
5823
5824 expdest = p;
5825
5826 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005827 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005828
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005829 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830
5831 if (flag != '"')
5832 recordregion(begoff, begoff + len, 0);
5833}
5834#endif
5835
5836/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005837static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005838
5839/*
5840 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5841 * characters to allow for further processing. Otherwise treat
5842 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005843 *
5844 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5845 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5846 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847 */
5848static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005849argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005850{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005851 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005852 '=',
5853 ':',
5854 CTLQUOTEMARK,
5855 CTLENDVAR,
5856 CTLESC,
5857 CTLVAR,
5858 CTLBACKQ,
5859 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005860#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861 CTLENDARI,
5862#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005863 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005864 };
5865 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005866 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5867 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005868 int inquotes;
5869 size_t length;
5870 int startloc;
5871
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005872 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005873 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005875 reject++;
5876 }
5877 inquotes = 0;
5878 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005879 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 char *q;
5881
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 tilde:
5884 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005886 q++;
5887 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005888 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005889 }
5890 start:
5891 startloc = expdest - (char *)stackblock();
5892 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005893 unsigned char c;
5894
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005895 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005896 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 if (c) {
5898 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005899#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005900 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005902 ) {
5903 /* c == '=' || c == ':' || c == CTLENDARI */
5904 length++;
5905 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005906 }
5907 if (length > 0) {
5908 int newloc;
5909 expdest = stack_nputstr(p, length, expdest);
5910 newloc = expdest - (char *)stackblock();
5911 if (breakall && !inquotes && newloc > startloc) {
5912 recordregion(startloc, newloc, 0);
5913 }
5914 startloc = newloc;
5915 }
5916 p += length + 1;
5917 length = 0;
5918
5919 switch (c) {
5920 case '\0':
5921 goto breakloop;
5922 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005923 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005924 p--;
5925 continue;
5926 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005927 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005928 reject++;
5929 /* fall through */
5930 case ':':
5931 /*
5932 * sort of a hack - expand tildes in variable
5933 * assignments (after the first '=' and after ':'s).
5934 */
5935 if (*--p == '~') {
5936 goto tilde;
5937 }
5938 continue;
5939 }
5940
5941 switch (c) {
5942 case CTLENDVAR: /* ??? */
5943 goto breakloop;
5944 case CTLQUOTEMARK:
5945 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005946 if (!inquotes
5947 && memcmp(p, dolatstr, 4) == 0
5948 && ( p[4] == CTLQUOTEMARK
5949 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5950 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005951 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005952 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005953 goto start;
5954 }
5955 inquotes = !inquotes;
5956 addquote:
5957 if (quotes) {
5958 p--;
5959 length++;
5960 startloc++;
5961 }
5962 break;
5963 case CTLESC:
5964 startloc++;
5965 length++;
5966 goto addquote;
5967 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005968 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005969 goto start;
5970 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005971 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005972 case CTLBACKQ|CTLQUOTE:
5973 expbackq(argbackq->n, c, quotes);
5974 argbackq = argbackq->next;
5975 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005976#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005977 case CTLENDARI:
5978 p--;
5979 expari(quotes);
5980 goto start;
5981#endif
5982 }
5983 }
5984 breakloop:
5985 ;
5986}
5987
5988static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005989scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005990 int zero)
5991{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005992// This commented out code was added by James Simmons <jsimmons@infradead.org>
5993// as part of a larger change when he added support for ${var/a/b}.
5994// However, it broke # and % operators:
5995//
5996//var=ababcdcd
5997// ok bad
5998//echo ${var#ab} abcdcd abcdcd
5999//echo ${var##ab} abcdcd abcdcd
6000//echo ${var#a*b} abcdcd ababcdcd (!)
6001//echo ${var##a*b} cdcd cdcd
6002//echo ${var#?} babcdcd ababcdcd (!)
6003//echo ${var##?} babcdcd babcdcd
6004//echo ${var#*} ababcdcd babcdcd (!)
6005//echo ${var##*}
6006//echo ${var%cd} ababcd ababcd
6007//echo ${var%%cd} ababcd abab (!)
6008//echo ${var%c*d} ababcd ababcd
6009//echo ${var%%c*d} abab ababcdcd (!)
6010//echo ${var%?} ababcdc ababcdc
6011//echo ${var%%?} ababcdc ababcdcd (!)
6012//echo ${var%*} ababcdcd ababcdcd
6013//echo ${var%%*}
6014//
6015// Commenting it back out helped. Remove it completely if it really
6016// is not needed.
6017
6018 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006019 char c;
6020
6021 loc = startp;
6022 loc2 = rmesc;
6023 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006024 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006025 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006026
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006027 c = *loc2;
6028 if (zero) {
6029 *loc2 = '\0';
6030 s = rmesc;
6031 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006032 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006033
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006034// // chop off end if its '*'
6035// full = strrchr(str, '*');
6036// if (full && full != str)
6037// match--;
6038//
6039// // If str starts with '*' replace with s.
6040// if ((*str == '*') && strlen(s) >= match) {
6041// full = xstrdup(s);
6042// strncpy(full+strlen(s)-match+1, str+1, match-1);
6043// } else
6044// full = xstrndup(str, match);
6045// match = strncmp(s, full, strlen(full));
6046// free(full);
6047//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006048 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006049 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006050 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006051 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006052 loc++;
6053 loc++;
6054 loc2++;
6055 } while (c);
6056 return 0;
6057}
6058
6059static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006060scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006061{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006062#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6063 int try2optimize = match_at_start;
6064#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006065 int esc = 0;
6066 char *loc;
6067 char *loc2;
6068
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006069 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6070 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6071 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6072 * Logic:
6073 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6074 * and on each iteration they go back two/one char until they reach the beginning.
6075 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6076 */
6077 /* TODO: document in what other circumstances we are called. */
6078
6079 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006080 int match;
6081 char c = *loc2;
6082 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006083 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006084 *loc2 = '\0';
6085 s = rmesc;
6086 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006087 match = pmatch(pattern, s);
6088 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006089 *loc2 = c;
6090 if (match)
6091 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006092#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6093 if (try2optimize) {
6094 /* Maybe we can optimize this:
6095 * if pattern ends with unescaped *, we can avoid checking
6096 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6097 * it wont match truncated "raw_value_of_" strings too.
6098 */
6099 unsigned plen = strlen(pattern);
6100 /* Does it end with "*"? */
6101 if (plen != 0 && pattern[--plen] == '*') {
6102 /* "xxxx*" is not escaped */
6103 /* "xxx\*" is escaped */
6104 /* "xx\\*" is not escaped */
6105 /* "x\\\*" is escaped */
6106 int slashes = 0;
6107 while (plen != 0 && pattern[--plen] == '\\')
6108 slashes++;
6109 if (!(slashes & 1))
6110 break; /* ends with unescaped "*" */
6111 }
6112 try2optimize = 0;
6113 }
6114#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006115 loc--;
6116 if (quotes) {
6117 if (--esc < 0) {
6118 esc = esclen(startp, loc);
6119 }
6120 if (esc % 2) {
6121 esc--;
6122 loc--;
6123 }
6124 }
6125 }
6126 return 0;
6127}
6128
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006129static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006130static void
6131varunset(const char *end, const char *var, const char *umsg, int varflags)
6132{
6133 const char *msg;
6134 const char *tail;
6135
6136 tail = nullstr;
6137 msg = "parameter not set";
6138 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006139 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006140 if (varflags & VSNUL)
6141 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006142 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006143 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006144 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145 }
6146 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6147}
6148
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006149#if ENABLE_ASH_BASH_COMPAT
6150static char *
6151parse_sub_pattern(char *arg, int inquotes)
6152{
6153 char *idx, *repl = NULL;
6154 unsigned char c;
6155
Denis Vlasenko2659c632008-06-14 06:04:59 +00006156 idx = arg;
6157 while (1) {
6158 c = *arg;
6159 if (!c)
6160 break;
6161 if (c == '/') {
6162 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006163 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006164 repl = idx + 1;
6165 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006166 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006167 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006168 *idx++ = c;
6169 if (!inquotes && c == '\\' && arg[1] == '\\')
6170 arg++; /* skip both \\, not just first one */
6171 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006172 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006173 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174
6175 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006176}
6177#endif /* ENABLE_ASH_BASH_COMPAT */
6178
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006179static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006180subevalvar(char *p, char *str, int strloc, int subtype,
6181 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006182{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006183 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006184 char *startp;
6185 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006186 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006187 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6188 IF_ASH_BASH_COMPAT(char null = '\0';)
6189 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006190 int saveherefd = herefd;
6191 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006192 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006193 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006194
6195 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006196 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6197 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006198 STPUTC('\0', expdest);
6199 herefd = saveherefd;
6200 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006201 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006202
6203 switch (subtype) {
6204 case VSASSIGN:
6205 setvar(str, startp, 0);
6206 amount = startp - expdest;
6207 STADJUST(amount, expdest);
6208 return startp;
6209
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006210#if ENABLE_ASH_BASH_COMPAT
6211 case VSSUBSTR:
6212 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006213 /* Read POS in ${var:POS:LEN} */
6214 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006215 len = str - startp - 1;
6216
6217 /* *loc != '\0', guaranteed by parser */
6218 if (quotes) {
6219 char *ptr;
6220
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006221 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006222 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006223 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006224 len--;
6225 ptr++;
6226 }
6227 }
6228 }
6229 orig_len = len;
6230
6231 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006232 /* ${var::LEN} */
6233 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006234 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006235 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006236 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006237 while (*loc && *loc != ':') {
6238 /* TODO?
6239 * bash complains on: var=qwe; echo ${var:1a:123}
6240 if (!isdigit(*loc))
6241 ash_msg_and_raise_error(msg_illnum, str);
6242 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006243 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006244 }
6245 if (*loc++ == ':') {
6246 len = number(loc);
6247 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006248 }
6249 if (pos >= orig_len) {
6250 pos = 0;
6251 len = 0;
6252 }
6253 if (len > (orig_len - pos))
6254 len = orig_len - pos;
6255
6256 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006257 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006258 str++;
6259 }
6260 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006261 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006262 *loc++ = *str++;
6263 *loc++ = *str++;
6264 }
6265 *loc = '\0';
6266 amount = loc - expdest;
6267 STADJUST(amount, expdest);
6268 return loc;
6269#endif
6270
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006271 case VSQUESTION:
6272 varunset(p, str, startp, varflags);
6273 /* NOTREACHED */
6274 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006275 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006276
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006277 /* We'll comeback here if we grow the stack while handling
6278 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6279 * stack will need rebasing, and we'll need to remove our work
6280 * areas each time
6281 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006282 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006283
6284 amount = expdest - ((char *)stackblock() + resetloc);
6285 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006286 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006287
6288 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006289 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006290 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006291 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006292 if (rmesc != startp) {
6293 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006294 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006295 }
6296 }
6297 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006298 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006299 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006300 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006301
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006302#if ENABLE_ASH_BASH_COMPAT
6303 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006304 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006305
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006306 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006307 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6308 if (!repl)
6309 repl = &null;
6310 }
6311
6312 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006313 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006314 return 0;
6315
6316 len = 0;
6317 idx = startp;
6318 end = str - 1;
6319 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006320 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006321 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6322 if (!loc) {
6323 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006324 char *restart_detect = stackblock();
6325 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006326 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006327 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006328 idx++;
6329 len++;
6330 STPUTC(*idx, expdest);
6331 }
6332 if (stackblock() != restart_detect)
6333 goto restart;
6334 idx++;
6335 len++;
6336 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006337 /* continue; - prone to quadratic behavior, smarter code: */
6338 if (idx >= end)
6339 break;
6340 if (str[0] == '*') {
6341 /* Pattern is "*foo". If "*foo" does not match "long_string",
6342 * it would never match "ong_string" etc, no point in trying.
6343 */
6344 goto skip_matching;
6345 }
6346 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006347 }
6348
6349 if (subtype == VSREPLACEALL) {
6350 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006351 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006352 idx++;
6353 idx++;
6354 rmesc++;
6355 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006356 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006357 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006358 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006359
6360 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006361 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006362 STPUTC(*loc, expdest);
6363 if (stackblock() != restart_detect)
6364 goto restart;
6365 len++;
6366 }
6367
6368 if (subtype == VSREPLACE) {
6369 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006370 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006371 STPUTC(*idx, expdest);
6372 if (stackblock() != restart_detect)
6373 goto restart;
6374 len++;
6375 idx++;
6376 }
6377 break;
6378 }
6379 }
6380
6381 /* We've put the replaced text into a buffer at workloc, now
6382 * move it to the right place and adjust the stack.
6383 */
6384 startp = stackblock() + startloc;
6385 STPUTC('\0', expdest);
6386 memmove(startp, stackblock() + workloc, len);
6387 startp[len++] = '\0';
6388 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6389 STADJUST(-amount, expdest);
6390 return startp;
6391 }
6392#endif /* ENABLE_ASH_BASH_COMPAT */
6393
6394 subtype -= VSTRIMRIGHT;
6395#if DEBUG
6396 if (subtype < 0 || subtype > 7)
6397 abort();
6398#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006399 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006400 zero = subtype >> 1;
6401 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6402 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6403
6404 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6405 if (loc) {
6406 if (zero) {
6407 memmove(startp, loc, str - loc);
6408 loc = startp + (str - loc) - 1;
6409 }
6410 *loc = '\0';
6411 amount = loc - expdest;
6412 STADJUST(amount, expdest);
6413 }
6414 return loc;
6415}
6416
6417/*
6418 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006419 * name parameter (examples):
6420 * ash -c 'echo $1' name:'1='
6421 * ash -c 'echo $qwe' name:'qwe='
6422 * ash -c 'echo $$' name:'$='
6423 * ash -c 'echo ${$}' name:'$='
6424 * ash -c 'echo ${$##q}' name:'$=q'
6425 * ash -c 'echo ${#$}' name:'$='
6426 * note: examples with bad shell syntax:
6427 * ash -c 'echo ${#$1}' name:'$=1'
6428 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006429 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006430static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006431varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006432{
Mike Frysinger98c52642009-04-02 10:02:37 +00006433 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006434 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006435 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006436 int sepq = 0;
6437 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006438 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006439 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006440 int quoted = varflags & VSQUOTE;
6441 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006442
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 switch (*name) {
6444 case '$':
6445 num = rootpid;
6446 goto numvar;
6447 case '?':
6448 num = exitstatus;
6449 goto numvar;
6450 case '#':
6451 num = shellparam.nparam;
6452 goto numvar;
6453 case '!':
6454 num = backgndpid;
6455 if (num == 0)
6456 return -1;
6457 numvar:
6458 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006459 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006460 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006461 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006462 for (i = NOPTS - 1; i >= 0; i--) {
6463 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006464 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006465 len++;
6466 }
6467 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006468 check_1char_name:
6469#if 0
6470 /* handles cases similar to ${#$1} */
6471 if (name[2] != '\0')
6472 raise_error_syntax("bad substitution");
6473#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006474 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006475 case '@': {
6476 char **ap;
6477 int sep;
6478
6479 if (quoted && (flags & EXP_FULL)) {
6480 /* note: this is not meant as PEOF value */
6481 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006483 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006484 /* fall through */
6485 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006486 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006487 i = SIT(sep, syntax);
6488 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006489 sepq = 1;
6490 param:
6491 ap = shellparam.p;
6492 if (!ap)
6493 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006494 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006495 size_t partlen;
6496
6497 partlen = strlen(p);
6498 len += partlen;
6499
6500 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6501 memtodest(p, partlen, syntax, quotes);
6502
6503 if (*ap && sep) {
6504 char *q;
6505
6506 len++;
6507 if (subtype == VSPLUS || subtype == VSLENGTH) {
6508 continue;
6509 }
6510 q = expdest;
6511 if (sepq)
6512 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006513 /* note: may put NUL despite sep != 0
6514 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006515 STPUTC(sep, q);
6516 expdest = q;
6517 }
6518 }
6519 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006520 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006521 case '0':
6522 case '1':
6523 case '2':
6524 case '3':
6525 case '4':
6526 case '5':
6527 case '6':
6528 case '7':
6529 case '8':
6530 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006531 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006532 if (num < 0 || num > shellparam.nparam)
6533 return -1;
6534 p = num ? shellparam.p[num - 1] : arg0;
6535 goto value;
6536 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006537 /* NB: name has form "VAR=..." */
6538
6539 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6540 * which should be considered before we check variables. */
6541 if (var_str_list) {
6542 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6543 p = NULL;
6544 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006545 char *str, *eq;
6546 str = var_str_list->text;
6547 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006548 if (!eq) /* stop at first non-assignment */
6549 break;
6550 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006551 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006552 && strncmp(str, name, name_len) == 0
6553 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006554 p = eq;
6555 /* goto value; - WRONG! */
6556 /* think "A=1 A=2 B=$A" */
6557 }
6558 var_str_list = var_str_list->next;
6559 } while (var_str_list);
6560 if (p)
6561 goto value;
6562 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006563 p = lookupvar(name);
6564 value:
6565 if (!p)
6566 return -1;
6567
6568 len = strlen(p);
6569 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6570 memtodest(p, len, syntax, quotes);
6571 return len;
6572 }
6573
6574 if (subtype == VSPLUS || subtype == VSLENGTH)
6575 STADJUST(-len, expdest);
6576 return len;
6577}
6578
6579/*
6580 * Expand a variable, and return a pointer to the next character in the
6581 * input string.
6582 */
6583static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006584evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006585{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006586 char varflags;
6587 char subtype;
6588 char quoted;
6589 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006590 char *var;
6591 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006592 int startloc;
6593 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006595 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006596 subtype = varflags & VSTYPE;
6597 quoted = varflags & VSQUOTE;
6598 var = p;
6599 easy = (!quoted || (*var == '@' && shellparam.nparam));
6600 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006601 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006602
6603 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006604 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006605 if (varflags & VSNUL)
6606 varlen--;
6607
6608 if (subtype == VSPLUS) {
6609 varlen = -1 - varlen;
6610 goto vsplus;
6611 }
6612
6613 if (subtype == VSMINUS) {
6614 vsplus:
6615 if (varlen < 0) {
6616 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006617 p, flags | EXP_TILDE |
6618 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006619 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006620 );
6621 goto end;
6622 }
6623 if (easy)
6624 goto record;
6625 goto end;
6626 }
6627
6628 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6629 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006630 if (subevalvar(p, var, /* strloc: */ 0,
6631 subtype, startloc, varflags,
6632 /* quotes: */ 0,
6633 var_str_list)
6634 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006635 varflags &= ~VSNUL;
6636 /*
6637 * Remove any recorded regions beyond
6638 * start of variable
6639 */
6640 removerecordregions(startloc);
6641 goto again;
6642 }
6643 goto end;
6644 }
6645 if (easy)
6646 goto record;
6647 goto end;
6648 }
6649
6650 if (varlen < 0 && uflag)
6651 varunset(p, var, 0, 0);
6652
6653 if (subtype == VSLENGTH) {
6654 cvtnum(varlen > 0 ? varlen : 0);
6655 goto record;
6656 }
6657
6658 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006659 if (easy)
6660 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006661 goto end;
6662 }
6663
6664#if DEBUG
6665 switch (subtype) {
6666 case VSTRIMLEFT:
6667 case VSTRIMLEFTMAX:
6668 case VSTRIMRIGHT:
6669 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006670#if ENABLE_ASH_BASH_COMPAT
6671 case VSSUBSTR:
6672 case VSREPLACE:
6673 case VSREPLACEALL:
6674#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006675 break;
6676 default:
6677 abort();
6678 }
6679#endif
6680
6681 if (varlen >= 0) {
6682 /*
6683 * Terminate the string and start recording the pattern
6684 * right after it
6685 */
6686 STPUTC('\0', expdest);
6687 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006688 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6689 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006690//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006691 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006692 var_str_list)
6693 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006694 int amount = expdest - (
6695 (char *)stackblock() + patloc - 1
6696 );
6697 STADJUST(-amount, expdest);
6698 }
6699 /* Remove any recorded regions beyond start of variable */
6700 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006701 record:
6702 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006703 }
6704
6705 end:
6706 if (subtype != VSNORMAL) { /* skip to end of alternative */
6707 int nesting = 1;
6708 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006709 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006710 if (c == CTLESC)
6711 p++;
6712 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6713 if (varlen >= 0)
6714 argbackq = argbackq->next;
6715 } else if (c == CTLVAR) {
6716 if ((*p++ & VSTYPE) != VSNORMAL)
6717 nesting++;
6718 } else if (c == CTLENDVAR) {
6719 if (--nesting == 0)
6720 break;
6721 }
6722 }
6723 }
6724 return p;
6725}
6726
6727/*
6728 * Break the argument string into pieces based upon IFS and add the
6729 * strings to the argument list. The regions of the string to be
6730 * searched for IFS characters have been stored by recordregion.
6731 */
6732static void
6733ifsbreakup(char *string, struct arglist *arglist)
6734{
6735 struct ifsregion *ifsp;
6736 struct strlist *sp;
6737 char *start;
6738 char *p;
6739 char *q;
6740 const char *ifs, *realifs;
6741 int ifsspc;
6742 int nulonly;
6743
6744 start = string;
6745 if (ifslastp != NULL) {
6746 ifsspc = 0;
6747 nulonly = 0;
6748 realifs = ifsset() ? ifsval() : defifs;
6749 ifsp = &ifsfirst;
6750 do {
6751 p = string + ifsp->begoff;
6752 nulonly = ifsp->nulonly;
6753 ifs = nulonly ? nullstr : realifs;
6754 ifsspc = 0;
6755 while (p < string + ifsp->endoff) {
6756 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006757 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006758 p++;
6759 if (!strchr(ifs, *p)) {
6760 p++;
6761 continue;
6762 }
6763 if (!nulonly)
6764 ifsspc = (strchr(defifs, *p) != NULL);
6765 /* Ignore IFS whitespace at start */
6766 if (q == start && ifsspc) {
6767 p++;
6768 start = p;
6769 continue;
6770 }
6771 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006772 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006773 sp->text = start;
6774 *arglist->lastp = sp;
6775 arglist->lastp = &sp->next;
6776 p++;
6777 if (!nulonly) {
6778 for (;;) {
6779 if (p >= string + ifsp->endoff) {
6780 break;
6781 }
6782 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006783 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006784 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006785 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006786 p = q;
6787 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006788 }
6789 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006790 if (ifsspc) {
6791 p++;
6792 ifsspc = 0;
6793 } else {
6794 p = q;
6795 break;
6796 }
6797 } else
6798 p++;
6799 }
6800 }
6801 start = p;
6802 } /* while */
6803 ifsp = ifsp->next;
6804 } while (ifsp != NULL);
6805 if (nulonly)
6806 goto add;
6807 }
6808
6809 if (!*start)
6810 return;
6811
6812 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006813 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006814 sp->text = start;
6815 *arglist->lastp = sp;
6816 arglist->lastp = &sp->next;
6817}
6818
6819static void
6820ifsfree(void)
6821{
6822 struct ifsregion *p;
6823
6824 INT_OFF;
6825 p = ifsfirst.next;
6826 do {
6827 struct ifsregion *ifsp;
6828 ifsp = p->next;
6829 free(p);
6830 p = ifsp;
6831 } while (p);
6832 ifslastp = NULL;
6833 ifsfirst.next = NULL;
6834 INT_ON;
6835}
6836
6837/*
6838 * Add a file name to the list.
6839 */
6840static void
6841addfname(const char *name)
6842{
6843 struct strlist *sp;
6844
Denis Vlasenko597906c2008-02-20 16:38:54 +00006845 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006846 sp->text = ststrdup(name);
6847 *exparg.lastp = sp;
6848 exparg.lastp = &sp->next;
6849}
6850
6851static char *expdir;
6852
6853/*
6854 * Do metacharacter (i.e. *, ?, [...]) expansion.
6855 */
6856static void
6857expmeta(char *enddir, char *name)
6858{
6859 char *p;
6860 const char *cp;
6861 char *start;
6862 char *endname;
6863 int metaflag;
6864 struct stat statb;
6865 DIR *dirp;
6866 struct dirent *dp;
6867 int atend;
6868 int matchdot;
6869
6870 metaflag = 0;
6871 start = name;
6872 for (p = name; *p; p++) {
6873 if (*p == '*' || *p == '?')
6874 metaflag = 1;
6875 else if (*p == '[') {
6876 char *q = p + 1;
6877 if (*q == '!')
6878 q++;
6879 for (;;) {
6880 if (*q == '\\')
6881 q++;
6882 if (*q == '/' || *q == '\0')
6883 break;
6884 if (*++q == ']') {
6885 metaflag = 1;
6886 break;
6887 }
6888 }
6889 } else if (*p == '\\')
6890 p++;
6891 else if (*p == '/') {
6892 if (metaflag)
6893 goto out;
6894 start = p + 1;
6895 }
6896 }
6897 out:
6898 if (metaflag == 0) { /* we've reached the end of the file name */
6899 if (enddir != expdir)
6900 metaflag++;
6901 p = name;
6902 do {
6903 if (*p == '\\')
6904 p++;
6905 *enddir++ = *p;
6906 } while (*p++);
6907 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6908 addfname(expdir);
6909 return;
6910 }
6911 endname = p;
6912 if (name < start) {
6913 p = name;
6914 do {
6915 if (*p == '\\')
6916 p++;
6917 *enddir++ = *p++;
6918 } while (p < start);
6919 }
6920 if (enddir == expdir) {
6921 cp = ".";
6922 } else if (enddir == expdir + 1 && *expdir == '/') {
6923 cp = "/";
6924 } else {
6925 cp = expdir;
6926 enddir[-1] = '\0';
6927 }
6928 dirp = opendir(cp);
6929 if (dirp == NULL)
6930 return;
6931 if (enddir != expdir)
6932 enddir[-1] = '/';
6933 if (*endname == 0) {
6934 atend = 1;
6935 } else {
6936 atend = 0;
6937 *endname++ = '\0';
6938 }
6939 matchdot = 0;
6940 p = start;
6941 if (*p == '\\')
6942 p++;
6943 if (*p == '.')
6944 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006945 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006946 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006947 continue;
6948 if (pmatch(start, dp->d_name)) {
6949 if (atend) {
6950 strcpy(enddir, dp->d_name);
6951 addfname(expdir);
6952 } else {
6953 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6954 continue;
6955 p[-1] = '/';
6956 expmeta(p, endname);
6957 }
6958 }
6959 }
6960 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006961 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006962 endname[-1] = '/';
6963}
6964
6965static struct strlist *
6966msort(struct strlist *list, int len)
6967{
6968 struct strlist *p, *q = NULL;
6969 struct strlist **lpp;
6970 int half;
6971 int n;
6972
6973 if (len <= 1)
6974 return list;
6975 half = len >> 1;
6976 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006977 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006978 q = p;
6979 p = p->next;
6980 }
6981 q->next = NULL; /* terminate first half of list */
6982 q = msort(list, half); /* sort first half of list */
6983 p = msort(p, len - half); /* sort second half */
6984 lpp = &list;
6985 for (;;) {
6986#if ENABLE_LOCALE_SUPPORT
6987 if (strcoll(p->text, q->text) < 0)
6988#else
6989 if (strcmp(p->text, q->text) < 0)
6990#endif
6991 {
6992 *lpp = p;
6993 lpp = &p->next;
6994 p = *lpp;
6995 if (p == NULL) {
6996 *lpp = q;
6997 break;
6998 }
6999 } else {
7000 *lpp = q;
7001 lpp = &q->next;
7002 q = *lpp;
7003 if (q == NULL) {
7004 *lpp = p;
7005 break;
7006 }
7007 }
7008 }
7009 return list;
7010}
7011
7012/*
7013 * Sort the results of file name expansion. It calculates the number of
7014 * strings to sort and then calls msort (short for merge sort) to do the
7015 * work.
7016 */
7017static struct strlist *
7018expsort(struct strlist *str)
7019{
7020 int len;
7021 struct strlist *sp;
7022
7023 len = 0;
7024 for (sp = str; sp; sp = sp->next)
7025 len++;
7026 return msort(str, len);
7027}
7028
7029static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007030expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007031{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007032 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007033 '*', '?', '[', 0
7034 };
7035 /* TODO - EXP_REDIR */
7036
7037 while (str) {
7038 struct strlist **savelastp;
7039 struct strlist *sp;
7040 char *p;
7041
7042 if (fflag)
7043 goto nometa;
7044 if (!strpbrk(str->text, metachars))
7045 goto nometa;
7046 savelastp = exparg.lastp;
7047
7048 INT_OFF;
7049 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7050 {
7051 int i = strlen(str->text);
7052 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7053 }
7054
7055 expmeta(expdir, p);
7056 free(expdir);
7057 if (p != str->text)
7058 free(p);
7059 INT_ON;
7060 if (exparg.lastp == savelastp) {
7061 /*
7062 * no matches
7063 */
7064 nometa:
7065 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007066 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007067 exparg.lastp = &str->next;
7068 } else {
7069 *exparg.lastp = NULL;
7070 *savelastp = sp = expsort(*savelastp);
7071 while (sp->next != NULL)
7072 sp = sp->next;
7073 exparg.lastp = &sp->next;
7074 }
7075 str = str->next;
7076 }
7077}
7078
7079/*
7080 * Perform variable substitution and command substitution on an argument,
7081 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7082 * perform splitting and file name expansion. When arglist is NULL, perform
7083 * here document expansion.
7084 */
7085static void
7086expandarg(union node *arg, struct arglist *arglist, int flag)
7087{
7088 struct strlist *sp;
7089 char *p;
7090
7091 argbackq = arg->narg.backquote;
7092 STARTSTACKSTR(expdest);
7093 ifsfirst.next = NULL;
7094 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007095 argstr(arg->narg.text, flag,
7096 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007097 p = _STPUTC('\0', expdest);
7098 expdest = p - 1;
7099 if (arglist == NULL) {
7100 return; /* here document expanded */
7101 }
7102 p = grabstackstr(p);
7103 exparg.lastp = &exparg.list;
7104 /*
7105 * TODO - EXP_REDIR
7106 */
7107 if (flag & EXP_FULL) {
7108 ifsbreakup(p, &exparg);
7109 *exparg.lastp = NULL;
7110 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007111 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007112 } else {
7113 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007114 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007115 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007116 sp->text = p;
7117 *exparg.lastp = sp;
7118 exparg.lastp = &sp->next;
7119 }
7120 if (ifsfirst.next)
7121 ifsfree();
7122 *exparg.lastp = NULL;
7123 if (exparg.list) {
7124 *arglist->lastp = exparg.list;
7125 arglist->lastp = exparg.lastp;
7126 }
7127}
7128
7129/*
7130 * Expand shell variables and backquotes inside a here document.
7131 */
7132static void
7133expandhere(union node *arg, int fd)
7134{
7135 herefd = fd;
7136 expandarg(arg, (struct arglist *)NULL, 0);
7137 full_write(fd, stackblock(), expdest - (char *)stackblock());
7138}
7139
7140/*
7141 * Returns true if the pattern matches the string.
7142 */
7143static int
7144patmatch(char *pattern, const char *string)
7145{
7146 return pmatch(preglob(pattern, 0, 0), string);
7147}
7148
7149/*
7150 * See if a pattern matches in a case statement.
7151 */
7152static int
7153casematch(union node *pattern, char *val)
7154{
7155 struct stackmark smark;
7156 int result;
7157
7158 setstackmark(&smark);
7159 argbackq = pattern->narg.backquote;
7160 STARTSTACKSTR(expdest);
7161 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007162 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7163 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007164 STACKSTRNUL(expdest);
7165 result = patmatch(stackblock(), val);
7166 popstackmark(&smark);
7167 return result;
7168}
7169
7170
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171/* ============ find_command */
7172
7173struct builtincmd {
7174 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007175 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176 /* unsigned flags; */
7177};
7178#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007179/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007180 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007182#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007183
7184struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007185 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007186 union param {
7187 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007188 /* index >= 0 for commands without path (slashes) */
7189 /* (TODO: what exactly does the value mean? PATH position?) */
7190 /* index == -1 for commands with slashes */
7191 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007192 const struct builtincmd *cmd;
7193 struct funcnode *func;
7194 } u;
7195};
7196/* values of cmdtype */
7197#define CMDUNKNOWN -1 /* no entry in table for command */
7198#define CMDNORMAL 0 /* command is an executable program */
7199#define CMDFUNCTION 1 /* command is a shell function */
7200#define CMDBUILTIN 2 /* command is a shell builtin */
7201
7202/* action to find_command() */
7203#define DO_ERR 0x01 /* prints errors */
7204#define DO_ABS 0x02 /* checks absolute paths */
7205#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7206#define DO_ALTPATH 0x08 /* using alternate path */
7207#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7208
7209static void find_command(char *, struct cmdentry *, int, const char *);
7210
7211
7212/* ============ Hashing commands */
7213
7214/*
7215 * When commands are first encountered, they are entered in a hash table.
7216 * This ensures that a full path search will not have to be done for them
7217 * on each invocation.
7218 *
7219 * We should investigate converting to a linear search, even though that
7220 * would make the command name "hash" a misnomer.
7221 */
7222
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007223struct tblentry {
7224 struct tblentry *next; /* next entry in hash chain */
7225 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007226 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007227 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007228 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007229};
7230
Denis Vlasenko01631112007-12-16 17:20:38 +00007231static struct tblentry **cmdtable;
7232#define INIT_G_cmdtable() do { \
7233 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7234} while (0)
7235
7236static int builtinloc = -1; /* index in path of %builtin, or -1 */
7237
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007238
7239static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007240tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007241{
7242 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007244#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007245 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007246 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007247 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007248 while (*envp)
7249 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007250 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007251 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007252 /* re-exec ourselves with the new arguments */
7253 execve(bb_busybox_exec_path, argv, envp);
7254 /* If they called chroot or otherwise made the binary no longer
7255 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007256 }
7257#endif
7258
7259 repeat:
7260#ifdef SYSV
7261 do {
7262 execve(cmd, argv, envp);
7263 } while (errno == EINTR);
7264#else
7265 execve(cmd, argv, envp);
7266#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007267 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007268 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007269 return;
7270 }
7271 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007272 char **ap;
7273 char **new;
7274
7275 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007276 continue;
7277 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007278 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007279 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280 ap += 2;
7281 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007282 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007283 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007284 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007285 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007286 goto repeat;
7287 }
7288}
7289
7290/*
7291 * Exec a program. Never returns. If you change this routine, you may
7292 * have to change the find_command routine as well.
7293 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007294static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007295static void
7296shellexec(char **argv, const char *path, int idx)
7297{
7298 char *cmdname;
7299 int e;
7300 char **envp;
7301 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007302#if ENABLE_FEATURE_SH_STANDALONE
7303 int applet_no = -1;
7304#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007305
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007306 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007307 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007308 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007309#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007310 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007311#endif
7312 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007313 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007314 e = errno;
7315 } else {
7316 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007317 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007318 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007319 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007320 if (errno != ENOENT && errno != ENOTDIR)
7321 e = errno;
7322 }
7323 stunalloc(cmdname);
7324 }
7325 }
7326
7327 /* Map to POSIX errors */
7328 switch (e) {
7329 case EACCES:
7330 exerrno = 126;
7331 break;
7332 case ENOENT:
7333 exerrno = 127;
7334 break;
7335 default:
7336 exerrno = 2;
7337 break;
7338 }
7339 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007340 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7341 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007342 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7343 /* NOTREACHED */
7344}
7345
7346static void
7347printentry(struct tblentry *cmdp)
7348{
7349 int idx;
7350 const char *path;
7351 char *name;
7352
7353 idx = cmdp->param.index;
7354 path = pathval();
7355 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007356 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007357 stunalloc(name);
7358 } while (--idx >= 0);
7359 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7360}
7361
7362/*
7363 * Clear out command entries. The argument specifies the first entry in
7364 * PATH which has changed.
7365 */
7366static void
7367clearcmdentry(int firstchange)
7368{
7369 struct tblentry **tblp;
7370 struct tblentry **pp;
7371 struct tblentry *cmdp;
7372
7373 INT_OFF;
7374 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7375 pp = tblp;
7376 while ((cmdp = *pp) != NULL) {
7377 if ((cmdp->cmdtype == CMDNORMAL &&
7378 cmdp->param.index >= firstchange)
7379 || (cmdp->cmdtype == CMDBUILTIN &&
7380 builtinloc >= firstchange)
7381 ) {
7382 *pp = cmdp->next;
7383 free(cmdp);
7384 } else {
7385 pp = &cmdp->next;
7386 }
7387 }
7388 }
7389 INT_ON;
7390}
7391
7392/*
7393 * Locate a command in the command hash table. If "add" is nonzero,
7394 * add the command to the table if it is not already present. The
7395 * variable "lastcmdentry" is set to point to the address of the link
7396 * pointing to the entry, so that delete_cmd_entry can delete the
7397 * entry.
7398 *
7399 * Interrupts must be off if called with add != 0.
7400 */
7401static struct tblentry **lastcmdentry;
7402
7403static struct tblentry *
7404cmdlookup(const char *name, int add)
7405{
7406 unsigned int hashval;
7407 const char *p;
7408 struct tblentry *cmdp;
7409 struct tblentry **pp;
7410
7411 p = name;
7412 hashval = (unsigned char)*p << 4;
7413 while (*p)
7414 hashval += (unsigned char)*p++;
7415 hashval &= 0x7FFF;
7416 pp = &cmdtable[hashval % CMDTABLESIZE];
7417 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7418 if (strcmp(cmdp->cmdname, name) == 0)
7419 break;
7420 pp = &cmdp->next;
7421 }
7422 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007423 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7424 + strlen(name)
7425 /* + 1 - already done because
7426 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007427 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007428 cmdp->cmdtype = CMDUNKNOWN;
7429 strcpy(cmdp->cmdname, name);
7430 }
7431 lastcmdentry = pp;
7432 return cmdp;
7433}
7434
7435/*
7436 * Delete the command entry returned on the last lookup.
7437 */
7438static void
7439delete_cmd_entry(void)
7440{
7441 struct tblentry *cmdp;
7442
7443 INT_OFF;
7444 cmdp = *lastcmdentry;
7445 *lastcmdentry = cmdp->next;
7446 if (cmdp->cmdtype == CMDFUNCTION)
7447 freefunc(cmdp->param.func);
7448 free(cmdp);
7449 INT_ON;
7450}
7451
7452/*
7453 * Add a new command entry, replacing any existing command entry for
7454 * the same name - except special builtins.
7455 */
7456static void
7457addcmdentry(char *name, struct cmdentry *entry)
7458{
7459 struct tblentry *cmdp;
7460
7461 cmdp = cmdlookup(name, 1);
7462 if (cmdp->cmdtype == CMDFUNCTION) {
7463 freefunc(cmdp->param.func);
7464 }
7465 cmdp->cmdtype = entry->cmdtype;
7466 cmdp->param = entry->u;
7467 cmdp->rehash = 0;
7468}
7469
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007470static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007471hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007472{
7473 struct tblentry **pp;
7474 struct tblentry *cmdp;
7475 int c;
7476 struct cmdentry entry;
7477 char *name;
7478
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007479 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007480 clearcmdentry(0);
7481 return 0;
7482 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007483
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007484 if (*argptr == NULL) {
7485 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7486 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7487 if (cmdp->cmdtype == CMDNORMAL)
7488 printentry(cmdp);
7489 }
7490 }
7491 return 0;
7492 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007493
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007494 c = 0;
7495 while ((name = *argptr) != NULL) {
7496 cmdp = cmdlookup(name, 0);
7497 if (cmdp != NULL
7498 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007499 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7500 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007501 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007502 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007503 find_command(name, &entry, DO_ERR, pathval());
7504 if (entry.cmdtype == CMDUNKNOWN)
7505 c = 1;
7506 argptr++;
7507 }
7508 return c;
7509}
7510
7511/*
7512 * Called when a cd is done. Marks all commands so the next time they
7513 * are executed they will be rehashed.
7514 */
7515static void
7516hashcd(void)
7517{
7518 struct tblentry **pp;
7519 struct tblentry *cmdp;
7520
7521 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7522 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007523 if (cmdp->cmdtype == CMDNORMAL
7524 || (cmdp->cmdtype == CMDBUILTIN
7525 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7526 && builtinloc > 0)
7527 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007528 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007529 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007530 }
7531 }
7532}
7533
7534/*
7535 * Fix command hash table when PATH changed.
7536 * Called before PATH is changed. The argument is the new value of PATH;
7537 * pathval() still returns the old value at this point.
7538 * Called with interrupts off.
7539 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007540static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007541changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007542{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007543 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007544 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007545 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007546 int idx_bltin;
7547
7548 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007549 firstchange = 9999; /* assume no change */
7550 idx = 0;
7551 idx_bltin = -1;
7552 for (;;) {
7553 if (*old != *new) {
7554 firstchange = idx;
7555 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007556 || (*old == ':' && *new == '\0')
7557 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007558 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007559 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007560 old = new; /* ignore subsequent differences */
7561 }
7562 if (*new == '\0')
7563 break;
7564 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7565 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007566 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007567 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007568 new++;
7569 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007570 }
7571 if (builtinloc < 0 && idx_bltin >= 0)
7572 builtinloc = idx_bltin; /* zap builtins */
7573 if (builtinloc >= 0 && idx_bltin < 0)
7574 firstchange = 0;
7575 clearcmdentry(firstchange);
7576 builtinloc = idx_bltin;
7577}
7578
7579#define TEOF 0
7580#define TNL 1
7581#define TREDIR 2
7582#define TWORD 3
7583#define TSEMI 4
7584#define TBACKGND 5
7585#define TAND 6
7586#define TOR 7
7587#define TPIPE 8
7588#define TLP 9
7589#define TRP 10
7590#define TENDCASE 11
7591#define TENDBQUOTE 12
7592#define TNOT 13
7593#define TCASE 14
7594#define TDO 15
7595#define TDONE 16
7596#define TELIF 17
7597#define TELSE 18
7598#define TESAC 19
7599#define TFI 20
7600#define TFOR 21
7601#define TIF 22
7602#define TIN 23
7603#define TTHEN 24
7604#define TUNTIL 25
7605#define TWHILE 26
7606#define TBEGIN 27
7607#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007608typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007609
7610/* first char is indicating which tokens mark the end of a list */
7611static const char *const tokname_array[] = {
7612 "\1end of file",
7613 "\0newline",
7614 "\0redirection",
7615 "\0word",
7616 "\0;",
7617 "\0&",
7618 "\0&&",
7619 "\0||",
7620 "\0|",
7621 "\0(",
7622 "\1)",
7623 "\1;;",
7624 "\1`",
7625#define KWDOFFSET 13
7626 /* the following are keywords */
7627 "\0!",
7628 "\0case",
7629 "\1do",
7630 "\1done",
7631 "\1elif",
7632 "\1else",
7633 "\1esac",
7634 "\1fi",
7635 "\0for",
7636 "\0if",
7637 "\0in",
7638 "\1then",
7639 "\0until",
7640 "\0while",
7641 "\0{",
7642 "\1}",
7643};
7644
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007645/* Wrapper around strcmp for qsort/bsearch/... */
7646static int
7647pstrcmp(const void *a, const void *b)
7648{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007649 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650}
7651
7652static const char *const *
7653findkwd(const char *s)
7654{
7655 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007656 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7657 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007658}
7659
7660/*
7661 * Locate and print what a word is...
7662 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007663static int
7664describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007665{
7666 struct cmdentry entry;
7667 struct tblentry *cmdp;
7668#if ENABLE_ASH_ALIAS
7669 const struct alias *ap;
7670#endif
7671 const char *path = pathval();
7672
7673 if (describe_command_verbose) {
7674 out1str(command);
7675 }
7676
7677 /* First look at the keywords */
7678 if (findkwd(command)) {
7679 out1str(describe_command_verbose ? " is a shell keyword" : command);
7680 goto out;
7681 }
7682
7683#if ENABLE_ASH_ALIAS
7684 /* Then look at the aliases */
7685 ap = lookupalias(command, 0);
7686 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007687 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007688 out1str("alias ");
7689 printalias(ap);
7690 return 0;
7691 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007692 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007693 goto out;
7694 }
7695#endif
7696 /* Then check if it is a tracked alias */
7697 cmdp = cmdlookup(command, 0);
7698 if (cmdp != NULL) {
7699 entry.cmdtype = cmdp->cmdtype;
7700 entry.u = cmdp->param;
7701 } else {
7702 /* Finally use brute force */
7703 find_command(command, &entry, DO_ABS, path);
7704 }
7705
7706 switch (entry.cmdtype) {
7707 case CMDNORMAL: {
7708 int j = entry.u.index;
7709 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007710 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007711 p = command;
7712 } else {
7713 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007714 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007715 stunalloc(p);
7716 } while (--j >= 0);
7717 }
7718 if (describe_command_verbose) {
7719 out1fmt(" is%s %s",
7720 (cmdp ? " a tracked alias for" : nullstr), p
7721 );
7722 } else {
7723 out1str(p);
7724 }
7725 break;
7726 }
7727
7728 case CMDFUNCTION:
7729 if (describe_command_verbose) {
7730 out1str(" is a shell function");
7731 } else {
7732 out1str(command);
7733 }
7734 break;
7735
7736 case CMDBUILTIN:
7737 if (describe_command_verbose) {
7738 out1fmt(" is a %sshell builtin",
7739 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7740 "special " : nullstr
7741 );
7742 } else {
7743 out1str(command);
7744 }
7745 break;
7746
7747 default:
7748 if (describe_command_verbose) {
7749 out1str(": not found\n");
7750 }
7751 return 127;
7752 }
7753 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007754 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007755 return 0;
7756}
7757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007758static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007759typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007760{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007761 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007762 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007763 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007764
Denis Vlasenko46846e22007-05-20 13:08:31 +00007765 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007766 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007767 i++;
7768 verbose = 0;
7769 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007770 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007771 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007772 }
7773 return err;
7774}
7775
7776#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007777static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007778commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007779{
7780 int c;
7781 enum {
7782 VERIFY_BRIEF = 1,
7783 VERIFY_VERBOSE = 2,
7784 } verify = 0;
7785
7786 while ((c = nextopt("pvV")) != '\0')
7787 if (c == 'V')
7788 verify |= VERIFY_VERBOSE;
7789 else if (c == 'v')
7790 verify |= VERIFY_BRIEF;
7791#if DEBUG
7792 else if (c != 'p')
7793 abort();
7794#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007795 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7796 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007797 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007798 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007799
7800 return 0;
7801}
7802#endif
7803
7804
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007805/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007806
Denis Vlasenko340299a2008-11-21 10:36:36 +00007807static int funcblocksize; /* size of structures in function */
7808static int funcstringsize; /* size of strings in node */
7809static void *funcblock; /* block to allocate function from */
7810static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007811
Eric Andersencb57d552001-06-28 07:25:16 +00007812/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007813#define EV_EXIT 01 /* exit after evaluating tree */
7814#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007815#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007816
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007817static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007818 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7819 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7820 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7821 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7822 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7823 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7824 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7825 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7827 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7828 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7829 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7830 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7831 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7832 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7833 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7834 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007835#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007836 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007837#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007838 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7839 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7840 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7842 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7843 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7844 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7845 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7846 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007847};
7848
7849static void calcsize(union node *n);
7850
7851static void
7852sizenodelist(struct nodelist *lp)
7853{
7854 while (lp) {
7855 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7856 calcsize(lp->n);
7857 lp = lp->next;
7858 }
7859}
7860
7861static void
7862calcsize(union node *n)
7863{
7864 if (n == NULL)
7865 return;
7866 funcblocksize += nodesize[n->type];
7867 switch (n->type) {
7868 case NCMD:
7869 calcsize(n->ncmd.redirect);
7870 calcsize(n->ncmd.args);
7871 calcsize(n->ncmd.assign);
7872 break;
7873 case NPIPE:
7874 sizenodelist(n->npipe.cmdlist);
7875 break;
7876 case NREDIR:
7877 case NBACKGND:
7878 case NSUBSHELL:
7879 calcsize(n->nredir.redirect);
7880 calcsize(n->nredir.n);
7881 break;
7882 case NAND:
7883 case NOR:
7884 case NSEMI:
7885 case NWHILE:
7886 case NUNTIL:
7887 calcsize(n->nbinary.ch2);
7888 calcsize(n->nbinary.ch1);
7889 break;
7890 case NIF:
7891 calcsize(n->nif.elsepart);
7892 calcsize(n->nif.ifpart);
7893 calcsize(n->nif.test);
7894 break;
7895 case NFOR:
7896 funcstringsize += strlen(n->nfor.var) + 1;
7897 calcsize(n->nfor.body);
7898 calcsize(n->nfor.args);
7899 break;
7900 case NCASE:
7901 calcsize(n->ncase.cases);
7902 calcsize(n->ncase.expr);
7903 break;
7904 case NCLIST:
7905 calcsize(n->nclist.body);
7906 calcsize(n->nclist.pattern);
7907 calcsize(n->nclist.next);
7908 break;
7909 case NDEFUN:
7910 case NARG:
7911 sizenodelist(n->narg.backquote);
7912 funcstringsize += strlen(n->narg.text) + 1;
7913 calcsize(n->narg.next);
7914 break;
7915 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007916#if ENABLE_ASH_BASH_COMPAT
7917 case NTO2:
7918#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007919 case NCLOBBER:
7920 case NFROM:
7921 case NFROMTO:
7922 case NAPPEND:
7923 calcsize(n->nfile.fname);
7924 calcsize(n->nfile.next);
7925 break;
7926 case NTOFD:
7927 case NFROMFD:
7928 calcsize(n->ndup.vname);
7929 calcsize(n->ndup.next);
7930 break;
7931 case NHERE:
7932 case NXHERE:
7933 calcsize(n->nhere.doc);
7934 calcsize(n->nhere.next);
7935 break;
7936 case NNOT:
7937 calcsize(n->nnot.com);
7938 break;
7939 };
7940}
7941
7942static char *
7943nodeckstrdup(char *s)
7944{
7945 char *rtn = funcstring;
7946
7947 strcpy(funcstring, s);
7948 funcstring += strlen(s) + 1;
7949 return rtn;
7950}
7951
7952static union node *copynode(union node *);
7953
7954static struct nodelist *
7955copynodelist(struct nodelist *lp)
7956{
7957 struct nodelist *start;
7958 struct nodelist **lpp;
7959
7960 lpp = &start;
7961 while (lp) {
7962 *lpp = funcblock;
7963 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7964 (*lpp)->n = copynode(lp->n);
7965 lp = lp->next;
7966 lpp = &(*lpp)->next;
7967 }
7968 *lpp = NULL;
7969 return start;
7970}
7971
7972static union node *
7973copynode(union node *n)
7974{
7975 union node *new;
7976
7977 if (n == NULL)
7978 return NULL;
7979 new = funcblock;
7980 funcblock = (char *) funcblock + nodesize[n->type];
7981
7982 switch (n->type) {
7983 case NCMD:
7984 new->ncmd.redirect = copynode(n->ncmd.redirect);
7985 new->ncmd.args = copynode(n->ncmd.args);
7986 new->ncmd.assign = copynode(n->ncmd.assign);
7987 break;
7988 case NPIPE:
7989 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007990 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007991 break;
7992 case NREDIR:
7993 case NBACKGND:
7994 case NSUBSHELL:
7995 new->nredir.redirect = copynode(n->nredir.redirect);
7996 new->nredir.n = copynode(n->nredir.n);
7997 break;
7998 case NAND:
7999 case NOR:
8000 case NSEMI:
8001 case NWHILE:
8002 case NUNTIL:
8003 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8004 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8005 break;
8006 case NIF:
8007 new->nif.elsepart = copynode(n->nif.elsepart);
8008 new->nif.ifpart = copynode(n->nif.ifpart);
8009 new->nif.test = copynode(n->nif.test);
8010 break;
8011 case NFOR:
8012 new->nfor.var = nodeckstrdup(n->nfor.var);
8013 new->nfor.body = copynode(n->nfor.body);
8014 new->nfor.args = copynode(n->nfor.args);
8015 break;
8016 case NCASE:
8017 new->ncase.cases = copynode(n->ncase.cases);
8018 new->ncase.expr = copynode(n->ncase.expr);
8019 break;
8020 case NCLIST:
8021 new->nclist.body = copynode(n->nclist.body);
8022 new->nclist.pattern = copynode(n->nclist.pattern);
8023 new->nclist.next = copynode(n->nclist.next);
8024 break;
8025 case NDEFUN:
8026 case NARG:
8027 new->narg.backquote = copynodelist(n->narg.backquote);
8028 new->narg.text = nodeckstrdup(n->narg.text);
8029 new->narg.next = copynode(n->narg.next);
8030 break;
8031 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008032#if ENABLE_ASH_BASH_COMPAT
8033 case NTO2:
8034#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008035 case NCLOBBER:
8036 case NFROM:
8037 case NFROMTO:
8038 case NAPPEND:
8039 new->nfile.fname = copynode(n->nfile.fname);
8040 new->nfile.fd = n->nfile.fd;
8041 new->nfile.next = copynode(n->nfile.next);
8042 break;
8043 case NTOFD:
8044 case NFROMFD:
8045 new->ndup.vname = copynode(n->ndup.vname);
8046 new->ndup.dupfd = n->ndup.dupfd;
8047 new->ndup.fd = n->ndup.fd;
8048 new->ndup.next = copynode(n->ndup.next);
8049 break;
8050 case NHERE:
8051 case NXHERE:
8052 new->nhere.doc = copynode(n->nhere.doc);
8053 new->nhere.fd = n->nhere.fd;
8054 new->nhere.next = copynode(n->nhere.next);
8055 break;
8056 case NNOT:
8057 new->nnot.com = copynode(n->nnot.com);
8058 break;
8059 };
8060 new->type = n->type;
8061 return new;
8062}
8063
8064/*
8065 * Make a copy of a parse tree.
8066 */
8067static struct funcnode *
8068copyfunc(union node *n)
8069{
8070 struct funcnode *f;
8071 size_t blocksize;
8072
8073 funcblocksize = offsetof(struct funcnode, n);
8074 funcstringsize = 0;
8075 calcsize(n);
8076 blocksize = funcblocksize;
8077 f = ckmalloc(blocksize + funcstringsize);
8078 funcblock = (char *) f + offsetof(struct funcnode, n);
8079 funcstring = (char *) f + blocksize;
8080 copynode(n);
8081 f->count = 0;
8082 return f;
8083}
8084
8085/*
8086 * Define a shell function.
8087 */
8088static void
8089defun(char *name, union node *func)
8090{
8091 struct cmdentry entry;
8092
8093 INT_OFF;
8094 entry.cmdtype = CMDFUNCTION;
8095 entry.u.func = copyfunc(func);
8096 addcmdentry(name, &entry);
8097 INT_ON;
8098}
8099
Denis Vlasenko4b875702009-03-19 13:30:04 +00008100/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008101#define SKIPBREAK (1 << 0)
8102#define SKIPCONT (1 << 1)
8103#define SKIPFUNC (1 << 2)
8104#define SKIPFILE (1 << 3)
8105#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008106static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008107static int skipcount; /* number of levels to skip */
8108static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008109static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008110
Denis Vlasenko4b875702009-03-19 13:30:04 +00008111/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008112static int evalstring(char *s, int mask);
8113
Denis Vlasenko4b875702009-03-19 13:30:04 +00008114/* Called to execute a trap.
8115 * Single callsite - at the end of evaltree().
8116 * If we return non-zero, exaltree raises EXEXIT exception.
8117 *
8118 * Perhaps we should avoid entering new trap handlers
8119 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008120 */
8121static int
8122dotrap(void)
8123{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008124 uint8_t *g;
8125 int sig;
8126 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008127
8128 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008129 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008130 xbarrier();
8131
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008132 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008133 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8134 int want_exexit;
8135 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008136
Denis Vlasenko4b875702009-03-19 13:30:04 +00008137 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008138 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008139 t = trap[sig];
8140 /* non-trapped SIGINT is handled separately by raise_interrupt,
8141 * don't upset it by resetting gotsig[SIGINT-1] */
8142 if (sig == SIGINT && !t)
8143 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008144
8145 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008146 *g = 0;
8147 if (!t)
8148 continue;
8149 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008150 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008151 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008152 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008153 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008154 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008155 }
8156
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008157 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008158 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008159}
8160
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008161/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008162static void evalloop(union node *, int);
8163static void evalfor(union node *, int);
8164static void evalcase(union node *, int);
8165static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008166static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008167static void evalpipe(union node *, int);
8168static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008169static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008170static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008171
Eric Andersen62483552001-07-10 06:09:16 +00008172/*
Eric Andersenc470f442003-07-28 09:56:35 +00008173 * Evaluate a parse tree. The value is left in the global variable
8174 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008175 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008176static void
Eric Andersenc470f442003-07-28 09:56:35 +00008177evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008178{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008179 struct jmploc *volatile savehandler = exception_handler;
8180 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008181 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008182 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008183 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008184 int int_level;
8185
8186 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008187
Eric Andersenc470f442003-07-28 09:56:35 +00008188 if (n == NULL) {
8189 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008190 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008191 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008192 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008193
8194 exception_handler = &jmploc;
8195 {
8196 int err = setjmp(jmploc.loc);
8197 if (err) {
8198 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008199 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008200 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8201 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008202 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008203 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008204 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008205 TRACE(("exception %d in evaltree, propagating err=%d\n",
8206 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008207 exception_handler = savehandler;
8208 longjmp(exception_handler->loc, err);
8209 }
8210 }
8211
Eric Andersenc470f442003-07-28 09:56:35 +00008212 switch (n->type) {
8213 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008214#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008215 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008216 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008217 break;
8218#endif
8219 case NNOT:
8220 evaltree(n->nnot.com, EV_TESTED);
8221 status = !exitstatus;
8222 goto setstatus;
8223 case NREDIR:
8224 expredir(n->nredir.redirect);
8225 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8226 if (!status) {
8227 evaltree(n->nredir.n, flags & EV_TESTED);
8228 status = exitstatus;
8229 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008230 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008231 goto setstatus;
8232 case NCMD:
8233 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008234 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008235 if (eflag && !(flags & EV_TESTED))
8236 checkexit = ~0;
8237 goto calleval;
8238 case NFOR:
8239 evalfn = evalfor;
8240 goto calleval;
8241 case NWHILE:
8242 case NUNTIL:
8243 evalfn = evalloop;
8244 goto calleval;
8245 case NSUBSHELL:
8246 case NBACKGND:
8247 evalfn = evalsubshell;
8248 goto calleval;
8249 case NPIPE:
8250 evalfn = evalpipe;
8251 goto checkexit;
8252 case NCASE:
8253 evalfn = evalcase;
8254 goto calleval;
8255 case NAND:
8256 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008257 case NSEMI: {
8258
Eric Andersenc470f442003-07-28 09:56:35 +00008259#if NAND + 1 != NOR
8260#error NAND + 1 != NOR
8261#endif
8262#if NOR + 1 != NSEMI
8263#error NOR + 1 != NSEMI
8264#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008265 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008266 evaltree(
8267 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008268 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008269 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008270 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008271 break;
8272 if (!evalskip) {
8273 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008274 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008275 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008276 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008277 evalfn(n, flags);
8278 break;
8279 }
8280 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008281 }
Eric Andersenc470f442003-07-28 09:56:35 +00008282 case NIF:
8283 evaltree(n->nif.test, EV_TESTED);
8284 if (evalskip)
8285 break;
8286 if (exitstatus == 0) {
8287 n = n->nif.ifpart;
8288 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008289 }
8290 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008291 n = n->nif.elsepart;
8292 goto evaln;
8293 }
8294 goto success;
8295 case NDEFUN:
8296 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008297 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008298 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008299 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008300 exitstatus = status;
8301 break;
8302 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008303
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008304 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008305 exception_handler = savehandler;
8306 out1:
8307 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008308 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008309 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008310 goto exexit;
8311
8312 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008313 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008314 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008315 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008316
8317 RESTORE_INT(int_level);
8318 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008319}
8320
Eric Andersenc470f442003-07-28 09:56:35 +00008321#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8322static
8323#endif
8324void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8325
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008326static void
Eric Andersenc470f442003-07-28 09:56:35 +00008327evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008328{
8329 int status;
8330
8331 loopnest++;
8332 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008333 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008334 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008335 int i;
8336
Eric Andersencb57d552001-06-28 07:25:16 +00008337 evaltree(n->nbinary.ch1, EV_TESTED);
8338 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008339 skipping:
8340 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008341 evalskip = 0;
8342 continue;
8343 }
8344 if (evalskip == SKIPBREAK && --skipcount <= 0)
8345 evalskip = 0;
8346 break;
8347 }
Eric Andersenc470f442003-07-28 09:56:35 +00008348 i = exitstatus;
8349 if (n->type != NWHILE)
8350 i = !i;
8351 if (i != 0)
8352 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008353 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008354 status = exitstatus;
8355 if (evalskip)
8356 goto skipping;
8357 }
8358 loopnest--;
8359 exitstatus = status;
8360}
8361
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008362static void
Eric Andersenc470f442003-07-28 09:56:35 +00008363evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008364{
8365 struct arglist arglist;
8366 union node *argp;
8367 struct strlist *sp;
8368 struct stackmark smark;
8369
8370 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008371 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008372 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008373 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008374 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008375 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008376 if (evalskip)
8377 goto out;
8378 }
8379 *arglist.lastp = NULL;
8380
8381 exitstatus = 0;
8382 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008383 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008384 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008385 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008386 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008387 if (evalskip) {
8388 if (evalskip == SKIPCONT && --skipcount <= 0) {
8389 evalskip = 0;
8390 continue;
8391 }
8392 if (evalskip == SKIPBREAK && --skipcount <= 0)
8393 evalskip = 0;
8394 break;
8395 }
8396 }
8397 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008398 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008399 popstackmark(&smark);
8400}
8401
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008402static void
Eric Andersenc470f442003-07-28 09:56:35 +00008403evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008404{
8405 union node *cp;
8406 union node *patp;
8407 struct arglist arglist;
8408 struct stackmark smark;
8409
8410 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008411 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008412 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008413 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008414 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008415 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8416 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008417 if (casematch(patp, arglist.list->text)) {
8418 if (evalskip == 0) {
8419 evaltree(cp->nclist.body, flags);
8420 }
8421 goto out;
8422 }
8423 }
8424 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008425 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008426 popstackmark(&smark);
8427}
8428
Eric Andersenc470f442003-07-28 09:56:35 +00008429/*
8430 * Kick off a subshell to evaluate a tree.
8431 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008432static void
Eric Andersenc470f442003-07-28 09:56:35 +00008433evalsubshell(union node *n, int flags)
8434{
8435 struct job *jp;
8436 int backgnd = (n->type == NBACKGND);
8437 int status;
8438
8439 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008440 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008441 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008442 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008443 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008444 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008445 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008446 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008447 flags |= EV_EXIT;
8448 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008449 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008450 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008451 redirect(n->nredir.redirect, 0);
8452 evaltreenr(n->nredir.n, flags);
8453 /* never returns */
8454 }
8455 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008456 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008457 status = waitforjob(jp);
8458 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008459 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008460}
8461
Eric Andersenc470f442003-07-28 09:56:35 +00008462/*
8463 * Compute the names of the files in a redirection list.
8464 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008465static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008466static void
8467expredir(union node *n)
8468{
8469 union node *redir;
8470
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008471 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008472 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008473
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008474 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008475 fn.lastp = &fn.list;
8476 switch (redir->type) {
8477 case NFROMTO:
8478 case NFROM:
8479 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008480#if ENABLE_ASH_BASH_COMPAT
8481 case NTO2:
8482#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008483 case NCLOBBER:
8484 case NAPPEND:
8485 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008486#if ENABLE_ASH_BASH_COMPAT
8487 store_expfname:
8488#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008489 redir->nfile.expfname = fn.list->text;
8490 break;
8491 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008492 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008493 if (redir->ndup.vname) {
8494 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008495 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008496 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008497#if ENABLE_ASH_BASH_COMPAT
8498//FIXME: we used expandarg with different args!
8499 if (!isdigit_str9(fn.list->text)) {
8500 /* >&file, not >&fd */
8501 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8502 ash_msg_and_raise_error("redir error");
8503 redir->type = NTO2;
8504 goto store_expfname;
8505 }
8506#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008507 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008508 }
8509 break;
8510 }
8511 }
8512}
8513
Eric Andersencb57d552001-06-28 07:25:16 +00008514/*
Eric Andersencb57d552001-06-28 07:25:16 +00008515 * Evaluate a pipeline. All the processes in the pipeline are children
8516 * of the process creating the pipeline. (This differs from some versions
8517 * of the shell, which make the last process in a pipeline the parent
8518 * of all the rest.)
8519 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008520static void
Eric Andersenc470f442003-07-28 09:56:35 +00008521evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008522{
8523 struct job *jp;
8524 struct nodelist *lp;
8525 int pipelen;
8526 int prevfd;
8527 int pip[2];
8528
Eric Andersenc470f442003-07-28 09:56:35 +00008529 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008530 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008531 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008532 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008533 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008534 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008535 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008536 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008537 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008538 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008539 pip[1] = -1;
8540 if (lp->next) {
8541 if (pipe(pip) < 0) {
8542 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008543 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008544 }
8545 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008546 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008547 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008548 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008549 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008550 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008551 if (prevfd > 0) {
8552 dup2(prevfd, 0);
8553 close(prevfd);
8554 }
8555 if (pip[1] > 1) {
8556 dup2(pip[1], 1);
8557 close(pip[1]);
8558 }
Eric Andersenc470f442003-07-28 09:56:35 +00008559 evaltreenr(lp->n, flags);
8560 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008561 }
8562 if (prevfd >= 0)
8563 close(prevfd);
8564 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008565 /* Don't want to trigger debugging */
8566 if (pip[1] != -1)
8567 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008568 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008569 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008570 exitstatus = waitforjob(jp);
8571 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008572 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008573 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008574}
8575
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008576/*
8577 * Controls whether the shell is interactive or not.
8578 */
8579static void
8580setinteractive(int on)
8581{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008582 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008583
8584 if (++on == is_interactive)
8585 return;
8586 is_interactive = on;
8587 setsignal(SIGINT);
8588 setsignal(SIGQUIT);
8589 setsignal(SIGTERM);
8590#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8591 if (is_interactive > 1) {
8592 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008593 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008594
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008595 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008596 /* note: ash and hush share this string */
8597 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008598 "Enter 'help' for a list of built-in commands."
8599 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008600 bb_banner,
8601 "built-in shell (ash)"
8602 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008603 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008604 }
8605 }
8606#endif
8607}
8608
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008609static void
8610optschanged(void)
8611{
8612#if DEBUG
8613 opentrace();
8614#endif
8615 setinteractive(iflag);
8616 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008617#if ENABLE_FEATURE_EDITING_VI
8618 if (viflag)
8619 line_input_state->flags |= VI_MODE;
8620 else
8621 line_input_state->flags &= ~VI_MODE;
8622#else
8623 viflag = 0; /* forcibly keep the option off */
8624#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008625}
8626
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008627static struct localvar *localvars;
8628
8629/*
8630 * Called after a function returns.
8631 * Interrupts must be off.
8632 */
8633static void
8634poplocalvars(void)
8635{
8636 struct localvar *lvp;
8637 struct var *vp;
8638
8639 while ((lvp = localvars) != NULL) {
8640 localvars = lvp->next;
8641 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008642 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008643 if (vp == NULL) { /* $- saved */
8644 memcpy(optlist, lvp->text, sizeof(optlist));
8645 free((char*)lvp->text);
8646 optschanged();
8647 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008648 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008649 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008650 if (vp->var_func)
8651 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008652 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008653 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008654 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008655 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008656 }
8657 free(lvp);
8658 }
8659}
8660
8661static int
8662evalfun(struct funcnode *func, int argc, char **argv, int flags)
8663{
8664 volatile struct shparam saveparam;
8665 struct localvar *volatile savelocalvars;
8666 struct jmploc *volatile savehandler;
8667 struct jmploc jmploc;
8668 int e;
8669
8670 saveparam = shellparam;
8671 savelocalvars = localvars;
8672 e = setjmp(jmploc.loc);
8673 if (e) {
8674 goto funcdone;
8675 }
8676 INT_OFF;
8677 savehandler = exception_handler;
8678 exception_handler = &jmploc;
8679 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008680 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008681 func->count++;
8682 funcnest++;
8683 INT_ON;
8684 shellparam.nparam = argc - 1;
8685 shellparam.p = argv + 1;
8686#if ENABLE_ASH_GETOPTS
8687 shellparam.optind = 1;
8688 shellparam.optoff = -1;
8689#endif
8690 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008691 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008692 INT_OFF;
8693 funcnest--;
8694 freefunc(func);
8695 poplocalvars();
8696 localvars = savelocalvars;
8697 freeparam(&shellparam);
8698 shellparam = saveparam;
8699 exception_handler = savehandler;
8700 INT_ON;
8701 evalskip &= ~SKIPFUNC;
8702 return e;
8703}
8704
Denis Vlasenko131ae172007-02-18 13:00:19 +00008705#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008706static char **
8707parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008708{
8709 char *cp, c;
8710
8711 for (;;) {
8712 cp = *++argv;
8713 if (!cp)
8714 return 0;
8715 if (*cp++ != '-')
8716 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008717 c = *cp++;
8718 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008719 break;
8720 if (c == '-' && !*cp) {
8721 argv++;
8722 break;
8723 }
8724 do {
8725 switch (c) {
8726 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008727 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008728 break;
8729 default:
8730 /* run 'typecmd' for other options */
8731 return 0;
8732 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008733 c = *cp++;
8734 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008735 }
8736 return argv;
8737}
8738#endif
8739
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008740/*
8741 * Make a variable a local variable. When a variable is made local, it's
8742 * value and flags are saved in a localvar structure. The saved values
8743 * will be restored when the shell function returns. We handle the name
8744 * "-" as a special case.
8745 */
8746static void
8747mklocal(char *name)
8748{
8749 struct localvar *lvp;
8750 struct var **vpp;
8751 struct var *vp;
8752
8753 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008754 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008755 if (LONE_DASH(name)) {
8756 char *p;
8757 p = ckmalloc(sizeof(optlist));
8758 lvp->text = memcpy(p, optlist, sizeof(optlist));
8759 vp = NULL;
8760 } else {
8761 char *eq;
8762
8763 vpp = hashvar(name);
8764 vp = *findvar(vpp, name);
8765 eq = strchr(name, '=');
8766 if (vp == NULL) {
8767 if (eq)
8768 setvareq(name, VSTRFIXED);
8769 else
8770 setvar(name, NULL, VSTRFIXED);
8771 vp = *vpp; /* the new variable */
8772 lvp->flags = VUNSET;
8773 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008774 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008775 lvp->flags = vp->flags;
8776 vp->flags |= VSTRFIXED|VTEXTFIXED;
8777 if (eq)
8778 setvareq(name, 0);
8779 }
8780 }
8781 lvp->vp = vp;
8782 lvp->next = localvars;
8783 localvars = lvp;
8784 INT_ON;
8785}
8786
8787/*
8788 * The "local" command.
8789 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008790static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008791localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008792{
8793 char *name;
8794
8795 argv = argptr;
8796 while ((name = *argv++) != NULL) {
8797 mklocal(name);
8798 }
8799 return 0;
8800}
8801
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008802static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008803falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008804{
8805 return 1;
8806}
8807
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008808static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008809truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008810{
8811 return 0;
8812}
8813
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008814static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008815execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008816{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008817 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008818 iflag = 0; /* exit on error */
8819 mflag = 0;
8820 optschanged();
8821 shellexec(argv + 1, pathval(), 0);
8822 }
8823 return 0;
8824}
8825
8826/*
8827 * The return command.
8828 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008830returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008831{
8832 /*
8833 * If called outside a function, do what ksh does;
8834 * skip the rest of the file.
8835 */
8836 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8837 return argv[1] ? number(argv[1]) : exitstatus;
8838}
8839
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008840/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008841static int breakcmd(int, char **) FAST_FUNC;
8842static int dotcmd(int, char **) FAST_FUNC;
8843static int evalcmd(int, char **) FAST_FUNC;
8844static int exitcmd(int, char **) FAST_FUNC;
8845static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008846#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008847static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008848#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008849#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008850static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008851#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008852#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008853static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008854#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008855static int readcmd(int, char **) FAST_FUNC;
8856static int setcmd(int, char **) FAST_FUNC;
8857static int shiftcmd(int, char **) FAST_FUNC;
8858static int timescmd(int, char **) FAST_FUNC;
8859static int trapcmd(int, char **) FAST_FUNC;
8860static int umaskcmd(int, char **) FAST_FUNC;
8861static int unsetcmd(int, char **) FAST_FUNC;
8862static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008863
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008864#define BUILTIN_NOSPEC "0"
8865#define BUILTIN_SPECIAL "1"
8866#define BUILTIN_REGULAR "2"
8867#define BUILTIN_SPEC_REG "3"
8868#define BUILTIN_ASSIGN "4"
8869#define BUILTIN_SPEC_ASSG "5"
8870#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008871#define BUILTIN_SPEC_REG_ASSG "7"
8872
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008873/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008874#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008875static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008876#endif
8877#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008878static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008879#endif
8880#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008881static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008882#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008883
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008884/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008885static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008886 { BUILTIN_SPEC_REG "." , dotcmd },
8887 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008888#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008889 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008890#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008891 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008892#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008893#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008894#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008895 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896#endif
8897#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008898 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008899#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008900 { BUILTIN_SPEC_REG "break" , breakcmd },
8901 { BUILTIN_REGULAR "cd" , cdcmd },
8902 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008903#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008904 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008905#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008906 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008907#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008908 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008909#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008910 { BUILTIN_SPEC_REG "eval" , evalcmd },
8911 { BUILTIN_SPEC_REG "exec" , execcmd },
8912 { BUILTIN_SPEC_REG "exit" , exitcmd },
8913 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8914 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008915#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008916 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008917#endif
8918#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008919 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008920#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008921 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008922#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008923 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008924#endif
8925#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008926 { BUILTIN_REGULAR "jobs" , jobscmd },
8927 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008928#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008929#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008930 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008931#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008932 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008933#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008934 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008935#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008936 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8937 { BUILTIN_REGULAR "read" , readcmd },
8938 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8939 { BUILTIN_SPEC_REG "return" , returncmd },
8940 { BUILTIN_SPEC_REG "set" , setcmd },
8941 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008942#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008943 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008944#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008945#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008946 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008947#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008948 { BUILTIN_SPEC_REG "times" , timescmd },
8949 { BUILTIN_SPEC_REG "trap" , trapcmd },
8950 { BUILTIN_REGULAR "true" , truecmd },
8951 { BUILTIN_NOSPEC "type" , typecmd },
8952 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8953 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008954#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008955 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008956#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008957 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8958 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008959};
8960
Denis Vlasenko80591b02008-03-25 07:49:43 +00008961/* Should match the above table! */
8962#define COMMANDCMD (builtintab + \
8963 2 + \
8964 1 * ENABLE_ASH_BUILTIN_TEST + \
8965 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8966 1 * ENABLE_ASH_ALIAS + \
8967 1 * ENABLE_ASH_JOB_CONTROL + \
8968 3)
8969#define EXECCMD (builtintab + \
8970 2 + \
8971 1 * ENABLE_ASH_BUILTIN_TEST + \
8972 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8973 1 * ENABLE_ASH_ALIAS + \
8974 1 * ENABLE_ASH_JOB_CONTROL + \
8975 3 + \
8976 1 * ENABLE_ASH_CMDCMD + \
8977 1 + \
8978 ENABLE_ASH_BUILTIN_ECHO + \
8979 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008980
8981/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008982 * Search the table of builtin commands.
8983 */
8984static struct builtincmd *
8985find_builtin(const char *name)
8986{
8987 struct builtincmd *bp;
8988
8989 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008990 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008991 pstrcmp
8992 );
8993 return bp;
8994}
8995
8996/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008997 * Execute a simple command.
8998 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008999static int
9000isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009001{
9002 const char *q = endofname(p);
9003 if (p == q)
9004 return 0;
9005 return *q == '=';
9006}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009007static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009008bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009009{
9010 /* Preserve exitstatus of a previous possible redirection
9011 * as POSIX mandates */
9012 return back_exitstatus;
9013}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009014static void
Eric Andersenc470f442003-07-28 09:56:35 +00009015evalcommand(union node *cmd, int flags)
9016{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009017 static const struct builtincmd null_bltin = {
9018 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009019 };
Eric Andersenc470f442003-07-28 09:56:35 +00009020 struct stackmark smark;
9021 union node *argp;
9022 struct arglist arglist;
9023 struct arglist varlist;
9024 char **argv;
9025 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009026 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009027 struct cmdentry cmdentry;
9028 struct job *jp;
9029 char *lastarg;
9030 const char *path;
9031 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009032 int status;
9033 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009034 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009035 smallint cmd_is_exec;
9036 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009037
9038 /* First expand the arguments. */
9039 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9040 setstackmark(&smark);
9041 back_exitstatus = 0;
9042
9043 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009044 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009045 varlist.lastp = &varlist.list;
9046 *varlist.lastp = NULL;
9047 arglist.lastp = &arglist.list;
9048 *arglist.lastp = NULL;
9049
9050 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009051 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009052 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9053 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9054 }
9055
Eric Andersenc470f442003-07-28 09:56:35 +00009056 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9057 struct strlist **spp;
9058
9059 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009060 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009061 expandarg(argp, &arglist, EXP_VARTILDE);
9062 else
9063 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9064
Eric Andersenc470f442003-07-28 09:56:35 +00009065 for (sp = *spp; sp; sp = sp->next)
9066 argc++;
9067 }
9068
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009069 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009070 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009071 TRACE(("evalcommand arg: %s\n", sp->text));
9072 *nargv++ = sp->text;
9073 }
9074 *nargv = NULL;
9075
9076 lastarg = NULL;
9077 if (iflag && funcnest == 0 && argc > 0)
9078 lastarg = nargv[-1];
9079
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009080 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009081 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009082 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009083
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009084 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009085 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9086 struct strlist **spp;
9087 char *p;
9088
9089 spp = varlist.lastp;
9090 expandarg(argp, &varlist, EXP_VARTILDE);
9091
9092 /*
9093 * Modify the command lookup path, if a PATH= assignment
9094 * is present
9095 */
9096 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009097 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009098 path = p;
9099 }
9100
9101 /* Print the command if xflag is set. */
9102 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009103 int n;
9104 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009105
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009106 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009107 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009108
9109 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009110 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009111 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009112 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009113 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009114 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009115 p--;
9116 }
9117 }
9118 sp = arglist.list;
9119 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009120 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009121 }
9122
9123 cmd_is_exec = 0;
9124 spclbltin = -1;
9125
9126 /* Now locate the command. */
9127 if (argc) {
9128 const char *oldpath;
9129 int cmd_flag = DO_ERR;
9130
9131 path += 5;
9132 oldpath = path;
9133 for (;;) {
9134 find_command(argv[0], &cmdentry, cmd_flag, path);
9135 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009136 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009137 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009138 goto bail;
9139 }
9140
9141 /* implement bltin and command here */
9142 if (cmdentry.cmdtype != CMDBUILTIN)
9143 break;
9144 if (spclbltin < 0)
9145 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9146 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009147 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009148#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009149 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009150 path = oldpath;
9151 nargv = parse_command_args(argv, &path);
9152 if (!nargv)
9153 break;
9154 argc -= nargv - argv;
9155 argv = nargv;
9156 cmd_flag |= DO_NOFUNC;
9157 } else
9158#endif
9159 break;
9160 }
9161 }
9162
9163 if (status) {
9164 /* We have a redirection error. */
9165 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009166 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009167 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009168 exitstatus = status;
9169 goto out;
9170 }
9171
9172 /* Execute the command. */
9173 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009174 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009175
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009176#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009177/* (1) BUG: if variables are set, we need to fork, or save/restore them
9178 * around run_nofork_applet() call.
9179 * (2) Should this check also be done in forkshell()?
9180 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9181 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009182 /* find_command() encodes applet_no as (-2 - applet_no) */
9183 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009184 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009185 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009186 /* run <applet>_main() */
9187 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009188 break;
9189 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009190#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009191 /* Can we avoid forking off? For example, very last command
9192 * in a script or a subshell does not need forking,
9193 * we can just exec it.
9194 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009195 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009196 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009197 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009198 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009199 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009200 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009201 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009202 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009203 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009204 break;
9205 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009206 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009207 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009208 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009209 }
9210 listsetvar(varlist.list, VEXPORT|VSTACK);
9211 shellexec(argv, path, cmdentry.u.index);
9212 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009213 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009214 case CMDBUILTIN:
9215 cmdenviron = varlist.list;
9216 if (cmdenviron) {
9217 struct strlist *list = cmdenviron;
9218 int i = VNOSET;
9219 if (spclbltin > 0 || argc == 0) {
9220 i = 0;
9221 if (cmd_is_exec && argc > 1)
9222 i = VEXPORT;
9223 }
9224 listsetvar(list, i);
9225 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009226 /* Tight loop with builtins only:
9227 * "while kill -0 $child; do true; done"
9228 * will never exit even if $child died, unless we do this
9229 * to reap the zombie and make kill detect that it's gone: */
9230 dowait(DOWAIT_NONBLOCK, NULL);
9231
Eric Andersenc470f442003-07-28 09:56:35 +00009232 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9233 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009234 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009235 if (i == EXEXIT)
9236 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009237 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009238 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009239 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009240 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009241 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009242 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009243 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009244 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009245 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009246 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009247 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009248 }
9249 break;
9250
9251 case CMDFUNCTION:
9252 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009253 /* See above for the rationale */
9254 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009255 if (evalfun(cmdentry.u.func, argc, argv, flags))
9256 goto raise;
9257 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009258
9259 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009260
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009261 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009262 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009263 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009264 /* dsl: I think this is intended to be used to support
9265 * '_' in 'vi' command mode during line editing...
9266 * However I implemented that within libedit itself.
9267 */
9268 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009269 }
Eric Andersenc470f442003-07-28 09:56:35 +00009270 popstackmark(&smark);
9271}
9272
9273static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009274evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9275{
Eric Andersenc470f442003-07-28 09:56:35 +00009276 char *volatile savecmdname;
9277 struct jmploc *volatile savehandler;
9278 struct jmploc jmploc;
9279 int i;
9280
9281 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009282 i = setjmp(jmploc.loc);
9283 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009284 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009285 savehandler = exception_handler;
9286 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009287 commandname = argv[0];
9288 argptr = argv + 1;
9289 optptr = NULL; /* initialize nextopt */
9290 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009291 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009292 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009293 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009294 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009295 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009296 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009297
9298 return i;
9299}
9300
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009301static int
9302goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009303{
9304 return !*endofname(p);
9305}
9306
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009307
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009308/*
9309 * Search for a command. This is called before we fork so that the
9310 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009311 * the child. The check for "goodname" is an overly conservative
9312 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009313 */
Eric Andersenc470f442003-07-28 09:56:35 +00009314static void
9315prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009316{
9317 struct cmdentry entry;
9318
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009319 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9320 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009321}
9322
Eric Andersencb57d552001-06-28 07:25:16 +00009323
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009324/* ============ Builtin commands
9325 *
9326 * Builtin commands whose functions are closely tied to evaluation
9327 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009328 */
9329
9330/*
Eric Andersencb57d552001-06-28 07:25:16 +00009331 * Handle break and continue commands. Break, continue, and return are
9332 * all handled by setting the evalskip flag. The evaluation routines
9333 * above all check this flag, and if it is set they start skipping
9334 * commands rather than executing them. The variable skipcount is
9335 * the number of loops to break/continue, or the number of function
9336 * levels to return. (The latter is always 1.) It should probably
9337 * be an error to break out of more loops than exist, but it isn't
9338 * in the standard shell so we don't make it one here.
9339 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009340static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009341breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009342{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009343 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009344
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009345 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009346 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009347 if (n > loopnest)
9348 n = loopnest;
9349 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009350 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009351 skipcount = n;
9352 }
9353 return 0;
9354}
9355
Eric Andersenc470f442003-07-28 09:56:35 +00009356
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009357/* ============ input.c
9358 *
Eric Andersen90898442003-08-06 11:20:52 +00009359 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009360 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009361
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009362enum {
9363 INPUT_PUSH_FILE = 1,
9364 INPUT_NOFILE_OK = 2,
9365};
Eric Andersencb57d552001-06-28 07:25:16 +00009366
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009367static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009368/* values of checkkwd variable */
9369#define CHKALIAS 0x1
9370#define CHKKWD 0x2
9371#define CHKNL 0x4
9372
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009373/*
9374 * Push a string back onto the input at this current parsefile level.
9375 * We handle aliases this way.
9376 */
9377#if !ENABLE_ASH_ALIAS
9378#define pushstring(s, ap) pushstring(s)
9379#endif
9380static void
9381pushstring(char *s, struct alias *ap)
9382{
9383 struct strpush *sp;
9384 int len;
9385
9386 len = strlen(s);
9387 INT_OFF;
9388 if (g_parsefile->strpush) {
9389 sp = ckzalloc(sizeof(*sp));
9390 sp->prev = g_parsefile->strpush;
9391 } else {
9392 sp = &(g_parsefile->basestrpush);
9393 }
9394 g_parsefile->strpush = sp;
9395 sp->prev_string = g_parsefile->next_to_pgetc;
9396 sp->prev_left_in_line = g_parsefile->left_in_line;
9397#if ENABLE_ASH_ALIAS
9398 sp->ap = ap;
9399 if (ap) {
9400 ap->flag |= ALIASINUSE;
9401 sp->string = s;
9402 }
9403#endif
9404 g_parsefile->next_to_pgetc = s;
9405 g_parsefile->left_in_line = len;
9406 INT_ON;
9407}
9408
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009409static void
9410popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009411{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009412 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009413
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009414 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009415#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009416 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009417 if (g_parsefile->next_to_pgetc[-1] == ' '
9418 || g_parsefile->next_to_pgetc[-1] == '\t'
9419 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009420 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009421 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009422 if (sp->string != sp->ap->val) {
9423 free(sp->string);
9424 }
9425 sp->ap->flag &= ~ALIASINUSE;
9426 if (sp->ap->flag & ALIASDEAD) {
9427 unalias(sp->ap->name);
9428 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009429 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009430#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009431 g_parsefile->next_to_pgetc = sp->prev_string;
9432 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009433 g_parsefile->strpush = sp->prev;
9434 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009435 free(sp);
9436 INT_ON;
9437}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009438
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009439//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9440//it peeks whether it is &>, and then pushes back both chars.
9441//This function needs to save last *next_to_pgetc to buf[0]
9442//to make two pungetc() reliable. Currently,
9443// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009444static int
9445preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009446{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009447 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009448 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009449
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009450 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009451#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009452 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009453 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9454 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009455 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009456#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009457 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009458#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009459 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009460 if (nr == 0) {
9461 /* Ctrl+C pressed */
9462 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009463 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009464 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009465 raise(SIGINT);
9466 return 1;
9467 }
Eric Andersenc470f442003-07-28 09:56:35 +00009468 goto retry;
9469 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009470 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009471 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009472 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009473 }
Eric Andersencb57d552001-06-28 07:25:16 +00009474 }
9475#else
Denys Vlasenko161bb8f2010-06-06 05:07:11 +02009476 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009477#endif
9478
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009479#if 0
9480/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009481 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009482 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009483 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009484 if (flags >= 0 && (flags & O_NONBLOCK)) {
9485 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009486 if (fcntl(0, F_SETFL, flags) >= 0) {
9487 out2str("sh: turning off NDELAY mode\n");
9488 goto retry;
9489 }
9490 }
9491 }
9492 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009493#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009494 return nr;
9495}
9496
9497/*
9498 * Refill the input buffer and return the next input character:
9499 *
9500 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9502 * or we are reading from a string so we can't refill the buffer,
9503 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009504 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009505 * 4) Process input up to the next newline, deleting nul characters.
9506 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9508#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009509static int
Eric Andersenc470f442003-07-28 09:56:35 +00009510preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009511{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009512 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009513 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009514
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009515 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009516#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009517 if (g_parsefile->left_in_line == -1
9518 && g_parsefile->strpush->ap
9519 && g_parsefile->next_to_pgetc[-1] != ' '
9520 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009521 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009522 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009523 return PEOA;
9524 }
Eric Andersen2870d962001-07-02 17:27:21 +00009525#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009526 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009527 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009528 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9529 g_parsefile->left_in_line,
9530 g_parsefile->next_to_pgetc,
9531 g_parsefile->next_to_pgetc);
9532 if (--g_parsefile->left_in_line >= 0)
9533 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009534 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009536 * "pgetc" needs refilling.
9537 */
9538
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009539 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009540 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009541 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009542 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009543 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009544 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545 /* even in failure keep left_in_line and next_to_pgetc
9546 * in lock step, for correct multi-layer pungetc.
9547 * left_in_line was decremented before preadbuffer(),
9548 * must inc next_to_pgetc: */
9549 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009550 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009551 }
Eric Andersencb57d552001-06-28 07:25:16 +00009552
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009553 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009554 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009555 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009556 again:
9557 more = preadfd();
9558 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009559 /* don't try reading again */
9560 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009561 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009562 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009563 return PEOF;
9564 }
9565 }
9566
Denis Vlasenko727752d2008-11-28 03:41:47 +00009567 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009568 * Set g_parsefile->left_in_line
9569 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009570 * NUL chars are deleted.
9571 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009572 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009573 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009574 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009575
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009576 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009577
Denis Vlasenko727752d2008-11-28 03:41:47 +00009578 c = *q;
9579 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009580 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009581 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009582 q++;
9583 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009584 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009585 break;
9586 }
Eric Andersencb57d552001-06-28 07:25:16 +00009587 }
9588
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009589 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009590 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9591 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009592 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009593 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009594 }
9595 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009596 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009597
Eric Andersencb57d552001-06-28 07:25:16 +00009598 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009599 char save = *q;
9600 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009601 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009602 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009603 }
9604
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009605 pgetc_debug("preadbuffer at %d:%p'%s'",
9606 g_parsefile->left_in_line,
9607 g_parsefile->next_to_pgetc,
9608 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009609 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009610}
9611
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009612#define pgetc_as_macro() \
9613 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009614 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009615 : preadbuffer() \
9616 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009617
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009618static int
9619pgetc(void)
9620{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009621 pgetc_debug("pgetc_fast at %d:%p'%s'",
9622 g_parsefile->left_in_line,
9623 g_parsefile->next_to_pgetc,
9624 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009625 return pgetc_as_macro();
9626}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009627
9628#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009629# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009630#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009631# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009632#endif
9633
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009634#if ENABLE_ASH_ALIAS
9635static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009636pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009637{
9638 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009640 pgetc_debug("pgetc_fast at %d:%p'%s'",
9641 g_parsefile->left_in_line,
9642 g_parsefile->next_to_pgetc,
9643 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009644 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009645 } while (c == PEOA);
9646 return c;
9647}
9648#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009649# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009650#endif
9651
9652/*
9653 * Read a line from the script.
9654 */
9655static char *
9656pfgets(char *line, int len)
9657{
9658 char *p = line;
9659 int nleft = len;
9660 int c;
9661
9662 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009663 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009664 if (c == PEOF) {
9665 if (p == line)
9666 return NULL;
9667 break;
9668 }
9669 *p++ = c;
9670 if (c == '\n')
9671 break;
9672 }
9673 *p = '\0';
9674 return line;
9675}
9676
Eric Andersenc470f442003-07-28 09:56:35 +00009677/*
9678 * Undo the last call to pgetc. Only one character may be pushed back.
9679 * PEOF may be pushed back.
9680 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009681static void
Eric Andersenc470f442003-07-28 09:56:35 +00009682pungetc(void)
9683{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009684 g_parsefile->left_in_line++;
9685 g_parsefile->next_to_pgetc--;
9686 pgetc_debug("pushed back to %d:%p'%s'",
9687 g_parsefile->left_in_line,
9688 g_parsefile->next_to_pgetc,
9689 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009690}
9691
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009692/*
9693 * To handle the "." command, a stack of input files is used. Pushfile
9694 * adds a new entry to the stack and popfile restores the previous level.
9695 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009696static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009697pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009698{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699 struct parsefile *pf;
9700
Denis Vlasenko597906c2008-02-20 16:38:54 +00009701 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009702 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009703 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009704 /*pf->strpush = NULL; - ckzalloc did it */
9705 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009706 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009707}
9708
9709static void
9710popfile(void)
9711{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009712 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009713
Denis Vlasenkob012b102007-02-19 22:43:01 +00009714 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009715 if (pf->pf_fd >= 0)
9716 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009717 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009718 while (pf->strpush)
9719 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009720 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009721 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009722 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009723}
9724
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009725/*
9726 * Return to top level.
9727 */
9728static void
9729popallfiles(void)
9730{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009731 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009732 popfile();
9733}
9734
9735/*
9736 * Close the file(s) that the shell is reading commands from. Called
9737 * after a fork is done.
9738 */
9739static void
9740closescript(void)
9741{
9742 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009743 if (g_parsefile->pf_fd > 0) {
9744 close(g_parsefile->pf_fd);
9745 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009746 }
9747}
9748
9749/*
9750 * Like setinputfile, but takes an open file descriptor. Call this with
9751 * interrupts off.
9752 */
9753static void
9754setinputfd(int fd, int push)
9755{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009756 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009757 if (push) {
9758 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009759 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009760 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009761 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009762 if (g_parsefile->buf == NULL)
9763 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009764 g_parsefile->left_in_buffer = 0;
9765 g_parsefile->left_in_line = 0;
9766 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009767}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009768
Eric Andersenc470f442003-07-28 09:56:35 +00009769/*
9770 * Set the input to take input from a file. If push is set, push the
9771 * old input onto the stack first.
9772 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009773static int
9774setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009775{
9776 int fd;
9777 int fd2;
9778
Denis Vlasenkob012b102007-02-19 22:43:01 +00009779 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009780 fd = open(fname, O_RDONLY);
9781 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009782 if (flags & INPUT_NOFILE_OK)
9783 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009784 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009785 }
Eric Andersenc470f442003-07-28 09:56:35 +00009786 if (fd < 10) {
9787 fd2 = copyfd(fd, 10);
9788 close(fd);
9789 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009790 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009791 fd = fd2;
9792 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009793 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009794 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009795 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009796 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009797}
9798
Eric Andersencb57d552001-06-28 07:25:16 +00009799/*
9800 * Like setinputfile, but takes input from a string.
9801 */
Eric Andersenc470f442003-07-28 09:56:35 +00009802static void
9803setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009804{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009805 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009806 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009807 g_parsefile->next_to_pgetc = string;
9808 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009809 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009810 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009811 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009812}
9813
9814
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009815/* ============ mail.c
9816 *
9817 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009818 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009819
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009820#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009821
Eric Andersencb57d552001-06-28 07:25:16 +00009822#define MAXMBOXES 10
9823
Eric Andersenc470f442003-07-28 09:56:35 +00009824/* times of mailboxes */
9825static time_t mailtime[MAXMBOXES];
9826/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009827static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009828
Eric Andersencb57d552001-06-28 07:25:16 +00009829/*
Eric Andersenc470f442003-07-28 09:56:35 +00009830 * Print appropriate message(s) if mail has arrived.
9831 * If mail_var_path_changed is set,
9832 * then the value of MAIL has mail_var_path_changed,
9833 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009834 */
Eric Andersenc470f442003-07-28 09:56:35 +00009835static void
9836chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009837{
Eric Andersencb57d552001-06-28 07:25:16 +00009838 const char *mpath;
9839 char *p;
9840 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009841 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009842 struct stackmark smark;
9843 struct stat statb;
9844
Eric Andersencb57d552001-06-28 07:25:16 +00009845 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009846 mpath = mpathset() ? mpathval() : mailval();
9847 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009848 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009849 if (p == NULL)
9850 break;
9851 if (*p == '\0')
9852 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009853 for (q = p; *q; q++)
9854 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009855#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009856 if (q[-1] != '/')
9857 abort();
9858#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009859 q[-1] = '\0'; /* delete trailing '/' */
9860 if (stat(p, &statb) < 0) {
9861 *mtp = 0;
9862 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009863 }
Eric Andersenc470f442003-07-28 09:56:35 +00009864 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9865 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009866 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009867 pathopt ? pathopt : "you have mail"
9868 );
9869 }
9870 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009871 }
Eric Andersenc470f442003-07-28 09:56:35 +00009872 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009873 popstackmark(&smark);
9874}
Eric Andersencb57d552001-06-28 07:25:16 +00009875
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009876static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009877changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009878{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009879 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009880}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009881
Denis Vlasenko131ae172007-02-18 13:00:19 +00009882#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009883
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009884
9885/* ============ ??? */
9886
Eric Andersencb57d552001-06-28 07:25:16 +00009887/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009888 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009889 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009890static void
9891setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009892{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009893 char **newparam;
9894 char **ap;
9895 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009896
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009897 for (nparam = 0; argv[nparam]; nparam++)
9898 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009899 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9900 while (*argv) {
9901 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009902 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009903 *ap = NULL;
9904 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009905 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009906 shellparam.nparam = nparam;
9907 shellparam.p = newparam;
9908#if ENABLE_ASH_GETOPTS
9909 shellparam.optind = 1;
9910 shellparam.optoff = -1;
9911#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009912}
9913
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009914/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009915 * Process shell options. The global variable argptr contains a pointer
9916 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009917 *
9918 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9919 * For a non-interactive shell, an error condition encountered
9920 * by a special built-in ... shall cause the shell to write a diagnostic message
9921 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009922 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009923 * ...
9924 * Utility syntax error (option or operand error) Shall exit
9925 * ...
9926 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9927 * we see that bash does not do that (set "finishes" with error code 1 instead,
9928 * and shell continues), and people rely on this behavior!
9929 * Testcase:
9930 * set -o barfoo 2>/dev/null
9931 * echo $?
9932 *
9933 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009934 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009935static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009936plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009937{
9938 int i;
9939
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009940 if (name) {
9941 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009942 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009943 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009944 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009945 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009946 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009947 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009948 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009949 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009950 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009951 if (val) {
9952 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9953 } else {
9954 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9955 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009956 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009957 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009958}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009959static void
9960setoption(int flag, int val)
9961{
9962 int i;
9963
9964 for (i = 0; i < NOPTS; i++) {
9965 if (optletters(i) == flag) {
9966 optlist[i] = val;
9967 return;
9968 }
9969 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009970 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009971 /* NOTREACHED */
9972}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009973static int
Eric Andersenc470f442003-07-28 09:56:35 +00009974options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009975{
9976 char *p;
9977 int val;
9978 int c;
9979
9980 if (cmdline)
9981 minusc = NULL;
9982 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009983 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009984 if (c != '-' && c != '+')
9985 break;
9986 argptr++;
9987 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009988 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009989 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009990 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009991 if (!cmdline) {
9992 /* "-" means turn off -x and -v */
9993 if (p[0] == '\0')
9994 xflag = vflag = 0;
9995 /* "--" means reset params */
9996 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009997 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009998 }
Eric Andersenc470f442003-07-28 09:56:35 +00009999 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010000 }
Eric Andersencb57d552001-06-28 07:25:16 +000010001 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010002 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010003 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010004 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010005 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010006 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010007 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010008 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010009 /* it already printed err message */
10010 return 1; /* error */
10011 }
Eric Andersencb57d552001-06-28 07:25:16 +000010012 if (*argptr)
10013 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010014 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10015 isloginsh = 1;
10016 /* bash does not accept +-login, we also won't */
10017 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010018 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010019 isloginsh = 1;
10020 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010021 } else {
10022 setoption(c, val);
10023 }
10024 }
10025 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010026 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010027}
10028
Eric Andersencb57d552001-06-28 07:25:16 +000010029/*
Eric Andersencb57d552001-06-28 07:25:16 +000010030 * The shift builtin command.
10031 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010032static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010033shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010034{
10035 int n;
10036 char **ap1, **ap2;
10037
10038 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010039 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010040 n = number(argv[1]);
10041 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010042 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010043 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010044 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010045 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010046 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010047 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010048 }
10049 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010050 while ((*ap2++ = *ap1++) != NULL)
10051 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010052#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010053 shellparam.optind = 1;
10054 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010055#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010056 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010057 return 0;
10058}
10059
Eric Andersencb57d552001-06-28 07:25:16 +000010060/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010061 * POSIX requires that 'set' (but not export or readonly) output the
10062 * variables in lexicographic order - by the locale's collating order (sigh).
10063 * Maybe we could keep them in an ordered balanced binary tree
10064 * instead of hashed lists.
10065 * For now just roll 'em through qsort for printing...
10066 */
10067static int
10068showvars(const char *sep_prefix, int on, int off)
10069{
10070 const char *sep;
10071 char **ep, **epend;
10072
10073 ep = listvars(on, off, &epend);
10074 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10075
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010076 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010077
10078 for (; ep < epend; ep++) {
10079 const char *p;
10080 const char *q;
10081
10082 p = strchrnul(*ep, '=');
10083 q = nullstr;
10084 if (*p)
10085 q = single_quote(++p);
10086 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10087 }
10088 return 0;
10089}
10090
10091/*
Eric Andersencb57d552001-06-28 07:25:16 +000010092 * The set command builtin.
10093 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010094static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010095setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010096{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010097 int retval;
10098
Denis Vlasenko68404f12008-03-17 09:00:54 +000010099 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010100 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010101 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010102 retval = 1;
10103 if (!options(0)) { /* if no parse error... */
10104 retval = 0;
10105 optschanged();
10106 if (*argptr != NULL) {
10107 setparam(argptr);
10108 }
Eric Andersencb57d552001-06-28 07:25:16 +000010109 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010110 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010111 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010112}
10113
Denis Vlasenko131ae172007-02-18 13:00:19 +000010114#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010115static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010116change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010117{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010118 uint32_t t;
10119
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010120 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010121 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010122 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010123 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010124 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010125 vrandom.flags &= ~VNOFUNC;
10126 } else {
10127 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010128 t = strtoul(value, NULL, 10);
10129 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010130 }
Eric Andersenef02f822004-03-11 13:34:24 +000010131}
Eric Andersen16767e22004-03-16 05:14:10 +000010132#endif
10133
Denis Vlasenko131ae172007-02-18 13:00:19 +000010134#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010135static int
Eric Andersenc470f442003-07-28 09:56:35 +000010136getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010137{
10138 char *p, *q;
10139 char c = '?';
10140 int done = 0;
10141 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010142 char s[12];
10143 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010144
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010145 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010146 return 1;
10147 optnext = optfirst + *param_optind - 1;
10148
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010149 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010150 p = NULL;
10151 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010152 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010153 if (p == NULL || *p == '\0') {
10154 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010155 p = *optnext;
10156 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010157 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010158 p = NULL;
10159 done = 1;
10160 goto out;
10161 }
10162 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010163 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010164 goto atend;
10165 }
10166
10167 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010168 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010169 if (*q == '\0') {
10170 if (optstr[0] == ':') {
10171 s[0] = c;
10172 s[1] = '\0';
10173 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010174 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010175 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010176 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010177 }
10178 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010179 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010180 }
10181 if (*++q == ':')
10182 q++;
10183 }
10184
10185 if (*++q == ':') {
10186 if (*p == '\0' && (p = *optnext) == NULL) {
10187 if (optstr[0] == ':') {
10188 s[0] = c;
10189 s[1] = '\0';
10190 err |= setvarsafe("OPTARG", s, 0);
10191 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010192 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010193 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010194 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010195 c = '?';
10196 }
Eric Andersenc470f442003-07-28 09:56:35 +000010197 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010198 }
10199
10200 if (p == *optnext)
10201 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010202 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010203 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010204 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010205 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010206 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010207 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010208 *param_optind = optnext - optfirst + 1;
10209 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010210 err |= setvarsafe("OPTIND", s, VNOFUNC);
10211 s[0] = c;
10212 s[1] = '\0';
10213 err |= setvarsafe(optvar, s, 0);
10214 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010215 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010216 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010217 flush_stdout_stderr();
10218 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010219 }
10220 return done;
10221}
Eric Andersenc470f442003-07-28 09:56:35 +000010222
10223/*
10224 * The getopts builtin. Shellparam.optnext points to the next argument
10225 * to be processed. Shellparam.optptr points to the next character to
10226 * be processed in the current argument. If shellparam.optnext is NULL,
10227 * then it's the first time getopts has been called.
10228 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010229static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010230getoptscmd(int argc, char **argv)
10231{
10232 char **optbase;
10233
10234 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010235 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010236 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010237 optbase = shellparam.p;
10238 if (shellparam.optind > shellparam.nparam + 1) {
10239 shellparam.optind = 1;
10240 shellparam.optoff = -1;
10241 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010242 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010243 optbase = &argv[3];
10244 if (shellparam.optind > argc - 2) {
10245 shellparam.optind = 1;
10246 shellparam.optoff = -1;
10247 }
10248 }
10249
10250 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010251 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010252}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010253#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010254
Eric Andersencb57d552001-06-28 07:25:16 +000010255
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010256/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010257
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010258struct heredoc {
10259 struct heredoc *next; /* next here document in list */
10260 union node *here; /* redirection node */
10261 char *eofmark; /* string indicating end of input */
10262 smallint striptabs; /* if set, strip leading tabs */
10263};
10264
10265static smallint tokpushback; /* last token pushed back */
10266static smallint parsebackquote; /* nonzero if we are inside backquotes */
10267static smallint quoteflag; /* set if (part of) last token was quoted */
10268static token_id_t lasttoken; /* last token read (integer id Txxx) */
10269static struct heredoc *heredoclist; /* list of here documents to read */
10270static char *wordtext; /* text of last word returned by readtoken */
10271static struct nodelist *backquotelist;
10272static union node *redirnode;
10273static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010274
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010275static const char *
10276tokname(char *buf, int tok)
10277{
10278 if (tok < TSEMI)
10279 return tokname_array[tok] + 1;
10280 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10281 return buf;
10282}
10283
10284/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010285 * Called when an unexpected token is read during the parse. The argument
10286 * is the token that is expected, or -1 if more than one type of token can
10287 * occur at this point.
10288 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010289static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010290static void
10291raise_error_unexpected_syntax(int token)
10292{
10293 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010294 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010295 int l;
10296
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010297 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010298 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010299 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010300 raise_error_syntax(msg);
10301 /* NOTREACHED */
10302}
Eric Andersencb57d552001-06-28 07:25:16 +000010303
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010304#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010305
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010306/* parsing is heavily cross-recursive, need these forward decls */
10307static union node *andor(void);
10308static union node *pipeline(void);
10309static union node *parse_command(void);
10310static void parseheredoc(void);
10311static char peektoken(void);
10312static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010313
Eric Andersenc470f442003-07-28 09:56:35 +000010314static union node *
10315list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010316{
10317 union node *n1, *n2, *n3;
10318 int tok;
10319
Eric Andersenc470f442003-07-28 09:56:35 +000010320 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10321 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010322 return NULL;
10323 n1 = NULL;
10324 for (;;) {
10325 n2 = andor();
10326 tok = readtoken();
10327 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010328 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010329 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010330 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010331 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010332 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010333 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010334 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010335 n2 = n3;
10336 }
10337 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010338 }
10339 }
10340 if (n1 == NULL) {
10341 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010342 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010343 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010344 n3->type = NSEMI;
10345 n3->nbinary.ch1 = n1;
10346 n3->nbinary.ch2 = n2;
10347 n1 = n3;
10348 }
10349 switch (tok) {
10350 case TBACKGND:
10351 case TSEMI:
10352 tok = readtoken();
10353 /* fall through */
10354 case TNL:
10355 if (tok == TNL) {
10356 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010357 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010358 return n1;
10359 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010360 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010361 }
Eric Andersenc470f442003-07-28 09:56:35 +000010362 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010363 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010364 return n1;
10365 break;
10366 case TEOF:
10367 if (heredoclist)
10368 parseheredoc();
10369 else
Eric Andersenc470f442003-07-28 09:56:35 +000010370 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010371 return n1;
10372 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010373 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010374 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010375 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010376 return n1;
10377 }
10378 }
10379}
10380
Eric Andersenc470f442003-07-28 09:56:35 +000010381static union node *
10382andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010383{
Eric Andersencb57d552001-06-28 07:25:16 +000010384 union node *n1, *n2, *n3;
10385 int t;
10386
Eric Andersencb57d552001-06-28 07:25:16 +000010387 n1 = pipeline();
10388 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010389 t = readtoken();
10390 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010391 t = NAND;
10392 } else if (t == TOR) {
10393 t = NOR;
10394 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010395 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010396 return n1;
10397 }
Eric Andersenc470f442003-07-28 09:56:35 +000010398 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010399 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010400 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010401 n3->type = t;
10402 n3->nbinary.ch1 = n1;
10403 n3->nbinary.ch2 = n2;
10404 n1 = n3;
10405 }
10406}
10407
Eric Andersenc470f442003-07-28 09:56:35 +000010408static union node *
10409pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010410{
Eric Andersencb57d552001-06-28 07:25:16 +000010411 union node *n1, *n2, *pipenode;
10412 struct nodelist *lp, *prev;
10413 int negate;
10414
10415 negate = 0;
10416 TRACE(("pipeline: entered\n"));
10417 if (readtoken() == TNOT) {
10418 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010419 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010420 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010421 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010422 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010423 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010424 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010425 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010426 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010427 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010428 pipenode->npipe.cmdlist = lp;
10429 lp->n = n1;
10430 do {
10431 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010432 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010433 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010434 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010435 prev->next = lp;
10436 } while (readtoken() == TPIPE);
10437 lp->next = NULL;
10438 n1 = pipenode;
10439 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010440 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010441 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010442 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010443 n2->type = NNOT;
10444 n2->nnot.com = n1;
10445 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010446 }
10447 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010448}
10449
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450static union node *
10451makename(void)
10452{
10453 union node *n;
10454
Denis Vlasenko597906c2008-02-20 16:38:54 +000010455 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010456 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010457 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010458 n->narg.text = wordtext;
10459 n->narg.backquote = backquotelist;
10460 return n;
10461}
10462
10463static void
10464fixredir(union node *n, const char *text, int err)
10465{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010466 int fd;
10467
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010468 TRACE(("Fix redir %s %d\n", text, err));
10469 if (!err)
10470 n->ndup.vname = NULL;
10471
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010472 fd = bb_strtou(text, NULL, 10);
10473 if (!errno && fd >= 0)
10474 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010475 else if (LONE_DASH(text))
10476 n->ndup.dupfd = -1;
10477 else {
10478 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010479 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010480 n->ndup.vname = makename();
10481 }
10482}
10483
10484/*
10485 * Returns true if the text contains nothing to expand (no dollar signs
10486 * or backquotes).
10487 */
10488static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010489noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010490{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010491 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010492
Denys Vlasenkocd716832009-11-28 22:14:02 +010010493 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010494 if (c == CTLQUOTEMARK)
10495 continue;
10496 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010497 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010498 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499 return 0;
10500 }
10501 return 1;
10502}
10503
10504static void
10505parsefname(void)
10506{
10507 union node *n = redirnode;
10508
10509 if (readtoken() != TWORD)
10510 raise_error_unexpected_syntax(-1);
10511 if (n->type == NHERE) {
10512 struct heredoc *here = heredoc;
10513 struct heredoc *p;
10514 int i;
10515
10516 if (quoteflag == 0)
10517 n->type = NXHERE;
10518 TRACE(("Here document %d\n", n->type));
10519 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010520 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010521 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010522 here->eofmark = wordtext;
10523 here->next = NULL;
10524 if (heredoclist == NULL)
10525 heredoclist = here;
10526 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010527 for (p = heredoclist; p->next; p = p->next)
10528 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010529 p->next = here;
10530 }
10531 } else if (n->type == NTOFD || n->type == NFROMFD) {
10532 fixredir(n, wordtext, 0);
10533 } else {
10534 n->nfile.fname = makename();
10535 }
10536}
Eric Andersencb57d552001-06-28 07:25:16 +000010537
Eric Andersenc470f442003-07-28 09:56:35 +000010538static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010539simplecmd(void)
10540{
10541 union node *args, **app;
10542 union node *n = NULL;
10543 union node *vars, **vpp;
10544 union node **rpp, *redir;
10545 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010546#if ENABLE_ASH_BASH_COMPAT
10547 smallint double_brackets_flag = 0;
10548#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010549
10550 args = NULL;
10551 app = &args;
10552 vars = NULL;
10553 vpp = &vars;
10554 redir = NULL;
10555 rpp = &redir;
10556
10557 savecheckkwd = CHKALIAS;
10558 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010559 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010560 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010561 t = readtoken();
10562 switch (t) {
10563#if ENABLE_ASH_BASH_COMPAT
10564 case TAND: /* "&&" */
10565 case TOR: /* "||" */
10566 if (!double_brackets_flag) {
10567 tokpushback = 1;
10568 goto out;
10569 }
10570 wordtext = (char *) (t == TAND ? "-a" : "-o");
10571#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010572 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010573 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010574 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010575 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010576 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010577#if ENABLE_ASH_BASH_COMPAT
10578 if (strcmp("[[", wordtext) == 0)
10579 double_brackets_flag = 1;
10580 else if (strcmp("]]", wordtext) == 0)
10581 double_brackets_flag = 0;
10582#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010583 n->narg.backquote = backquotelist;
10584 if (savecheckkwd && isassignment(wordtext)) {
10585 *vpp = n;
10586 vpp = &n->narg.next;
10587 } else {
10588 *app = n;
10589 app = &n->narg.next;
10590 savecheckkwd = 0;
10591 }
10592 break;
10593 case TREDIR:
10594 *rpp = n = redirnode;
10595 rpp = &n->nfile.next;
10596 parsefname(); /* read name of redirection file */
10597 break;
10598 case TLP:
10599 if (args && app == &args->narg.next
10600 && !vars && !redir
10601 ) {
10602 struct builtincmd *bcmd;
10603 const char *name;
10604
10605 /* We have a function */
10606 if (readtoken() != TRP)
10607 raise_error_unexpected_syntax(TRP);
10608 name = n->narg.text;
10609 if (!goodname(name)
10610 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10611 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010612 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010613 }
10614 n->type = NDEFUN;
10615 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10616 n->narg.next = parse_command();
10617 return n;
10618 }
10619 /* fall through */
10620 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010621 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010622 goto out;
10623 }
10624 }
10625 out:
10626 *app = NULL;
10627 *vpp = NULL;
10628 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010629 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010630 n->type = NCMD;
10631 n->ncmd.args = args;
10632 n->ncmd.assign = vars;
10633 n->ncmd.redirect = redir;
10634 return n;
10635}
10636
10637static union node *
10638parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010639{
Eric Andersencb57d552001-06-28 07:25:16 +000010640 union node *n1, *n2;
10641 union node *ap, **app;
10642 union node *cp, **cpp;
10643 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010644 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010645 int t;
10646
10647 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010648 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010649
Eric Andersencb57d552001-06-28 07:25:16 +000010650 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010651 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010652 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010653 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010654 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010655 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010656 n1->type = NIF;
10657 n1->nif.test = list(0);
10658 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010659 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010660 n1->nif.ifpart = list(0);
10661 n2 = n1;
10662 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010663 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010664 n2 = n2->nif.elsepart;
10665 n2->type = NIF;
10666 n2->nif.test = list(0);
10667 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010668 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010669 n2->nif.ifpart = list(0);
10670 }
10671 if (lasttoken == TELSE)
10672 n2->nif.elsepart = list(0);
10673 else {
10674 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010675 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 }
Eric Andersenc470f442003-07-28 09:56:35 +000010677 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010678 break;
10679 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010680 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010681 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010682 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010683 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010684 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010685 got = readtoken();
10686 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010687 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010688 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010689 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010690 }
10691 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010692 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010693 break;
10694 }
10695 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010696 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010697 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010698 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010699 n1->type = NFOR;
10700 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010701 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010702 if (readtoken() == TIN) {
10703 app = &ap;
10704 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010705 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010706 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010707 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010708 n2->narg.text = wordtext;
10709 n2->narg.backquote = backquotelist;
10710 *app = n2;
10711 app = &n2->narg.next;
10712 }
10713 *app = NULL;
10714 n1->nfor.args = ap;
10715 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010716 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010717 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010718 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010719 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010720 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010721 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010722 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010723 n1->nfor.args = n2;
10724 /*
10725 * Newline or semicolon here is optional (but note
10726 * that the original Bourne shell only allowed NL).
10727 */
10728 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010729 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010730 }
Eric Andersenc470f442003-07-28 09:56:35 +000010731 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010732 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010733 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010734 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010735 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010736 break;
10737 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010738 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010739 n1->type = NCASE;
10740 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010741 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010742 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010743 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010744 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010745 n2->narg.text = wordtext;
10746 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010747 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010748 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010749 } while (readtoken() == TNL);
10750 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010751 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010752 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010753 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010754 checkkwd = CHKNL | CHKKWD;
10755 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010756 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010757 if (lasttoken == TLP)
10758 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010759 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010760 cp->type = NCLIST;
10761 app = &cp->nclist.pattern;
10762 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010763 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010764 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010765 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010766 ap->narg.text = wordtext;
10767 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010768 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010769 break;
10770 app = &ap->narg.next;
10771 readtoken();
10772 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010773 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010774 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010775 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010776 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010777
Eric Andersenc470f442003-07-28 09:56:35 +000010778 cpp = &cp->nclist.next;
10779
10780 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010781 t = readtoken();
10782 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010783 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010784 raise_error_unexpected_syntax(TENDCASE);
10785 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010786 }
Eric Andersenc470f442003-07-28 09:56:35 +000010787 }
Eric Andersencb57d552001-06-28 07:25:16 +000010788 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010789 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010790 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010791 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010792 n1->type = NSUBSHELL;
10793 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010794 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010795 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010796 break;
10797 case TBEGIN:
10798 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010799 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010800 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010801 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010802 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010803 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010804 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010805 }
10806
Eric Andersenc470f442003-07-28 09:56:35 +000010807 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010808 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010809
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010810 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010811 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010812 checkkwd = CHKKWD | CHKALIAS;
10813 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010814 while (readtoken() == TREDIR) {
10815 *rpp = n2 = redirnode;
10816 rpp = &n2->nfile.next;
10817 parsefname();
10818 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010819 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010820 *rpp = NULL;
10821 if (redir) {
10822 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010823 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010824 n2->type = NREDIR;
10825 n2->nredir.n = n1;
10826 n1 = n2;
10827 }
10828 n1->nredir.redirect = redir;
10829 }
Eric Andersencb57d552001-06-28 07:25:16 +000010830 return n1;
10831}
10832
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010833#if ENABLE_ASH_BASH_COMPAT
10834static int decode_dollar_squote(void)
10835{
10836 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10837 int c, cnt;
10838 char *p;
10839 char buf[4];
10840
10841 c = pgetc();
10842 p = strchr(C_escapes, c);
10843 if (p) {
10844 buf[0] = c;
10845 p = buf;
10846 cnt = 3;
10847 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10848 do {
10849 c = pgetc();
10850 *++p = c;
10851 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10852 pungetc();
10853 } else if (c == 'x') { /* \xHH */
10854 do {
10855 c = pgetc();
10856 *++p = c;
10857 } while (isxdigit(c) && --cnt);
10858 pungetc();
10859 if (cnt == 3) { /* \x but next char is "bad" */
10860 c = 'x';
10861 goto unrecognized;
10862 }
10863 } else { /* simple seq like \\ or \t */
10864 p++;
10865 }
10866 *p = '\0';
10867 p = buf;
10868 c = bb_process_escape_sequence((void*)&p);
10869 } else { /* unrecognized "\z": print both chars unless ' or " */
10870 if (c != '\'' && c != '"') {
10871 unrecognized:
10872 c |= 0x100; /* "please encode \, then me" */
10873 }
10874 }
10875 return c;
10876}
10877#endif
10878
Eric Andersencb57d552001-06-28 07:25:16 +000010879/*
10880 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10881 * is not NULL, read a here document. In the latter case, eofmark is the
10882 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010883 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010884 * is the first character of the input token or document.
10885 *
10886 * Because C does not have internal subroutines, I have simulated them
10887 * using goto's to implement the subroutine linkage. The following macros
10888 * will run code that appears at the end of readtoken1.
10889 */
Eric Andersen2870d962001-07-02 17:27:21 +000010890#define CHECKEND() {goto checkend; checkend_return:;}
10891#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10892#define PARSESUB() {goto parsesub; parsesub_return:;}
10893#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10894#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10895#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010896static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010897readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010898{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010899 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010900 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010901 char *out;
10902 int len;
10903 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010904 struct nodelist *bqlist;
10905 smallint quotef;
10906 smallint dblquote;
10907 smallint oldstyle;
10908 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010909#if ENABLE_ASH_EXPAND_PRMT
10910 smallint pssyntax; /* we are expanding a prompt string */
10911#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010912 int varnest; /* levels of variables expansion */
10913 int arinest; /* levels of arithmetic expansion */
10914 int parenlevel; /* levels of parens in arithmetic */
10915 int dqvarnest; /* levels of variables expansion within double quotes */
10916
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010917 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010918
Eric Andersencb57d552001-06-28 07:25:16 +000010919#if __GNUC__
10920 /* Avoid longjmp clobbering */
10921 (void) &out;
10922 (void) &quotef;
10923 (void) &dblquote;
10924 (void) &varnest;
10925 (void) &arinest;
10926 (void) &parenlevel;
10927 (void) &dqvarnest;
10928 (void) &oldstyle;
10929 (void) &prevsyntax;
10930 (void) &syntax;
10931#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010932 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010933 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010934 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010935 oldstyle = 0;
10936 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010937#if ENABLE_ASH_EXPAND_PRMT
10938 pssyntax = (syntax == PSSYNTAX);
10939 if (pssyntax)
10940 syntax = DQSYNTAX;
10941#endif
10942 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010943 varnest = 0;
10944 arinest = 0;
10945 parenlevel = 0;
10946 dqvarnest = 0;
10947
10948 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010949 loop:
10950 /* For each line, until end of word */
10951 {
Eric Andersenc470f442003-07-28 09:56:35 +000010952 CHECKEND(); /* set c to PEOF if at end of here document */
10953 for (;;) { /* until end of line or end of word */
10954 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010955 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010956 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010957 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010958 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010959 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010960 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010961 if (doprompt)
10962 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010963 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010964 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010965 case CWORD:
10966 USTPUTC(c, out);
10967 break;
10968 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010969 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010970 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010971#if ENABLE_ASH_BASH_COMPAT
10972 if (c == '\\' && bash_dollar_squote) {
10973 c = decode_dollar_squote();
10974 if (c & 0x100) {
10975 USTPUTC('\\', out);
10976 c = (unsigned char)c;
10977 }
10978 }
10979#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010980 USTPUTC(c, out);
10981 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010982 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010983 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010984 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010985 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010986 USTPUTC('\\', out);
10987 pungetc();
10988 } else if (c == '\n') {
10989 if (doprompt)
10990 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010991 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010992#if ENABLE_ASH_EXPAND_PRMT
10993 if (c == '$' && pssyntax) {
10994 USTPUTC(CTLESC, out);
10995 USTPUTC('\\', out);
10996 }
10997#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010998 if (dblquote && c != '\\'
10999 && c != '`' && c != '$'
11000 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000011001 ) {
11002 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011003 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011004 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011005 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000011006 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011007 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011008 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011009 }
11010 break;
11011 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011012 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011013 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011014 if (eofmark == NULL) {
11015 USTPUTC(CTLQUOTEMARK, out);
11016 }
Eric Andersencb57d552001-06-28 07:25:16 +000011017 break;
11018 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011019 syntax = DQSYNTAX;
11020 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011021 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011022 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011023 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011024 if (eofmark != NULL && arinest == 0
11025 && varnest == 0
11026 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011027 USTPUTC(c, out);
11028 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011029 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011030 syntax = BASESYNTAX;
11031 dblquote = 0;
11032 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011033 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011034 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011035 }
11036 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011037 case CVAR: /* '$' */
11038 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011039 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011040 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011041 if (varnest > 0) {
11042 varnest--;
11043 if (dqvarnest > 0) {
11044 dqvarnest--;
11045 }
11046 USTPUTC(CTLENDVAR, out);
11047 } else {
11048 USTPUTC(c, out);
11049 }
11050 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011051#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011052 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011053 parenlevel++;
11054 USTPUTC(c, out);
11055 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011056 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011057 if (parenlevel > 0) {
11058 USTPUTC(c, out);
11059 --parenlevel;
11060 } else {
11061 if (pgetc() == ')') {
11062 if (--arinest == 0) {
11063 USTPUTC(CTLENDARI, out);
11064 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011065 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011066 } else
11067 USTPUTC(')', out);
11068 } else {
11069 /*
11070 * unbalanced parens
11071 * (don't 2nd guess - no error)
11072 */
11073 pungetc();
11074 USTPUTC(')', out);
11075 }
11076 }
11077 break;
11078#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011079 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011080 PARSEBACKQOLD();
11081 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011082 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011083 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011084 case CIGN:
11085 break;
11086 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011087 if (varnest == 0) {
11088#if ENABLE_ASH_BASH_COMPAT
11089 if (c == '&') {
11090 if (pgetc() == '>')
11091 c = 0x100 + '>'; /* flag &> */
11092 pungetc();
11093 }
11094#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011095 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011096 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011097 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011098 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011099
Eric Andersencb57d552001-06-28 07:25:16 +000011100 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011101 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011102 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011103 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011104 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011105#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011106 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011107 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011108#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011109 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011110 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011111 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011112 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011113 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011114 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011115 }
11116 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011117 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011118 out = stackblock();
11119 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011120 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011121 && quotef == 0
11122 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011123 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011124 PARSEREDIR(); /* passed as params: out, c */
11125 lasttoken = TREDIR;
11126 return lasttoken;
11127 }
11128 /* else: non-number X seen, interpret it
11129 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011130 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011131 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011132 }
11133 quoteflag = quotef;
11134 backquotelist = bqlist;
11135 grabstackblock(len);
11136 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011137 lasttoken = TWORD;
11138 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011139/* end of readtoken routine */
11140
Eric Andersencb57d552001-06-28 07:25:16 +000011141/*
11142 * Check to see whether we are at the end of the here document. When this
11143 * is called, c is set to the first character of the next input line. If
11144 * we are at the end of the here document, this routine sets the c to PEOF.
11145 */
Eric Andersenc470f442003-07-28 09:56:35 +000011146checkend: {
11147 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011148#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011149 if (c == PEOA)
11150 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011151#endif
11152 if (striptabs) {
11153 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011154 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011155 }
Eric Andersenc470f442003-07-28 09:56:35 +000011156 }
11157 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011158 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011159 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011160
Eric Andersenc470f442003-07-28 09:56:35 +000011161 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011162 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11163 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011164 if (*p == '\n' && *q == '\0') {
11165 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011166 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011167 needprompt = doprompt;
11168 } else {
11169 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011170 }
11171 }
11172 }
11173 }
Eric Andersenc470f442003-07-28 09:56:35 +000011174 goto checkend_return;
11175}
Eric Andersencb57d552001-06-28 07:25:16 +000011176
Eric Andersencb57d552001-06-28 07:25:16 +000011177/*
11178 * Parse a redirection operator. The variable "out" points to a string
11179 * specifying the fd to be redirected. The variable "c" contains the
11180 * first character of the redirection operator.
11181 */
Eric Andersenc470f442003-07-28 09:56:35 +000011182parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011183 /* out is already checked to be a valid number or "" */
11184 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011185 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011186
Denis Vlasenko597906c2008-02-20 16:38:54 +000011187 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011188 if (c == '>') {
11189 np->nfile.fd = 1;
11190 c = pgetc();
11191 if (c == '>')
11192 np->type = NAPPEND;
11193 else if (c == '|')
11194 np->type = NCLOBBER;
11195 else if (c == '&')
11196 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011197 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011198 else {
11199 np->type = NTO;
11200 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011201 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011202 }
11203#if ENABLE_ASH_BASH_COMPAT
11204 else if (c == 0x100 + '>') { /* this flags &> redirection */
11205 np->nfile.fd = 1;
11206 pgetc(); /* this is '>', no need to check */
11207 np->type = NTO2;
11208 }
11209#endif
11210 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011211 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011212 c = pgetc();
11213 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011214 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011215 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011216 np = stzalloc(sizeof(struct nhere));
11217 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011218 }
11219 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011220 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011221 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011222 c = pgetc();
11223 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011224 heredoc->striptabs = 1;
11225 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011226 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011227 pungetc();
11228 }
11229 break;
11230
11231 case '&':
11232 np->type = NFROMFD;
11233 break;
11234
11235 case '>':
11236 np->type = NFROMTO;
11237 break;
11238
11239 default:
11240 np->type = NFROM;
11241 pungetc();
11242 break;
11243 }
Eric Andersencb57d552001-06-28 07:25:16 +000011244 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011245 if (fd >= 0)
11246 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011247 redirnode = np;
11248 goto parseredir_return;
11249}
Eric Andersencb57d552001-06-28 07:25:16 +000011250
Eric Andersencb57d552001-06-28 07:25:16 +000011251/*
11252 * Parse a substitution. At this point, we have read the dollar sign
11253 * and nothing else.
11254 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011255
11256/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11257 * (assuming ascii char codes, as the original implementation did) */
11258#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011259 (((unsigned)(c) - 33 < 32) \
11260 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011261parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011262 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011263 int typeloc;
11264 int flags;
11265 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011266 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011267
Eric Andersenc470f442003-07-28 09:56:35 +000011268 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011269 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011270 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011271 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011272#if ENABLE_ASH_BASH_COMPAT
11273 if (c == '\'')
11274 bash_dollar_squote = 1;
11275 else
11276#endif
11277 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011278 pungetc();
11279 } else if (c == '(') { /* $(command) or $((arith)) */
11280 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011281#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011282 PARSEARITH();
11283#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011284 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011285#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011286 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011287 pungetc();
11288 PARSEBACKQNEW();
11289 }
11290 } else {
11291 USTPUTC(CTLVAR, out);
11292 typeloc = out - (char *)stackblock();
11293 USTPUTC(VSNORMAL, out);
11294 subtype = VSNORMAL;
11295 if (c == '{') {
11296 c = pgetc();
11297 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011298 c = pgetc();
11299 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011300 c = '#';
11301 else
11302 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011303 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011304 subtype = 0;
11305 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011306 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011307 do {
11308 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011309 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011310 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011311 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011312 do {
11313 STPUTC(c, out);
11314 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011315 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011316 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011317 USTPUTC(c, out);
11318 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011319 } else {
11320 badsub:
11321 raise_error_syntax("bad substitution");
11322 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011323 if (c != '}' && subtype == VSLENGTH)
11324 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011325
Eric Andersenc470f442003-07-28 09:56:35 +000011326 STPUTC('=', out);
11327 flags = 0;
11328 if (subtype == 0) {
11329 switch (c) {
11330 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011331 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011332#if ENABLE_ASH_BASH_COMPAT
11333 if (c == ':' || c == '$' || isdigit(c)) {
11334 pungetc();
11335 subtype = VSSUBSTR;
11336 break;
11337 }
11338#endif
11339 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011340 /*FALLTHROUGH*/
11341 default:
11342 p = strchr(types, c);
11343 if (p == NULL)
11344 goto badsub;
11345 subtype = p - types + VSNORMAL;
11346 break;
11347 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011348 case '#': {
11349 int cc = c;
11350 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11351 c = pgetc();
11352 if (c == cc)
11353 subtype++;
11354 else
11355 pungetc();
11356 break;
11357 }
11358#if ENABLE_ASH_BASH_COMPAT
11359 case '/':
11360 subtype = VSREPLACE;
11361 c = pgetc();
11362 if (c == '/')
11363 subtype++; /* VSREPLACEALL */
11364 else
11365 pungetc();
11366 break;
11367#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011368 }
Eric Andersenc470f442003-07-28 09:56:35 +000011369 } else {
11370 pungetc();
11371 }
11372 if (dblquote || arinest)
11373 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011374 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011375 if (subtype != VSNORMAL) {
11376 varnest++;
11377 if (dblquote || arinest) {
11378 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011379 }
11380 }
11381 }
Eric Andersenc470f442003-07-28 09:56:35 +000011382 goto parsesub_return;
11383}
Eric Andersencb57d552001-06-28 07:25:16 +000011384
Eric Andersencb57d552001-06-28 07:25:16 +000011385/*
11386 * Called to parse command substitutions. Newstyle is set if the command
11387 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11388 * list of commands (passed by reference), and savelen is the number of
11389 * characters on the top of the stack which must be preserved.
11390 */
Eric Andersenc470f442003-07-28 09:56:35 +000011391parsebackq: {
11392 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011393 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011394 union node *n;
11395 char *volatile str;
11396 struct jmploc jmploc;
11397 struct jmploc *volatile savehandler;
11398 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011399 smallint saveprompt = 0;
11400
Eric Andersencb57d552001-06-28 07:25:16 +000011401#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011402 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011403#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011404 savepbq = parsebackquote;
11405 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011406 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011407 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011408 exception_handler = savehandler;
11409 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011410 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011411 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011412 str = NULL;
11413 savelen = out - (char *)stackblock();
11414 if (savelen > 0) {
11415 str = ckmalloc(savelen);
11416 memcpy(str, stackblock(), savelen);
11417 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011418 savehandler = exception_handler;
11419 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011420 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011421 if (oldstyle) {
11422 /* We must read until the closing backquote, giving special
11423 treatment to some slashes, and then push the string and
11424 reread it as input, interpreting it normally. */
11425 char *pout;
11426 int pc;
11427 size_t psavelen;
11428 char *pstr;
11429
11430
11431 STARTSTACKSTR(pout);
11432 for (;;) {
11433 if (needprompt) {
11434 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011435 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011436 pc = pgetc();
11437 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011438 case '`':
11439 goto done;
11440
11441 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011442 pc = pgetc();
11443 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011444 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011445 if (doprompt)
11446 setprompt(2);
11447 /*
11448 * If eating a newline, avoid putting
11449 * the newline into the new character
11450 * stream (via the STPUTC after the
11451 * switch).
11452 */
11453 continue;
11454 }
11455 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011456 && (!dblquote || pc != '"')
11457 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011458 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011459 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011460 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011461 break;
11462 }
11463 /* fall through */
11464
11465 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011466 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011467 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011468 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011469
11470 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011471 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011472 needprompt = doprompt;
11473 break;
11474
11475 default:
11476 break;
11477 }
11478 STPUTC(pc, pout);
11479 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011480 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011481 STPUTC('\0', pout);
11482 psavelen = pout - (char *)stackblock();
11483 if (psavelen > 0) {
11484 pstr = grabstackstr(pout);
11485 setinputstring(pstr);
11486 }
11487 }
11488 nlpp = &bqlist;
11489 while (*nlpp)
11490 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011491 *nlpp = stzalloc(sizeof(**nlpp));
11492 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011493 parsebackquote = oldstyle;
11494
11495 if (oldstyle) {
11496 saveprompt = doprompt;
11497 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011498 }
11499
Eric Andersenc470f442003-07-28 09:56:35 +000011500 n = list(2);
11501
11502 if (oldstyle)
11503 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011504 else if (readtoken() != TRP)
11505 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011506
11507 (*nlpp)->n = n;
11508 if (oldstyle) {
11509 /*
11510 * Start reading from old file again, ignoring any pushed back
11511 * tokens left from the backquote parsing
11512 */
11513 popfile();
11514 tokpushback = 0;
11515 }
11516 while (stackblocksize() <= savelen)
11517 growstackblock();
11518 STARTSTACKSTR(out);
11519 if (str) {
11520 memcpy(out, str, savelen);
11521 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011522 INT_OFF;
11523 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011524 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011525 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011526 }
11527 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011528 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011529 if (arinest || dblquote)
11530 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11531 else
11532 USTPUTC(CTLBACKQ, out);
11533 if (oldstyle)
11534 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011535 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011536}
11537
Mike Frysinger98c52642009-04-02 10:02:37 +000011538#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011539/*
11540 * Parse an arithmetic expansion (indicate start of one and set state)
11541 */
Eric Andersenc470f442003-07-28 09:56:35 +000011542parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011543 if (++arinest == 1) {
11544 prevsyntax = syntax;
11545 syntax = ARISYNTAX;
11546 USTPUTC(CTLARI, out);
11547 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011548 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011549 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011550 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011551 } else {
11552 /*
11553 * we collapse embedded arithmetic expansion to
11554 * parenthesis, which should be equivalent
11555 */
11556 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011557 }
Eric Andersenc470f442003-07-28 09:56:35 +000011558 goto parsearith_return;
11559}
11560#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011561
Eric Andersenc470f442003-07-28 09:56:35 +000011562} /* end of readtoken */
11563
Eric Andersencb57d552001-06-28 07:25:16 +000011564/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011565 * Read the next input token.
11566 * If the token is a word, we set backquotelist to the list of cmds in
11567 * backquotes. We set quoteflag to true if any part of the word was
11568 * quoted.
11569 * If the token is TREDIR, then we set redirnode to a structure containing
11570 * the redirection.
11571 * In all cases, the variable startlinno is set to the number of the line
11572 * on which the token starts.
11573 *
11574 * [Change comment: here documents and internal procedures]
11575 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11576 * word parsing code into a separate routine. In this case, readtoken
11577 * doesn't need to have any internal procedures, but parseword does.
11578 * We could also make parseoperator in essence the main routine, and
11579 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011580 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011581#define NEW_xxreadtoken
11582#ifdef NEW_xxreadtoken
11583/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011584static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011585 '\n', '(', ')', /* singles */
11586 '&', '|', ';', /* doubles */
11587 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011588};
Eric Andersencb57d552001-06-28 07:25:16 +000011589
Denis Vlasenko834dee72008-10-07 09:18:30 +000011590#define xxreadtoken_singles 3
11591#define xxreadtoken_doubles 3
11592
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011593static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011594 TNL, TLP, TRP, /* only single occurrence allowed */
11595 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11596 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011597 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011598};
11599
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011600static int
11601xxreadtoken(void)
11602{
11603 int c;
11604
11605 if (tokpushback) {
11606 tokpushback = 0;
11607 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011608 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011609 if (needprompt) {
11610 setprompt(2);
11611 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011612 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011613 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011614 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011615 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011616 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011617
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011618 if (c == '#') {
11619 while ((c = pgetc()) != '\n' && c != PEOF)
11620 continue;
11621 pungetc();
11622 } else if (c == '\\') {
11623 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011625 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011626 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011627 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011628 if (doprompt)
11629 setprompt(2);
11630 } else {
11631 const char *p;
11632
11633 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11634 if (c != PEOF) {
11635 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011636 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011637 needprompt = doprompt;
11638 }
11639
11640 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011641 if (p == NULL)
11642 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011643
Denis Vlasenko834dee72008-10-07 09:18:30 +000011644 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11645 int cc = pgetc();
11646 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011647 p += xxreadtoken_doubles + 1;
11648 } else {
11649 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011650#if ENABLE_ASH_BASH_COMPAT
11651 if (c == '&' && cc == '>') /* &> */
11652 break; /* return readtoken1(...) */
11653#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011654 }
11655 }
11656 }
11657 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11658 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011659 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011660 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011661
11662 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011663}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011664#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011665#define RETURN(token) return lasttoken = token
11666static int
11667xxreadtoken(void)
11668{
11669 int c;
11670
11671 if (tokpushback) {
11672 tokpushback = 0;
11673 return lasttoken;
11674 }
11675 if (needprompt) {
11676 setprompt(2);
11677 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011678 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011679 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011680 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011681 switch (c) {
11682 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011683 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011684 continue;
11685 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011686 while ((c = pgetc()) != '\n' && c != PEOF)
11687 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011688 pungetc();
11689 continue;
11690 case '\\':
11691 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011692 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011693 if (doprompt)
11694 setprompt(2);
11695 continue;
11696 }
11697 pungetc();
11698 goto breakloop;
11699 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011700 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011701 needprompt = doprompt;
11702 RETURN(TNL);
11703 case PEOF:
11704 RETURN(TEOF);
11705 case '&':
11706 if (pgetc() == '&')
11707 RETURN(TAND);
11708 pungetc();
11709 RETURN(TBACKGND);
11710 case '|':
11711 if (pgetc() == '|')
11712 RETURN(TOR);
11713 pungetc();
11714 RETURN(TPIPE);
11715 case ';':
11716 if (pgetc() == ';')
11717 RETURN(TENDCASE);
11718 pungetc();
11719 RETURN(TSEMI);
11720 case '(':
11721 RETURN(TLP);
11722 case ')':
11723 RETURN(TRP);
11724 default:
11725 goto breakloop;
11726 }
11727 }
11728 breakloop:
11729 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11730#undef RETURN
11731}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011732#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011733
11734static int
11735readtoken(void)
11736{
11737 int t;
11738#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011739 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011740#endif
11741
11742#if ENABLE_ASH_ALIAS
11743 top:
11744#endif
11745
11746 t = xxreadtoken();
11747
11748 /*
11749 * eat newlines
11750 */
11751 if (checkkwd & CHKNL) {
11752 while (t == TNL) {
11753 parseheredoc();
11754 t = xxreadtoken();
11755 }
11756 }
11757
11758 if (t != TWORD || quoteflag) {
11759 goto out;
11760 }
11761
11762 /*
11763 * check for keywords
11764 */
11765 if (checkkwd & CHKKWD) {
11766 const char *const *pp;
11767
11768 pp = findkwd(wordtext);
11769 if (pp) {
11770 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011771 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011772 goto out;
11773 }
11774 }
11775
11776 if (checkkwd & CHKALIAS) {
11777#if ENABLE_ASH_ALIAS
11778 struct alias *ap;
11779 ap = lookupalias(wordtext, 1);
11780 if (ap != NULL) {
11781 if (*ap->val) {
11782 pushstring(ap->val, ap);
11783 }
11784 goto top;
11785 }
11786#endif
11787 }
11788 out:
11789 checkkwd = 0;
11790#if DEBUG
11791 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011792 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011793 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011794 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011795#endif
11796 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011797}
11798
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011799static char
11800peektoken(void)
11801{
11802 int t;
11803
11804 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011805 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011806 return tokname_array[t][0];
11807}
Eric Andersencb57d552001-06-28 07:25:16 +000011808
11809/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011810 * Read and parse a command. Returns NODE_EOF on end of file.
11811 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011812 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011813static union node *
11814parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011815{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011816 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011817
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 tokpushback = 0;
11819 doprompt = interact;
11820 if (doprompt)
11821 setprompt(doprompt);
11822 needprompt = 0;
11823 t = readtoken();
11824 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011825 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011826 if (t == TNL)
11827 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011828 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011829 return list(1);
11830}
11831
11832/*
11833 * Input any here documents.
11834 */
11835static void
11836parseheredoc(void)
11837{
11838 struct heredoc *here;
11839 union node *n;
11840
11841 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011842 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011843
11844 while (here) {
11845 if (needprompt) {
11846 setprompt(2);
11847 }
11848 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11849 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011850 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011851 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011852 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011853 n->narg.text = wordtext;
11854 n->narg.backquote = backquotelist;
11855 here->here->nhere.doc = n;
11856 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011857 }
Eric Andersencb57d552001-06-28 07:25:16 +000011858}
11859
11860
11861/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011862 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011863 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011864#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011865static const char *
11866expandstr(const char *ps)
11867{
11868 union node n;
11869
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011870 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11871 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011872 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011873 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011874 popfile();
11875
11876 n.narg.type = NARG;
11877 n.narg.next = NULL;
11878 n.narg.text = wordtext;
11879 n.narg.backquote = backquotelist;
11880
11881 expandarg(&n, NULL, 0);
11882 return stackblock();
11883}
11884#endif
11885
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011886/*
11887 * Execute a command or commands contained in a string.
11888 */
11889static int
11890evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011891{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011892 union node *n;
11893 struct stackmark smark;
11894 int skip;
11895
11896 setinputstring(s);
11897 setstackmark(&smark);
11898
11899 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011900 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011901 evaltree(n, 0);
11902 popstackmark(&smark);
11903 skip = evalskip;
11904 if (skip)
11905 break;
11906 }
11907 popfile();
11908
11909 skip &= mask;
11910 evalskip = skip;
11911 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011912}
11913
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011914/*
11915 * The eval command.
11916 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011917static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011918evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011919{
11920 char *p;
11921 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011922
Denis Vlasenko68404f12008-03-17 09:00:54 +000011923 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011924 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011925 argv += 2;
11926 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011927 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011928 for (;;) {
11929 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011930 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011931 if (p == NULL)
11932 break;
11933 STPUTC(' ', concat);
11934 }
11935 STPUTC('\0', concat);
11936 p = grabstackstr(concat);
11937 }
11938 evalstring(p, ~SKIPEVAL);
11939
11940 }
11941 return exitstatus;
11942}
11943
11944/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011945 * Read and execute commands.
11946 * "Top" is nonzero for the top level command loop;
11947 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011948 */
11949static int
11950cmdloop(int top)
11951{
11952 union node *n;
11953 struct stackmark smark;
11954 int inter;
11955 int numeof = 0;
11956
11957 TRACE(("cmdloop(%d) called\n", top));
11958 for (;;) {
11959 int skip;
11960
11961 setstackmark(&smark);
11962#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011963 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011964 showjobs(stderr, SHOW_CHANGED);
11965#endif
11966 inter = 0;
11967 if (iflag && top) {
11968 inter++;
11969#if ENABLE_ASH_MAIL
11970 chkmail();
11971#endif
11972 }
11973 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011974#if DEBUG
11975 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011976 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011977#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011978 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011979 if (!top || numeof >= 50)
11980 break;
11981 if (!stoppedjobs()) {
11982 if (!Iflag)
11983 break;
11984 out2str("\nUse \"exit\" to leave shell.\n");
11985 }
11986 numeof++;
11987 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011988 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11989 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011990 numeof = 0;
11991 evaltree(n, 0);
11992 }
11993 popstackmark(&smark);
11994 skip = evalskip;
11995
11996 if (skip) {
11997 evalskip = 0;
11998 return skip & SKIPEVAL;
11999 }
12000 }
12001 return 0;
12002}
12003
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012004/*
12005 * Take commands from a file. To be compatible we should do a path
12006 * search for the file, which is necessary to find sub-commands.
12007 */
12008static char *
12009find_dot_file(char *name)
12010{
12011 char *fullname;
12012 const char *path = pathval();
12013 struct stat statb;
12014
12015 /* don't try this for absolute or relative paths */
12016 if (strchr(name, '/'))
12017 return name;
12018
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012019 /* IIRC standards do not say whether . is to be searched.
12020 * And it is even smaller this way, making it unconditional for now:
12021 */
12022 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12023 fullname = name;
12024 goto try_cur_dir;
12025 }
12026
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012027 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012028 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012029 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12030 /*
12031 * Don't bother freeing here, since it will
12032 * be freed by the caller.
12033 */
12034 return fullname;
12035 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012036 if (fullname != name)
12037 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012038 }
12039
12040 /* not found in the PATH */
12041 ash_msg_and_raise_error("%s: not found", name);
12042 /* NOTREACHED */
12043}
12044
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012045static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046dotcmd(int argc, char **argv)
12047{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012048 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012049 struct strlist *sp;
12050 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012051
12052 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012053 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012054
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012055 if (!argv[1]) {
12056 /* bash says: "bash: .: filename argument required" */
12057 return 2; /* bash compat */
12058 }
12059
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012060 /* "false; . empty_file; echo $?" should print 0, not 1: */
12061 exitstatus = 0;
12062
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012063 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012064
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012065 argv += 2;
12066 argc -= 2;
12067 if (argc) { /* argc > 0, argv[0] != NULL */
12068 saveparam = shellparam;
12069 shellparam.malloced = 0;
12070 shellparam.nparam = argc;
12071 shellparam.p = argv;
12072 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012073
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012074 setinputfile(fullname, INPUT_PUSH_FILE);
12075 commandname = fullname;
12076 cmdloop(0);
12077 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012078
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012079 if (argc) {
12080 freeparam(&shellparam);
12081 shellparam = saveparam;
12082 };
12083
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012084 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012085}
12086
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012087static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012088exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012089{
12090 if (stoppedjobs())
12091 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012092 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012093 exitstatus = number(argv[1]);
12094 raise_exception(EXEXIT);
12095 /* NOTREACHED */
12096}
12097
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012098/*
12099 * Read a file containing shell functions.
12100 */
12101static void
12102readcmdfile(char *name)
12103{
12104 setinputfile(name, INPUT_PUSH_FILE);
12105 cmdloop(0);
12106 popfile();
12107}
12108
12109
Denis Vlasenkocc571512007-02-23 21:10:35 +000012110/* ============ find_command inplementation */
12111
12112/*
12113 * Resolve a command name. If you change this routine, you may have to
12114 * change the shellexec routine as well.
12115 */
12116static void
12117find_command(char *name, struct cmdentry *entry, int act, const char *path)
12118{
12119 struct tblentry *cmdp;
12120 int idx;
12121 int prev;
12122 char *fullname;
12123 struct stat statb;
12124 int e;
12125 int updatetbl;
12126 struct builtincmd *bcmd;
12127
12128 /* If name contains a slash, don't use PATH or hash table */
12129 if (strchr(name, '/') != NULL) {
12130 entry->u.index = -1;
12131 if (act & DO_ABS) {
12132 while (stat(name, &statb) < 0) {
12133#ifdef SYSV
12134 if (errno == EINTR)
12135 continue;
12136#endif
12137 entry->cmdtype = CMDUNKNOWN;
12138 return;
12139 }
12140 }
12141 entry->cmdtype = CMDNORMAL;
12142 return;
12143 }
12144
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012145/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012146
12147 updatetbl = (path == pathval());
12148 if (!updatetbl) {
12149 act |= DO_ALTPATH;
12150 if (strstr(path, "%builtin") != NULL)
12151 act |= DO_ALTBLTIN;
12152 }
12153
12154 /* If name is in the table, check answer will be ok */
12155 cmdp = cmdlookup(name, 0);
12156 if (cmdp != NULL) {
12157 int bit;
12158
12159 switch (cmdp->cmdtype) {
12160 default:
12161#if DEBUG
12162 abort();
12163#endif
12164 case CMDNORMAL:
12165 bit = DO_ALTPATH;
12166 break;
12167 case CMDFUNCTION:
12168 bit = DO_NOFUNC;
12169 break;
12170 case CMDBUILTIN:
12171 bit = DO_ALTBLTIN;
12172 break;
12173 }
12174 if (act & bit) {
12175 updatetbl = 0;
12176 cmdp = NULL;
12177 } else if (cmdp->rehash == 0)
12178 /* if not invalidated by cd, we're done */
12179 goto success;
12180 }
12181
12182 /* If %builtin not in path, check for builtin next */
12183 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012184 if (bcmd) {
12185 if (IS_BUILTIN_REGULAR(bcmd))
12186 goto builtin_success;
12187 if (act & DO_ALTPATH) {
12188 if (!(act & DO_ALTBLTIN))
12189 goto builtin_success;
12190 } else if (builtinloc <= 0) {
12191 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012192 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012193 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012194
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012195#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012196 {
12197 int applet_no = find_applet_by_name(name);
12198 if (applet_no >= 0) {
12199 entry->cmdtype = CMDNORMAL;
12200 entry->u.index = -2 - applet_no;
12201 return;
12202 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012203 }
12204#endif
12205
Denis Vlasenkocc571512007-02-23 21:10:35 +000012206 /* We have to search path. */
12207 prev = -1; /* where to start */
12208 if (cmdp && cmdp->rehash) { /* doing a rehash */
12209 if (cmdp->cmdtype == CMDBUILTIN)
12210 prev = builtinloc;
12211 else
12212 prev = cmdp->param.index;
12213 }
12214
12215 e = ENOENT;
12216 idx = -1;
12217 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012218 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012219 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012220 /* NB: code below will still use fullname
12221 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012222 idx++;
12223 if (pathopt) {
12224 if (prefix(pathopt, "builtin")) {
12225 if (bcmd)
12226 goto builtin_success;
12227 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012228 }
12229 if ((act & DO_NOFUNC)
12230 || !prefix(pathopt, "func")
12231 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012232 continue;
12233 }
12234 }
12235 /* if rehash, don't redo absolute path names */
12236 if (fullname[0] == '/' && idx <= prev) {
12237 if (idx < prev)
12238 continue;
12239 TRACE(("searchexec \"%s\": no change\n", name));
12240 goto success;
12241 }
12242 while (stat(fullname, &statb) < 0) {
12243#ifdef SYSV
12244 if (errno == EINTR)
12245 continue;
12246#endif
12247 if (errno != ENOENT && errno != ENOTDIR)
12248 e = errno;
12249 goto loop;
12250 }
12251 e = EACCES; /* if we fail, this will be the error */
12252 if (!S_ISREG(statb.st_mode))
12253 continue;
12254 if (pathopt) { /* this is a %func directory */
12255 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012256 /* NB: stalloc will return space pointed by fullname
12257 * (because we don't have any intervening allocations
12258 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012259 readcmdfile(fullname);
12260 cmdp = cmdlookup(name, 0);
12261 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12262 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12263 stunalloc(fullname);
12264 goto success;
12265 }
12266 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12267 if (!updatetbl) {
12268 entry->cmdtype = CMDNORMAL;
12269 entry->u.index = idx;
12270 return;
12271 }
12272 INT_OFF;
12273 cmdp = cmdlookup(name, 1);
12274 cmdp->cmdtype = CMDNORMAL;
12275 cmdp->param.index = idx;
12276 INT_ON;
12277 goto success;
12278 }
12279
12280 /* We failed. If there was an entry for this command, delete it */
12281 if (cmdp && updatetbl)
12282 delete_cmd_entry();
12283 if (act & DO_ERR)
12284 ash_msg("%s: %s", name, errmsg(e, "not found"));
12285 entry->cmdtype = CMDUNKNOWN;
12286 return;
12287
12288 builtin_success:
12289 if (!updatetbl) {
12290 entry->cmdtype = CMDBUILTIN;
12291 entry->u.cmd = bcmd;
12292 return;
12293 }
12294 INT_OFF;
12295 cmdp = cmdlookup(name, 1);
12296 cmdp->cmdtype = CMDBUILTIN;
12297 cmdp->param.cmd = bcmd;
12298 INT_ON;
12299 success:
12300 cmdp->rehash = 0;
12301 entry->cmdtype = cmdp->cmdtype;
12302 entry->u = cmdp->param;
12303}
12304
12305
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012306/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012307
Eric Andersencb57d552001-06-28 07:25:16 +000012308/*
Eric Andersencb57d552001-06-28 07:25:16 +000012309 * The trap builtin.
12310 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012311static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012312trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012313{
12314 char *action;
12315 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012316 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012317
Eric Andersenc470f442003-07-28 09:56:35 +000012318 nextopt(nullstr);
12319 ap = argptr;
12320 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012321 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012322 char *tr = trap_ptr[signo];
12323 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012324 /* note: bash adds "SIG", but only if invoked
12325 * as "bash". If called as "sh", or if set -o posix,
12326 * then it prints short signal names.
12327 * We are printing short names: */
12328 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012329 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012330 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012331 /* trap_ptr != trap only if we are in special-cased `trap` code.
12332 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012333 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012334 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012335 }
12336 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012337 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012338 if (trap_ptr != trap) {
12339 free(trap_ptr);
12340 trap_ptr = trap;
12341 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012342 */
Eric Andersencb57d552001-06-28 07:25:16 +000012343 return 0;
12344 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012345
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012346 action = NULL;
12347 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012348 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012349 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012350 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012351 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012352 if (signo < 0) {
12353 /* Mimic bash message exactly */
12354 ash_msg("%s: invalid signal specification", *ap);
12355 exitcode = 1;
12356 goto next;
12357 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012358 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012359 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012360 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012361 action = NULL;
12362 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012363 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012364 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012365 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012366 if (action)
12367 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012368 trap[signo] = action;
12369 if (signo != 0)
12370 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012371 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012372 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012373 ap++;
12374 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012375 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012376}
12377
Eric Andersenc470f442003-07-28 09:56:35 +000012378
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012379/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012380
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012381#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012382/*
12383 * Lists available builtins
12384 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012385static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012386helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012387{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012388 unsigned col;
12389 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012390
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012391 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012392 "Built-in commands:\n"
12393 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012394 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012395 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012396 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012397 if (col > 60) {
12398 out1fmt("\n");
12399 col = 0;
12400 }
12401 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012402#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012403 {
12404 const char *a = applet_names;
12405 while (*a) {
12406 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12407 if (col > 60) {
12408 out1fmt("\n");
12409 col = 0;
12410 }
12411 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012412 }
12413 }
12414#endif
12415 out1fmt("\n\n");
12416 return EXIT_SUCCESS;
12417}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012418#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012419
Eric Andersencb57d552001-06-28 07:25:16 +000012420/*
Eric Andersencb57d552001-06-28 07:25:16 +000012421 * The export and readonly commands.
12422 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012423static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012424exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012425{
12426 struct var *vp;
12427 char *name;
12428 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012429 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012430 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012431
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012432 if (nextopt("p") != 'p') {
12433 aptr = argptr;
12434 name = *aptr;
12435 if (name) {
12436 do {
12437 p = strchr(name, '=');
12438 if (p != NULL) {
12439 p++;
12440 } else {
12441 vp = *findvar(hashvar(name), name);
12442 if (vp) {
12443 vp->flags |= flag;
12444 continue;
12445 }
Eric Andersencb57d552001-06-28 07:25:16 +000012446 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012447 setvar(name, p, flag);
12448 } while ((name = *++aptr) != NULL);
12449 return 0;
12450 }
Eric Andersencb57d552001-06-28 07:25:16 +000012451 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012452 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012453 return 0;
12454}
12455
Eric Andersencb57d552001-06-28 07:25:16 +000012456/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012457 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012458 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012459static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012460unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012461{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012462 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012463
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012464 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012465 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012466 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012467}
12468
Eric Andersencb57d552001-06-28 07:25:16 +000012469/*
Eric Andersencb57d552001-06-28 07:25:16 +000012470 * The unset builtin command. We unset the function before we unset the
12471 * variable to allow a function to be unset when there is a readonly variable
12472 * with the same name.
12473 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012474static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012475unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012476{
12477 char **ap;
12478 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012479 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012480 int ret = 0;
12481
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012482 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012483 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012484 }
Eric Andersencb57d552001-06-28 07:25:16 +000012485
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012486 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012487 if (flag != 'f') {
12488 i = unsetvar(*ap);
12489 ret |= i;
12490 if (!(i & 2))
12491 continue;
12492 }
12493 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012494 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012495 }
Eric Andersenc470f442003-07-28 09:56:35 +000012496 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012497}
12498
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012499static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012500 ' ', offsetof(struct tms, tms_utime),
12501 '\n', offsetof(struct tms, tms_stime),
12502 ' ', offsetof(struct tms, tms_cutime),
12503 '\n', offsetof(struct tms, tms_cstime),
12504 0
12505};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012506static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012507timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012508{
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012509 unsigned long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012510 const unsigned char *p;
12511 struct tms buf;
12512
12513 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012514 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012515
12516 p = timescmd_str;
12517 do {
12518 t = *(clock_t *)(((char *) &buf) + p[1]);
12519 s = t / clk_tck;
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012520 t = t % clk_tck;
12521 out1fmt("%lum%lu.%03lus%c",
12522 s / 60, s % 60,
12523 (t * 1000) / clk_tck,
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012524 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012525 p += 2;
12526 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012527
Eric Andersencb57d552001-06-28 07:25:16 +000012528 return 0;
12529}
12530
Mike Frysinger98c52642009-04-02 10:02:37 +000012531#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012532/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012533 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012534 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012535 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012536 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012537 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012538static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012539letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012540{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012541 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012542
Denis Vlasenko68404f12008-03-17 09:00:54 +000012543 argv++;
12544 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012545 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012546 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012547 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012548 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012549
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012550 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012551}
Eric Andersenc470f442003-07-28 09:56:35 +000012552#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012553
Eric Andersenc470f442003-07-28 09:56:35 +000012554/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012555 * The read builtin. Options:
12556 * -r Do not interpret '\' specially
12557 * -s Turn off echo (tty only)
12558 * -n NCHARS Read NCHARS max
12559 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12560 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12561 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012562 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563 * TODO: bash also has:
12564 * -a ARRAY Read into array[0],[1],etc
12565 * -d DELIM End on DELIM char, not newline
12566 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012567 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012568static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012569readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012570{
Denys Vlasenko73067272010-01-12 22:11:24 +010012571 char *opt_n = NULL;
12572 char *opt_p = NULL;
12573 char *opt_t = NULL;
12574 char *opt_u = NULL;
12575 int read_flags = 0;
12576 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012577 int i;
12578
Denys Vlasenko73067272010-01-12 22:11:24 +010012579 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012580 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012581 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012582 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012583 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012584 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012585 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012586 break;
12587 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012588 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012589 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012590 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012591 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012593 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012594 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012595 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012596 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012597 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012598 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012599 default:
12600 break;
12601 }
Eric Andersenc470f442003-07-28 09:56:35 +000012602 }
Paul Fox02eb9342005-09-07 16:56:02 +000012603
Denys Vlasenko03dad222010-01-12 23:29:57 +010012604 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012605 argptr,
12606 bltinlookup("IFS"), /* can be NULL */
12607 read_flags,
12608 opt_n,
12609 opt_p,
12610 opt_t,
12611 opt_u
12612 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012613
Denys Vlasenko73067272010-01-12 22:11:24 +010012614 if ((uintptr_t)r > 1)
12615 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012616
Denys Vlasenko73067272010-01-12 22:11:24 +010012617 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012618}
12619
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012620static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012621umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012622{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012623 static const char permuser[3] ALIGN1 = "ugo";
12624 static const char permmode[3] ALIGN1 = "rwx";
12625 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012626 S_IRUSR, S_IWUSR, S_IXUSR,
12627 S_IRGRP, S_IWGRP, S_IXGRP,
12628 S_IROTH, S_IWOTH, S_IXOTH
12629 };
12630
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012631 /* TODO: use bb_parse_mode() instead */
12632
Eric Andersenc470f442003-07-28 09:56:35 +000012633 char *ap;
12634 mode_t mask;
12635 int i;
12636 int symbolic_mode = 0;
12637
12638 while (nextopt("S") != '\0') {
12639 symbolic_mode = 1;
12640 }
12641
Denis Vlasenkob012b102007-02-19 22:43:01 +000012642 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012643 mask = umask(0);
12644 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012645 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012646
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012647 ap = *argptr;
12648 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012649 if (symbolic_mode) {
12650 char buf[18];
12651 char *p = buf;
12652
12653 for (i = 0; i < 3; i++) {
12654 int j;
12655
12656 *p++ = permuser[i];
12657 *p++ = '=';
12658 for (j = 0; j < 3; j++) {
12659 if ((mask & permmask[3 * i + j]) == 0) {
12660 *p++ = permmode[j];
12661 }
12662 }
12663 *p++ = ',';
12664 }
12665 *--p = 0;
12666 puts(buf);
12667 } else {
12668 out1fmt("%.4o\n", mask);
12669 }
12670 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012671 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012672 mask = 0;
12673 do {
12674 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012675 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012676 mask = (mask << 3) + (*ap - '0');
12677 } while (*++ap != '\0');
12678 umask(mask);
12679 } else {
12680 mask = ~mask & 0777;
12681 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012682 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012683 }
12684 umask(~mask & 0777);
12685 }
12686 }
12687 return 0;
12688}
12689
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012690static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012691ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012692{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012693 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012694}
12695
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012696/* ============ main() and helpers */
12697
12698/*
12699 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012700 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012701static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012702static void
12703exitshell(void)
12704{
12705 struct jmploc loc;
12706 char *p;
12707 int status;
12708
12709 status = exitstatus;
12710 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12711 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012712 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012713/* dash bug: it just does _exit(exitstatus) here
12714 * but we have to do setjobctl(0) first!
12715 * (bug is still not fixed in dash-0.5.3 - if you run dash
12716 * under Midnight Commander, on exit from dash MC is backgrounded) */
12717 status = exitstatus;
12718 goto out;
12719 }
12720 exception_handler = &loc;
12721 p = trap[0];
12722 if (p) {
12723 trap[0] = NULL;
12724 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012725 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012726 }
12727 flush_stdout_stderr();
12728 out:
12729 setjobctl(0);
12730 _exit(status);
12731 /* NOTREACHED */
12732}
12733
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012734static void
12735init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012736{
12737 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012738 /* we will never free this */
12739 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012740
12741 /* from trap.c: */
12742 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012743 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12744 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12745 */
12746 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012747
12748 /* from var.c: */
12749 {
12750 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012751 const char *p;
12752 struct stat st1, st2;
12753
12754 initvar();
12755 for (envp = environ; envp && *envp; envp++) {
12756 if (strchr(*envp, '=')) {
12757 setvareq(*envp, VEXPORT|VTEXTFIXED);
12758 }
12759 }
12760
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012761 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012762
12763 p = lookupvar("PWD");
12764 if (p)
12765 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12766 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12767 p = '\0';
12768 setpwd(p, 0);
12769 }
12770}
12771
12772/*
12773 * Process the shell command line arguments.
12774 */
12775static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012776procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012777{
12778 int i;
12779 const char *xminusc;
12780 char **xargv;
12781
12782 xargv = argv;
12783 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012784 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012785 xargv++;
12786 for (i = 0; i < NOPTS; i++)
12787 optlist[i] = 2;
12788 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012789 if (options(1)) {
12790 /* it already printed err message */
12791 raise_exception(EXERROR);
12792 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012793 xargv = argptr;
12794 xminusc = minusc;
12795 if (*xargv == NULL) {
12796 if (xminusc)
12797 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12798 sflag = 1;
12799 }
12800 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12801 iflag = 1;
12802 if (mflag == 2)
12803 mflag = iflag;
12804 for (i = 0; i < NOPTS; i++)
12805 if (optlist[i] == 2)
12806 optlist[i] = 0;
12807#if DEBUG == 2
12808 debug = 1;
12809#endif
12810 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12811 if (xminusc) {
12812 minusc = *xargv++;
12813 if (*xargv)
12814 goto setarg0;
12815 } else if (!sflag) {
12816 setinputfile(*xargv, 0);
12817 setarg0:
12818 arg0 = *xargv++;
12819 commandname = arg0;
12820 }
12821
12822 shellparam.p = xargv;
12823#if ENABLE_ASH_GETOPTS
12824 shellparam.optind = 1;
12825 shellparam.optoff = -1;
12826#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012827 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012828 while (*xargv) {
12829 shellparam.nparam++;
12830 xargv++;
12831 }
12832 optschanged();
12833}
12834
12835/*
12836 * Read /etc/profile or .profile.
12837 */
12838static void
12839read_profile(const char *name)
12840{
12841 int skip;
12842
12843 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12844 return;
12845 skip = cmdloop(0);
12846 popfile();
12847 if (skip)
12848 exitshell();
12849}
12850
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012851/*
12852 * This routine is called when an error or an interrupt occurs in an
12853 * interactive shell and control is returned to the main command loop.
12854 */
12855static void
12856reset(void)
12857{
12858 /* from eval.c: */
12859 evalskip = 0;
12860 loopnest = 0;
12861 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012862 g_parsefile->left_in_buffer = 0;
12863 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012864 popallfiles();
12865 /* from parser.c: */
12866 tokpushback = 0;
12867 checkkwd = 0;
12868 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012869 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012870}
12871
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012872#if PROFILE
12873static short profile_buf[16384];
12874extern int etext();
12875#endif
12876
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012877/*
12878 * Main routine. We initialize things, parse the arguments, execute
12879 * profiles if we're a login shell, and then call cmdloop to execute
12880 * commands. The setjmp call sets up the location to jump to when an
12881 * exception occurs. When an exception occurs the variable "state"
12882 * is used to figure out how far we had gotten.
12883 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012884int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012885int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012886{
Mike Frysinger98c52642009-04-02 10:02:37 +000012887 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012888 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012889 struct jmploc jmploc;
12890 struct stackmark smark;
12891
Denis Vlasenko01631112007-12-16 17:20:38 +000012892 /* Initialize global data */
12893 INIT_G_misc();
12894 INIT_G_memstack();
12895 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012896#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012897 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012898#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012899 INIT_G_cmdtable();
12900
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012901#if PROFILE
12902 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12903#endif
12904
12905#if ENABLE_FEATURE_EDITING
12906 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12907#endif
12908 state = 0;
12909 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012910 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012911 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012912
12913 reset();
12914
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012915 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012916 if (e == EXERROR)
12917 exitstatus = 2;
12918 s = state;
12919 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12920 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012921 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012922 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012923
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012924 popstackmark(&smark);
12925 FORCE_INT_ON; /* enable interrupts */
12926 if (s == 1)
12927 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012928 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012929 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012930 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012931 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012932 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012933 }
12934 exception_handler = &jmploc;
12935#if DEBUG
12936 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012937 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012938 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012939#endif
12940 rootpid = getpid();
12941
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012942 init();
12943 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012944 procargs(argv);
12945
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012946#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12947 if (iflag) {
12948 const char *hp = lookupvar("HISTFILE");
12949
12950 if (hp == NULL) {
12951 hp = lookupvar("HOME");
12952 if (hp != NULL) {
12953 char *defhp = concat_path_file(hp, ".ash_history");
12954 setvar("HISTFILE", defhp, 0);
12955 free(defhp);
12956 }
12957 }
12958 }
12959#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012960 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012961 isloginsh = 1;
12962 if (isloginsh) {
12963 state = 1;
12964 read_profile("/etc/profile");
12965 state1:
12966 state = 2;
12967 read_profile(".profile");
12968 }
12969 state2:
12970 state = 3;
12971 if (
12972#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012973 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012974#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012975 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012976 ) {
12977 shinit = lookupvar("ENV");
12978 if (shinit != NULL && *shinit != '\0') {
12979 read_profile(shinit);
12980 }
12981 }
12982 state3:
12983 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012984 if (minusc) {
12985 /* evalstring pushes parsefile stack.
12986 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012987 * is one of stacked source fds.
12988 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020012989 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020012990 // ^^ not necessary since now we special-case fd 0
12991 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012992 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012993 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012994
12995 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010012996#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000012997 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012998 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012999 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013000 line_input_state->hist_file = hp;
13001 }
13002#endif
13003 state4: /* XXX ??? - why isn't this before the "if" statement */
13004 cmdloop(1);
13005 }
13006#if PROFILE
13007 monitor(0);
13008#endif
13009#ifdef GPROF
13010 {
13011 extern void _mcleanup(void);
13012 _mcleanup();
13013 }
13014#endif
13015 exitshell();
13016 /* NOTREACHED */
13017}
13018
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013019
Eric Andersendf82f612001-06-28 07:46:40 +000013020/*-
13021 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013022 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013023 *
13024 * This code is derived from software contributed to Berkeley by
13025 * Kenneth Almquist.
13026 *
13027 * Redistribution and use in source and binary forms, with or without
13028 * modification, are permitted provided that the following conditions
13029 * are met:
13030 * 1. Redistributions of source code must retain the above copyright
13031 * notice, this list of conditions and the following disclaimer.
13032 * 2. Redistributions in binary form must reproduce the above copyright
13033 * notice, this list of conditions and the following disclaimer in the
13034 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013035 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013036 * may be used to endorse or promote products derived from this software
13037 * without specific prior written permission.
13038 *
13039 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13040 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13041 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13042 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13043 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13044 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13045 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13046 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13047 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13048 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13049 * SUCH DAMAGE.
13050 */