blob: 0a8b6c0f2e9d3bf34321caebfd5aa2e7de308496 [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000016 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenkob012b102007-02-19 22:43:01 +000039#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000040# ifndef _GNU_SOURCE
41# define _GNU_SOURCE
42# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000043#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000044
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000045#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000046//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
47//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000048#include <paths.h>
49#include <setjmp.h>
50#include <fnmatch.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010051
52#include "shell_common.h"
53#include "builtin_read.h"
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010054#include "builtin_ulimit.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000055#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020056#if ENABLE_ASH_RANDOM_SUPPORT
57# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020058#else
59# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020060#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000061
62#if defined SINGLE_APPLET_MAIN
63/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020064# undef CONFIG_FEATURE_SH_STANDALONE
65# undef ENABLE_FEATURE_SH_STANDALONE
66# undef IF_FEATURE_SH_STANDALONE
67# undef IF_NOT_FEATURE_SH_STANDALONE(...)
68# define ENABLE_FEATURE_SH_STANDALONE 0
69# define IF_FEATURE_SH_STANDALONE(...)
70# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000071#endif
72
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000074# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000075#endif
76
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010077#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000078# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000079#endif
80
Denis Vlasenkob012b102007-02-19 22:43:01 +000081
Denis Vlasenko01631112007-12-16 17:20:38 +000082/* ============ Hash table sizes. Configurable. */
83
84#define VTABSIZE 39
85#define ATABSIZE 39
86#define CMDTABLESIZE 31 /* should be prime */
87
88
Denis Vlasenkob012b102007-02-19 22:43:01 +000089/* ============ Shell options */
90
91static const char *const optletters_optnames[] = {
92 "e" "errexit",
93 "f" "noglob",
94 "I" "ignoreeof",
95 "i" "interactive",
96 "m" "monitor",
97 "n" "noexec",
98 "s" "stdin",
99 "x" "xtrace",
100 "v" "verbose",
101 "C" "noclobber",
102 "a" "allexport",
103 "b" "notify",
104 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100105 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100106#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100107 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100108#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000110 ,"\0" "nolog"
111 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112#endif
113};
114
Denys Vlasenko285ad152009-12-04 23:02:27 +0100115#define optletters(n) optletters_optnames[n][0]
116#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000117
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000118enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000119
Eric Andersenc470f442003-07-28 09:56:35 +0000120
Denis Vlasenkob012b102007-02-19 22:43:01 +0000121/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000122
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000123static const char homestr[] ALIGN1 = "HOME";
124static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200125static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000126
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000127/*
Eric Andersenc470f442003-07-28 09:56:35 +0000128 * We enclose jmp_buf in a structure so that we can declare pointers to
129 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000130 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000131 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000132 * exception handlers, the user should save the value of handler on entry
133 * to an inner scope, set handler to point to a jmploc structure for the
134 * inner scope, and restore handler on exit from the scope.
135 */
Eric Andersenc470f442003-07-28 09:56:35 +0000136struct jmploc {
137 jmp_buf loc;
138};
Denis Vlasenko01631112007-12-16 17:20:38 +0000139
140struct globals_misc {
141 /* pid of main shell */
142 int rootpid;
143 /* shell level: 0 for the main shell, 1 for its children, and so on */
144 int shlvl;
145#define rootshell (!shlvl)
146 char *minusc; /* argument to -c option */
147
148 char *curdir; // = nullstr; /* current working directory */
149 char *physdir; // = nullstr; /* physical working directory */
150
151 char *arg0; /* value of $0 */
152
153 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000154
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200155 volatile int suppress_int; /* counter */
156 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000157 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200158 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000159 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000160 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000161#define EXINT 0 /* SIGINT received */
162#define EXERROR 1 /* a generic error */
163#define EXSHELLPROC 2 /* execute a shell procedure */
164#define EXEXEC 3 /* command execution failed */
165#define EXEXIT 4 /* exit the shell */
166#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000167
Denis Vlasenko01631112007-12-16 17:20:38 +0000168 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000169 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000170
171 char optlist[NOPTS];
172#define eflag optlist[0]
173#define fflag optlist[1]
174#define Iflag optlist[2]
175#define iflag optlist[3]
176#define mflag optlist[4]
177#define nflag optlist[5]
178#define sflag optlist[6]
179#define xflag optlist[7]
180#define vflag optlist[8]
181#define Cflag optlist[9]
182#define aflag optlist[10]
183#define bflag optlist[11]
184#define uflag optlist[12]
185#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100186#if ENABLE_ASH_BASH_COMPAT
187# define pipefail optlist[14]
188#else
189# define pipefail 0
190#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000191#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100192# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
193# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000194#endif
195
196 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000197 /*
198 * Sigmode records the current value of the signal handlers for the various
199 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000200 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000201 */
202 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000203#define S_DFL 1 /* default signal handling (SIG_DFL) */
204#define S_CATCH 2 /* signal is caught */
205#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000206#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000207
Denis Vlasenko01631112007-12-16 17:20:38 +0000208 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000209 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000210 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200211 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000212
213 /* Rarely referenced stuff */
214#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200215 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000216#endif
217 pid_t backgndpid; /* pid of last background process */
218 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000219};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000220extern struct globals_misc *const ash_ptr_to_globals_misc;
221#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000222#define rootpid (G_misc.rootpid )
223#define shlvl (G_misc.shlvl )
224#define minusc (G_misc.minusc )
225#define curdir (G_misc.curdir )
226#define physdir (G_misc.physdir )
227#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000228#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000229#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200230#define suppress_int (G_misc.suppress_int )
231#define pending_int (G_misc.pending_int )
232#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000233#define isloginsh (G_misc.isloginsh )
234#define nullstr (G_misc.nullstr )
235#define optlist (G_misc.optlist )
236#define sigmode (G_misc.sigmode )
237#define gotsig (G_misc.gotsig )
238#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200239#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200240#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000241#define backgndpid (G_misc.backgndpid )
242#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000243#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
245 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000246 curdir = nullstr; \
247 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200248 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000249} while (0)
250
251
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252/* ============ DEBUG */
253#if DEBUG
254static void trace_printf(const char *fmt, ...);
255static void trace_vprintf(const char *fmt, va_list va);
256# define TRACE(param) trace_printf param
257# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000258# define close(fd) do { \
259 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000260 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200261 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000262 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000263} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#else
265# define TRACE(param)
266# define TRACEV(param)
267#endif
268
269
Denis Vlasenko559691a2008-10-05 18:39:31 +0000270/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000271#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272
Denis Vlasenko559691a2008-10-05 18:39:31 +0000273static int isdigit_str9(const char *str)
274{
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
277 str++;
278 return (*str == '\0');
279}
Denis Vlasenko01631112007-12-16 17:20:38 +0000280
Denis Vlasenko559691a2008-10-05 18:39:31 +0000281
282/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000283/*
Eric Andersen2870d962001-07-02 17:27:21 +0000284 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000285 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000286 * much more efficient and portable. (But hacking the kernel is so much
287 * more fun than worrying about efficiency and portability. :-))
288 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000289#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200290 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000291 xbarrier(); \
292} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000293
294/*
295 * Called to raise an exception. Since C doesn't include exceptions, we
296 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000297 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000299static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300static void
301raise_exception(int e)
302{
303#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000304 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000305 abort();
306#endif
307 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000308 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000309 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000310}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000311#if DEBUG
312#define raise_exception(e) do { \
313 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
314 raise_exception(e); \
315} while (0)
316#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317
318/*
319 * Called from trap.c when a SIGINT is received. (If the user specifies
320 * that SIGINT is to be trapped or ignored using the trap builtin, then
321 * this routine is not called.) Suppressint is nonzero when interrupts
322 * are held using the INT_OFF macro. (The test for iflag is just
323 * defensive programming.)
324 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000325static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000326static void
327raise_interrupt(void)
328{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000329 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000330
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200331 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000332 /* Signal is not automatically unmasked after it is raised,
333 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000334 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200335 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000336
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
339 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000340 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000341 signal(SIGINT, SIG_DFL);
342 raise(SIGINT);
343 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000344 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000346 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000347 /* NOTREACHED */
348}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000349#if DEBUG
350#define raise_interrupt() do { \
351 TRACE(("raising interrupt on line %d\n", __LINE__)); \
352 raise_interrupt(); \
353} while (0)
354#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000356static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000357int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000358{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000359 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200360 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361 raise_interrupt();
362 }
363}
364#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000365static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000366force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000367{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000368 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200369 suppress_int = 0;
370 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000371 raise_interrupt();
372}
373#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000374
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200375#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000377#define RESTORE_INT(v) do { \
378 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200379 suppress_int = (v); \
380 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000381 raise_interrupt(); \
382} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000383
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000384
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000385/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000386
Eric Andersenc470f442003-07-28 09:56:35 +0000387static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000388outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000389{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390 INT_OFF;
391 fputs(p, file);
392 INT_ON;
393}
394
395static void
396flush_stdout_stderr(void)
397{
398 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100399 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000400 INT_ON;
401}
402
403static void
404outcslow(int c, FILE *dest)
405{
406 INT_OFF;
407 putc(c, dest);
408 fflush(dest);
409 INT_ON;
410}
411
412static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
413static int
414out1fmt(const char *fmt, ...)
415{
416 va_list ap;
417 int r;
418
419 INT_OFF;
420 va_start(ap, fmt);
421 r = vprintf(fmt, ap);
422 va_end(ap);
423 INT_ON;
424 return r;
425}
426
427static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
428static int
429fmtstr(char *outbuf, size_t length, const char *fmt, ...)
430{
431 va_list ap;
432 int ret;
433
434 va_start(ap, fmt);
435 INT_OFF;
436 ret = vsnprintf(outbuf, length, fmt, ap);
437 va_end(ap);
438 INT_ON;
439 return ret;
440}
441
442static void
443out1str(const char *p)
444{
445 outstr(p, stdout);
446}
447
448static void
449out2str(const char *p)
450{
451 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100452 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000453}
454
455
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000456/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000457
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000458/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100459#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200460#define CTLESC ((unsigned char)'\201') /* escape next character */
461#define CTLVAR ((unsigned char)'\202') /* variable defn */
462#define CTLENDVAR ((unsigned char)'\203')
463#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000464#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
465/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200466#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
467#define CTLENDARI ((unsigned char)'\207')
468#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100469#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000470
471/* variable substitution byte (follows CTLVAR) */
472#define VSTYPE 0x0f /* type of variable substitution */
473#define VSNUL 0x10 /* colon--treat the empty string as unset */
474#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475
476/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000477#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478#define VSMINUS 0x2 /* ${var-text} */
479#define VSPLUS 0x3 /* ${var+text} */
480#define VSQUESTION 0x4 /* ${var?message} */
481#define VSASSIGN 0x5 /* ${var=text} */
482#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484#define VSTRIMLEFT 0x8 /* ${var#pattern} */
485#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486#define VSLENGTH 0xa /* ${#var} */
487#if ENABLE_ASH_BASH_COMPAT
488#define VSSUBSTR 0xc /* ${var:position:length} */
489#define VSREPLACE 0xd /* ${var/pattern/replacement} */
490#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000492
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000493static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
495};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000496
Denis Vlasenko559691a2008-10-05 18:39:31 +0000497#define NCMD 0
498#define NPIPE 1
499#define NREDIR 2
500#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000501#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000502#define NAND 5
503#define NOR 6
504#define NSEMI 7
505#define NIF 8
506#define NWHILE 9
507#define NUNTIL 10
508#define NFOR 11
509#define NCASE 12
510#define NCLIST 13
511#define NDEFUN 14
512#define NARG 15
513#define NTO 16
514#if ENABLE_ASH_BASH_COMPAT
515#define NTO2 17
516#endif
517#define NCLOBBER 18
518#define NFROM 19
519#define NFROMTO 20
520#define NAPPEND 21
521#define NTOFD 22
522#define NFROMFD 23
523#define NHERE 24
524#define NXHERE 25
525#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000526#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000527
528union node;
529
530struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000531 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000532 union node *assign;
533 union node *args;
534 union node *redirect;
535};
536
537struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000538 smallint type;
539 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 struct nodelist *cmdlist;
541};
542
543struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000544 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000545 union node *n;
546 union node *redirect;
547};
548
549struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000550 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000551 union node *ch1;
552 union node *ch2;
553};
554
555struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000556 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000557 union node *test;
558 union node *ifpart;
559 union node *elsepart;
560};
561
562struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000563 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000564 union node *args;
565 union node *body;
566 char *var;
567};
568
569struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000570 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000571 union node *expr;
572 union node *cases;
573};
574
575struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000576 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000577 union node *next;
578 union node *pattern;
579 union node *body;
580};
581
582struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000583 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584 union node *next;
585 char *text;
586 struct nodelist *backquote;
587};
588
Denis Vlasenko559691a2008-10-05 18:39:31 +0000589/* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
592 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000594 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000595 union node *next;
596 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *fname;
599 char *expfname;
600};
601
602struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000603 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000604 union node *next;
605 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 int dupfd;
607 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000608 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609};
610
611struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000612 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000613 union node *next;
614 int fd;
615 union node *doc;
616};
617
618struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 union node *com;
621};
622
623union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000624 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000625 struct ncmd ncmd;
626 struct npipe npipe;
627 struct nredir nredir;
628 struct nbinary nbinary;
629 struct nif nif;
630 struct nfor nfor;
631 struct ncase ncase;
632 struct nclist nclist;
633 struct narg narg;
634 struct nfile nfile;
635 struct ndup ndup;
636 struct nhere nhere;
637 struct nnot nnot;
638};
639
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200640/*
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
643 */
644#define NODE_EOF ((union node *) -1L)
645
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000646struct nodelist {
647 struct nodelist *next;
648 union node *n;
649};
650
651struct funcnode {
652 int count;
653 union node n;
654};
655
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000656/*
657 * Free a parse tree.
658 */
659static void
660freefunc(struct funcnode *f)
661{
662 if (f && --f->count < 0)
663 free(f);
664}
665
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000666
667/* ============ Debugging output */
668
669#if DEBUG
670
671static FILE *tracefile;
672
673static void
674trace_printf(const char *fmt, ...)
675{
676 va_list va;
677
678 if (debug != 1)
679 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000680 if (DEBUG_TIME)
681 fprintf(tracefile, "%u ", (int) time(NULL));
682 if (DEBUG_PID)
683 fprintf(tracefile, "[%u] ", (int) getpid());
684 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000686 va_start(va, fmt);
687 vfprintf(tracefile, fmt, va);
688 va_end(va);
689}
690
691static void
692trace_vprintf(const char *fmt, va_list va)
693{
694 if (debug != 1)
695 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000696 if (DEBUG_TIME)
697 fprintf(tracefile, "%u ", (int) time(NULL));
698 if (DEBUG_PID)
699 fprintf(tracefile, "[%u] ", (int) getpid());
700 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000702 vfprintf(tracefile, fmt, va);
703}
704
705static void
706trace_puts(const char *s)
707{
708 if (debug != 1)
709 return;
710 fputs(s, tracefile);
711}
712
713static void
714trace_puts_quoted(char *s)
715{
716 char *p;
717 char c;
718
719 if (debug != 1)
720 return;
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100723 switch ((unsigned char)*p) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '\"': c = '\"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000734 backslash:
735 putc('\\', tracefile);
736 putc(c, tracefile);
737 break;
738 default:
739 if (*p >= ' ' && *p <= '~')
740 putc(*p, tracefile);
741 else {
742 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100743 putc((*p >> 6) & 03, tracefile);
744 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000745 putc(*p & 07, tracefile);
746 }
747 break;
748 }
749 }
750 putc('"', tracefile);
751}
752
753static void
754trace_puts_args(char **ap)
755{
756 if (debug != 1)
757 return;
758 if (!*ap)
759 return;
760 while (1) {
761 trace_puts_quoted(*ap);
762 if (!*++ap) {
763 putc('\n', tracefile);
764 break;
765 }
766 putc(' ', tracefile);
767 }
768}
769
770static void
771opentrace(void)
772{
773 char s[100];
774#ifdef O_APPEND
775 int flags;
776#endif
777
778 if (debug != 1) {
779 if (tracefile)
780 fflush(tracefile);
781 /* leave open because libedit might be using it */
782 return;
783 }
784 strcpy(s, "./trace");
785 if (tracefile) {
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
788 debug = 0;
789 return;
790 }
791 } else {
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
795 debug = 0;
796 return;
797 }
798 }
799#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000800 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000801 if (flags >= 0)
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
803#endif
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
806}
807
808static void
809indent(int amount, char *pfx, FILE *fp)
810{
811 int i;
812
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
815 fputs(pfx, fp);
816 putc('\t', fp);
817 }
818}
819
820/* little circular references here... */
821static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822
823static void
824sharg(union node *arg, FILE *fp)
825{
826 char *p;
827 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100828 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000829
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
832 abort();
833 }
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100836 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837 case CTLESC:
838 putc(*++p, fp);
839 break;
840 case CTLVAR:
841 putc('$', fp);
842 putc('{', fp);
843 subtype = *++p;
844 if (subtype == VSLENGTH)
845 putc('#', fp);
846
847 while (*p != '=')
848 putc(*p++, fp);
849
850 if (subtype & VSNUL)
851 putc(':', fp);
852
853 switch (subtype & VSTYPE) {
854 case VSNORMAL:
855 putc('}', fp);
856 break;
857 case VSMINUS:
858 putc('-', fp);
859 break;
860 case VSPLUS:
861 putc('+', fp);
862 break;
863 case VSQUESTION:
864 putc('?', fp);
865 break;
866 case VSASSIGN:
867 putc('=', fp);
868 break;
869 case VSTRIMLEFT:
870 putc('#', fp);
871 break;
872 case VSTRIMLEFTMAX:
873 putc('#', fp);
874 putc('#', fp);
875 break;
876 case VSTRIMRIGHT:
877 putc('%', fp);
878 break;
879 case VSTRIMRIGHTMAX:
880 putc('%', fp);
881 putc('%', fp);
882 break;
883 case VSLENGTH:
884 break;
885 default:
886 out1fmt("<subtype %d>", subtype);
887 }
888 break;
889 case CTLENDVAR:
890 putc('}', fp);
891 break;
892 case CTLBACKQ:
893 case CTLBACKQ|CTLQUOTE:
894 putc('$', fp);
895 putc('(', fp);
896 shtree(bqlist->n, -1, NULL, fp);
897 putc(')', fp);
898 break;
899 default:
900 putc(*p, fp);
901 break;
902 }
903 }
904}
905
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200906static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000907shcmd(union node *cmd, FILE *fp)
908{
909 union node *np;
910 int first;
911 const char *s;
912 int dftfd;
913
914 first = 1;
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000916 if (!first)
917 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000918 sharg(np, fp);
919 first = 0;
920 }
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000922 if (!first)
923 putc(' ', fp);
924 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000925 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000929#if ENABLE_ASH_BASH_COMPAT
930 case NTO2:
931#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000933 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000937 }
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
940 fputs(s, fp);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
943 } else {
944 sharg(np->nfile.fname, fp);
945 }
946 first = 0;
947 }
948}
949
950static void
951shtree(union node *n, int ind, char *pfx, FILE *fp)
952{
953 struct nodelist *lp;
954 const char *s;
955
956 if (n == NULL)
957 return;
958
959 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200960
961 if (n == NODE_EOF) {
962 fputs("<EOF>", fp);
963 return;
964 }
965
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000966 switch (n->type) {
967 case NSEMI:
968 s = "; ";
969 goto binop;
970 case NAND:
971 s = " && ";
972 goto binop;
973 case NOR:
974 s = " || ";
975 binop:
976 shtree(n->nbinary.ch1, ind, NULL, fp);
977 /* if (ind < 0) */
978 fputs(s, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
980 break;
981 case NCMD:
982 shcmd(n, fp);
983 if (ind >= 0)
984 putc('\n', fp);
985 break;
986 case NPIPE:
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200988 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989 if (lp->next)
990 fputs(" | ", fp);
991 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000992 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000993 fputs(" &", fp);
994 if (ind >= 0)
995 putc('\n', fp);
996 break;
997 default:
998 fprintf(fp, "<node type %d>", n->type);
999 if (ind >= 0)
1000 putc('\n', fp);
1001 break;
1002 }
1003}
1004
1005static void
1006showtree(union node *n)
1007{
1008 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001009 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010}
1011
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001012#endif /* DEBUG */
1013
1014
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001015/* ============ Parser data */
1016
1017/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001020struct strlist {
1021 struct strlist *next;
1022 char *text;
1023};
1024
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001025struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001026
Denis Vlasenkob012b102007-02-19 22:43:01 +00001027struct strpush {
1028 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001029 char *prev_string;
1030 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001031#if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1033#endif
1034 char *string; /* remember the string since it may change */
1035};
1036
1037struct parsefile {
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
1040 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1047};
1048
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001049static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001050static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051static int startlinno; /* line # where last token started */
1052static char *commandname; /* currently executing command */
1053static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001054static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001055
1056
1057/* ============ Message printing */
1058
1059static void
1060ash_vmsg(const char *msg, va_list ap)
1061{
1062 fprintf(stderr, "%s: ", arg0);
1063 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001066 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001068 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001071}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072
1073/*
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1077 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001078static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001079static void
1080ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001081{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082#if DEBUG
1083 if (msg) {
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1085 TRACEV((msg, ap));
1086 TRACE(("\") pid=%d\n", getpid()));
1087 } else
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1089 if (msg)
1090#endif
1091 ash_vmsg(msg, ap);
1092
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1095 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001096}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001098static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001099static void
1100ash_msg_and_raise_error(const char *msg, ...)
1101{
1102 va_list ap;
1103
1104 va_start(ap, msg);
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1106 /* NOTREACHED */
1107 va_end(ap);
1108}
1109
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001110static void raise_error_syntax(const char *) NORETURN;
1111static void
1112raise_error_syntax(const char *msg)
1113{
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1115 /* NOTREACHED */
1116}
1117
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001118static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001119static void
1120ash_msg_and_raise(int cond, const char *msg, ...)
1121{
1122 va_list ap;
1123
1124 va_start(ap, msg);
1125 ash_vmsg_and_raise(cond, msg, ap);
1126 /* NOTREACHED */
1127 va_end(ap);
1128}
1129
1130/*
1131 * error/warning routines for external builtins
1132 */
1133static void
1134ash_msg(const char *fmt, ...)
1135{
1136 va_list ap;
1137
1138 va_start(ap, fmt);
1139 ash_vmsg(fmt, ap);
1140 va_end(ap);
1141}
1142
1143/*
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1147 */
1148static const char *
1149errmsg(int e, const char *em)
1150{
1151 if (e == ENOENT || e == ENOTDIR) {
1152 return em;
1153 }
1154 return strerror(e);
1155}
1156
1157
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001158/* ============ Memory allocation */
1159
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001160#if 0
1161/* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1165 */
1166static void *
1167ckrealloc(void * p, size_t nbytes)
1168{
1169 p = realloc(p, nbytes);
1170 if (!p)
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1172 return p;
1173}
1174
1175static void *
1176ckmalloc(size_t nbytes)
1177{
1178 return ckrealloc(NULL, nbytes);
1179}
1180
1181static void *
1182ckzalloc(size_t nbytes)
1183{
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1185}
1186
1187static char *
1188ckstrdup(const char *s)
1189{
1190 char *p = strdup(s);
1191 if (!p)
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1193 return p;
1194}
1195#else
1196/* Using bbox equivalents. They exit if out of memory */
1197# define ckrealloc xrealloc
1198# define ckmalloc xmalloc
1199# define ckzalloc xzalloc
1200# define ckstrdup xstrdup
1201#endif
1202
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001203/*
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1206 */
1207#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1208enum {
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001214 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001215};
1216
1217struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1220};
1221
1222struct stackmark {
1223 struct stack_block *stackp;
1224 char *stacknxt;
1225 size_t stacknleft;
1226 struct stackmark *marknext;
1227};
1228
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001229
Denis Vlasenko01631112007-12-16 17:20:38 +00001230struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1238};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001239extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001241#define g_stackp (G_memstack.g_stackp )
1242#define markp (G_memstack.markp )
1243#define g_stacknxt (G_memstack.g_stacknxt )
1244#define sstrend (G_memstack.sstrend )
1245#define g_stacknleft (G_memstack.g_stacknleft)
1246#define herefd (G_memstack.herefd )
1247#define stackbase (G_memstack.stackbase )
1248#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1250 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1255 herefd = -1; \
1256} while (0)
1257
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001258
Denis Vlasenko01631112007-12-16 17:20:38 +00001259#define stackblock() ((void *)g_stacknxt)
1260#define stackblocksize() g_stacknleft
1261
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001262/*
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1266 *
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1268 * well.
1269 */
1270static void *
1271stalloc(size_t nbytes)
1272{
1273 char *p;
1274 size_t aligned;
1275
1276 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001277 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001278 size_t len;
1279 size_t blocksize;
1280 struct stack_block *sp;
1281
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1288 INT_OFF;
1289 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1294 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001295 INT_ON;
1296 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001297 p = g_stacknxt;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300 return p;
1301}
1302
Denis Vlasenko597906c2008-02-20 16:38:54 +00001303static void *
1304stzalloc(size_t nbytes)
1305{
1306 return memset(stalloc(nbytes), 0, nbytes);
1307}
1308
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001309static void
1310stunalloc(void *p)
1311{
1312#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001314 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001315 abort();
1316 }
1317#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001318 g_stacknleft += g_stacknxt - (char *)p;
1319 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001320}
1321
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001322/*
1323 * Like strdup but works with the ash stack.
1324 */
1325static char *
1326ststrdup(const char *p)
1327{
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1330}
1331
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001332static void
1333setstackmark(struct stackmark *mark)
1334{
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338 mark->marknext = markp;
1339 markp = mark;
1340}
1341
1342static void
1343popstackmark(struct stackmark *mark)
1344{
1345 struct stack_block *sp;
1346
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001347 if (!mark->stackp)
1348 return;
1349
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350 INT_OFF;
1351 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001352 while (g_stackp != mark->stackp) {
1353 sp = g_stackp;
1354 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001355 free(sp);
1356 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001359 sstrend = mark->stacknxt + mark->stacknleft;
1360 INT_ON;
1361}
1362
1363/*
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1371 */
1372static void
1373growstackblock(void)
1374{
1375 size_t newlen;
1376
Denis Vlasenko01631112007-12-16 17:20:38 +00001377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1380 if (newlen < 128)
1381 newlen += 128;
1382
Denis Vlasenko01631112007-12-16 17:20:38 +00001383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1388 size_t grosslen;
1389
1390 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 oldstackp = g_stackp;
1392 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001397 g_stackp = sp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 sstrend = sp->space + newlen;
1401
1402 /*
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1405 */
1406 xmark = markp;
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001411 xmark = xmark->marknext;
1412 }
1413 INT_ON;
1414 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001416 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001417 char *p = stalloc(newlen);
1418
1419 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001422 }
1423}
1424
1425static void
1426grabstackblock(size_t len)
1427{
1428 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001429 g_stacknxt += len;
1430 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001431}
1432
1433/*
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1445 *
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1449 */
1450static void *
1451growstackstr(void)
1452{
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1457 }
1458 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001459 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001460}
1461
1462/*
1463 * Called from CHECKSTRSPACE.
1464 */
1465static char *
1466makestrspace(size_t newlen, char *p)
1467{
Denis Vlasenko01631112007-12-16 17:20:38 +00001468 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001469 size_t size = stackblocksize();
1470
1471 for (;;) {
1472 size_t nleft;
1473
1474 size = stackblocksize();
1475 nleft = size - len;
1476 if (nleft >= newlen)
1477 break;
1478 growstackblock();
1479 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001480 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001481}
1482
1483static char *
1484stack_nputstr(const char *s, size_t n, char *p)
1485{
1486 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001487 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001488 return p;
1489}
1490
1491static char *
1492stack_putstr(const char *s, char *p)
1493{
1494 return stack_nputstr(s, strlen(s), p);
1495}
1496
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001497static char *
1498_STPUTC(int c, char *p)
1499{
1500 if (p == sstrend)
1501 p = growstackstr();
1502 *p++ = c;
1503 return p;
1504}
1505
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001506#define STARTSTACKSTR(p) ((p) = stackblock())
1507#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001508#define CHECKSTRSPACE(n, p) do { \
1509 char *q = (p); \
1510 size_t l = (n); \
1511 size_t m = sstrend - q; \
1512 if (l > m) \
1513 (p) = makestrspace(l, q); \
1514} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001515#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1519 *(p) = '\0'; \
1520} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001521#define STUNPUTC(p) (--(p))
1522#define STTOPC(p) ((p)[-1])
1523#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001524
1525#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001526#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001527#define stackstrend() ((void *)sstrend)
1528
1529
1530/* ============ String helpers */
1531
1532/*
1533 * prefix -- see if pfx is a prefix of string.
1534 */
1535static char *
1536prefix(const char *string, const char *pfx)
1537{
1538 while (*pfx) {
1539 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001540 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001541 }
1542 return (char *) string;
1543}
1544
1545/*
1546 * Check for a valid number. This should be elsewhere.
1547 */
1548static int
1549is_number(const char *p)
1550{
1551 do {
1552 if (!isdigit(*p))
1553 return 0;
1554 } while (*++p != '\0');
1555 return 1;
1556}
1557
1558/*
1559 * Convert a string of digits to an integer, printing an error message on
1560 * failure.
1561 */
1562static int
1563number(const char *s)
1564{
1565 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001566 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001567 return atoi(s);
1568}
1569
1570/*
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1573 */
1574static char *
1575single_quote(const char *s)
1576{
1577 char *p;
1578
1579 STARTSTACKSTR(p);
1580
1581 do {
1582 char *q;
1583 size_t len;
1584
1585 len = strchrnul(s, '\'') - s;
1586
1587 q = p = makestrspace(len + 3, p);
1588
1589 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001590 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001591 *q++ = '\'';
1592 s += len;
1593
1594 STADJUST(q - p, p);
1595
Denys Vlasenkocd716832009-11-28 22:14:02 +01001596 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001597 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001598 len = 0;
1599 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001600
1601 q = p = makestrspace(len + 3, p);
1602
1603 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001604 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001606
1607 STADJUST(q - p, p);
1608 } while (*s);
1609
Denys Vlasenkocd716832009-11-28 22:14:02 +01001610 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001611
1612 return stackblock();
1613}
1614
1615
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001616/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001617
1618static char **argptr; /* argument list for builtin commands */
1619static char *optionarg; /* set by nextopt (like getopt) */
1620static char *optptr; /* used by nextopt */
1621
1622/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001626 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001631 */
1632static int
1633nextopt(const char *optstring)
1634{
1635 char *p;
1636 const char *q;
1637 char c;
1638
1639 p = optptr;
1640 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 if (p == NULL)
1644 return '\0';
1645 if (*p != '-')
1646 return '\0';
1647 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 return '\0';
1649 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001656 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001658 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 if (*++q == ':')
1660 q++;
1661 }
1662 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001663 if (*p == '\0') {
1664 p = *argptr++;
1665 if (p == NULL)
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1667 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001668 optionarg = p;
1669 p = NULL;
1670 }
1671 optptr = p;
1672 return c;
1673}
1674
1675
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001676/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001677
Denis Vlasenko01631112007-12-16 17:20:38 +00001678/*
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1681 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001682struct shparam {
1683 int nparam; /* # of positional parameters (without $0) */
1684#if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1687#endif
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1690};
1691
1692/*
1693 * Free the list of positional parameters.
1694 */
1695static void
1696freeparam(volatile struct shparam *param)
1697{
Denis Vlasenko01631112007-12-16 17:20:38 +00001698 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001699 char **ap, **ap1;
1700 ap = ap1 = param->p;
1701 while (*ap)
1702 free(*ap++);
1703 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001704 }
1705}
1706
1707#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001708static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001709#endif
1710
1711struct var {
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
1714 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001715 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001716 /* the variable gets set/unset */
1717};
1718
1719struct localvar {
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1724};
1725
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726/* flags */
1727#define VEXPORT 0x01 /* variable is exported */
1728#define VREADONLY 0x02 /* variable cannot be modified */
1729#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730#define VTEXTFIXED 0x08 /* text is statically allocated */
1731#define VSTACK 0x10 /* text is allocated on the stack */
1732#define VUNSET 0x20 /* the variable is not set */
1733#define VNOFUNC 0x40 /* don't call the callback function */
1734#define VNOSET 0x80 /* do not set variable - just readonly test */
1735#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001736#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001737# define VDYNAMIC 0x200 /* dynamic variable */
1738#else
1739# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#endif
1741
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001742
Denis Vlasenko01631112007-12-16 17:20:38 +00001743/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001744#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001745static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001746change_lc_all(const char *value)
1747{
1748 if (value && *value != '\0')
1749 setlocale(LC_ALL, value);
1750}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001751static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001752change_lc_ctype(const char *value)
1753{
1754 if (value && *value != '\0')
1755 setlocale(LC_CTYPE, value);
1756}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001757#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001758#if ENABLE_ASH_MAIL
1759static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001760static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001764static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#endif
1766
Denis Vlasenko01631112007-12-16 17:20:38 +00001767static const struct {
1768 int flags;
1769 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001770 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001771} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001772 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1778 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001782 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#endif
1784#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#endif
1791#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001792 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794};
1795
Denis Vlasenko0b769642008-07-24 07:54:57 +00001796struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001797
1798struct globals_var {
1799 struct shparam shellparam; /* $@ current positional parameters */
1800 struct redirtab *redirlist;
1801 int g_nullredirs;
1802 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1803 struct var *vartab[VTABSIZE];
1804 struct var varinit[ARRAY_SIZE(varinit_data)];
1805};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001806extern struct globals_var *const ash_ptr_to_globals_var;
1807#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001808#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001809//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001810#define g_nullredirs (G_var.g_nullredirs )
1811#define preverrout_fd (G_var.preverrout_fd)
1812#define vartab (G_var.vartab )
1813#define varinit (G_var.varinit )
1814#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001815 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001816 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001818 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1819 varinit[i].flags = varinit_data[i].flags; \
1820 varinit[i].text = varinit_data[i].text; \
1821 varinit[i].func = varinit_data[i].func; \
1822 } \
1823} while (0)
1824
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001825#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001826#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827# define vmail (&vifs)[1]
1828# define vmpath (&vmail)[1]
1829# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001830#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001831# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833#define vps1 (&vpath)[1]
1834#define vps2 (&vps1)[1]
1835#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001836#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001837# define voptind (&vps4)[1]
1838# if ENABLE_ASH_RANDOM_SUPPORT
1839# define vrandom (&voptind)[1]
1840# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842# if ENABLE_ASH_RANDOM_SUPPORT
1843# define vrandom (&vps4)[1]
1844# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846
1847/*
1848 * The following macros access the values of the above variables.
1849 * They have to skip over the name. They return the null string
1850 * for unset variables.
1851 */
1852#define ifsval() (vifs.text + 4)
1853#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001854#if ENABLE_ASH_MAIL
1855# define mailval() (vmail.text + 5)
1856# define mpathval() (vmpath.text + 9)
1857# define mpathset() ((vmpath.flags & VUNSET) == 0)
1858#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001859#define pathval() (vpath.text + 5)
1860#define ps1val() (vps1.text + 4)
1861#define ps2val() (vps2.text + 4)
1862#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001863#if ENABLE_ASH_GETOPTS
1864# define optindval() (voptind.text + 7)
1865#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001866
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1869#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870
Denis Vlasenko01631112007-12-16 17:20:38 +00001871#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001872static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001873getoptsreset(const char *value)
1874{
1875 shellparam.optind = number(value);
1876 shellparam.optoff = -1;
1877}
1878#endif
1879
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001880/*
1881 * Return of a legal variable name (a letter or underscore followed by zero or
1882 * more letters, underscores, and digits).
1883 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001884static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001885endofname(const char *name)
1886{
1887 char *p;
1888
1889 p = (char *) name;
1890 if (!is_name(*p))
1891 return p;
1892 while (*++p) {
1893 if (!is_in_name(*p))
1894 break;
1895 }
1896 return p;
1897}
1898
1899/*
1900 * Compares two strings up to the first = or '\0'. The first
1901 * string must be terminated by '='; the second may be terminated by
1902 * either '=' or '\0'.
1903 */
1904static int
1905varcmp(const char *p, const char *q)
1906{
1907 int c, d;
1908
1909 while ((c = *p) == (d = *q)) {
1910 if (!c || c == '=')
1911 goto out;
1912 p++;
1913 q++;
1914 }
1915 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001916 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001917 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001918 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001919 out:
1920 return c - d;
1921}
1922
1923static int
1924varequal(const char *a, const char *b)
1925{
1926 return !varcmp(a, b);
1927}
1928
1929/*
1930 * Find the appropriate entry in the hash table from the name.
1931 */
1932static struct var **
1933hashvar(const char *p)
1934{
1935 unsigned hashval;
1936
1937 hashval = ((unsigned char) *p) << 4;
1938 while (*p && *p != '=')
1939 hashval += (unsigned char) *p++;
1940 return &vartab[hashval % VTABSIZE];
1941}
1942
1943static int
1944vpcmp(const void *a, const void *b)
1945{
1946 return varcmp(*(const char **)a, *(const char **)b);
1947}
1948
1949/*
1950 * This routine initializes the builtin variables.
1951 */
1952static void
1953initvar(void)
1954{
1955 struct var *vp;
1956 struct var *end;
1957 struct var **vpp;
1958
1959 /*
1960 * PS1 depends on uid
1961 */
1962#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1963 vps1.text = "PS1=\\w \\$ ";
1964#else
1965 if (!geteuid())
1966 vps1.text = "PS1=# ";
1967#endif
1968 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001969 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001970 do {
1971 vpp = hashvar(vp->text);
1972 vp->next = *vpp;
1973 *vpp = vp;
1974 } while (++vp < end);
1975}
1976
1977static struct var **
1978findvar(struct var **vpp, const char *name)
1979{
1980 for (; *vpp; vpp = &(*vpp)->next) {
1981 if (varequal((*vpp)->text, name)) {
1982 break;
1983 }
1984 }
1985 return vpp;
1986}
1987
1988/*
1989 * Find the value of a variable. Returns NULL if not set.
1990 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001991static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001992lookupvar(const char *name)
1993{
1994 struct var *v;
1995
1996 v = *findvar(hashvar(name), name);
1997 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001998#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001999 /*
2000 * Dynamic variables are implemented roughly the same way they are
2001 * in bash. Namely, they're "special" so long as they aren't unset.
2002 * As soon as they're unset, they're no longer dynamic, and dynamic
2003 * lookup will no longer happen at that point. -- PFM.
2004 */
2005 if ((v->flags & VDYNAMIC))
2006 (*v->func)(NULL);
2007#endif
2008 if (!(v->flags & VUNSET))
2009 return strchrnul(v->text, '=') + 1;
2010 }
2011 return NULL;
2012}
2013
2014/*
2015 * Search the environment of a builtin command.
2016 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002017static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002018bltinlookup(const char *name)
2019{
2020 struct strlist *sp;
2021
2022 for (sp = cmdenviron; sp; sp = sp->next) {
2023 if (varequal(sp->text, name))
2024 return strchrnul(sp->text, '=') + 1;
2025 }
2026 return lookupvar(name);
2027}
2028
2029/*
2030 * Same as setvar except that the variable and value are passed in
2031 * the first argument as name=value. Since the first argument will
2032 * be actually stored in the table, it should not be a string that
2033 * will go away.
2034 * Called with interrupts off.
2035 */
2036static void
2037setvareq(char *s, int flags)
2038{
2039 struct var *vp, **vpp;
2040
2041 vpp = hashvar(s);
2042 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2043 vp = *findvar(vpp, s);
2044 if (vp) {
2045 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2046 const char *n;
2047
2048 if (flags & VNOSAVE)
2049 free(s);
2050 n = vp->text;
2051 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2052 }
2053
2054 if (flags & VNOSET)
2055 return;
2056
2057 if (vp->func && (flags & VNOFUNC) == 0)
2058 (*vp->func)(strchrnul(s, '=') + 1);
2059
2060 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2061 free((char*)vp->text);
2062
2063 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2064 } else {
2065 if (flags & VNOSET)
2066 return;
2067 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002068 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002069 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002070 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002071 *vpp = vp;
2072 }
2073 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2074 s = ckstrdup(s);
2075 vp->text = s;
2076 vp->flags = flags;
2077}
2078
2079/*
2080 * Set the value of a variable. The flags argument is ored with the
2081 * flags of the variable. If val is NULL, the variable is unset.
2082 */
2083static void
2084setvar(const char *name, const char *val, int flags)
2085{
2086 char *p, *q;
2087 size_t namelen;
2088 char *nameeq;
2089 size_t vallen;
2090
2091 q = endofname(name);
2092 p = strchrnul(q, '=');
2093 namelen = p - name;
2094 if (!namelen || p != q)
2095 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2096 vallen = 0;
2097 if (val == NULL) {
2098 flags |= VUNSET;
2099 } else {
2100 vallen = strlen(val);
2101 }
2102 INT_OFF;
2103 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002104 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002105 if (val) {
2106 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002107 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002108 }
2109 *p = '\0';
2110 setvareq(nameeq, flags | VNOSAVE);
2111 INT_ON;
2112}
2113
Denys Vlasenko03dad222010-01-12 23:29:57 +01002114static void FAST_FUNC
2115setvar2(const char *name, const char *val)
2116{
2117 setvar(name, val, 0);
2118}
2119
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002120#if ENABLE_ASH_GETOPTS
2121/*
2122 * Safe version of setvar, returns 1 on success 0 on failure.
2123 */
2124static int
2125setvarsafe(const char *name, const char *val, int flags)
2126{
2127 int err;
2128 volatile int saveint;
2129 struct jmploc *volatile savehandler = exception_handler;
2130 struct jmploc jmploc;
2131
2132 SAVE_INT(saveint);
2133 if (setjmp(jmploc.loc))
2134 err = 1;
2135 else {
2136 exception_handler = &jmploc;
2137 setvar(name, val, flags);
2138 err = 0;
2139 }
2140 exception_handler = savehandler;
2141 RESTORE_INT(saveint);
2142 return err;
2143}
2144#endif
2145
2146/*
2147 * Unset the specified variable.
2148 */
2149static int
2150unsetvar(const char *s)
2151{
2152 struct var **vpp;
2153 struct var *vp;
2154 int retval;
2155
2156 vpp = findvar(hashvar(s), s);
2157 vp = *vpp;
2158 retval = 2;
2159 if (vp) {
2160 int flags = vp->flags;
2161
2162 retval = 1;
2163 if (flags & VREADONLY)
2164 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002165#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002166 vp->flags &= ~VDYNAMIC;
2167#endif
2168 if (flags & VUNSET)
2169 goto ok;
2170 if ((flags & VSTRFIXED) == 0) {
2171 INT_OFF;
2172 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2173 free((char*)vp->text);
2174 *vpp = vp->next;
2175 free(vp);
2176 INT_ON;
2177 } else {
2178 setvar(s, 0, 0);
2179 vp->flags &= ~VEXPORT;
2180 }
2181 ok:
2182 retval = 0;
2183 }
2184 out:
2185 return retval;
2186}
2187
2188/*
2189 * Process a linked list of variable assignments.
2190 */
2191static void
2192listsetvar(struct strlist *list_set_var, int flags)
2193{
2194 struct strlist *lp = list_set_var;
2195
2196 if (!lp)
2197 return;
2198 INT_OFF;
2199 do {
2200 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002201 lp = lp->next;
2202 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002203 INT_ON;
2204}
2205
2206/*
2207 * Generate a list of variables satisfying the given conditions.
2208 */
2209static char **
2210listvars(int on, int off, char ***end)
2211{
2212 struct var **vpp;
2213 struct var *vp;
2214 char **ep;
2215 int mask;
2216
2217 STARTSTACKSTR(ep);
2218 vpp = vartab;
2219 mask = on | off;
2220 do {
2221 for (vp = *vpp; vp; vp = vp->next) {
2222 if ((vp->flags & mask) == on) {
2223 if (ep == stackstrend())
2224 ep = growstackstr();
2225 *ep++ = (char *) vp->text;
2226 }
2227 }
2228 } while (++vpp < vartab + VTABSIZE);
2229 if (ep == stackstrend())
2230 ep = growstackstr();
2231 if (end)
2232 *end = ep;
2233 *ep++ = NULL;
2234 return grabstackstr(ep);
2235}
2236
2237
2238/* ============ Path search helper
2239 *
2240 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002241 * of the path before the first call; path_advance will update
2242 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002243 * the possible path expansions in sequence. If an option (indicated by
2244 * a percent sign) appears in the path entry then the global variable
2245 * pathopt will be set to point to it; otherwise pathopt will be set to
2246 * NULL.
2247 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002248static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002249
2250static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002251path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002252{
2253 const char *p;
2254 char *q;
2255 const char *start;
2256 size_t len;
2257
2258 if (*path == NULL)
2259 return NULL;
2260 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002261 for (p = start; *p && *p != ':' && *p != '%'; p++)
2262 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002263 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2264 while (stackblocksize() < len)
2265 growstackblock();
2266 q = stackblock();
2267 if (p != start) {
2268 memcpy(q, start, p - start);
2269 q += p - start;
2270 *q++ = '/';
2271 }
2272 strcpy(q, name);
2273 pathopt = NULL;
2274 if (*p == '%') {
2275 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002276 while (*p && *p != ':')
2277 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002278 }
2279 if (*p == ':')
2280 *path = p + 1;
2281 else
2282 *path = NULL;
2283 return stalloc(len);
2284}
2285
2286
2287/* ============ Prompt */
2288
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002289static smallint doprompt; /* if set, prompt the user */
2290static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002291
2292#if ENABLE_FEATURE_EDITING
2293static line_input_t *line_input_state;
2294static const char *cmdedit_prompt;
2295static void
2296putprompt(const char *s)
2297{
2298 if (ENABLE_ASH_EXPAND_PRMT) {
2299 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002300 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002301 return;
2302 }
2303 cmdedit_prompt = s;
2304}
2305#else
2306static void
2307putprompt(const char *s)
2308{
2309 out2str(s);
2310}
2311#endif
2312
2313#if ENABLE_ASH_EXPAND_PRMT
2314/* expandstr() needs parsing machinery, so it is far away ahead... */
2315static const char *expandstr(const char *ps);
2316#else
2317#define expandstr(s) s
2318#endif
2319
2320static void
2321setprompt(int whichprompt)
2322{
2323 const char *prompt;
2324#if ENABLE_ASH_EXPAND_PRMT
2325 struct stackmark smark;
2326#endif
2327
2328 needprompt = 0;
2329
2330 switch (whichprompt) {
2331 case 1:
2332 prompt = ps1val();
2333 break;
2334 case 2:
2335 prompt = ps2val();
2336 break;
2337 default: /* 0 */
2338 prompt = nullstr;
2339 }
2340#if ENABLE_ASH_EXPAND_PRMT
2341 setstackmark(&smark);
2342 stalloc(stackblocksize());
2343#endif
2344 putprompt(expandstr(prompt));
2345#if ENABLE_ASH_EXPAND_PRMT
2346 popstackmark(&smark);
2347#endif
2348}
2349
2350
2351/* ============ The cd and pwd commands */
2352
2353#define CD_PHYSICAL 1
2354#define CD_PRINT 2
2355
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002356static int
2357cdopt(void)
2358{
2359 int flags = 0;
2360 int i, j;
2361
2362 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002363 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002364 if (i != j) {
2365 flags ^= CD_PHYSICAL;
2366 j = i;
2367 }
2368 }
2369
2370 return flags;
2371}
2372
2373/*
2374 * Update curdir (the name of the current directory) in response to a
2375 * cd command.
2376 */
2377static const char *
2378updatepwd(const char *dir)
2379{
2380 char *new;
2381 char *p;
2382 char *cdcomppath;
2383 const char *lim;
2384
2385 cdcomppath = ststrdup(dir);
2386 STARTSTACKSTR(new);
2387 if (*dir != '/') {
2388 if (curdir == nullstr)
2389 return 0;
2390 new = stack_putstr(curdir, new);
2391 }
2392 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002393 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002394 if (*dir != '/') {
2395 if (new[-1] != '/')
2396 USTPUTC('/', new);
2397 if (new > lim && *lim == '/')
2398 lim++;
2399 } else {
2400 USTPUTC('/', new);
2401 cdcomppath++;
2402 if (dir[1] == '/' && dir[2] != '/') {
2403 USTPUTC('/', new);
2404 cdcomppath++;
2405 lim++;
2406 }
2407 }
2408 p = strtok(cdcomppath, "/");
2409 while (p) {
2410 switch (*p) {
2411 case '.':
2412 if (p[1] == '.' && p[2] == '\0') {
2413 while (new > lim) {
2414 STUNPUTC(new);
2415 if (new[-1] == '/')
2416 break;
2417 }
2418 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002419 }
2420 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002421 break;
2422 /* fall through */
2423 default:
2424 new = stack_putstr(p, new);
2425 USTPUTC('/', new);
2426 }
2427 p = strtok(0, "/");
2428 }
2429 if (new > lim)
2430 STUNPUTC(new);
2431 *new = 0;
2432 return stackblock();
2433}
2434
2435/*
2436 * Find out what the current directory is. If we already know the current
2437 * directory, this routine returns immediately.
2438 */
2439static char *
2440getpwd(void)
2441{
Denis Vlasenko01631112007-12-16 17:20:38 +00002442 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002443 return dir ? dir : nullstr;
2444}
2445
2446static void
2447setpwd(const char *val, int setold)
2448{
2449 char *oldcur, *dir;
2450
2451 oldcur = dir = curdir;
2452
2453 if (setold) {
2454 setvar("OLDPWD", oldcur, VEXPORT);
2455 }
2456 INT_OFF;
2457 if (physdir != nullstr) {
2458 if (physdir != oldcur)
2459 free(physdir);
2460 physdir = nullstr;
2461 }
2462 if (oldcur == val || !val) {
2463 char *s = getpwd();
2464 physdir = s;
2465 if (!val)
2466 dir = s;
2467 } else
2468 dir = ckstrdup(val);
2469 if (oldcur != dir && oldcur != nullstr) {
2470 free(oldcur);
2471 }
2472 curdir = dir;
2473 INT_ON;
2474 setvar("PWD", dir, VEXPORT);
2475}
2476
2477static void hashcd(void);
2478
2479/*
2480 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2481 * know that the current directory has changed.
2482 */
2483static int
2484docd(const char *dest, int flags)
2485{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002486 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002487 int err;
2488
2489 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2490
2491 INT_OFF;
2492 if (!(flags & CD_PHYSICAL)) {
2493 dir = updatepwd(dest);
2494 if (dir)
2495 dest = dir;
2496 }
2497 err = chdir(dest);
2498 if (err)
2499 goto out;
2500 setpwd(dir, 1);
2501 hashcd();
2502 out:
2503 INT_ON;
2504 return err;
2505}
2506
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002507static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002508cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002509{
2510 const char *dest;
2511 const char *path;
2512 const char *p;
2513 char c;
2514 struct stat statb;
2515 int flags;
2516
2517 flags = cdopt();
2518 dest = *argptr;
2519 if (!dest)
2520 dest = bltinlookup(homestr);
2521 else if (LONE_DASH(dest)) {
2522 dest = bltinlookup("OLDPWD");
2523 flags |= CD_PRINT;
2524 }
2525 if (!dest)
2526 dest = nullstr;
2527 if (*dest == '/')
2528 goto step7;
2529 if (*dest == '.') {
2530 c = dest[1];
2531 dotdot:
2532 switch (c) {
2533 case '\0':
2534 case '/':
2535 goto step6;
2536 case '.':
2537 c = dest[2];
2538 if (c != '.')
2539 goto dotdot;
2540 }
2541 }
2542 if (!*dest)
2543 dest = ".";
2544 path = bltinlookup("CDPATH");
2545 if (!path) {
2546 step6:
2547 step7:
2548 p = dest;
2549 goto docd;
2550 }
2551 do {
2552 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002553 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002554 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2555 if (c && c != ':')
2556 flags |= CD_PRINT;
2557 docd:
2558 if (!docd(p, flags))
2559 goto out;
2560 break;
2561 }
2562 } while (path);
2563 ash_msg_and_raise_error("can't cd to %s", dest);
2564 /* NOTREACHED */
2565 out:
2566 if (flags & CD_PRINT)
2567 out1fmt(snlfmt, curdir);
2568 return 0;
2569}
2570
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002571static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002572pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002573{
2574 int flags;
2575 const char *dir = curdir;
2576
2577 flags = cdopt();
2578 if (flags) {
2579 if (physdir == nullstr)
2580 setpwd(dir, 0);
2581 dir = physdir;
2582 }
2583 out1fmt(snlfmt, dir);
2584 return 0;
2585}
2586
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002587
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002588/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002589
Denis Vlasenko834dee72008-10-07 09:18:30 +00002590
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002591#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592/* buffer for top level input file */
2593#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002594
Eric Andersenc470f442003-07-28 09:56:35 +00002595/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002596#define CWORD 0 /* character is nothing special */
2597#define CNL 1 /* newline character */
2598#define CBACK 2 /* a backslash character */
2599#define CSQUOTE 3 /* single quote */
2600#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002602#define CBQUOTE 6 /* backwards single quote */
2603#define CVAR 7 /* a dollar sign */
2604#define CENDVAR 8 /* a '}' character */
2605#define CLP 9 /* a left paren in arithmetic */
2606#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002607#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002608#define CCTL 12 /* like CWORD, except it must be escaped */
2609#define CSPCL 13 /* these terminate a word */
2610#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002611
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002612#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002613#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002614# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002615#endif
2616
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002617#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002618
Mike Frysinger98c52642009-04-02 10:02:37 +00002619#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002621#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002624static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002625#if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627#endif
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002639#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2643#endif
2644#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002645};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002646/* Constants below must match table above */
2647enum {
2648#if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650#endif
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2665};
Eric Andersen2870d962001-07-02 17:27:21 +00002666
Denys Vlasenkocd716832009-11-28 22:14:02 +01002667/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2669 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002670/* Values for syntax param */
2671#define BASESYNTAX 0 /* not in quotes */
2672#define DQSYNTAX 1 /* in double quotes */
2673#define SQSYNTAX 2 /* in single quotes */
2674#define ARISYNTAX 3 /* in arithmetic */
2675#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002676
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002677#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002678
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002679static int
2680SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002681{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002683# if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2688 11, 3 /* "}~" */
2689 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002690# else
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2695 10, 2 /* "}~" */
2696 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002697# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002698 const char *s;
2699 int indx;
2700
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002702 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002703# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002706 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002707# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 ) {
2714 return CCTL;
2715 }
2716 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002717 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002719 indx = syntax_index_table[s - spec_symbls];
2720 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002722}
2723
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002724#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002725
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002726static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002985# if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2987# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002988};
2989
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002990# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002991
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002992#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002993
Eric Andersen2870d962001-07-02 17:27:21 +00002994
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002995/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002996
Denis Vlasenko131ae172007-02-18 13:00:19 +00002997#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002998
2999#define ALIASINUSE 1
3000#define ALIASDEAD 2
3001
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003002struct alias {
3003 struct alias *next;
3004 char *name;
3005 char *val;
3006 int flag;
3007};
3008
Denis Vlasenko01631112007-12-16 17:20:38 +00003009
3010static struct alias **atab; // [ATABSIZE];
3011#define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3013} while (0)
3014
Eric Andersen2870d962001-07-02 17:27:21 +00003015
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003016static struct alias **
3017__lookupalias(const char *name) {
3018 unsigned int hashval;
3019 struct alias **app;
3020 const char *p;
3021 unsigned int ch;
3022
3023 p = name;
3024
3025 ch = (unsigned char)*p;
3026 hashval = ch << 4;
3027 while (ch) {
3028 hashval += ch;
3029 ch = (unsigned char)*++p;
3030 }
3031 app = &atab[hashval % ATABSIZE];
3032
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3035 break;
3036 }
3037 }
3038
3039 return app;
3040}
3041
3042static struct alias *
3043lookupalias(const char *name, int check)
3044{
3045 struct alias *ap = *__lookupalias(name);
3046
3047 if (check && ap && (ap->flag & ALIASINUSE))
3048 return NULL;
3049 return ap;
3050}
3051
3052static struct alias *
3053freealias(struct alias *ap)
3054{
3055 struct alias *next;
3056
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3059 return ap;
3060 }
3061
3062 next = ap->next;
3063 free(ap->name);
3064 free(ap->val);
3065 free(ap);
3066 return next;
3067}
Eric Andersencb57d552001-06-28 07:25:16 +00003068
Eric Andersenc470f442003-07-28 09:56:35 +00003069static void
3070setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003071{
3072 struct alias *ap, **app;
3073
3074 app = __lookupalias(name);
3075 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003076 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003077 if (ap) {
3078 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003079 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003080 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003081 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003082 ap->flag &= ~ALIASDEAD;
3083 } else {
3084 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003085 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003090 *app = ap;
3091 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003092 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003093}
3094
Eric Andersenc470f442003-07-28 09:56:35 +00003095static int
3096unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003097{
Eric Andersencb57d552001-06-28 07:25:16 +00003098 struct alias **app;
3099
3100 app = __lookupalias(name);
3101
3102 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003103 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003104 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003106 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003107 }
3108
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003109 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003110}
3111
Eric Andersenc470f442003-07-28 09:56:35 +00003112static void
3113rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003114{
Eric Andersencb57d552001-06-28 07:25:16 +00003115 struct alias *ap, **app;
3116 int i;
3117
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003119 for (i = 0; i < ATABSIZE; i++) {
3120 app = &atab[i];
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3123 if (ap == *app) {
3124 app = &ap->next;
3125 }
3126 }
3127 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003128 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003129}
3130
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003131static void
3132printalias(const struct alias *ap)
3133{
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3135}
3136
Eric Andersencb57d552001-06-28 07:25:16 +00003137/*
3138 * TODO - sort output
3139 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003140static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003141aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003142{
3143 char *n, *v;
3144 int ret = 0;
3145 struct alias *ap;
3146
Denis Vlasenko68404f12008-03-17 09:00:54 +00003147 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003148 int i;
3149
Denis Vlasenko68404f12008-03-17 09:00:54 +00003150 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003151 for (ap = atab[i]; ap; ap = ap->next) {
3152 printalias(ap);
3153 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003154 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003155 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003156 }
3157 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3161 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003162 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003163 ret = 1;
3164 } else
3165 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003166 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003167 *v++ = '\0';
3168 setalias(n, v);
3169 }
3170 }
3171
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003172 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003173}
3174
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003175static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003176unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003177{
3178 int i;
3179
3180 while ((i = nextopt("a")) != '\0') {
3181 if (i == 'a') {
3182 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003183 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003184 }
3185 }
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003189 i = 1;
3190 }
3191 }
3192
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003193 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003194}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003195
Denis Vlasenko131ae172007-02-18 13:00:19 +00003196#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003197
Eric Andersenc470f442003-07-28 09:56:35 +00003198
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003199/* ============ jobs.c */
3200
3201/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003202#define FORK_FG 0
3203#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003204#define FORK_NOJOB 2
3205
3206/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003207#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003210
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211/*
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3215 * array of pids.
3216 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003217struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003221};
3222
3223struct job {
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3226#if JOBS
3227 int stopstatus; /* status of a stopped job */
3228#endif
3229 uint32_t
3230 nprocs: 16, /* number of processes */
3231 state: 8,
3232#define JOBRUNNING 0 /* at least one proc running */
3233#define JOBSTOPPED 1 /* all procs are stopped */
3234#define JOBDONE 2 /* all procs are completed */
3235#if JOBS
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3238#endif
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3243};
3244
Denis Vlasenko68404f12008-03-17 09:00:54 +00003245static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246static int forkshell(struct job *, union node *, int);
3247static int waitforjob(struct job *);
3248
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003249#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003250enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003251#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003253static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003254static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255#endif
3256
3257/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003258 * Ignore a signal.
3259 */
3260static void
3261ignoresig(int signo)
3262{
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3267 }
3268 sigmode[signo - 1] = S_HARD_IGN;
3269}
3270
3271/*
3272 * Signal handler. Only one usage site - in setsignal()
3273 */
3274static void
3275onsig(int signo)
3276{
3277 gotsig[signo - 1] = 1;
3278
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3281 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 raise_interrupt(); /* does not return */
3283 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003284 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003285 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003286 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 }
3288}
3289
3290/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3293 */
3294static void
3295setsignal(int signo)
3296{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003297 char *t;
3298 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003299 struct sigaction act;
3300
3301 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003302 new_act = S_DFL;
3303 if (t != NULL) { /* trap for this sig is set */
3304 new_act = S_CATCH;
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3306 new_act = S_IGN;
3307 }
3308
3309 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003310 switch (signo) {
3311 case SIGINT:
3312 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003313 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003314 break;
3315 case SIGQUIT:
3316#if DEBUG
3317 if (debug)
3318 break;
3319#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003320 /* man bash:
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3325 new_act = S_IGN;
3326 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 case SIGTERM:
3328 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 break;
3331#if JOBS
3332 case SIGTSTP:
3333 case SIGTTOU:
3334 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003335 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003336 break;
3337#endif
3338 }
3339 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003340//TODO: if !rootshell, we reset SIGQUIT to DFL,
3341//whereas we have to restore it to what shell got on entry
3342//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343
3344 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 cur_act = *t;
3346 if (cur_act == 0) {
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 return;
3354 }
3355 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003356 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 if (mflag
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003361 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 }
3363 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003366
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003367 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 case S_CATCH:
3370 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003373 break;
3374 case S_IGN:
3375 act.sa_handler = SIG_IGN;
3376 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003377 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003378 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379
3380 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003381}
3382
3383/* mode flags for set_curjob */
3384#define CUR_DELETE 2
3385#define CUR_RUNNING 1
3386#define CUR_STOPPED 0
3387
3388/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003389#define DOWAIT_NONBLOCK WNOHANG
3390#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391
3392#if JOBS
3393/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static int initialpgrp; //references:2
3395static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396#endif
3397/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003398static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003400static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003402static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003403/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003404static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405
3406static void
3407set_curjob(struct job *jp, unsigned mode)
3408{
3409 struct job *jp1;
3410 struct job **jpp, **curp;
3411
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3414 do {
3415 jp1 = *jpp;
3416 if (jp1 == jp)
3417 break;
3418 jpp = &jp1->prev_job;
3419 } while (1);
3420 *jpp = jp1->prev_job;
3421
3422 /* Then re-insert in correct position */
3423 jpp = curp;
3424 switch (mode) {
3425 default:
3426#if DEBUG
3427 abort();
3428#endif
3429 case CUR_DELETE:
3430 /* job being deleted */
3431 break;
3432 case CUR_RUNNING:
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3435 do {
3436 jp1 = *jpp;
3437#if JOBS
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3439#endif
3440 break;
3441 jpp = &jp1->prev_job;
3442 } while (1);
3443 /* FALLTHROUGH */
3444#if JOBS
3445 case CUR_STOPPED:
3446#endif
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3449 *jpp = jp;
3450 break;
3451 }
3452}
3453
3454#if JOBS || DEBUG
3455static int
3456jobno(const struct job *jp)
3457{
3458 return jp - jobtab + 1;
3459}
3460#endif
3461
3462/*
3463 * Convert a job name to a job structure.
3464 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003465#if !JOBS
3466#define getjob(name, getctl) getjob(name)
3467#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003468static struct job *
3469getjob(const char *name, int getctl)
3470{
3471 struct job *jp;
3472 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003473 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003474 unsigned num;
3475 int c;
3476 const char *p;
3477 char *(*match)(const char *, const char *);
3478
3479 jp = curjob;
3480 p = name;
3481 if (!p)
3482 goto currentjob;
3483
3484 if (*p != '%')
3485 goto err;
3486
3487 c = *++p;
3488 if (!c)
3489 goto currentjob;
3490
3491 if (!p[1]) {
3492 if (c == '+' || c == '%') {
3493 currentjob:
3494 err_msg = "No current job";
3495 goto check;
3496 }
3497 if (c == '-') {
3498 if (jp)
3499 jp = jp->prev_job;
3500 err_msg = "No previous job";
3501 check:
3502 if (!jp)
3503 goto err;
3504 goto gotit;
3505 }
3506 }
3507
3508 if (is_number(p)) {
3509 num = atoi(p);
3510 if (num < njobs) {
3511 jp = jobtab + num - 1;
3512 if (jp->used)
3513 goto gotit;
3514 goto err;
3515 }
3516 }
3517
3518 match = prefix;
3519 if (*p == '?') {
3520 match = strstr;
3521 p++;
3522 }
3523
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003524 found = NULL;
3525 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003526 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003527 if (found)
3528 goto err;
3529 found = jp;
3530 err_msg = "%s: ambiguous";
3531 }
3532 jp = jp->prev_job;
3533 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003534 if (!found)
3535 goto err;
3536 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003537
3538 gotit:
3539#if JOBS
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3542 goto err;
3543#endif
3544 return jp;
3545 err:
3546 ash_msg_and_raise_error(err_msg, name);
3547}
3548
3549/*
3550 * Mark a job structure as unused.
3551 */
3552static void
3553freejob(struct job *jp)
3554{
3555 struct procstat *ps;
3556 int i;
3557
3558 INT_OFF;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003560 if (ps->ps_cmd != nullstr)
3561 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003562 }
3563 if (jp->ps != &jp->ps0)
3564 free(jp->ps);
3565 jp->used = 0;
3566 set_curjob(jp, CUR_DELETE);
3567 INT_ON;
3568}
3569
3570#if JOBS
3571static void
3572xtcsetpgrp(int fd, pid_t pgrp)
3573{
3574 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003575 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003576}
3577
3578/*
3579 * Turn job control on and off.
3580 *
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3584 *
3585 * Called with interrupts off.
3586 */
3587static void
3588setjobctl(int on)
3589{
3590 int fd;
3591 int pgrp;
3592
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003593 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003594 return;
3595 if (on) {
3596 int ofd;
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 if (fd < 0) {
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003603 fd = 2;
3604 while (!isatty(fd))
3605 if (--fd < 0)
3606 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003607 }
3608 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003609 if (ofd >= 0)
3610 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003611 if (fd < 0)
3612 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003613 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003614 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3617 if (pgrp < 0) {
3618 out:
3619 ash_msg("can't access tty; job control turned off");
3620 mflag = on = 0;
3621 goto close;
3622 }
3623 if (pgrp == getpgrp())
3624 break;
3625 killpg(0, SIGTTIN);
3626 } while (1);
3627 initialpgrp = pgrp;
3628
3629 setsignal(SIGTSTP);
3630 setsignal(SIGTTOU);
3631 setsignal(SIGTTIN);
3632 pgrp = rootpid;
3633 setpgid(0, pgrp);
3634 xtcsetpgrp(fd, pgrp);
3635 } else {
3636 /* turning job control off */
3637 fd = ttyfd;
3638 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003639 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003640 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003641 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003642 setpgid(0, pgrp);
3643 setsignal(SIGTSTP);
3644 setsignal(SIGTTOU);
3645 setsignal(SIGTTIN);
3646 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003647 if (fd >= 0)
3648 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003649 fd = -1;
3650 }
3651 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003652 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653}
3654
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003655static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656killcmd(int argc, char **argv)
3657{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003658 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003660 do {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003663 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003670 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003671 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003673 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674}
3675
3676static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003677showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003679 struct procstat *ps;
3680 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681
Denys Vlasenko285ad152009-12-04 23:02:27 +01003682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003686 flush_stdout_stderr();
3687}
3688
3689
3690static int
3691restartjob(struct job *jp, int mode)
3692{
3693 struct procstat *ps;
3694 int i;
3695 int status;
3696 pid_t pgid;
3697
3698 INT_OFF;
3699 if (jp->state == JOBDONE)
3700 goto out;
3701 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003702 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3706 ps = jp->ps;
3707 i = jp->nprocs;
3708 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003709 if (WIFSTOPPED(ps->ps_status)) {
3710 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 ps++;
3713 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714 out:
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3716 INT_ON;
3717 return status;
3718}
3719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003720static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003721fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003722{
3723 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003724 int mode;
3725 int retval;
3726
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 nextopt(nullstr);
3729 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 do {
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003734 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003735 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3740 return retval;
3741}
3742#endif
3743
3744static int
3745sprint_status(char *s, int status, int sigonly)
3746{
3747 int col;
3748 int st;
3749
3750 col = 0;
3751 if (!WIFEXITED(status)) {
3752#if JOBS
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3755 else
3756#endif
3757 st = WTERMSIG(status);
3758 if (sigonly) {
3759 if (st == SIGINT || st == SIGPIPE)
3760 goto out;
3761#if JOBS
3762 if (WIFSTOPPED(status))
3763 goto out;
3764#endif
3765 }
3766 st &= 0x7f;
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3770 }
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3773 if (st)
3774 col = fmtstr(s, 16, "Done(%d)", st);
3775 else
3776 col = fmtstr(s, 16, "Done");
3777 }
3778 out:
3779 return col;
3780}
3781
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003782static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003783dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784{
3785 int pid;
3786 int status;
3787 struct job *jp;
3788 struct job *thisjob;
3789 int state;
3790
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003791 TRACE(("dowait(0x%x) called\n", wait_flags));
3792
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003796 if (doing_jobctl)
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003801 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003802 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003803
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003804 INT_OFF;
3805 thisjob = NULL;
3806 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 struct procstat *ps;
3808 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809 if (jp->state == JOBDONE)
3810 continue;
3811 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 ps = jp->ps;
3813 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003814 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003820 thisjob = jp;
3821 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003822 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 state = JOBRUNNING;
3824#if JOBS
3825 if (state == JOBRUNNING)
3826 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003829 state = JOBSTOPPED;
3830 }
3831#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003832 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003833 if (thisjob)
3834 goto gotjob;
3835 }
3836#if JOBS
3837 if (!WIFSTOPPED(status))
3838#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003839 jobless--;
3840 goto out;
3841
3842 gotjob:
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3845
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3850#if JOBS
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3853 }
3854#endif
3855 }
3856 }
3857
3858 out:
3859 INT_ON;
3860
3861 if (thisjob && thisjob == job) {
3862 char s[48 + 1];
3863 int len;
3864
3865 len = sprint_status(s, status, 1);
3866 if (len) {
3867 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003868 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 out2str(s);
3870 }
3871 }
3872 return pid;
3873}
3874
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003875static int
3876blocking_wait_with_raise_on_sig(struct job *job)
3877{
3878 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003879 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003880 raise_exception(EXSIG);
3881 return pid;
3882}
3883
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884#if JOBS
3885static void
3886showjob(FILE *out, struct job *jp, int mode)
3887{
3888 struct procstat *ps;
3889 struct procstat *psend;
3890 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003891 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 char s[80];
3893
3894 ps = jp->ps;
3895
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003897 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003898 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 return;
3900 }
3901
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003903 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
3905 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003906 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003908 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003910 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912
3913 psend = ps + jp->nprocs;
3914
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3918 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003919 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3923 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3933 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003935 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003937 s[0] = '\0';
3938 col = 33;
3939 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003942 fprintf(out, "%s%*c%s%s",
3943 s,
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3946 ps->ps_cmd
3947 );
3948 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003949 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003950
3951 jp->changed = 0;
3952
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3955 freejob(jp);
3956 }
3957}
3958
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003959/*
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3962 */
3963static void
3964showjobs(FILE *out, int mode)
3965{
3966 struct job *jp;
3967
Denys Vlasenko883cea42009-07-11 15:31:59 +02003968 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003970 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972 continue;
3973
3974 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 }
3979}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003981static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003982jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983{
3984 int mode, m;
3985
3986 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003987 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003988 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003990 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003991 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 }
3993
3994 argv = argptr;
3995 if (*argv) {
3996 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003997 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003998 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003999 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004000 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004001 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004002
4003 return 0;
4004}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005#endif /* JOBS */
4006
Michael Abbott359da5e2009-12-04 23:03:29 +01004007/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008static int
4009getstatus(struct job *job)
4010{
4011 int status;
4012 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004013 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004014
Michael Abbott359da5e2009-12-04 23:03:29 +01004015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4018 if (pipefail) {
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4022 }
4023
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4026#if JOBS
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4029#endif
4030 {
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4033#if JOBS
4034 if (retval == SIGINT)
4035 job->sigint = 1;
4036#endif
4037 }
4038 retval += 128;
4039 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041 jobno(job), job->nprocs, status, retval));
4042 return retval;
4043}
4044
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004045static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004046waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004047{
4048 struct job *job;
4049 int retval;
4050 struct job *jp;
4051
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004052 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004053 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004054
4055 nextopt(nullstr);
4056 retval = 0;
4057
4058 argv = argptr;
4059 if (!*argv) {
4060 /* wait for all jobs */
4061 for (;;) {
4062 jp = curjob;
4063 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004064 if (!jp) /* no running procs */
4065 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066 if (jp->state == JOBRUNNING)
4067 break;
4068 jp->waited = 1;
4069 jp = jp->prev_job;
4070 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004071 /* man bash:
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
4077 * Do we do it that way? */
4078 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004079 }
4080 }
4081
4082 retval = 127;
4083 do {
4084 if (**argv != '%') {
4085 pid_t pid = number(*argv);
4086 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004087 while (1) {
4088 if (!job)
4089 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004090 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004091 break;
4092 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004093 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004094 } else
4095 job = getjob(*argv, 0);
4096 /* loop until process terminated or stopped */
4097 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004098 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004099 job->waited = 1;
4100 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004101 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004102 } while (*++argv);
4103
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004104 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004105 return retval;
4106}
4107
4108static struct job *
4109growjobtab(void)
4110{
4111 size_t len;
4112 ptrdiff_t offset;
4113 struct job *jp, *jq;
4114
4115 len = njobs * sizeof(*jp);
4116 jq = jobtab;
4117 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4118
4119 offset = (char *)jp - (char *)jq;
4120 if (offset) {
4121 /* Relocate pointers */
4122 size_t l = len;
4123
4124 jq = (struct job *)((char *)jq + l);
4125 while (l) {
4126 l -= sizeof(*jp);
4127 jq--;
4128#define joff(p) ((struct job *)((char *)(p) + l))
4129#define jmove(p) (p) = (void *)((char *)(p) + offset)
4130 if (joff(jp)->ps == &jq->ps0)
4131 jmove(joff(jp)->ps);
4132 if (joff(jp)->prev_job)
4133 jmove(joff(jp)->prev_job);
4134 }
4135 if (curjob)
4136 jmove(curjob);
4137#undef joff
4138#undef jmove
4139 }
4140
4141 njobs += 4;
4142 jobtab = jp;
4143 jp = (struct job *)((char *)jp + len);
4144 jq = jp + 3;
4145 do {
4146 jq->used = 0;
4147 } while (--jq >= jp);
4148 return jp;
4149}
4150
4151/*
4152 * Return a new job structure.
4153 * Called with interrupts off.
4154 */
4155static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004156makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004157{
4158 int i;
4159 struct job *jp;
4160
4161 for (i = njobs, jp = jobtab; ; jp++) {
4162 if (--i < 0) {
4163 jp = growjobtab();
4164 break;
4165 }
4166 if (jp->used == 0)
4167 break;
4168 if (jp->state != JOBDONE || !jp->waited)
4169 continue;
4170#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004171 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004172 continue;
4173#endif
4174 freejob(jp);
4175 break;
4176 }
4177 memset(jp, 0, sizeof(*jp));
4178#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004179 /* jp->jobctl is a bitfield.
4180 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004181 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004182 jp->jobctl = 1;
4183#endif
4184 jp->prev_job = curjob;
4185 curjob = jp;
4186 jp->used = 1;
4187 jp->ps = &jp->ps0;
4188 if (nprocs > 1) {
4189 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4190 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004191 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004192 jobno(jp)));
4193 return jp;
4194}
4195
4196#if JOBS
4197/*
4198 * Return a string identifying a command (to be printed by the
4199 * jobs command).
4200 */
4201static char *cmdnextc;
4202
4203static void
4204cmdputs(const char *s)
4205{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004206 static const char vstype[VSTYPE + 1][3] = {
4207 "", "}", "-", "+", "?", "=",
4208 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004209 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004210 };
4211
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004212 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004213 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004215 unsigned char c;
4216 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004218
Denys Vlasenko46a14772009-12-10 21:27:13 +01004219 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4221 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004222 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004223 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224 switch (c) {
4225 case CTLESC:
4226 c = *p++;
4227 break;
4228 case CTLVAR:
4229 subtype = *p++;
4230 if ((subtype & VSTYPE) == VSLENGTH)
4231 str = "${#";
4232 else
4233 str = "${";
4234 if (!(subtype & VSQUOTE) == !(quoted & 1))
4235 goto dostr;
4236 quoted ^= 1;
4237 c = '"';
4238 break;
4239 case CTLENDVAR:
4240 str = "\"}" + !(quoted & 1);
4241 quoted >>= 1;
4242 subtype = 0;
4243 goto dostr;
4244 case CTLBACKQ:
4245 str = "$(...)";
4246 goto dostr;
4247 case CTLBACKQ+CTLQUOTE:
4248 str = "\"$(...)\"";
4249 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004250#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004251 case CTLARI:
4252 str = "$((";
4253 goto dostr;
4254 case CTLENDARI:
4255 str = "))";
4256 goto dostr;
4257#endif
4258 case CTLQUOTEMARK:
4259 quoted ^= 1;
4260 c = '"';
4261 break;
4262 case '=':
4263 if (subtype == 0)
4264 break;
4265 if ((subtype & VSTYPE) != VSNORMAL)
4266 quoted <<= 1;
4267 str = vstype[subtype & VSTYPE];
4268 if (subtype & VSNUL)
4269 c = ':';
4270 else
4271 goto checkstr;
4272 break;
4273 case '\'':
4274 case '\\':
4275 case '"':
4276 case '$':
4277 /* These can only happen inside quotes */
4278 cc[0] = c;
4279 str = cc;
4280 c = '\\';
4281 break;
4282 default:
4283 break;
4284 }
4285 USTPUTC(c, nextc);
4286 checkstr:
4287 if (!str)
4288 continue;
4289 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004290 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004291 USTPUTC(c, nextc);
4292 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004293 } /* while *p++ not NUL */
4294
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004295 if (quoted & 1) {
4296 USTPUTC('"', nextc);
4297 }
4298 *nextc = 0;
4299 cmdnextc = nextc;
4300}
4301
4302/* cmdtxt() and cmdlist() call each other */
4303static void cmdtxt(union node *n);
4304
4305static void
4306cmdlist(union node *np, int sep)
4307{
4308 for (; np; np = np->narg.next) {
4309 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004310 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004311 cmdtxt(np);
4312 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004313 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004314 }
4315}
4316
4317static void
4318cmdtxt(union node *n)
4319{
4320 union node *np;
4321 struct nodelist *lp;
4322 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004323
4324 if (!n)
4325 return;
4326 switch (n->type) {
4327 default:
4328#if DEBUG
4329 abort();
4330#endif
4331 case NPIPE:
4332 lp = n->npipe.cmdlist;
4333 for (;;) {
4334 cmdtxt(lp->n);
4335 lp = lp->next;
4336 if (!lp)
4337 break;
4338 cmdputs(" | ");
4339 }
4340 break;
4341 case NSEMI:
4342 p = "; ";
4343 goto binop;
4344 case NAND:
4345 p = " && ";
4346 goto binop;
4347 case NOR:
4348 p = " || ";
4349 binop:
4350 cmdtxt(n->nbinary.ch1);
4351 cmdputs(p);
4352 n = n->nbinary.ch2;
4353 goto donode;
4354 case NREDIR:
4355 case NBACKGND:
4356 n = n->nredir.n;
4357 goto donode;
4358 case NNOT:
4359 cmdputs("!");
4360 n = n->nnot.com;
4361 donode:
4362 cmdtxt(n);
4363 break;
4364 case NIF:
4365 cmdputs("if ");
4366 cmdtxt(n->nif.test);
4367 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004368 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004369 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004370 cmdputs("; else ");
4371 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004372 } else {
4373 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004374 }
4375 p = "; fi";
4376 goto dotail;
4377 case NSUBSHELL:
4378 cmdputs("(");
4379 n = n->nredir.n;
4380 p = ")";
4381 goto dotail;
4382 case NWHILE:
4383 p = "while ";
4384 goto until;
4385 case NUNTIL:
4386 p = "until ";
4387 until:
4388 cmdputs(p);
4389 cmdtxt(n->nbinary.ch1);
4390 n = n->nbinary.ch2;
4391 p = "; done";
4392 dodo:
4393 cmdputs("; do ");
4394 dotail:
4395 cmdtxt(n);
4396 goto dotail2;
4397 case NFOR:
4398 cmdputs("for ");
4399 cmdputs(n->nfor.var);
4400 cmdputs(" in ");
4401 cmdlist(n->nfor.args, 1);
4402 n = n->nfor.body;
4403 p = "; done";
4404 goto dodo;
4405 case NDEFUN:
4406 cmdputs(n->narg.text);
4407 p = "() { ... }";
4408 goto dotail2;
4409 case NCMD:
4410 cmdlist(n->ncmd.args, 1);
4411 cmdlist(n->ncmd.redirect, 0);
4412 break;
4413 case NARG:
4414 p = n->narg.text;
4415 dotail2:
4416 cmdputs(p);
4417 break;
4418 case NHERE:
4419 case NXHERE:
4420 p = "<<...";
4421 goto dotail2;
4422 case NCASE:
4423 cmdputs("case ");
4424 cmdputs(n->ncase.expr->narg.text);
4425 cmdputs(" in ");
4426 for (np = n->ncase.cases; np; np = np->nclist.next) {
4427 cmdtxt(np->nclist.pattern);
4428 cmdputs(") ");
4429 cmdtxt(np->nclist.body);
4430 cmdputs(";; ");
4431 }
4432 p = "esac";
4433 goto dotail2;
4434 case NTO:
4435 p = ">";
4436 goto redir;
4437 case NCLOBBER:
4438 p = ">|";
4439 goto redir;
4440 case NAPPEND:
4441 p = ">>";
4442 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004443#if ENABLE_ASH_BASH_COMPAT
4444 case NTO2:
4445#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004446 case NTOFD:
4447 p = ">&";
4448 goto redir;
4449 case NFROM:
4450 p = "<";
4451 goto redir;
4452 case NFROMFD:
4453 p = "<&";
4454 goto redir;
4455 case NFROMTO:
4456 p = "<>";
4457 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004458 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004459 cmdputs(p);
4460 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004461 cmdputs(utoa(n->ndup.dupfd));
4462 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004463 }
4464 n = n->nfile.fname;
4465 goto donode;
4466 }
4467}
4468
4469static char *
4470commandtext(union node *n)
4471{
4472 char *name;
4473
4474 STARTSTACKSTR(cmdnextc);
4475 cmdtxt(n);
4476 name = stackblock();
4477 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4478 name, cmdnextc, cmdnextc));
4479 return ckstrdup(name);
4480}
4481#endif /* JOBS */
4482
4483/*
4484 * Fork off a subshell. If we are doing job control, give the subshell its
4485 * own process group. Jp is a job structure that the job is to be added to.
4486 * N is the command that will be evaluated by the child. Both jp and n may
4487 * be NULL. The mode parameter can be one of the following:
4488 * FORK_FG - Fork off a foreground process.
4489 * FORK_BG - Fork off a background process.
4490 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4491 * process group even if job control is on.
4492 *
4493 * When job control is turned off, background processes have their standard
4494 * input redirected to /dev/null (except for the second and later processes
4495 * in a pipeline).
4496 *
4497 * Called with interrupts off.
4498 */
4499/*
4500 * Clear traps on a fork.
4501 */
4502static void
4503clear_traps(void)
4504{
4505 char **tp;
4506
4507 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004508 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004509 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004510 if (trap_ptr == trap)
4511 free(*tp);
4512 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004513 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004514 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004515 setsignal(tp - trap);
4516 INT_ON;
4517 }
4518 }
4519}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004520
4521/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004522static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004523
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004524/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004525static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004526forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004527{
4528 int oldlvl;
4529
4530 TRACE(("Child shell %d\n", getpid()));
4531 oldlvl = shlvl;
4532 shlvl++;
4533
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004534 /* man bash: "Non-builtin commands run by bash have signal handlers
4535 * set to the values inherited by the shell from its parent".
4536 * Do we do it correctly? */
4537
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004538 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004539
4540 if (mode == FORK_NOJOB /* is it `xxx` ? */
4541 && n && n->type == NCMD /* is it single cmd? */
4542 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004543 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004544 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4545 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4546 ) {
4547 TRACE(("Trap hack\n"));
4548 /* Awful hack for `trap` or $(trap).
4549 *
4550 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4551 * contains an example where "trap" is executed in a subshell:
4552 *
4553 * save_traps=$(trap)
4554 * ...
4555 * eval "$save_traps"
4556 *
4557 * Standard does not say that "trap" in subshell shall print
4558 * parent shell's traps. It only says that its output
4559 * must have suitable form, but then, in the above example
4560 * (which is not supposed to be normative), it implies that.
4561 *
4562 * bash (and probably other shell) does implement it
4563 * (traps are reset to defaults, but "trap" still shows them),
4564 * but as a result, "trap" logic is hopelessly messed up:
4565 *
4566 * # trap
4567 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4568 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4569 * # true | trap <--- trap is in subshell - no output (ditto)
4570 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4571 * trap -- 'echo Ho' SIGWINCH
4572 * # echo `(trap)` <--- in subshell in subshell - output
4573 * trap -- 'echo Ho' SIGWINCH
4574 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4575 * trap -- 'echo Ho' SIGWINCH
4576 *
4577 * The rules when to forget and when to not forget traps
4578 * get really complex and nonsensical.
4579 *
4580 * Our solution: ONLY bare $(trap) or `trap` is special.
4581 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004582 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004583 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004584 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004585 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004586 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004587#if JOBS
4588 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004589 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004590 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4591 pid_t pgrp;
4592
4593 if (jp->nprocs == 0)
4594 pgrp = getpid();
4595 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004596 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004597 /* this can fail because we are doing it in the parent also */
4598 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004599 if (mode == FORK_FG)
4600 xtcsetpgrp(ttyfd, pgrp);
4601 setsignal(SIGTSTP);
4602 setsignal(SIGTTOU);
4603 } else
4604#endif
4605 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004606 /* man bash: "When job control is not in effect,
4607 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004608 ignoresig(SIGINT);
4609 ignoresig(SIGQUIT);
4610 if (jp->nprocs == 0) {
4611 close(0);
4612 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004613 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004614 }
4615 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004616 if (!oldlvl) {
4617 if (iflag) { /* why if iflag only? */
4618 setsignal(SIGINT);
4619 setsignal(SIGTERM);
4620 }
4621 /* man bash:
4622 * "In all cases, bash ignores SIGQUIT. Non-builtin
4623 * commands run by bash have signal handlers
4624 * set to the values inherited by the shell
4625 * from its parent".
4626 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004628 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004629#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004630 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004631 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004632 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004633 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004634 /* "jobs": we do not want to clear job list for it,
4635 * instead we remove only _its_ own_ job from job list.
4636 * This makes "jobs .... | cat" more useful.
4637 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004638 freejob(curjob);
4639 return;
4640 }
4641#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004642 for (jp = curjob; jp; jp = jp->prev_job)
4643 freejob(jp);
4644 jobless = 0;
4645}
4646
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004647/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004648#if !JOBS
4649#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4650#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004651static void
4652forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4653{
4654 TRACE(("In parent shell: child = %d\n", pid));
4655 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004656 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4657 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004658 jobless++;
4659 return;
4660 }
4661#if JOBS
4662 if (mode != FORK_NOJOB && jp->jobctl) {
4663 int pgrp;
4664
4665 if (jp->nprocs == 0)
4666 pgrp = pid;
4667 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004668 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004669 /* This can fail because we are doing it in the child also */
4670 setpgid(pid, pgrp);
4671 }
4672#endif
4673 if (mode == FORK_BG) {
4674 backgndpid = pid; /* set $! */
4675 set_curjob(jp, CUR_RUNNING);
4676 }
4677 if (jp) {
4678 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004679 ps->ps_pid = pid;
4680 ps->ps_status = -1;
4681 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004682#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004683 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004684 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004685#endif
4686 }
4687}
4688
4689static int
4690forkshell(struct job *jp, union node *n, int mode)
4691{
4692 int pid;
4693
4694 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4695 pid = fork();
4696 if (pid < 0) {
4697 TRACE(("Fork failed, errno=%d", errno));
4698 if (jp)
4699 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004700 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004701 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004702 if (pid == 0) {
4703 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004704 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004705 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004706 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004707 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004708 return pid;
4709}
4710
4711/*
4712 * Wait for job to finish.
4713 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004714 * Under job control we have the problem that while a child process
4715 * is running interrupts generated by the user are sent to the child
4716 * but not to the shell. This means that an infinite loop started by
4717 * an interactive user may be hard to kill. With job control turned off,
4718 * an interactive user may place an interactive program inside a loop.
4719 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004720 * these interrupts to also abort the loop. The approach we take here
4721 * is to have the shell ignore interrupt signals while waiting for a
4722 * foreground process to terminate, and then send itself an interrupt
4723 * signal if the child process was terminated by an interrupt signal.
4724 * Unfortunately, some programs want to do a bit of cleanup and then
4725 * exit on interrupt; unless these processes terminate themselves by
4726 * sending a signal to themselves (instead of calling exit) they will
4727 * confuse this approach.
4728 *
4729 * Called with interrupts off.
4730 */
4731static int
4732waitforjob(struct job *jp)
4733{
4734 int st;
4735
4736 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004737
4738 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004739 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004740 /* In non-interactive shells, we _can_ get
4741 * a keyboard signal here and be EINTRed,
4742 * but we just loop back, waiting for command to complete.
4743 *
4744 * man bash:
4745 * "If bash is waiting for a command to complete and receives
4746 * a signal for which a trap has been set, the trap
4747 * will not be executed until the command completes."
4748 *
4749 * Reality is that even if trap is not set, bash
4750 * will not act on the signal until command completes.
4751 * Try this. sleep5intoff.c:
4752 * #include <signal.h>
4753 * #include <unistd.h>
4754 * int main() {
4755 * sigset_t set;
4756 * sigemptyset(&set);
4757 * sigaddset(&set, SIGINT);
4758 * sigaddset(&set, SIGQUIT);
4759 * sigprocmask(SIG_BLOCK, &set, NULL);
4760 * sleep(5);
4761 * return 0;
4762 * }
4763 * $ bash -c './sleep5intoff; echo hi'
4764 * ^C^C^C^C <--- pressing ^C once a second
4765 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004766 * $ bash -c './sleep5intoff; echo hi'
4767 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4768 * $ _
4769 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004770 dowait(DOWAIT_BLOCK, jp);
4771 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004772 INT_ON;
4773
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004774 st = getstatus(jp);
4775#if JOBS
4776 if (jp->jobctl) {
4777 xtcsetpgrp(ttyfd, rootpid);
4778 /*
4779 * This is truly gross.
4780 * If we're doing job control, then we did a TIOCSPGRP which
4781 * caused us (the shell) to no longer be in the controlling
4782 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4783 * intuit from the subprocess exit status whether a SIGINT
4784 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4785 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004786 if (jp->sigint) /* TODO: do the same with all signals */
4787 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004788 }
4789 if (jp->state == JOBDONE)
4790#endif
4791 freejob(jp);
4792 return st;
4793}
4794
4795/*
4796 * return 1 if there are stopped jobs, otherwise 0
4797 */
4798static int
4799stoppedjobs(void)
4800{
4801 struct job *jp;
4802 int retval;
4803
4804 retval = 0;
4805 if (job_warning)
4806 goto out;
4807 jp = curjob;
4808 if (jp && jp->state == JOBSTOPPED) {
4809 out2str("You have stopped jobs.\n");
4810 job_warning = 2;
4811 retval++;
4812 }
4813 out:
4814 return retval;
4815}
4816
4817
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004818/* ============ redir.c
4819 *
4820 * Code for dealing with input/output redirection.
4821 */
4822
4823#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004824#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004825
4826/*
4827 * Open a file in noclobber mode.
4828 * The code was copied from bash.
4829 */
4830static int
4831noclobberopen(const char *fname)
4832{
4833 int r, fd;
4834 struct stat finfo, finfo2;
4835
4836 /*
4837 * If the file exists and is a regular file, return an error
4838 * immediately.
4839 */
4840 r = stat(fname, &finfo);
4841 if (r == 0 && S_ISREG(finfo.st_mode)) {
4842 errno = EEXIST;
4843 return -1;
4844 }
4845
4846 /*
4847 * If the file was not present (r != 0), make sure we open it
4848 * exclusively so that if it is created before we open it, our open
4849 * will fail. Make sure that we do not truncate an existing file.
4850 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4851 * file was not a regular file, we leave O_EXCL off.
4852 */
4853 if (r != 0)
4854 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4855 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4856
4857 /* If the open failed, return the file descriptor right away. */
4858 if (fd < 0)
4859 return fd;
4860
4861 /*
4862 * OK, the open succeeded, but the file may have been changed from a
4863 * non-regular file to a regular file between the stat and the open.
4864 * We are assuming that the O_EXCL open handles the case where FILENAME
4865 * did not exist and is symlinked to an existing file between the stat
4866 * and open.
4867 */
4868
4869 /*
4870 * If we can open it and fstat the file descriptor, and neither check
4871 * revealed that it was a regular file, and the file has not been
4872 * replaced, return the file descriptor.
4873 */
4874 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4875 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4876 return fd;
4877
4878 /* The file has been replaced. badness. */
4879 close(fd);
4880 errno = EEXIST;
4881 return -1;
4882}
4883
4884/*
4885 * Handle here documents. Normally we fork off a process to write the
4886 * data to a pipe. If the document is short, we can stuff the data in
4887 * the pipe without forking.
4888 */
4889/* openhere needs this forward reference */
4890static void expandhere(union node *arg, int fd);
4891static int
4892openhere(union node *redir)
4893{
4894 int pip[2];
4895 size_t len = 0;
4896
4897 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004898 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004899 if (redir->type == NHERE) {
4900 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004901 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004902 full_write(pip[1], redir->nhere.doc->narg.text, len);
4903 goto out;
4904 }
4905 }
4906 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004907 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004908 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004909 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4910 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4911 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4912 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004913 signal(SIGPIPE, SIG_DFL);
4914 if (redir->type == NHERE)
4915 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004916 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004917 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004918 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004919 }
4920 out:
4921 close(pip[1]);
4922 return pip[0];
4923}
4924
4925static int
4926openredirect(union node *redir)
4927{
4928 char *fname;
4929 int f;
4930
4931 switch (redir->nfile.type) {
4932 case NFROM:
4933 fname = redir->nfile.expfname;
4934 f = open(fname, O_RDONLY);
4935 if (f < 0)
4936 goto eopen;
4937 break;
4938 case NFROMTO:
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4941 if (f < 0)
4942 goto ecreate;
4943 break;
4944 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004945#if ENABLE_ASH_BASH_COMPAT
4946 case NTO2:
4947#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004948 /* Take care of noclobber mode. */
4949 if (Cflag) {
4950 fname = redir->nfile.expfname;
4951 f = noclobberopen(fname);
4952 if (f < 0)
4953 goto ecreate;
4954 break;
4955 }
4956 /* FALLTHROUGH */
4957 case NCLOBBER:
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4960 if (f < 0)
4961 goto ecreate;
4962 break;
4963 case NAPPEND:
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4966 if (f < 0)
4967 goto ecreate;
4968 break;
4969 default:
4970#if DEBUG
4971 abort();
4972#endif
4973 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004974/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004975// case NTOFD:
4976// case NFROMFD:
4977// f = -1;
4978// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004979 case NHERE:
4980 case NXHERE:
4981 f = openhere(redir);
4982 break;
4983 }
4984
4985 return f;
4986 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004987 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004988 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004989 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004990}
4991
4992/*
4993 * Copy a file descriptor to be >= to. Returns -1
4994 * if the source file descriptor is closed, EMPTY if there are no unused
4995 * file descriptors left.
4996 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004997/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4998 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004999enum {
5000 COPYFD_EXACT = (int)~(INT_MAX),
5001 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5002};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003static int
5004copyfd(int from, int to)
5005{
5006 int newfd;
5007
Denis Vlasenko5a867312008-07-24 19:46:38 +00005008 if (to & COPYFD_EXACT) {
5009 to &= ~COPYFD_EXACT;
5010 /*if (from != to)*/
5011 newfd = dup2(from, to);
5012 } else {
5013 newfd = fcntl(from, F_DUPFD, to);
5014 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005015 if (newfd < 0) {
5016 if (errno == EMFILE)
5017 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005018 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005019 ash_msg_and_raise_error("%d: %m", from);
5020 }
5021 return newfd;
5022}
5023
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005024/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005025struct two_fd_t {
5026 int orig, copy;
5027};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005028struct redirtab {
5029 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005030 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005031 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005032 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005033};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005034#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005035
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005036static int need_to_remember(struct redirtab *rp, int fd)
5037{
5038 int i;
5039
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005040 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005041 return 0;
5042
5043 for (i = 0; i < rp->pair_count; i++) {
5044 if (rp->two_fd[i].orig == fd) {
5045 /* already remembered */
5046 return 0;
5047 }
5048 }
5049 return 1;
5050}
5051
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005052/* "hidden" fd is a fd used to read scripts, or a copy of such */
5053static int is_hidden_fd(struct redirtab *rp, int fd)
5054{
5055 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005056 struct parsefile *pf;
5057
5058 if (fd == -1)
5059 return 0;
5060 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005061 while (pf) {
5062 if (fd == pf->fd) {
5063 return 1;
5064 }
5065 pf = pf->prev;
5066 }
5067 if (!rp)
5068 return 0;
5069 fd |= COPYFD_RESTORE;
5070 for (i = 0; i < rp->pair_count; i++) {
5071 if (rp->two_fd[i].copy == fd) {
5072 return 1;
5073 }
5074 }
5075 return 0;
5076}
5077
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005078/*
5079 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5080 * old file descriptors are stashed away so that the redirection can be
5081 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5082 * standard output, and the standard error if it becomes a duplicate of
5083 * stdout, is saved in memory.
5084 */
5085/* flags passed to redirect */
5086#define REDIR_PUSH 01 /* save previous values of file descriptors */
5087#define REDIR_SAVEFD2 03 /* set preverrout */
5088static void
5089redirect(union node *redir, int flags)
5090{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005091 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005092 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005093 int i;
5094 int fd;
5095 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005096 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005097
Denis Vlasenko01631112007-12-16 17:20:38 +00005098 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 if (!redir) {
5100 return;
5101 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005102
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005103 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005104 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005105 INT_OFF;
5106 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005107 union node *tmp = redir;
5108 do {
5109 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005110#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005111 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005112 sv_pos++;
5113#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005114 tmp = tmp->nfile.next;
5115 } while (tmp);
5116 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005117 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005119 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005120 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005121 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 while (sv_pos > 0) {
5123 sv_pos--;
5124 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5125 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005126 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005127
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005128 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005129 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005130 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005131 int right_fd = redir->ndup.dupfd;
5132 /* redirect from/to same file descriptor? */
5133 if (right_fd == fd)
5134 continue;
5135 /* echo >&10 and 10 is a fd opened to the sh script? */
5136 if (is_hidden_fd(sv, right_fd)) {
5137 errno = EBADF; /* as if it is closed */
5138 ash_msg_and_raise_error("%d: %m", right_fd);
5139 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005140 newfd = -1;
5141 } else {
5142 newfd = openredirect(redir); /* always >= 0 */
5143 if (fd == newfd) {
5144 /* Descriptor wasn't open before redirect.
5145 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005146 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005147 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005148 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005149 continue;
5150 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005151 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005152#if ENABLE_ASH_BASH_COMPAT
5153 redirect_more:
5154#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005155 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005156 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005157 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005158/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5159 * are closed in popredir() in the child, preventing them from leaking
5160 * into child. (popredir() also cleans up the mess in case of failures)
5161 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005162 if (i == -1) {
5163 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005164 if (i != EBADF) {
5165 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005166 if (newfd >= 0)
5167 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005168 errno = i;
5169 ash_msg_and_raise_error("%d: %m", fd);
5170 /* NOTREACHED */
5171 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005172 /* EBADF: it is not open - good, remember to close it */
5173 remember_to_close:
5174 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005175 } else { /* fd is open, save its copy */
5176 /* "exec fd>&-" should not close fds
5177 * which point to script file(s).
5178 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005179 if (is_hidden_fd(sv, fd))
5180 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005181 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005182 if (fd == 2)
5183 copied_fd2 = i;
5184 sv->two_fd[sv_pos].orig = fd;
5185 sv->two_fd[sv_pos].copy = i;
5186 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005187 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005188 if (newfd < 0) {
5189 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005190 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005191 /* Don't want to trigger debugging */
5192 if (fd != -1)
5193 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005194 } else {
5195 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005196 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005197 } else if (fd != newfd) { /* move newfd to fd */
5198 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005199#if ENABLE_ASH_BASH_COMPAT
5200 if (!(redir->nfile.type == NTO2 && fd == 2))
5201#endif
5202 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005203 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005204#if ENABLE_ASH_BASH_COMPAT
5205 if (redir->nfile.type == NTO2 && fd == 1) {
5206 /* We already redirected it to fd 1, now copy it to 2 */
5207 newfd = 1;
5208 fd = 2;
5209 goto redirect_more;
5210 }
5211#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005212 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005213
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005214 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005215 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5216 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005217}
5218
5219/*
5220 * Undo the effects of the last redirection.
5221 */
5222static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005223popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005224{
5225 struct redirtab *rp;
5226 int i;
5227
Denis Vlasenko01631112007-12-16 17:20:38 +00005228 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005229 return;
5230 INT_OFF;
5231 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005232 for (i = 0; i < rp->pair_count; i++) {
5233 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005234 int copy = rp->two_fd[i].copy;
5235 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005236 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005237 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005238 continue;
5239 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005240 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005241 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005242 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005243 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005244 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005246 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005247 }
5248 }
5249 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005250 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005251 free(rp);
5252 INT_ON;
5253}
5254
5255/*
5256 * Undo all redirections. Called on error or interrupt.
5257 */
5258
5259/*
5260 * Discard all saved file descriptors.
5261 */
5262static void
5263clearredir(int drop)
5264{
5265 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005266 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005267 if (!redirlist)
5268 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005269 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005270 }
5271}
5272
5273static int
5274redirectsafe(union node *redir, int flags)
5275{
5276 int err;
5277 volatile int saveint;
5278 struct jmploc *volatile savehandler = exception_handler;
5279 struct jmploc jmploc;
5280
5281 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005282 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5283 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005284 if (!err) {
5285 exception_handler = &jmploc;
5286 redirect(redir, flags);
5287 }
5288 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005289 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005290 longjmp(exception_handler->loc, 1);
5291 RESTORE_INT(saveint);
5292 return err;
5293}
5294
5295
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005296/* ============ Routines to expand arguments to commands
5297 *
5298 * We have to deal with backquotes, shell variables, and file metacharacters.
5299 */
5300
Mike Frysinger98c52642009-04-02 10:02:37 +00005301#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005302static arith_t
5303ash_arith(const char *s)
5304{
5305 arith_eval_hooks_t math_hooks;
5306 arith_t result;
5307 int errcode = 0;
5308
5309 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005310 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005311 math_hooks.endofname = endofname;
5312
5313 INT_OFF;
5314 result = arith(s, &errcode, &math_hooks);
5315 if (errcode < 0) {
5316 if (errcode == -3)
5317 ash_msg_and_raise_error("exponent less than 0");
5318 if (errcode == -2)
5319 ash_msg_and_raise_error("divide by zero");
5320 if (errcode == -5)
5321 ash_msg_and_raise_error("expression recursion loop detected");
5322 raise_error_syntax(s);
5323 }
5324 INT_ON;
5325
5326 return result;
5327}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005328#endif
5329
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005330/*
5331 * expandarg flags
5332 */
5333#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5334#define EXP_TILDE 0x2 /* do normal tilde expansion */
5335#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5336#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5337#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5338#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5339#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5340#define EXP_WORD 0x80 /* expand word in parameter expansion */
5341#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5342/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005343 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005344 */
5345#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5346#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5347#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5348#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5349#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5350
5351/*
5352 * Structure specifying which parts of the string should be searched
5353 * for IFS characters.
5354 */
5355struct ifsregion {
5356 struct ifsregion *next; /* next region in list */
5357 int begoff; /* offset of start of region */
5358 int endoff; /* offset of end of region */
5359 int nulonly; /* search for nul bytes only */
5360};
5361
5362struct arglist {
5363 struct strlist *list;
5364 struct strlist **lastp;
5365};
5366
5367/* output of current string */
5368static char *expdest;
5369/* list of back quote expressions */
5370static struct nodelist *argbackq;
5371/* first struct in list of ifs regions */
5372static struct ifsregion ifsfirst;
5373/* last struct in list */
5374static struct ifsregion *ifslastp;
5375/* holds expanded arg list */
5376static struct arglist exparg;
5377
5378/*
5379 * Our own itoa().
5380 */
5381static int
5382cvtnum(arith_t num)
5383{
5384 int len;
5385
5386 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005387 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005388 STADJUST(len, expdest);
5389 return len;
5390}
5391
5392static size_t
5393esclen(const char *start, const char *p)
5394{
5395 size_t esc = 0;
5396
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005397 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005398 esc++;
5399 }
5400 return esc;
5401}
5402
5403/*
5404 * Remove any CTLESC characters from a string.
5405 */
5406static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005407rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005408{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005409 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005410
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005412 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005413 unsigned protect_against_glob;
5414 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005415
5416 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005417 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005418 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005419
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005420 q = p;
5421 r = str;
5422 if (flag & RMESCAPE_ALLOC) {
5423 size_t len = p - str;
5424 size_t fulllen = len + strlen(p) + 1;
5425
5426 if (flag & RMESCAPE_GROW) {
5427 r = makestrspace(fulllen, expdest);
5428 } else if (flag & RMESCAPE_HEAP) {
5429 r = ckmalloc(fulllen);
5430 } else {
5431 r = stalloc(fulllen);
5432 }
5433 q = r;
5434 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005435 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436 }
5437 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5440 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005442 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005443 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005444// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5445// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5446// Note: both inquotes and protect_against_glob only affect whether
5447// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 inquotes = ~inquotes;
5449 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005450 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005451 continue;
5452 }
5453 if (*p == '\\') {
5454 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005455 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005456 goto copy;
5457 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005458 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005459 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 *q++ = '\\';
5462 }
5463 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005464 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005465 copy:
5466 *q++ = *p++;
5467 }
5468 *q = '\0';
5469 if (flag & RMESCAPE_GROW) {
5470 expdest = r;
5471 STADJUST(q - r + 1, expdest);
5472 }
5473 return r;
5474}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475#define pmatch(a, b) !fnmatch((a), (b), 0)
5476
5477/*
5478 * Prepare a pattern for a expmeta (internal glob(3)) call.
5479 *
5480 * Returns an stalloced string.
5481 */
5482static char *
5483preglob(const char *pattern, int quoted, int flag)
5484{
5485 flag |= RMESCAPE_GLOB;
5486 if (quoted) {
5487 flag |= RMESCAPE_QUOTED;
5488 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005489 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005490}
5491
5492/*
5493 * Put a string on the stack.
5494 */
5495static void
5496memtodest(const char *p, size_t len, int syntax, int quotes)
5497{
5498 char *q = expdest;
5499
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005500 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005501
5502 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005503 unsigned char c = *p++;
5504 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005505 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005506 if (quotes) {
5507 int n = SIT(c, syntax);
5508 if (n == CCTL || n == CBACK)
5509 USTPUTC(CTLESC, q);
5510 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005511 USTPUTC(c, q);
5512 }
5513
5514 expdest = q;
5515}
5516
5517static void
5518strtodest(const char *p, int syntax, int quotes)
5519{
5520 memtodest(p, strlen(p), syntax, quotes);
5521}
5522
5523/*
5524 * Record the fact that we have to scan this region of the
5525 * string for IFS characters.
5526 */
5527static void
5528recordregion(int start, int end, int nulonly)
5529{
5530 struct ifsregion *ifsp;
5531
5532 if (ifslastp == NULL) {
5533 ifsp = &ifsfirst;
5534 } else {
5535 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005536 ifsp = ckzalloc(sizeof(*ifsp));
5537 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005538 ifslastp->next = ifsp;
5539 INT_ON;
5540 }
5541 ifslastp = ifsp;
5542 ifslastp->begoff = start;
5543 ifslastp->endoff = end;
5544 ifslastp->nulonly = nulonly;
5545}
5546
5547static void
5548removerecordregions(int endoff)
5549{
5550 if (ifslastp == NULL)
5551 return;
5552
5553 if (ifsfirst.endoff > endoff) {
5554 while (ifsfirst.next != NULL) {
5555 struct ifsregion *ifsp;
5556 INT_OFF;
5557 ifsp = ifsfirst.next->next;
5558 free(ifsfirst.next);
5559 ifsfirst.next = ifsp;
5560 INT_ON;
5561 }
5562 if (ifsfirst.begoff > endoff)
5563 ifslastp = NULL;
5564 else {
5565 ifslastp = &ifsfirst;
5566 ifsfirst.endoff = endoff;
5567 }
5568 return;
5569 }
5570
5571 ifslastp = &ifsfirst;
5572 while (ifslastp->next && ifslastp->next->begoff < endoff)
5573 ifslastp=ifslastp->next;
5574 while (ifslastp->next != NULL) {
5575 struct ifsregion *ifsp;
5576 INT_OFF;
5577 ifsp = ifslastp->next->next;
5578 free(ifslastp->next);
5579 ifslastp->next = ifsp;
5580 INT_ON;
5581 }
5582 if (ifslastp->endoff > endoff)
5583 ifslastp->endoff = endoff;
5584}
5585
5586static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005587exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005588{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005589 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005590 char *name;
5591 struct passwd *pw;
5592 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005593 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005594 int startloc;
5595
5596 name = p + 1;
5597
5598 while ((c = *++p) != '\0') {
5599 switch (c) {
5600 case CTLESC:
5601 return startp;
5602 case CTLQUOTEMARK:
5603 return startp;
5604 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005605 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005606 goto done;
5607 break;
5608 case '/':
5609 case CTLENDVAR:
5610 goto done;
5611 }
5612 }
5613 done:
5614 *p = '\0';
5615 if (*name == '\0') {
5616 home = lookupvar(homestr);
5617 } else {
5618 pw = getpwnam(name);
5619 if (pw == NULL)
5620 goto lose;
5621 home = pw->pw_dir;
5622 }
5623 if (!home || !*home)
5624 goto lose;
5625 *p = c;
5626 startloc = expdest - (char *)stackblock();
5627 strtodest(home, SQSYNTAX, quotes);
5628 recordregion(startloc, expdest - (char *)stackblock(), 0);
5629 return p;
5630 lose:
5631 *p = c;
5632 return startp;
5633}
5634
5635/*
5636 * Execute a command inside back quotes. If it's a builtin command, we
5637 * want to save its output in a block obtained from malloc. Otherwise
5638 * we fork off a subprocess and get the output of the command via a pipe.
5639 * Should be called with interrupts off.
5640 */
5641struct backcmd { /* result of evalbackcmd */
5642 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005643 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005644 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005645 struct job *jp; /* job structure for command */
5646};
5647
5648/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005649static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005650#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005651static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005652
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005653static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005654evalbackcmd(union node *n, struct backcmd *result)
5655{
5656 int saveherefd;
5657
5658 result->fd = -1;
5659 result->buf = NULL;
5660 result->nleft = 0;
5661 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005662 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005663 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664
5665 saveherefd = herefd;
5666 herefd = -1;
5667
5668 {
5669 int pip[2];
5670 struct job *jp;
5671
5672 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005673 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005674 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005675 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5676 FORCE_INT_ON;
5677 close(pip[0]);
5678 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005679 /*close(1);*/
5680 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005681 close(pip[1]);
5682 }
5683 eflag = 0;
5684 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5685 /* NOTREACHED */
5686 }
5687 close(pip[1]);
5688 result->fd = pip[0];
5689 result->jp = jp;
5690 }
5691 herefd = saveherefd;
5692 out:
5693 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5694 result->fd, result->buf, result->nleft, result->jp));
5695}
5696
5697/*
5698 * Expand stuff in backwards quotes.
5699 */
5700static void
5701expbackq(union node *cmd, int quoted, int quotes)
5702{
5703 struct backcmd in;
5704 int i;
5705 char buf[128];
5706 char *p;
5707 char *dest;
5708 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005709 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005710 struct stackmark smark;
5711
5712 INT_OFF;
5713 setstackmark(&smark);
5714 dest = expdest;
5715 startloc = dest - (char *)stackblock();
5716 grabstackstr(dest);
5717 evalbackcmd(cmd, &in);
5718 popstackmark(&smark);
5719
5720 p = in.buf;
5721 i = in.nleft;
5722 if (i == 0)
5723 goto read;
5724 for (;;) {
5725 memtodest(p, i, syntax, quotes);
5726 read:
5727 if (in.fd < 0)
5728 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005729 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005730 TRACE(("expbackq: read returns %d\n", i));
5731 if (i <= 0)
5732 break;
5733 p = buf;
5734 }
5735
Denis Vlasenko60818682007-09-28 22:07:23 +00005736 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005737 if (in.fd >= 0) {
5738 close(in.fd);
5739 back_exitstatus = waitforjob(in.jp);
5740 }
5741 INT_ON;
5742
5743 /* Eat all trailing newlines */
5744 dest = expdest;
5745 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5746 STUNPUTC(dest);
5747 expdest = dest;
5748
5749 if (quoted == 0)
5750 recordregion(startloc, dest - (char *)stackblock(), 0);
5751 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5752 (dest - (char *)stackblock()) - startloc,
5753 (dest - (char *)stackblock()) - startloc,
5754 stackblock() + startloc));
5755}
5756
Mike Frysinger98c52642009-04-02 10:02:37 +00005757#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005758/*
5759 * Expand arithmetic expression. Backup to start of expression,
5760 * evaluate, place result in (backed up) result, adjust string position.
5761 */
5762static void
5763expari(int quotes)
5764{
5765 char *p, *start;
5766 int begoff;
5767 int flag;
5768 int len;
5769
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005770 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005771
5772 /*
5773 * This routine is slightly over-complicated for
5774 * efficiency. Next we scan backwards looking for the
5775 * start of arithmetic.
5776 */
5777 start = stackblock();
5778 p = expdest - 1;
5779 *p = '\0';
5780 p--;
5781 do {
5782 int esc;
5783
Denys Vlasenkocd716832009-11-28 22:14:02 +01005784 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005785 p--;
5786#if DEBUG
5787 if (p < start) {
5788 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5789 }
5790#endif
5791 }
5792
5793 esc = esclen(start, p);
5794 if (!(esc % 2)) {
5795 break;
5796 }
5797
5798 p -= esc + 1;
5799 } while (1);
5800
5801 begoff = p - start;
5802
5803 removerecordregions(begoff);
5804
5805 flag = p[1];
5806
5807 expdest = p;
5808
5809 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005810 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005811
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005812 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005813
5814 if (flag != '"')
5815 recordregion(begoff, begoff + len, 0);
5816}
5817#endif
5818
5819/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005820static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005821
5822/*
5823 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5824 * characters to allow for further processing. Otherwise treat
5825 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005826 *
5827 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5828 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5829 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830 */
5831static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005832argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005833{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005834 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005835 '=',
5836 ':',
5837 CTLQUOTEMARK,
5838 CTLENDVAR,
5839 CTLESC,
5840 CTLVAR,
5841 CTLBACKQ,
5842 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005843#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005844 CTLENDARI,
5845#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005846 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847 };
5848 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005849 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5850 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005851 int inquotes;
5852 size_t length;
5853 int startloc;
5854
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005855 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005856 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005857 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858 reject++;
5859 }
5860 inquotes = 0;
5861 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005862 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 char *q;
5864
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005865 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 tilde:
5867 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 q++;
5870 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005871 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 }
5873 start:
5874 startloc = expdest - (char *)stackblock();
5875 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005876 unsigned char c;
5877
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005879 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (c) {
5881 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005882#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005883 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005884#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 ) {
5886 /* c == '=' || c == ':' || c == CTLENDARI */
5887 length++;
5888 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005889 }
5890 if (length > 0) {
5891 int newloc;
5892 expdest = stack_nputstr(p, length, expdest);
5893 newloc = expdest - (char *)stackblock();
5894 if (breakall && !inquotes && newloc > startloc) {
5895 recordregion(startloc, newloc, 0);
5896 }
5897 startloc = newloc;
5898 }
5899 p += length + 1;
5900 length = 0;
5901
5902 switch (c) {
5903 case '\0':
5904 goto breakloop;
5905 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005906 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005907 p--;
5908 continue;
5909 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005910 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005911 reject++;
5912 /* fall through */
5913 case ':':
5914 /*
5915 * sort of a hack - expand tildes in variable
5916 * assignments (after the first '=' and after ':'s).
5917 */
5918 if (*--p == '~') {
5919 goto tilde;
5920 }
5921 continue;
5922 }
5923
5924 switch (c) {
5925 case CTLENDVAR: /* ??? */
5926 goto breakloop;
5927 case CTLQUOTEMARK:
5928 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005929 if (!inquotes
5930 && memcmp(p, dolatstr, 4) == 0
5931 && ( p[4] == CTLQUOTEMARK
5932 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5933 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005934 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005935 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005936 goto start;
5937 }
5938 inquotes = !inquotes;
5939 addquote:
5940 if (quotes) {
5941 p--;
5942 length++;
5943 startloc++;
5944 }
5945 break;
5946 case CTLESC:
5947 startloc++;
5948 length++;
5949 goto addquote;
5950 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005951 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005952 goto start;
5953 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005955 case CTLBACKQ|CTLQUOTE:
5956 expbackq(argbackq->n, c, quotes);
5957 argbackq = argbackq->next;
5958 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005959#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005960 case CTLENDARI:
5961 p--;
5962 expari(quotes);
5963 goto start;
5964#endif
5965 }
5966 }
5967 breakloop:
5968 ;
5969}
5970
5971static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005972scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 int zero)
5974{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005975// This commented out code was added by James Simmons <jsimmons@infradead.org>
5976// as part of a larger change when he added support for ${var/a/b}.
5977// However, it broke # and % operators:
5978//
5979//var=ababcdcd
5980// ok bad
5981//echo ${var#ab} abcdcd abcdcd
5982//echo ${var##ab} abcdcd abcdcd
5983//echo ${var#a*b} abcdcd ababcdcd (!)
5984//echo ${var##a*b} cdcd cdcd
5985//echo ${var#?} babcdcd ababcdcd (!)
5986//echo ${var##?} babcdcd babcdcd
5987//echo ${var#*} ababcdcd babcdcd (!)
5988//echo ${var##*}
5989//echo ${var%cd} ababcd ababcd
5990//echo ${var%%cd} ababcd abab (!)
5991//echo ${var%c*d} ababcd ababcd
5992//echo ${var%%c*d} abab ababcdcd (!)
5993//echo ${var%?} ababcdc ababcdc
5994//echo ${var%%?} ababcdc ababcdcd (!)
5995//echo ${var%*} ababcdcd ababcdcd
5996//echo ${var%%*}
5997//
5998// Commenting it back out helped. Remove it completely if it really
5999// is not needed.
6000
6001 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006002 char c;
6003
6004 loc = startp;
6005 loc2 = rmesc;
6006 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006007 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006008 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006009
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006010 c = *loc2;
6011 if (zero) {
6012 *loc2 = '\0';
6013 s = rmesc;
6014 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006015 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006016
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006017// // chop off end if its '*'
6018// full = strrchr(str, '*');
6019// if (full && full != str)
6020// match--;
6021//
6022// // If str starts with '*' replace with s.
6023// if ((*str == '*') && strlen(s) >= match) {
6024// full = xstrdup(s);
6025// strncpy(full+strlen(s)-match+1, str+1, match-1);
6026// } else
6027// full = xstrndup(str, match);
6028// match = strncmp(s, full, strlen(full));
6029// free(full);
6030//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006031 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006032 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006034 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006035 loc++;
6036 loc++;
6037 loc2++;
6038 } while (c);
6039 return 0;
6040}
6041
6042static char *
6043scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6044 int zero)
6045{
6046 int esc = 0;
6047 char *loc;
6048 char *loc2;
6049
6050 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6051 int match;
6052 char c = *loc2;
6053 const char *s = loc2;
6054 if (zero) {
6055 *loc2 = '\0';
6056 s = rmesc;
6057 }
6058 match = pmatch(str, s);
6059 *loc2 = c;
6060 if (match)
6061 return loc;
6062 loc--;
6063 if (quotes) {
6064 if (--esc < 0) {
6065 esc = esclen(startp, loc);
6066 }
6067 if (esc % 2) {
6068 esc--;
6069 loc--;
6070 }
6071 }
6072 }
6073 return 0;
6074}
6075
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006076static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006077static void
6078varunset(const char *end, const char *var, const char *umsg, int varflags)
6079{
6080 const char *msg;
6081 const char *tail;
6082
6083 tail = nullstr;
6084 msg = "parameter not set";
6085 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006086 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006087 if (varflags & VSNUL)
6088 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006089 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006090 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006091 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006092 }
6093 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6094}
6095
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006096#if ENABLE_ASH_BASH_COMPAT
6097static char *
6098parse_sub_pattern(char *arg, int inquotes)
6099{
6100 char *idx, *repl = NULL;
6101 unsigned char c;
6102
Denis Vlasenko2659c632008-06-14 06:04:59 +00006103 idx = arg;
6104 while (1) {
6105 c = *arg;
6106 if (!c)
6107 break;
6108 if (c == '/') {
6109 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006110 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006111 repl = idx + 1;
6112 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006113 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006114 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006115 *idx++ = c;
6116 if (!inquotes && c == '\\' && arg[1] == '\\')
6117 arg++; /* skip both \\, not just first one */
6118 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006119 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006120 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006121
6122 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006123}
6124#endif /* ENABLE_ASH_BASH_COMPAT */
6125
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006126static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006127subevalvar(char *p, char *str, int strloc, int subtype,
6128 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006129{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006130 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006131 char *startp;
6132 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006133 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006134 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6135 IF_ASH_BASH_COMPAT(char null = '\0';)
6136 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 int saveherefd = herefd;
6138 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006139 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006140 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006141
6142 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006143 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6144 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145 STPUTC('\0', expdest);
6146 herefd = saveherefd;
6147 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006148 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149
6150 switch (subtype) {
6151 case VSASSIGN:
6152 setvar(str, startp, 0);
6153 amount = startp - expdest;
6154 STADJUST(amount, expdest);
6155 return startp;
6156
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157#if ENABLE_ASH_BASH_COMPAT
6158 case VSSUBSTR:
6159 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006160 /* Read POS in ${var:POS:LEN} */
6161 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006162 len = str - startp - 1;
6163
6164 /* *loc != '\0', guaranteed by parser */
6165 if (quotes) {
6166 char *ptr;
6167
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006168 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006169 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006170 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006171 len--;
6172 ptr++;
6173 }
6174 }
6175 }
6176 orig_len = len;
6177
6178 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006179 /* ${var::LEN} */
6180 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006181 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006182 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006183 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006184 while (*loc && *loc != ':') {
6185 /* TODO?
6186 * bash complains on: var=qwe; echo ${var:1a:123}
6187 if (!isdigit(*loc))
6188 ash_msg_and_raise_error(msg_illnum, str);
6189 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006190 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006191 }
6192 if (*loc++ == ':') {
6193 len = number(loc);
6194 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006195 }
6196 if (pos >= orig_len) {
6197 pos = 0;
6198 len = 0;
6199 }
6200 if (len > (orig_len - pos))
6201 len = orig_len - pos;
6202
6203 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006204 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006205 str++;
6206 }
6207 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006208 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006209 *loc++ = *str++;
6210 *loc++ = *str++;
6211 }
6212 *loc = '\0';
6213 amount = loc - expdest;
6214 STADJUST(amount, expdest);
6215 return loc;
6216#endif
6217
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006218 case VSQUESTION:
6219 varunset(p, str, startp, varflags);
6220 /* NOTREACHED */
6221 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006222 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006223
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006224 /* We'll comeback here if we grow the stack while handling
6225 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6226 * stack will need rebasing, and we'll need to remove our work
6227 * areas each time
6228 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006229 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006230
6231 amount = expdest - ((char *)stackblock() + resetloc);
6232 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006233 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006234
6235 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006236 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006237 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006238 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006239 if (rmesc != startp) {
6240 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006241 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006242 }
6243 }
6244 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006245 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006246 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006247 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006248
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006249#if ENABLE_ASH_BASH_COMPAT
6250 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6251 char *idx, *end, *restart_detect;
6252
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006253 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006254 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6255 if (!repl)
6256 repl = &null;
6257 }
6258
6259 /* If there's no pattern to match, return the expansion unmolested */
6260 if (*str == '\0')
6261 return 0;
6262
6263 len = 0;
6264 idx = startp;
6265 end = str - 1;
6266 while (idx < end) {
6267 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6268 if (!loc) {
6269 /* No match, advance */
6270 restart_detect = stackblock();
6271 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006272 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006273 idx++;
6274 len++;
6275 STPUTC(*idx, expdest);
6276 }
6277 if (stackblock() != restart_detect)
6278 goto restart;
6279 idx++;
6280 len++;
6281 rmesc++;
6282 continue;
6283 }
6284
6285 if (subtype == VSREPLACEALL) {
6286 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006287 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006288 idx++;
6289 idx++;
6290 rmesc++;
6291 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006292 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006293 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006294 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006295
6296 for (loc = repl; *loc; loc++) {
6297 restart_detect = stackblock();
6298 STPUTC(*loc, expdest);
6299 if (stackblock() != restart_detect)
6300 goto restart;
6301 len++;
6302 }
6303
6304 if (subtype == VSREPLACE) {
6305 while (*idx) {
6306 restart_detect = stackblock();
6307 STPUTC(*idx, expdest);
6308 if (stackblock() != restart_detect)
6309 goto restart;
6310 len++;
6311 idx++;
6312 }
6313 break;
6314 }
6315 }
6316
6317 /* We've put the replaced text into a buffer at workloc, now
6318 * move it to the right place and adjust the stack.
6319 */
6320 startp = stackblock() + startloc;
6321 STPUTC('\0', expdest);
6322 memmove(startp, stackblock() + workloc, len);
6323 startp[len++] = '\0';
6324 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6325 STADJUST(-amount, expdest);
6326 return startp;
6327 }
6328#endif /* ENABLE_ASH_BASH_COMPAT */
6329
6330 subtype -= VSTRIMRIGHT;
6331#if DEBUG
6332 if (subtype < 0 || subtype > 7)
6333 abort();
6334#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006335 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6336 zero = subtype >> 1;
6337 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6338 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6339
6340 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6341 if (loc) {
6342 if (zero) {
6343 memmove(startp, loc, str - loc);
6344 loc = startp + (str - loc) - 1;
6345 }
6346 *loc = '\0';
6347 amount = loc - expdest;
6348 STADJUST(amount, expdest);
6349 }
6350 return loc;
6351}
6352
6353/*
6354 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006355 * name parameter (examples):
6356 * ash -c 'echo $1' name:'1='
6357 * ash -c 'echo $qwe' name:'qwe='
6358 * ash -c 'echo $$' name:'$='
6359 * ash -c 'echo ${$}' name:'$='
6360 * ash -c 'echo ${$##q}' name:'$=q'
6361 * ash -c 'echo ${#$}' name:'$='
6362 * note: examples with bad shell syntax:
6363 * ash -c 'echo ${#$1}' name:'$=1'
6364 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006365 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006366static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006367varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006368{
Mike Frysinger98c52642009-04-02 10:02:37 +00006369 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006370 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006371 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006372 int sepq = 0;
6373 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006374 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006375 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006376 int quoted = varflags & VSQUOTE;
6377 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006378
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006379 switch (*name) {
6380 case '$':
6381 num = rootpid;
6382 goto numvar;
6383 case '?':
6384 num = exitstatus;
6385 goto numvar;
6386 case '#':
6387 num = shellparam.nparam;
6388 goto numvar;
6389 case '!':
6390 num = backgndpid;
6391 if (num == 0)
6392 return -1;
6393 numvar:
6394 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006395 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006396 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006397 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006398 for (i = NOPTS - 1; i >= 0; i--) {
6399 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006400 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006401 len++;
6402 }
6403 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006404 check_1char_name:
6405#if 0
6406 /* handles cases similar to ${#$1} */
6407 if (name[2] != '\0')
6408 raise_error_syntax("bad substitution");
6409#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006410 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006411 case '@': {
6412 char **ap;
6413 int sep;
6414
6415 if (quoted && (flags & EXP_FULL)) {
6416 /* note: this is not meant as PEOF value */
6417 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006418 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006419 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006420 /* fall through */
6421 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006422 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006423 i = SIT(sep, syntax);
6424 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425 sepq = 1;
6426 param:
6427 ap = shellparam.p;
6428 if (!ap)
6429 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006430 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006431 size_t partlen;
6432
6433 partlen = strlen(p);
6434 len += partlen;
6435
6436 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6437 memtodest(p, partlen, syntax, quotes);
6438
6439 if (*ap && sep) {
6440 char *q;
6441
6442 len++;
6443 if (subtype == VSPLUS || subtype == VSLENGTH) {
6444 continue;
6445 }
6446 q = expdest;
6447 if (sepq)
6448 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006449 /* note: may put NUL despite sep != 0
6450 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006451 STPUTC(sep, q);
6452 expdest = q;
6453 }
6454 }
6455 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006456 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006457 case '0':
6458 case '1':
6459 case '2':
6460 case '3':
6461 case '4':
6462 case '5':
6463 case '6':
6464 case '7':
6465 case '8':
6466 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006467 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006468 if (num < 0 || num > shellparam.nparam)
6469 return -1;
6470 p = num ? shellparam.p[num - 1] : arg0;
6471 goto value;
6472 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006473 /* NB: name has form "VAR=..." */
6474
6475 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6476 * which should be considered before we check variables. */
6477 if (var_str_list) {
6478 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6479 p = NULL;
6480 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006481 char *str, *eq;
6482 str = var_str_list->text;
6483 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006484 if (!eq) /* stop at first non-assignment */
6485 break;
6486 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006487 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006488 && strncmp(str, name, name_len) == 0
6489 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006490 p = eq;
6491 /* goto value; - WRONG! */
6492 /* think "A=1 A=2 B=$A" */
6493 }
6494 var_str_list = var_str_list->next;
6495 } while (var_str_list);
6496 if (p)
6497 goto value;
6498 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006499 p = lookupvar(name);
6500 value:
6501 if (!p)
6502 return -1;
6503
6504 len = strlen(p);
6505 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6506 memtodest(p, len, syntax, quotes);
6507 return len;
6508 }
6509
6510 if (subtype == VSPLUS || subtype == VSLENGTH)
6511 STADJUST(-len, expdest);
6512 return len;
6513}
6514
6515/*
6516 * Expand a variable, and return a pointer to the next character in the
6517 * input string.
6518 */
6519static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006520evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006521{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006522 char varflags;
6523 char subtype;
6524 char quoted;
6525 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006526 char *var;
6527 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006528 int startloc;
6529 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006530
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006531 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006532 subtype = varflags & VSTYPE;
6533 quoted = varflags & VSQUOTE;
6534 var = p;
6535 easy = (!quoted || (*var == '@' && shellparam.nparam));
6536 startloc = expdest - (char *)stackblock();
6537 p = strchr(p, '=') + 1;
6538
6539 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006540 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006541 if (varflags & VSNUL)
6542 varlen--;
6543
6544 if (subtype == VSPLUS) {
6545 varlen = -1 - varlen;
6546 goto vsplus;
6547 }
6548
6549 if (subtype == VSMINUS) {
6550 vsplus:
6551 if (varlen < 0) {
6552 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006553 p, flags | EXP_TILDE |
6554 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006555 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006556 );
6557 goto end;
6558 }
6559 if (easy)
6560 goto record;
6561 goto end;
6562 }
6563
6564 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6565 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006566 if (subevalvar(p, var, /* strloc: */ 0,
6567 subtype, startloc, varflags,
6568 /* quotes: */ 0,
6569 var_str_list)
6570 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 varflags &= ~VSNUL;
6572 /*
6573 * Remove any recorded regions beyond
6574 * start of variable
6575 */
6576 removerecordregions(startloc);
6577 goto again;
6578 }
6579 goto end;
6580 }
6581 if (easy)
6582 goto record;
6583 goto end;
6584 }
6585
6586 if (varlen < 0 && uflag)
6587 varunset(p, var, 0, 0);
6588
6589 if (subtype == VSLENGTH) {
6590 cvtnum(varlen > 0 ? varlen : 0);
6591 goto record;
6592 }
6593
6594 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006595 if (easy)
6596 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006597 goto end;
6598 }
6599
6600#if DEBUG
6601 switch (subtype) {
6602 case VSTRIMLEFT:
6603 case VSTRIMLEFTMAX:
6604 case VSTRIMRIGHT:
6605 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006606#if ENABLE_ASH_BASH_COMPAT
6607 case VSSUBSTR:
6608 case VSREPLACE:
6609 case VSREPLACEALL:
6610#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006611 break;
6612 default:
6613 abort();
6614 }
6615#endif
6616
6617 if (varlen >= 0) {
6618 /*
6619 * Terminate the string and start recording the pattern
6620 * right after it
6621 */
6622 STPUTC('\0', expdest);
6623 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006624 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6625 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006626//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006627 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006628 var_str_list)
6629 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006630 int amount = expdest - (
6631 (char *)stackblock() + patloc - 1
6632 );
6633 STADJUST(-amount, expdest);
6634 }
6635 /* Remove any recorded regions beyond start of variable */
6636 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006637 record:
6638 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006639 }
6640
6641 end:
6642 if (subtype != VSNORMAL) { /* skip to end of alternative */
6643 int nesting = 1;
6644 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006645 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006646 if (c == CTLESC)
6647 p++;
6648 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6649 if (varlen >= 0)
6650 argbackq = argbackq->next;
6651 } else if (c == CTLVAR) {
6652 if ((*p++ & VSTYPE) != VSNORMAL)
6653 nesting++;
6654 } else if (c == CTLENDVAR) {
6655 if (--nesting == 0)
6656 break;
6657 }
6658 }
6659 }
6660 return p;
6661}
6662
6663/*
6664 * Break the argument string into pieces based upon IFS and add the
6665 * strings to the argument list. The regions of the string to be
6666 * searched for IFS characters have been stored by recordregion.
6667 */
6668static void
6669ifsbreakup(char *string, struct arglist *arglist)
6670{
6671 struct ifsregion *ifsp;
6672 struct strlist *sp;
6673 char *start;
6674 char *p;
6675 char *q;
6676 const char *ifs, *realifs;
6677 int ifsspc;
6678 int nulonly;
6679
6680 start = string;
6681 if (ifslastp != NULL) {
6682 ifsspc = 0;
6683 nulonly = 0;
6684 realifs = ifsset() ? ifsval() : defifs;
6685 ifsp = &ifsfirst;
6686 do {
6687 p = string + ifsp->begoff;
6688 nulonly = ifsp->nulonly;
6689 ifs = nulonly ? nullstr : realifs;
6690 ifsspc = 0;
6691 while (p < string + ifsp->endoff) {
6692 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006693 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006694 p++;
6695 if (!strchr(ifs, *p)) {
6696 p++;
6697 continue;
6698 }
6699 if (!nulonly)
6700 ifsspc = (strchr(defifs, *p) != NULL);
6701 /* Ignore IFS whitespace at start */
6702 if (q == start && ifsspc) {
6703 p++;
6704 start = p;
6705 continue;
6706 }
6707 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006708 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006709 sp->text = start;
6710 *arglist->lastp = sp;
6711 arglist->lastp = &sp->next;
6712 p++;
6713 if (!nulonly) {
6714 for (;;) {
6715 if (p >= string + ifsp->endoff) {
6716 break;
6717 }
6718 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006719 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006720 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006721 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006722 p = q;
6723 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006724 }
6725 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006726 if (ifsspc) {
6727 p++;
6728 ifsspc = 0;
6729 } else {
6730 p = q;
6731 break;
6732 }
6733 } else
6734 p++;
6735 }
6736 }
6737 start = p;
6738 } /* while */
6739 ifsp = ifsp->next;
6740 } while (ifsp != NULL);
6741 if (nulonly)
6742 goto add;
6743 }
6744
6745 if (!*start)
6746 return;
6747
6748 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006749 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006750 sp->text = start;
6751 *arglist->lastp = sp;
6752 arglist->lastp = &sp->next;
6753}
6754
6755static void
6756ifsfree(void)
6757{
6758 struct ifsregion *p;
6759
6760 INT_OFF;
6761 p = ifsfirst.next;
6762 do {
6763 struct ifsregion *ifsp;
6764 ifsp = p->next;
6765 free(p);
6766 p = ifsp;
6767 } while (p);
6768 ifslastp = NULL;
6769 ifsfirst.next = NULL;
6770 INT_ON;
6771}
6772
6773/*
6774 * Add a file name to the list.
6775 */
6776static void
6777addfname(const char *name)
6778{
6779 struct strlist *sp;
6780
Denis Vlasenko597906c2008-02-20 16:38:54 +00006781 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006782 sp->text = ststrdup(name);
6783 *exparg.lastp = sp;
6784 exparg.lastp = &sp->next;
6785}
6786
6787static char *expdir;
6788
6789/*
6790 * Do metacharacter (i.e. *, ?, [...]) expansion.
6791 */
6792static void
6793expmeta(char *enddir, char *name)
6794{
6795 char *p;
6796 const char *cp;
6797 char *start;
6798 char *endname;
6799 int metaflag;
6800 struct stat statb;
6801 DIR *dirp;
6802 struct dirent *dp;
6803 int atend;
6804 int matchdot;
6805
6806 metaflag = 0;
6807 start = name;
6808 for (p = name; *p; p++) {
6809 if (*p == '*' || *p == '?')
6810 metaflag = 1;
6811 else if (*p == '[') {
6812 char *q = p + 1;
6813 if (*q == '!')
6814 q++;
6815 for (;;) {
6816 if (*q == '\\')
6817 q++;
6818 if (*q == '/' || *q == '\0')
6819 break;
6820 if (*++q == ']') {
6821 metaflag = 1;
6822 break;
6823 }
6824 }
6825 } else if (*p == '\\')
6826 p++;
6827 else if (*p == '/') {
6828 if (metaflag)
6829 goto out;
6830 start = p + 1;
6831 }
6832 }
6833 out:
6834 if (metaflag == 0) { /* we've reached the end of the file name */
6835 if (enddir != expdir)
6836 metaflag++;
6837 p = name;
6838 do {
6839 if (*p == '\\')
6840 p++;
6841 *enddir++ = *p;
6842 } while (*p++);
6843 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6844 addfname(expdir);
6845 return;
6846 }
6847 endname = p;
6848 if (name < start) {
6849 p = name;
6850 do {
6851 if (*p == '\\')
6852 p++;
6853 *enddir++ = *p++;
6854 } while (p < start);
6855 }
6856 if (enddir == expdir) {
6857 cp = ".";
6858 } else if (enddir == expdir + 1 && *expdir == '/') {
6859 cp = "/";
6860 } else {
6861 cp = expdir;
6862 enddir[-1] = '\0';
6863 }
6864 dirp = opendir(cp);
6865 if (dirp == NULL)
6866 return;
6867 if (enddir != expdir)
6868 enddir[-1] = '/';
6869 if (*endname == 0) {
6870 atend = 1;
6871 } else {
6872 atend = 0;
6873 *endname++ = '\0';
6874 }
6875 matchdot = 0;
6876 p = start;
6877 if (*p == '\\')
6878 p++;
6879 if (*p == '.')
6880 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006881 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006882 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006883 continue;
6884 if (pmatch(start, dp->d_name)) {
6885 if (atend) {
6886 strcpy(enddir, dp->d_name);
6887 addfname(expdir);
6888 } else {
6889 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6890 continue;
6891 p[-1] = '/';
6892 expmeta(p, endname);
6893 }
6894 }
6895 }
6896 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006897 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006898 endname[-1] = '/';
6899}
6900
6901static struct strlist *
6902msort(struct strlist *list, int len)
6903{
6904 struct strlist *p, *q = NULL;
6905 struct strlist **lpp;
6906 int half;
6907 int n;
6908
6909 if (len <= 1)
6910 return list;
6911 half = len >> 1;
6912 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006913 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006914 q = p;
6915 p = p->next;
6916 }
6917 q->next = NULL; /* terminate first half of list */
6918 q = msort(list, half); /* sort first half of list */
6919 p = msort(p, len - half); /* sort second half */
6920 lpp = &list;
6921 for (;;) {
6922#if ENABLE_LOCALE_SUPPORT
6923 if (strcoll(p->text, q->text) < 0)
6924#else
6925 if (strcmp(p->text, q->text) < 0)
6926#endif
6927 {
6928 *lpp = p;
6929 lpp = &p->next;
6930 p = *lpp;
6931 if (p == NULL) {
6932 *lpp = q;
6933 break;
6934 }
6935 } else {
6936 *lpp = q;
6937 lpp = &q->next;
6938 q = *lpp;
6939 if (q == NULL) {
6940 *lpp = p;
6941 break;
6942 }
6943 }
6944 }
6945 return list;
6946}
6947
6948/*
6949 * Sort the results of file name expansion. It calculates the number of
6950 * strings to sort and then calls msort (short for merge sort) to do the
6951 * work.
6952 */
6953static struct strlist *
6954expsort(struct strlist *str)
6955{
6956 int len;
6957 struct strlist *sp;
6958
6959 len = 0;
6960 for (sp = str; sp; sp = sp->next)
6961 len++;
6962 return msort(str, len);
6963}
6964
6965static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006966expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006967{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006968 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006969 '*', '?', '[', 0
6970 };
6971 /* TODO - EXP_REDIR */
6972
6973 while (str) {
6974 struct strlist **savelastp;
6975 struct strlist *sp;
6976 char *p;
6977
6978 if (fflag)
6979 goto nometa;
6980 if (!strpbrk(str->text, metachars))
6981 goto nometa;
6982 savelastp = exparg.lastp;
6983
6984 INT_OFF;
6985 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6986 {
6987 int i = strlen(str->text);
6988 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6989 }
6990
6991 expmeta(expdir, p);
6992 free(expdir);
6993 if (p != str->text)
6994 free(p);
6995 INT_ON;
6996 if (exparg.lastp == savelastp) {
6997 /*
6998 * no matches
6999 */
7000 nometa:
7001 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007002 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007003 exparg.lastp = &str->next;
7004 } else {
7005 *exparg.lastp = NULL;
7006 *savelastp = sp = expsort(*savelastp);
7007 while (sp->next != NULL)
7008 sp = sp->next;
7009 exparg.lastp = &sp->next;
7010 }
7011 str = str->next;
7012 }
7013}
7014
7015/*
7016 * Perform variable substitution and command substitution on an argument,
7017 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7018 * perform splitting and file name expansion. When arglist is NULL, perform
7019 * here document expansion.
7020 */
7021static void
7022expandarg(union node *arg, struct arglist *arglist, int flag)
7023{
7024 struct strlist *sp;
7025 char *p;
7026
7027 argbackq = arg->narg.backquote;
7028 STARTSTACKSTR(expdest);
7029 ifsfirst.next = NULL;
7030 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007031 argstr(arg->narg.text, flag,
7032 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007033 p = _STPUTC('\0', expdest);
7034 expdest = p - 1;
7035 if (arglist == NULL) {
7036 return; /* here document expanded */
7037 }
7038 p = grabstackstr(p);
7039 exparg.lastp = &exparg.list;
7040 /*
7041 * TODO - EXP_REDIR
7042 */
7043 if (flag & EXP_FULL) {
7044 ifsbreakup(p, &exparg);
7045 *exparg.lastp = NULL;
7046 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007047 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007048 } else {
7049 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007050 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007051 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007052 sp->text = p;
7053 *exparg.lastp = sp;
7054 exparg.lastp = &sp->next;
7055 }
7056 if (ifsfirst.next)
7057 ifsfree();
7058 *exparg.lastp = NULL;
7059 if (exparg.list) {
7060 *arglist->lastp = exparg.list;
7061 arglist->lastp = exparg.lastp;
7062 }
7063}
7064
7065/*
7066 * Expand shell variables and backquotes inside a here document.
7067 */
7068static void
7069expandhere(union node *arg, int fd)
7070{
7071 herefd = fd;
7072 expandarg(arg, (struct arglist *)NULL, 0);
7073 full_write(fd, stackblock(), expdest - (char *)stackblock());
7074}
7075
7076/*
7077 * Returns true if the pattern matches the string.
7078 */
7079static int
7080patmatch(char *pattern, const char *string)
7081{
7082 return pmatch(preglob(pattern, 0, 0), string);
7083}
7084
7085/*
7086 * See if a pattern matches in a case statement.
7087 */
7088static int
7089casematch(union node *pattern, char *val)
7090{
7091 struct stackmark smark;
7092 int result;
7093
7094 setstackmark(&smark);
7095 argbackq = pattern->narg.backquote;
7096 STARTSTACKSTR(expdest);
7097 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007098 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7099 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007100 STACKSTRNUL(expdest);
7101 result = patmatch(stackblock(), val);
7102 popstackmark(&smark);
7103 return result;
7104}
7105
7106
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007107/* ============ find_command */
7108
7109struct builtincmd {
7110 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007111 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007112 /* unsigned flags; */
7113};
7114#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007115/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007116 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007117#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007118#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007119
7120struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007121 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007122 union param {
7123 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007124 /* index >= 0 for commands without path (slashes) */
7125 /* (TODO: what exactly does the value mean? PATH position?) */
7126 /* index == -1 for commands with slashes */
7127 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007128 const struct builtincmd *cmd;
7129 struct funcnode *func;
7130 } u;
7131};
7132/* values of cmdtype */
7133#define CMDUNKNOWN -1 /* no entry in table for command */
7134#define CMDNORMAL 0 /* command is an executable program */
7135#define CMDFUNCTION 1 /* command is a shell function */
7136#define CMDBUILTIN 2 /* command is a shell builtin */
7137
7138/* action to find_command() */
7139#define DO_ERR 0x01 /* prints errors */
7140#define DO_ABS 0x02 /* checks absolute paths */
7141#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7142#define DO_ALTPATH 0x08 /* using alternate path */
7143#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7144
7145static void find_command(char *, struct cmdentry *, int, const char *);
7146
7147
7148/* ============ Hashing commands */
7149
7150/*
7151 * When commands are first encountered, they are entered in a hash table.
7152 * This ensures that a full path search will not have to be done for them
7153 * on each invocation.
7154 *
7155 * We should investigate converting to a linear search, even though that
7156 * would make the command name "hash" a misnomer.
7157 */
7158
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007159struct tblentry {
7160 struct tblentry *next; /* next entry in hash chain */
7161 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007162 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007163 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007164 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007165};
7166
Denis Vlasenko01631112007-12-16 17:20:38 +00007167static struct tblentry **cmdtable;
7168#define INIT_G_cmdtable() do { \
7169 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7170} while (0)
7171
7172static int builtinloc = -1; /* index in path of %builtin, or -1 */
7173
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174
7175static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007176tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007177{
7178 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007179
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007180#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007181 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007182 if (APPLET_IS_NOEXEC(applet_no)) {
7183 while (*envp)
7184 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007185 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007186 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007187 /* re-exec ourselves with the new arguments */
7188 execve(bb_busybox_exec_path, argv, envp);
7189 /* If they called chroot or otherwise made the binary no longer
7190 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007191 }
7192#endif
7193
7194 repeat:
7195#ifdef SYSV
7196 do {
7197 execve(cmd, argv, envp);
7198 } while (errno == EINTR);
7199#else
7200 execve(cmd, argv, envp);
7201#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007202 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007203 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007204 return;
7205 }
7206 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007207 char **ap;
7208 char **new;
7209
7210 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007211 continue;
7212 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007213 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007214 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007215 ap += 2;
7216 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007217 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007218 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007219 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007220 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007221 goto repeat;
7222 }
7223}
7224
7225/*
7226 * Exec a program. Never returns. If you change this routine, you may
7227 * have to change the find_command routine as well.
7228 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007229static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007230static void
7231shellexec(char **argv, const char *path, int idx)
7232{
7233 char *cmdname;
7234 int e;
7235 char **envp;
7236 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007237#if ENABLE_FEATURE_SH_STANDALONE
7238 int applet_no = -1;
7239#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007240
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007241 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007242 envp = listvars(VEXPORT, VUNSET, 0);
7243 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007244#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007245 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246#endif
7247 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007248 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007249 e = errno;
7250 } else {
7251 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007252 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007253 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007254 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007255 if (errno != ENOENT && errno != ENOTDIR)
7256 e = errno;
7257 }
7258 stunalloc(cmdname);
7259 }
7260 }
7261
7262 /* Map to POSIX errors */
7263 switch (e) {
7264 case EACCES:
7265 exerrno = 126;
7266 break;
7267 case ENOENT:
7268 exerrno = 127;
7269 break;
7270 default:
7271 exerrno = 2;
7272 break;
7273 }
7274 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007275 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7276 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007277 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7278 /* NOTREACHED */
7279}
7280
7281static void
7282printentry(struct tblentry *cmdp)
7283{
7284 int idx;
7285 const char *path;
7286 char *name;
7287
7288 idx = cmdp->param.index;
7289 path = pathval();
7290 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007291 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007292 stunalloc(name);
7293 } while (--idx >= 0);
7294 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7295}
7296
7297/*
7298 * Clear out command entries. The argument specifies the first entry in
7299 * PATH which has changed.
7300 */
7301static void
7302clearcmdentry(int firstchange)
7303{
7304 struct tblentry **tblp;
7305 struct tblentry **pp;
7306 struct tblentry *cmdp;
7307
7308 INT_OFF;
7309 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7310 pp = tblp;
7311 while ((cmdp = *pp) != NULL) {
7312 if ((cmdp->cmdtype == CMDNORMAL &&
7313 cmdp->param.index >= firstchange)
7314 || (cmdp->cmdtype == CMDBUILTIN &&
7315 builtinloc >= firstchange)
7316 ) {
7317 *pp = cmdp->next;
7318 free(cmdp);
7319 } else {
7320 pp = &cmdp->next;
7321 }
7322 }
7323 }
7324 INT_ON;
7325}
7326
7327/*
7328 * Locate a command in the command hash table. If "add" is nonzero,
7329 * add the command to the table if it is not already present. The
7330 * variable "lastcmdentry" is set to point to the address of the link
7331 * pointing to the entry, so that delete_cmd_entry can delete the
7332 * entry.
7333 *
7334 * Interrupts must be off if called with add != 0.
7335 */
7336static struct tblentry **lastcmdentry;
7337
7338static struct tblentry *
7339cmdlookup(const char *name, int add)
7340{
7341 unsigned int hashval;
7342 const char *p;
7343 struct tblentry *cmdp;
7344 struct tblentry **pp;
7345
7346 p = name;
7347 hashval = (unsigned char)*p << 4;
7348 while (*p)
7349 hashval += (unsigned char)*p++;
7350 hashval &= 0x7FFF;
7351 pp = &cmdtable[hashval % CMDTABLESIZE];
7352 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7353 if (strcmp(cmdp->cmdname, name) == 0)
7354 break;
7355 pp = &cmdp->next;
7356 }
7357 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007358 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7359 + strlen(name)
7360 /* + 1 - already done because
7361 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007362 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007363 cmdp->cmdtype = CMDUNKNOWN;
7364 strcpy(cmdp->cmdname, name);
7365 }
7366 lastcmdentry = pp;
7367 return cmdp;
7368}
7369
7370/*
7371 * Delete the command entry returned on the last lookup.
7372 */
7373static void
7374delete_cmd_entry(void)
7375{
7376 struct tblentry *cmdp;
7377
7378 INT_OFF;
7379 cmdp = *lastcmdentry;
7380 *lastcmdentry = cmdp->next;
7381 if (cmdp->cmdtype == CMDFUNCTION)
7382 freefunc(cmdp->param.func);
7383 free(cmdp);
7384 INT_ON;
7385}
7386
7387/*
7388 * Add a new command entry, replacing any existing command entry for
7389 * the same name - except special builtins.
7390 */
7391static void
7392addcmdentry(char *name, struct cmdentry *entry)
7393{
7394 struct tblentry *cmdp;
7395
7396 cmdp = cmdlookup(name, 1);
7397 if (cmdp->cmdtype == CMDFUNCTION) {
7398 freefunc(cmdp->param.func);
7399 }
7400 cmdp->cmdtype = entry->cmdtype;
7401 cmdp->param = entry->u;
7402 cmdp->rehash = 0;
7403}
7404
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007405static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007406hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007407{
7408 struct tblentry **pp;
7409 struct tblentry *cmdp;
7410 int c;
7411 struct cmdentry entry;
7412 char *name;
7413
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007414 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007415 clearcmdentry(0);
7416 return 0;
7417 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007418
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007419 if (*argptr == NULL) {
7420 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7421 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7422 if (cmdp->cmdtype == CMDNORMAL)
7423 printentry(cmdp);
7424 }
7425 }
7426 return 0;
7427 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007428
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007429 c = 0;
7430 while ((name = *argptr) != NULL) {
7431 cmdp = cmdlookup(name, 0);
7432 if (cmdp != NULL
7433 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007434 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7435 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007436 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007437 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007438 find_command(name, &entry, DO_ERR, pathval());
7439 if (entry.cmdtype == CMDUNKNOWN)
7440 c = 1;
7441 argptr++;
7442 }
7443 return c;
7444}
7445
7446/*
7447 * Called when a cd is done. Marks all commands so the next time they
7448 * are executed they will be rehashed.
7449 */
7450static void
7451hashcd(void)
7452{
7453 struct tblentry **pp;
7454 struct tblentry *cmdp;
7455
7456 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7457 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007458 if (cmdp->cmdtype == CMDNORMAL
7459 || (cmdp->cmdtype == CMDBUILTIN
7460 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7461 && builtinloc > 0)
7462 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007463 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007464 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007465 }
7466 }
7467}
7468
7469/*
7470 * Fix command hash table when PATH changed.
7471 * Called before PATH is changed. The argument is the new value of PATH;
7472 * pathval() still returns the old value at this point.
7473 * Called with interrupts off.
7474 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007475static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007476changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007477{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007478 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007479 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007480 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007481 int idx_bltin;
7482
7483 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007484 firstchange = 9999; /* assume no change */
7485 idx = 0;
7486 idx_bltin = -1;
7487 for (;;) {
7488 if (*old != *new) {
7489 firstchange = idx;
7490 if ((*old == '\0' && *new == ':')
7491 || (*old == ':' && *new == '\0'))
7492 firstchange++;
7493 old = new; /* ignore subsequent differences */
7494 }
7495 if (*new == '\0')
7496 break;
7497 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7498 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007499 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007500 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007501 new++, old++;
7502 }
7503 if (builtinloc < 0 && idx_bltin >= 0)
7504 builtinloc = idx_bltin; /* zap builtins */
7505 if (builtinloc >= 0 && idx_bltin < 0)
7506 firstchange = 0;
7507 clearcmdentry(firstchange);
7508 builtinloc = idx_bltin;
7509}
7510
7511#define TEOF 0
7512#define TNL 1
7513#define TREDIR 2
7514#define TWORD 3
7515#define TSEMI 4
7516#define TBACKGND 5
7517#define TAND 6
7518#define TOR 7
7519#define TPIPE 8
7520#define TLP 9
7521#define TRP 10
7522#define TENDCASE 11
7523#define TENDBQUOTE 12
7524#define TNOT 13
7525#define TCASE 14
7526#define TDO 15
7527#define TDONE 16
7528#define TELIF 17
7529#define TELSE 18
7530#define TESAC 19
7531#define TFI 20
7532#define TFOR 21
7533#define TIF 22
7534#define TIN 23
7535#define TTHEN 24
7536#define TUNTIL 25
7537#define TWHILE 26
7538#define TBEGIN 27
7539#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007540typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007541
7542/* first char is indicating which tokens mark the end of a list */
7543static const char *const tokname_array[] = {
7544 "\1end of file",
7545 "\0newline",
7546 "\0redirection",
7547 "\0word",
7548 "\0;",
7549 "\0&",
7550 "\0&&",
7551 "\0||",
7552 "\0|",
7553 "\0(",
7554 "\1)",
7555 "\1;;",
7556 "\1`",
7557#define KWDOFFSET 13
7558 /* the following are keywords */
7559 "\0!",
7560 "\0case",
7561 "\1do",
7562 "\1done",
7563 "\1elif",
7564 "\1else",
7565 "\1esac",
7566 "\1fi",
7567 "\0for",
7568 "\0if",
7569 "\0in",
7570 "\1then",
7571 "\0until",
7572 "\0while",
7573 "\0{",
7574 "\1}",
7575};
7576
7577static const char *
7578tokname(int tok)
7579{
7580 static char buf[16];
7581
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007582//try this:
7583//if (tok < TSEMI) return tokname_array[tok] + 1;
7584//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7585//return buf;
7586
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007587 if (tok >= TSEMI)
7588 buf[0] = '"';
7589 sprintf(buf + (tok >= TSEMI), "%s%c",
7590 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7591 return buf;
7592}
7593
7594/* Wrapper around strcmp for qsort/bsearch/... */
7595static int
7596pstrcmp(const void *a, const void *b)
7597{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007598 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007599}
7600
7601static const char *const *
7602findkwd(const char *s)
7603{
7604 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007605 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7606 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007607}
7608
7609/*
7610 * Locate and print what a word is...
7611 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007612static int
7613describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007614{
7615 struct cmdentry entry;
7616 struct tblentry *cmdp;
7617#if ENABLE_ASH_ALIAS
7618 const struct alias *ap;
7619#endif
7620 const char *path = pathval();
7621
7622 if (describe_command_verbose) {
7623 out1str(command);
7624 }
7625
7626 /* First look at the keywords */
7627 if (findkwd(command)) {
7628 out1str(describe_command_verbose ? " is a shell keyword" : command);
7629 goto out;
7630 }
7631
7632#if ENABLE_ASH_ALIAS
7633 /* Then look at the aliases */
7634 ap = lookupalias(command, 0);
7635 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007636 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007637 out1str("alias ");
7638 printalias(ap);
7639 return 0;
7640 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007641 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007642 goto out;
7643 }
7644#endif
7645 /* Then check if it is a tracked alias */
7646 cmdp = cmdlookup(command, 0);
7647 if (cmdp != NULL) {
7648 entry.cmdtype = cmdp->cmdtype;
7649 entry.u = cmdp->param;
7650 } else {
7651 /* Finally use brute force */
7652 find_command(command, &entry, DO_ABS, path);
7653 }
7654
7655 switch (entry.cmdtype) {
7656 case CMDNORMAL: {
7657 int j = entry.u.index;
7658 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007659 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007660 p = command;
7661 } else {
7662 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007663 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007664 stunalloc(p);
7665 } while (--j >= 0);
7666 }
7667 if (describe_command_verbose) {
7668 out1fmt(" is%s %s",
7669 (cmdp ? " a tracked alias for" : nullstr), p
7670 );
7671 } else {
7672 out1str(p);
7673 }
7674 break;
7675 }
7676
7677 case CMDFUNCTION:
7678 if (describe_command_verbose) {
7679 out1str(" is a shell function");
7680 } else {
7681 out1str(command);
7682 }
7683 break;
7684
7685 case CMDBUILTIN:
7686 if (describe_command_verbose) {
7687 out1fmt(" is a %sshell builtin",
7688 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7689 "special " : nullstr
7690 );
7691 } else {
7692 out1str(command);
7693 }
7694 break;
7695
7696 default:
7697 if (describe_command_verbose) {
7698 out1str(": not found\n");
7699 }
7700 return 127;
7701 }
7702 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007703 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007704 return 0;
7705}
7706
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007707static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007708typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007709{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007710 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007711 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007712 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007713
Denis Vlasenko46846e22007-05-20 13:08:31 +00007714 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007715 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007716 i++;
7717 verbose = 0;
7718 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007719 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007720 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007721 }
7722 return err;
7723}
7724
7725#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007726static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007727commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007728{
7729 int c;
7730 enum {
7731 VERIFY_BRIEF = 1,
7732 VERIFY_VERBOSE = 2,
7733 } verify = 0;
7734
7735 while ((c = nextopt("pvV")) != '\0')
7736 if (c == 'V')
7737 verify |= VERIFY_VERBOSE;
7738 else if (c == 'v')
7739 verify |= VERIFY_BRIEF;
7740#if DEBUG
7741 else if (c != 'p')
7742 abort();
7743#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007744 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7745 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007746 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007747 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007748
7749 return 0;
7750}
7751#endif
7752
7753
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007754/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007755
Denis Vlasenko340299a2008-11-21 10:36:36 +00007756static int funcblocksize; /* size of structures in function */
7757static int funcstringsize; /* size of strings in node */
7758static void *funcblock; /* block to allocate function from */
7759static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007760
Eric Andersencb57d552001-06-28 07:25:16 +00007761/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007762#define EV_EXIT 01 /* exit after evaluating tree */
7763#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007764#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007765
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007766static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007767 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7768 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7769 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7770 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7771 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7772 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7773 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7774 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7775 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7776 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7777 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7778 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7779 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7780 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7781 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7782 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7783 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007784#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007785 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007786#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007787 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7788 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7789 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7790 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7791 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7792 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7793 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7794 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7795 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007796};
7797
7798static void calcsize(union node *n);
7799
7800static void
7801sizenodelist(struct nodelist *lp)
7802{
7803 while (lp) {
7804 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7805 calcsize(lp->n);
7806 lp = lp->next;
7807 }
7808}
7809
7810static void
7811calcsize(union node *n)
7812{
7813 if (n == NULL)
7814 return;
7815 funcblocksize += nodesize[n->type];
7816 switch (n->type) {
7817 case NCMD:
7818 calcsize(n->ncmd.redirect);
7819 calcsize(n->ncmd.args);
7820 calcsize(n->ncmd.assign);
7821 break;
7822 case NPIPE:
7823 sizenodelist(n->npipe.cmdlist);
7824 break;
7825 case NREDIR:
7826 case NBACKGND:
7827 case NSUBSHELL:
7828 calcsize(n->nredir.redirect);
7829 calcsize(n->nredir.n);
7830 break;
7831 case NAND:
7832 case NOR:
7833 case NSEMI:
7834 case NWHILE:
7835 case NUNTIL:
7836 calcsize(n->nbinary.ch2);
7837 calcsize(n->nbinary.ch1);
7838 break;
7839 case NIF:
7840 calcsize(n->nif.elsepart);
7841 calcsize(n->nif.ifpart);
7842 calcsize(n->nif.test);
7843 break;
7844 case NFOR:
7845 funcstringsize += strlen(n->nfor.var) + 1;
7846 calcsize(n->nfor.body);
7847 calcsize(n->nfor.args);
7848 break;
7849 case NCASE:
7850 calcsize(n->ncase.cases);
7851 calcsize(n->ncase.expr);
7852 break;
7853 case NCLIST:
7854 calcsize(n->nclist.body);
7855 calcsize(n->nclist.pattern);
7856 calcsize(n->nclist.next);
7857 break;
7858 case NDEFUN:
7859 case NARG:
7860 sizenodelist(n->narg.backquote);
7861 funcstringsize += strlen(n->narg.text) + 1;
7862 calcsize(n->narg.next);
7863 break;
7864 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007865#if ENABLE_ASH_BASH_COMPAT
7866 case NTO2:
7867#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007868 case NCLOBBER:
7869 case NFROM:
7870 case NFROMTO:
7871 case NAPPEND:
7872 calcsize(n->nfile.fname);
7873 calcsize(n->nfile.next);
7874 break;
7875 case NTOFD:
7876 case NFROMFD:
7877 calcsize(n->ndup.vname);
7878 calcsize(n->ndup.next);
7879 break;
7880 case NHERE:
7881 case NXHERE:
7882 calcsize(n->nhere.doc);
7883 calcsize(n->nhere.next);
7884 break;
7885 case NNOT:
7886 calcsize(n->nnot.com);
7887 break;
7888 };
7889}
7890
7891static char *
7892nodeckstrdup(char *s)
7893{
7894 char *rtn = funcstring;
7895
7896 strcpy(funcstring, s);
7897 funcstring += strlen(s) + 1;
7898 return rtn;
7899}
7900
7901static union node *copynode(union node *);
7902
7903static struct nodelist *
7904copynodelist(struct nodelist *lp)
7905{
7906 struct nodelist *start;
7907 struct nodelist **lpp;
7908
7909 lpp = &start;
7910 while (lp) {
7911 *lpp = funcblock;
7912 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7913 (*lpp)->n = copynode(lp->n);
7914 lp = lp->next;
7915 lpp = &(*lpp)->next;
7916 }
7917 *lpp = NULL;
7918 return start;
7919}
7920
7921static union node *
7922copynode(union node *n)
7923{
7924 union node *new;
7925
7926 if (n == NULL)
7927 return NULL;
7928 new = funcblock;
7929 funcblock = (char *) funcblock + nodesize[n->type];
7930
7931 switch (n->type) {
7932 case NCMD:
7933 new->ncmd.redirect = copynode(n->ncmd.redirect);
7934 new->ncmd.args = copynode(n->ncmd.args);
7935 new->ncmd.assign = copynode(n->ncmd.assign);
7936 break;
7937 case NPIPE:
7938 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007939 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007940 break;
7941 case NREDIR:
7942 case NBACKGND:
7943 case NSUBSHELL:
7944 new->nredir.redirect = copynode(n->nredir.redirect);
7945 new->nredir.n = copynode(n->nredir.n);
7946 break;
7947 case NAND:
7948 case NOR:
7949 case NSEMI:
7950 case NWHILE:
7951 case NUNTIL:
7952 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7953 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7954 break;
7955 case NIF:
7956 new->nif.elsepart = copynode(n->nif.elsepart);
7957 new->nif.ifpart = copynode(n->nif.ifpart);
7958 new->nif.test = copynode(n->nif.test);
7959 break;
7960 case NFOR:
7961 new->nfor.var = nodeckstrdup(n->nfor.var);
7962 new->nfor.body = copynode(n->nfor.body);
7963 new->nfor.args = copynode(n->nfor.args);
7964 break;
7965 case NCASE:
7966 new->ncase.cases = copynode(n->ncase.cases);
7967 new->ncase.expr = copynode(n->ncase.expr);
7968 break;
7969 case NCLIST:
7970 new->nclist.body = copynode(n->nclist.body);
7971 new->nclist.pattern = copynode(n->nclist.pattern);
7972 new->nclist.next = copynode(n->nclist.next);
7973 break;
7974 case NDEFUN:
7975 case NARG:
7976 new->narg.backquote = copynodelist(n->narg.backquote);
7977 new->narg.text = nodeckstrdup(n->narg.text);
7978 new->narg.next = copynode(n->narg.next);
7979 break;
7980 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007981#if ENABLE_ASH_BASH_COMPAT
7982 case NTO2:
7983#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007984 case NCLOBBER:
7985 case NFROM:
7986 case NFROMTO:
7987 case NAPPEND:
7988 new->nfile.fname = copynode(n->nfile.fname);
7989 new->nfile.fd = n->nfile.fd;
7990 new->nfile.next = copynode(n->nfile.next);
7991 break;
7992 case NTOFD:
7993 case NFROMFD:
7994 new->ndup.vname = copynode(n->ndup.vname);
7995 new->ndup.dupfd = n->ndup.dupfd;
7996 new->ndup.fd = n->ndup.fd;
7997 new->ndup.next = copynode(n->ndup.next);
7998 break;
7999 case NHERE:
8000 case NXHERE:
8001 new->nhere.doc = copynode(n->nhere.doc);
8002 new->nhere.fd = n->nhere.fd;
8003 new->nhere.next = copynode(n->nhere.next);
8004 break;
8005 case NNOT:
8006 new->nnot.com = copynode(n->nnot.com);
8007 break;
8008 };
8009 new->type = n->type;
8010 return new;
8011}
8012
8013/*
8014 * Make a copy of a parse tree.
8015 */
8016static struct funcnode *
8017copyfunc(union node *n)
8018{
8019 struct funcnode *f;
8020 size_t blocksize;
8021
8022 funcblocksize = offsetof(struct funcnode, n);
8023 funcstringsize = 0;
8024 calcsize(n);
8025 blocksize = funcblocksize;
8026 f = ckmalloc(blocksize + funcstringsize);
8027 funcblock = (char *) f + offsetof(struct funcnode, n);
8028 funcstring = (char *) f + blocksize;
8029 copynode(n);
8030 f->count = 0;
8031 return f;
8032}
8033
8034/*
8035 * Define a shell function.
8036 */
8037static void
8038defun(char *name, union node *func)
8039{
8040 struct cmdentry entry;
8041
8042 INT_OFF;
8043 entry.cmdtype = CMDFUNCTION;
8044 entry.u.func = copyfunc(func);
8045 addcmdentry(name, &entry);
8046 INT_ON;
8047}
8048
Denis Vlasenko4b875702009-03-19 13:30:04 +00008049/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008050#define SKIPBREAK (1 << 0)
8051#define SKIPCONT (1 << 1)
8052#define SKIPFUNC (1 << 2)
8053#define SKIPFILE (1 << 3)
8054#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008055static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008056static int skipcount; /* number of levels to skip */
8057static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008058static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008059
Denis Vlasenko4b875702009-03-19 13:30:04 +00008060/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008061static int evalstring(char *s, int mask);
8062
Denis Vlasenko4b875702009-03-19 13:30:04 +00008063/* Called to execute a trap.
8064 * Single callsite - at the end of evaltree().
8065 * If we return non-zero, exaltree raises EXEXIT exception.
8066 *
8067 * Perhaps we should avoid entering new trap handlers
8068 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008069 */
8070static int
8071dotrap(void)
8072{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008073 uint8_t *g;
8074 int sig;
8075 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008076
8077 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008078 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008079 xbarrier();
8080
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008081 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008082 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8083 int want_exexit;
8084 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008085
Denis Vlasenko4b875702009-03-19 13:30:04 +00008086 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008087 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008088 t = trap[sig];
8089 /* non-trapped SIGINT is handled separately by raise_interrupt,
8090 * don't upset it by resetting gotsig[SIGINT-1] */
8091 if (sig == SIGINT && !t)
8092 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008093
8094 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008095 *g = 0;
8096 if (!t)
8097 continue;
8098 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008099 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008100 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008101 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008102 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008103 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008104 }
8105
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008106 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008107 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008108}
8109
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008110/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008111static void evalloop(union node *, int);
8112static void evalfor(union node *, int);
8113static void evalcase(union node *, int);
8114static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008115static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008116static void evalpipe(union node *, int);
8117static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008118static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008119static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008120
Eric Andersen62483552001-07-10 06:09:16 +00008121/*
Eric Andersenc470f442003-07-28 09:56:35 +00008122 * Evaluate a parse tree. The value is left in the global variable
8123 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008124 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008125static void
Eric Andersenc470f442003-07-28 09:56:35 +00008126evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008127{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008128 struct jmploc *volatile savehandler = exception_handler;
8129 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008130 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008131 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008132 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008133 int int_level;
8134
8135 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136
Eric Andersenc470f442003-07-28 09:56:35 +00008137 if (n == NULL) {
8138 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008139 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008140 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008141 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008142
8143 exception_handler = &jmploc;
8144 {
8145 int err = setjmp(jmploc.loc);
8146 if (err) {
8147 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008148 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008149 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8150 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008151 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008152 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008153 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008154 TRACE(("exception %d in evaltree, propagating err=%d\n",
8155 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008156 exception_handler = savehandler;
8157 longjmp(exception_handler->loc, err);
8158 }
8159 }
8160
Eric Andersenc470f442003-07-28 09:56:35 +00008161 switch (n->type) {
8162 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008163#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008164 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008165 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008166 break;
8167#endif
8168 case NNOT:
8169 evaltree(n->nnot.com, EV_TESTED);
8170 status = !exitstatus;
8171 goto setstatus;
8172 case NREDIR:
8173 expredir(n->nredir.redirect);
8174 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8175 if (!status) {
8176 evaltree(n->nredir.n, flags & EV_TESTED);
8177 status = exitstatus;
8178 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008179 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008180 goto setstatus;
8181 case NCMD:
8182 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008183 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008184 if (eflag && !(flags & EV_TESTED))
8185 checkexit = ~0;
8186 goto calleval;
8187 case NFOR:
8188 evalfn = evalfor;
8189 goto calleval;
8190 case NWHILE:
8191 case NUNTIL:
8192 evalfn = evalloop;
8193 goto calleval;
8194 case NSUBSHELL:
8195 case NBACKGND:
8196 evalfn = evalsubshell;
8197 goto calleval;
8198 case NPIPE:
8199 evalfn = evalpipe;
8200 goto checkexit;
8201 case NCASE:
8202 evalfn = evalcase;
8203 goto calleval;
8204 case NAND:
8205 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008206 case NSEMI: {
8207
Eric Andersenc470f442003-07-28 09:56:35 +00008208#if NAND + 1 != NOR
8209#error NAND + 1 != NOR
8210#endif
8211#if NOR + 1 != NSEMI
8212#error NOR + 1 != NSEMI
8213#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008214 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008215 evaltree(
8216 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008217 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008218 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008219 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008220 break;
8221 if (!evalskip) {
8222 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008223 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008224 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008225 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008226 evalfn(n, flags);
8227 break;
8228 }
8229 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008230 }
Eric Andersenc470f442003-07-28 09:56:35 +00008231 case NIF:
8232 evaltree(n->nif.test, EV_TESTED);
8233 if (evalskip)
8234 break;
8235 if (exitstatus == 0) {
8236 n = n->nif.ifpart;
8237 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008238 }
8239 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008240 n = n->nif.elsepart;
8241 goto evaln;
8242 }
8243 goto success;
8244 case NDEFUN:
8245 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008246 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008247 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008248 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008249 exitstatus = status;
8250 break;
8251 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008252
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008253 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008254 exception_handler = savehandler;
8255 out1:
8256 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008257 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008258 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008259 goto exexit;
8260
8261 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008262 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008263 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008264 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008265
8266 RESTORE_INT(int_level);
8267 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008268}
8269
Eric Andersenc470f442003-07-28 09:56:35 +00008270#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8271static
8272#endif
8273void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8274
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008275static void
Eric Andersenc470f442003-07-28 09:56:35 +00008276evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008277{
8278 int status;
8279
8280 loopnest++;
8281 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008282 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008283 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008284 int i;
8285
Eric Andersencb57d552001-06-28 07:25:16 +00008286 evaltree(n->nbinary.ch1, EV_TESTED);
8287 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008288 skipping:
8289 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008290 evalskip = 0;
8291 continue;
8292 }
8293 if (evalskip == SKIPBREAK && --skipcount <= 0)
8294 evalskip = 0;
8295 break;
8296 }
Eric Andersenc470f442003-07-28 09:56:35 +00008297 i = exitstatus;
8298 if (n->type != NWHILE)
8299 i = !i;
8300 if (i != 0)
8301 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008302 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008303 status = exitstatus;
8304 if (evalskip)
8305 goto skipping;
8306 }
8307 loopnest--;
8308 exitstatus = status;
8309}
8310
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008311static void
Eric Andersenc470f442003-07-28 09:56:35 +00008312evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008313{
8314 struct arglist arglist;
8315 union node *argp;
8316 struct strlist *sp;
8317 struct stackmark smark;
8318
8319 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008320 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008321 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008322 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008323 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008324 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008325 if (evalskip)
8326 goto out;
8327 }
8328 *arglist.lastp = NULL;
8329
8330 exitstatus = 0;
8331 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008332 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008333 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008334 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008335 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008336 if (evalskip) {
8337 if (evalskip == SKIPCONT && --skipcount <= 0) {
8338 evalskip = 0;
8339 continue;
8340 }
8341 if (evalskip == SKIPBREAK && --skipcount <= 0)
8342 evalskip = 0;
8343 break;
8344 }
8345 }
8346 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008347 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008348 popstackmark(&smark);
8349}
8350
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008351static void
Eric Andersenc470f442003-07-28 09:56:35 +00008352evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008353{
8354 union node *cp;
8355 union node *patp;
8356 struct arglist arglist;
8357 struct stackmark smark;
8358
8359 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008360 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008361 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008362 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008363 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008364 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8365 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008366 if (casematch(patp, arglist.list->text)) {
8367 if (evalskip == 0) {
8368 evaltree(cp->nclist.body, flags);
8369 }
8370 goto out;
8371 }
8372 }
8373 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008374 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008375 popstackmark(&smark);
8376}
8377
Eric Andersenc470f442003-07-28 09:56:35 +00008378/*
8379 * Kick off a subshell to evaluate a tree.
8380 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008381static void
Eric Andersenc470f442003-07-28 09:56:35 +00008382evalsubshell(union node *n, int flags)
8383{
8384 struct job *jp;
8385 int backgnd = (n->type == NBACKGND);
8386 int status;
8387
8388 expredir(n->nredir.redirect);
8389 if (!backgnd && flags & EV_EXIT && !trap[0])
8390 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008391 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008392 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008393 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008394 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008395 flags |= EV_EXIT;
8396 if (backgnd)
8397 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008398 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008399 redirect(n->nredir.redirect, 0);
8400 evaltreenr(n->nredir.n, flags);
8401 /* never returns */
8402 }
8403 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008404 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008405 status = waitforjob(jp);
8406 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008407 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008408}
8409
Eric Andersenc470f442003-07-28 09:56:35 +00008410/*
8411 * Compute the names of the files in a redirection list.
8412 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008413static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008414static void
8415expredir(union node *n)
8416{
8417 union node *redir;
8418
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008419 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008420 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008421
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008422 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008423 fn.lastp = &fn.list;
8424 switch (redir->type) {
8425 case NFROMTO:
8426 case NFROM:
8427 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008428#if ENABLE_ASH_BASH_COMPAT
8429 case NTO2:
8430#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008431 case NCLOBBER:
8432 case NAPPEND:
8433 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008434#if ENABLE_ASH_BASH_COMPAT
8435 store_expfname:
8436#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008437 redir->nfile.expfname = fn.list->text;
8438 break;
8439 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008440 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008441 if (redir->ndup.vname) {
8442 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008443 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008444 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008445#if ENABLE_ASH_BASH_COMPAT
8446//FIXME: we used expandarg with different args!
8447 if (!isdigit_str9(fn.list->text)) {
8448 /* >&file, not >&fd */
8449 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8450 ash_msg_and_raise_error("redir error");
8451 redir->type = NTO2;
8452 goto store_expfname;
8453 }
8454#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008455 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008456 }
8457 break;
8458 }
8459 }
8460}
8461
Eric Andersencb57d552001-06-28 07:25:16 +00008462/*
Eric Andersencb57d552001-06-28 07:25:16 +00008463 * Evaluate a pipeline. All the processes in the pipeline are children
8464 * of the process creating the pipeline. (This differs from some versions
8465 * of the shell, which make the last process in a pipeline the parent
8466 * of all the rest.)
8467 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008468static void
Eric Andersenc470f442003-07-28 09:56:35 +00008469evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008470{
8471 struct job *jp;
8472 struct nodelist *lp;
8473 int pipelen;
8474 int prevfd;
8475 int pip[2];
8476
Eric Andersenc470f442003-07-28 09:56:35 +00008477 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008478 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008479 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008480 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008481 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008482 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008483 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008484 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008485 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008486 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008487 pip[1] = -1;
8488 if (lp->next) {
8489 if (pipe(pip) < 0) {
8490 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008491 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008492 }
8493 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008494 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008495 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008496 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008497 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008498 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008499 if (prevfd > 0) {
8500 dup2(prevfd, 0);
8501 close(prevfd);
8502 }
8503 if (pip[1] > 1) {
8504 dup2(pip[1], 1);
8505 close(pip[1]);
8506 }
Eric Andersenc470f442003-07-28 09:56:35 +00008507 evaltreenr(lp->n, flags);
8508 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008509 }
8510 if (prevfd >= 0)
8511 close(prevfd);
8512 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008513 /* Don't want to trigger debugging */
8514 if (pip[1] != -1)
8515 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008516 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008517 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008518 exitstatus = waitforjob(jp);
8519 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008520 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008521 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008522}
8523
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008524/*
8525 * Controls whether the shell is interactive or not.
8526 */
8527static void
8528setinteractive(int on)
8529{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008530 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008531
8532 if (++on == is_interactive)
8533 return;
8534 is_interactive = on;
8535 setsignal(SIGINT);
8536 setsignal(SIGQUIT);
8537 setsignal(SIGTERM);
8538#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8539 if (is_interactive > 1) {
8540 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008541 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008542
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008543 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008544 /* note: ash and hush share this string */
8545 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008546 "Enter 'help' for a list of built-in commands."
8547 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008548 bb_banner,
8549 "built-in shell (ash)"
8550 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008551 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008552 }
8553 }
8554#endif
8555}
8556
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008557static void
8558optschanged(void)
8559{
8560#if DEBUG
8561 opentrace();
8562#endif
8563 setinteractive(iflag);
8564 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008565#if ENABLE_FEATURE_EDITING_VI
8566 if (viflag)
8567 line_input_state->flags |= VI_MODE;
8568 else
8569 line_input_state->flags &= ~VI_MODE;
8570#else
8571 viflag = 0; /* forcibly keep the option off */
8572#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008573}
8574
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008575static struct localvar *localvars;
8576
8577/*
8578 * Called after a function returns.
8579 * Interrupts must be off.
8580 */
8581static void
8582poplocalvars(void)
8583{
8584 struct localvar *lvp;
8585 struct var *vp;
8586
8587 while ((lvp = localvars) != NULL) {
8588 localvars = lvp->next;
8589 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008590 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008591 if (vp == NULL) { /* $- saved */
8592 memcpy(optlist, lvp->text, sizeof(optlist));
8593 free((char*)lvp->text);
8594 optschanged();
8595 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8596 unsetvar(vp->text);
8597 } else {
8598 if (vp->func)
8599 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8600 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8601 free((char*)vp->text);
8602 vp->flags = lvp->flags;
8603 vp->text = lvp->text;
8604 }
8605 free(lvp);
8606 }
8607}
8608
8609static int
8610evalfun(struct funcnode *func, int argc, char **argv, int flags)
8611{
8612 volatile struct shparam saveparam;
8613 struct localvar *volatile savelocalvars;
8614 struct jmploc *volatile savehandler;
8615 struct jmploc jmploc;
8616 int e;
8617
8618 saveparam = shellparam;
8619 savelocalvars = localvars;
8620 e = setjmp(jmploc.loc);
8621 if (e) {
8622 goto funcdone;
8623 }
8624 INT_OFF;
8625 savehandler = exception_handler;
8626 exception_handler = &jmploc;
8627 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008628 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008629 func->count++;
8630 funcnest++;
8631 INT_ON;
8632 shellparam.nparam = argc - 1;
8633 shellparam.p = argv + 1;
8634#if ENABLE_ASH_GETOPTS
8635 shellparam.optind = 1;
8636 shellparam.optoff = -1;
8637#endif
8638 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008639 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008640 INT_OFF;
8641 funcnest--;
8642 freefunc(func);
8643 poplocalvars();
8644 localvars = savelocalvars;
8645 freeparam(&shellparam);
8646 shellparam = saveparam;
8647 exception_handler = savehandler;
8648 INT_ON;
8649 evalskip &= ~SKIPFUNC;
8650 return e;
8651}
8652
Denis Vlasenko131ae172007-02-18 13:00:19 +00008653#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008654static char **
8655parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008656{
8657 char *cp, c;
8658
8659 for (;;) {
8660 cp = *++argv;
8661 if (!cp)
8662 return 0;
8663 if (*cp++ != '-')
8664 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008665 c = *cp++;
8666 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008667 break;
8668 if (c == '-' && !*cp) {
8669 argv++;
8670 break;
8671 }
8672 do {
8673 switch (c) {
8674 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008675 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008676 break;
8677 default:
8678 /* run 'typecmd' for other options */
8679 return 0;
8680 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008681 c = *cp++;
8682 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008683 }
8684 return argv;
8685}
8686#endif
8687
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008688/*
8689 * Make a variable a local variable. When a variable is made local, it's
8690 * value and flags are saved in a localvar structure. The saved values
8691 * will be restored when the shell function returns. We handle the name
8692 * "-" as a special case.
8693 */
8694static void
8695mklocal(char *name)
8696{
8697 struct localvar *lvp;
8698 struct var **vpp;
8699 struct var *vp;
8700
8701 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008702 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008703 if (LONE_DASH(name)) {
8704 char *p;
8705 p = ckmalloc(sizeof(optlist));
8706 lvp->text = memcpy(p, optlist, sizeof(optlist));
8707 vp = NULL;
8708 } else {
8709 char *eq;
8710
8711 vpp = hashvar(name);
8712 vp = *findvar(vpp, name);
8713 eq = strchr(name, '=');
8714 if (vp == NULL) {
8715 if (eq)
8716 setvareq(name, VSTRFIXED);
8717 else
8718 setvar(name, NULL, VSTRFIXED);
8719 vp = *vpp; /* the new variable */
8720 lvp->flags = VUNSET;
8721 } else {
8722 lvp->text = vp->text;
8723 lvp->flags = vp->flags;
8724 vp->flags |= VSTRFIXED|VTEXTFIXED;
8725 if (eq)
8726 setvareq(name, 0);
8727 }
8728 }
8729 lvp->vp = vp;
8730 lvp->next = localvars;
8731 localvars = lvp;
8732 INT_ON;
8733}
8734
8735/*
8736 * The "local" command.
8737 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008738static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008739localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008740{
8741 char *name;
8742
8743 argv = argptr;
8744 while ((name = *argv++) != NULL) {
8745 mklocal(name);
8746 }
8747 return 0;
8748}
8749
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008750static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008751falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008752{
8753 return 1;
8754}
8755
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008756static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008757truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008758{
8759 return 0;
8760}
8761
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008762static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008763execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008764{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008765 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008766 iflag = 0; /* exit on error */
8767 mflag = 0;
8768 optschanged();
8769 shellexec(argv + 1, pathval(), 0);
8770 }
8771 return 0;
8772}
8773
8774/*
8775 * The return command.
8776 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008777static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008778returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008779{
8780 /*
8781 * If called outside a function, do what ksh does;
8782 * skip the rest of the file.
8783 */
8784 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8785 return argv[1] ? number(argv[1]) : exitstatus;
8786}
8787
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008788/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008789static int breakcmd(int, char **) FAST_FUNC;
8790static int dotcmd(int, char **) FAST_FUNC;
8791static int evalcmd(int, char **) FAST_FUNC;
8792static int exitcmd(int, char **) FAST_FUNC;
8793static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008794#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008795static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008796#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008797#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008798static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008799#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008800#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008801static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008802#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008803static int readcmd(int, char **) FAST_FUNC;
8804static int setcmd(int, char **) FAST_FUNC;
8805static int shiftcmd(int, char **) FAST_FUNC;
8806static int timescmd(int, char **) FAST_FUNC;
8807static int trapcmd(int, char **) FAST_FUNC;
8808static int umaskcmd(int, char **) FAST_FUNC;
8809static int unsetcmd(int, char **) FAST_FUNC;
8810static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008811
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008812#define BUILTIN_NOSPEC "0"
8813#define BUILTIN_SPECIAL "1"
8814#define BUILTIN_REGULAR "2"
8815#define BUILTIN_SPEC_REG "3"
8816#define BUILTIN_ASSIGN "4"
8817#define BUILTIN_SPEC_ASSG "5"
8818#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008819#define BUILTIN_SPEC_REG_ASSG "7"
8820
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008822#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008823static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008824#endif
8825#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008826static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008827#endif
8828#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008830#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008831
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008832/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008833static const struct builtincmd builtintab[] = {
8834 { BUILTIN_SPEC_REG ".", dotcmd },
8835 { BUILTIN_SPEC_REG ":", truecmd },
8836#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008837 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008838#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008839 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008840#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008841#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008842#if ENABLE_ASH_ALIAS
8843 { BUILTIN_REG_ASSG "alias", aliascmd },
8844#endif
8845#if JOBS
8846 { BUILTIN_REGULAR "bg", fg_bgcmd },
8847#endif
8848 { BUILTIN_SPEC_REG "break", breakcmd },
8849 { BUILTIN_REGULAR "cd", cdcmd },
8850 { BUILTIN_NOSPEC "chdir", cdcmd },
8851#if ENABLE_ASH_CMDCMD
8852 { BUILTIN_REGULAR "command", commandcmd },
8853#endif
8854 { BUILTIN_SPEC_REG "continue", breakcmd },
8855#if ENABLE_ASH_BUILTIN_ECHO
8856 { BUILTIN_REGULAR "echo", echocmd },
8857#endif
8858 { BUILTIN_SPEC_REG "eval", evalcmd },
8859 { BUILTIN_SPEC_REG "exec", execcmd },
8860 { BUILTIN_SPEC_REG "exit", exitcmd },
8861 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8862 { BUILTIN_REGULAR "false", falsecmd },
8863#if JOBS
8864 { BUILTIN_REGULAR "fg", fg_bgcmd },
8865#endif
8866#if ENABLE_ASH_GETOPTS
8867 { BUILTIN_REGULAR "getopts", getoptscmd },
8868#endif
8869 { BUILTIN_NOSPEC "hash", hashcmd },
8870#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8871 { BUILTIN_NOSPEC "help", helpcmd },
8872#endif
8873#if JOBS
8874 { BUILTIN_REGULAR "jobs", jobscmd },
8875 { BUILTIN_REGULAR "kill", killcmd },
8876#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008877#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008878 { BUILTIN_NOSPEC "let", letcmd },
8879#endif
8880 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008881#if ENABLE_ASH_BUILTIN_PRINTF
8882 { BUILTIN_REGULAR "printf", printfcmd },
8883#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008884 { BUILTIN_NOSPEC "pwd", pwdcmd },
8885 { BUILTIN_REGULAR "read", readcmd },
8886 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8887 { BUILTIN_SPEC_REG "return", returncmd },
8888 { BUILTIN_SPEC_REG "set", setcmd },
8889 { BUILTIN_SPEC_REG "shift", shiftcmd },
8890 { BUILTIN_SPEC_REG "source", dotcmd },
8891#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008892 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008893#endif
8894 { BUILTIN_SPEC_REG "times", timescmd },
8895 { BUILTIN_SPEC_REG "trap", trapcmd },
8896 { BUILTIN_REGULAR "true", truecmd },
8897 { BUILTIN_NOSPEC "type", typecmd },
8898 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8899 { BUILTIN_REGULAR "umask", umaskcmd },
8900#if ENABLE_ASH_ALIAS
8901 { BUILTIN_REGULAR "unalias", unaliascmd },
8902#endif
8903 { BUILTIN_SPEC_REG "unset", unsetcmd },
8904 { BUILTIN_REGULAR "wait", waitcmd },
8905};
8906
Denis Vlasenko80591b02008-03-25 07:49:43 +00008907/* Should match the above table! */
8908#define COMMANDCMD (builtintab + \
8909 2 + \
8910 1 * ENABLE_ASH_BUILTIN_TEST + \
8911 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8912 1 * ENABLE_ASH_ALIAS + \
8913 1 * ENABLE_ASH_JOB_CONTROL + \
8914 3)
8915#define EXECCMD (builtintab + \
8916 2 + \
8917 1 * ENABLE_ASH_BUILTIN_TEST + \
8918 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8919 1 * ENABLE_ASH_ALIAS + \
8920 1 * ENABLE_ASH_JOB_CONTROL + \
8921 3 + \
8922 1 * ENABLE_ASH_CMDCMD + \
8923 1 + \
8924 ENABLE_ASH_BUILTIN_ECHO + \
8925 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008926
8927/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008928 * Search the table of builtin commands.
8929 */
8930static struct builtincmd *
8931find_builtin(const char *name)
8932{
8933 struct builtincmd *bp;
8934
8935 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008936 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008937 pstrcmp
8938 );
8939 return bp;
8940}
8941
8942/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008943 * Execute a simple command.
8944 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008945static int
8946isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008947{
8948 const char *q = endofname(p);
8949 if (p == q)
8950 return 0;
8951 return *q == '=';
8952}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008953static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008954bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008955{
8956 /* Preserve exitstatus of a previous possible redirection
8957 * as POSIX mandates */
8958 return back_exitstatus;
8959}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008960static void
Eric Andersenc470f442003-07-28 09:56:35 +00008961evalcommand(union node *cmd, int flags)
8962{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008963 static const struct builtincmd null_bltin = {
8964 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008965 };
Eric Andersenc470f442003-07-28 09:56:35 +00008966 struct stackmark smark;
8967 union node *argp;
8968 struct arglist arglist;
8969 struct arglist varlist;
8970 char **argv;
8971 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008972 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008973 struct cmdentry cmdentry;
8974 struct job *jp;
8975 char *lastarg;
8976 const char *path;
8977 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008978 int status;
8979 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008980 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008981 smallint cmd_is_exec;
8982 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008983
8984 /* First expand the arguments. */
8985 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8986 setstackmark(&smark);
8987 back_exitstatus = 0;
8988
8989 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008990 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008991 varlist.lastp = &varlist.list;
8992 *varlist.lastp = NULL;
8993 arglist.lastp = &arglist.list;
8994 *arglist.lastp = NULL;
8995
8996 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008997 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008998 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8999 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9000 }
9001
Eric Andersenc470f442003-07-28 09:56:35 +00009002 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9003 struct strlist **spp;
9004
9005 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009006 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009007 expandarg(argp, &arglist, EXP_VARTILDE);
9008 else
9009 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9010
Eric Andersenc470f442003-07-28 09:56:35 +00009011 for (sp = *spp; sp; sp = sp->next)
9012 argc++;
9013 }
9014
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009015 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009016 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009017 TRACE(("evalcommand arg: %s\n", sp->text));
9018 *nargv++ = sp->text;
9019 }
9020 *nargv = NULL;
9021
9022 lastarg = NULL;
9023 if (iflag && funcnest == 0 && argc > 0)
9024 lastarg = nargv[-1];
9025
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009026 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009027 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009028 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009029
9030 path = vpath.text;
9031 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9032 struct strlist **spp;
9033 char *p;
9034
9035 spp = varlist.lastp;
9036 expandarg(argp, &varlist, EXP_VARTILDE);
9037
9038 /*
9039 * Modify the command lookup path, if a PATH= assignment
9040 * is present
9041 */
9042 p = (*spp)->text;
9043 if (varequal(p, path))
9044 path = p;
9045 }
9046
9047 /* Print the command if xflag is set. */
9048 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009049 int n;
9050 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009051
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009052 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009053 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009054
9055 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009056 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009057 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009058 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009059 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009060 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009061 p--;
9062 }
9063 }
9064 sp = arglist.list;
9065 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009066 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009067 }
9068
9069 cmd_is_exec = 0;
9070 spclbltin = -1;
9071
9072 /* Now locate the command. */
9073 if (argc) {
9074 const char *oldpath;
9075 int cmd_flag = DO_ERR;
9076
9077 path += 5;
9078 oldpath = path;
9079 for (;;) {
9080 find_command(argv[0], &cmdentry, cmd_flag, path);
9081 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009082 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009083 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009084 goto bail;
9085 }
9086
9087 /* implement bltin and command here */
9088 if (cmdentry.cmdtype != CMDBUILTIN)
9089 break;
9090 if (spclbltin < 0)
9091 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9092 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009093 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009094#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009095 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009096 path = oldpath;
9097 nargv = parse_command_args(argv, &path);
9098 if (!nargv)
9099 break;
9100 argc -= nargv - argv;
9101 argv = nargv;
9102 cmd_flag |= DO_NOFUNC;
9103 } else
9104#endif
9105 break;
9106 }
9107 }
9108
9109 if (status) {
9110 /* We have a redirection error. */
9111 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009112 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009113 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009114 exitstatus = status;
9115 goto out;
9116 }
9117
9118 /* Execute the command. */
9119 switch (cmdentry.cmdtype) {
9120 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009121
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009122#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009123/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9124 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009125 {
9126 /* find_command() encodes applet_no as (-2 - applet_no) */
9127 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009128 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009129 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009130 /* run <applet>_main() */
9131 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009132 break;
9133 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009134 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009135#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009136 /* Fork off a child process if necessary. */
9137 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009138 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009139 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009140 if (forkshell(jp, cmd, FORK_FG) != 0) {
9141 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009142 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009143 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009144 break;
9145 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009146 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009147 }
9148 listsetvar(varlist.list, VEXPORT|VSTACK);
9149 shellexec(argv, path, cmdentry.u.index);
9150 /* NOTREACHED */
9151
9152 case CMDBUILTIN:
9153 cmdenviron = varlist.list;
9154 if (cmdenviron) {
9155 struct strlist *list = cmdenviron;
9156 int i = VNOSET;
9157 if (spclbltin > 0 || argc == 0) {
9158 i = 0;
9159 if (cmd_is_exec && argc > 1)
9160 i = VEXPORT;
9161 }
9162 listsetvar(list, i);
9163 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009164 /* Tight loop with builtins only:
9165 * "while kill -0 $child; do true; done"
9166 * will never exit even if $child died, unless we do this
9167 * to reap the zombie and make kill detect that it's gone: */
9168 dowait(DOWAIT_NONBLOCK, NULL);
9169
Eric Andersenc470f442003-07-28 09:56:35 +00009170 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9171 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009172 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009173 if (i == EXEXIT)
9174 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009175 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009176 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009177 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009178 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009179 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009180 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009181 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009182 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009183 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009184 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009185 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009186 }
9187 break;
9188
9189 case CMDFUNCTION:
9190 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009191 /* See above for the rationale */
9192 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009193 if (evalfun(cmdentry.u.func, argc, argv, flags))
9194 goto raise;
9195 break;
9196 }
9197
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009198 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009199 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009200 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009201 /* dsl: I think this is intended to be used to support
9202 * '_' in 'vi' command mode during line editing...
9203 * However I implemented that within libedit itself.
9204 */
9205 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009206 }
Eric Andersenc470f442003-07-28 09:56:35 +00009207 popstackmark(&smark);
9208}
9209
9210static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009211evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9212{
Eric Andersenc470f442003-07-28 09:56:35 +00009213 char *volatile savecmdname;
9214 struct jmploc *volatile savehandler;
9215 struct jmploc jmploc;
9216 int i;
9217
9218 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009219 i = setjmp(jmploc.loc);
9220 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009221 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009222 savehandler = exception_handler;
9223 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009224 commandname = argv[0];
9225 argptr = argv + 1;
9226 optptr = NULL; /* initialize nextopt */
9227 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009228 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009229 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009230 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009231 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009232 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009233 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009234
9235 return i;
9236}
9237
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009238static int
9239goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009240{
9241 return !*endofname(p);
9242}
9243
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009244
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009245/*
9246 * Search for a command. This is called before we fork so that the
9247 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009248 * the child. The check for "goodname" is an overly conservative
9249 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009250 */
Eric Andersenc470f442003-07-28 09:56:35 +00009251static void
9252prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009253{
9254 struct cmdentry entry;
9255
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009256 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9257 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009258}
9259
Eric Andersencb57d552001-06-28 07:25:16 +00009260
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009261/* ============ Builtin commands
9262 *
9263 * Builtin commands whose functions are closely tied to evaluation
9264 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009265 */
9266
9267/*
Eric Andersencb57d552001-06-28 07:25:16 +00009268 * Handle break and continue commands. Break, continue, and return are
9269 * all handled by setting the evalskip flag. The evaluation routines
9270 * above all check this flag, and if it is set they start skipping
9271 * commands rather than executing them. The variable skipcount is
9272 * the number of loops to break/continue, or the number of function
9273 * levels to return. (The latter is always 1.) It should probably
9274 * be an error to break out of more loops than exist, but it isn't
9275 * in the standard shell so we don't make it one here.
9276 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009277static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009278breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009279{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009280 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009281
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009282 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009283 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009284 if (n > loopnest)
9285 n = loopnest;
9286 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009287 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009288 skipcount = n;
9289 }
9290 return 0;
9291}
9292
Eric Andersenc470f442003-07-28 09:56:35 +00009293
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009294/* ============ input.c
9295 *
Eric Andersen90898442003-08-06 11:20:52 +00009296 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009297 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009298
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009299enum {
9300 INPUT_PUSH_FILE = 1,
9301 INPUT_NOFILE_OK = 2,
9302};
Eric Andersencb57d552001-06-28 07:25:16 +00009303
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009304static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009305/* values of checkkwd variable */
9306#define CHKALIAS 0x1
9307#define CHKKWD 0x2
9308#define CHKNL 0x4
9309
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009310/*
9311 * Push a string back onto the input at this current parsefile level.
9312 * We handle aliases this way.
9313 */
9314#if !ENABLE_ASH_ALIAS
9315#define pushstring(s, ap) pushstring(s)
9316#endif
9317static void
9318pushstring(char *s, struct alias *ap)
9319{
9320 struct strpush *sp;
9321 int len;
9322
9323 len = strlen(s);
9324 INT_OFF;
9325 if (g_parsefile->strpush) {
9326 sp = ckzalloc(sizeof(*sp));
9327 sp->prev = g_parsefile->strpush;
9328 } else {
9329 sp = &(g_parsefile->basestrpush);
9330 }
9331 g_parsefile->strpush = sp;
9332 sp->prev_string = g_parsefile->next_to_pgetc;
9333 sp->prev_left_in_line = g_parsefile->left_in_line;
9334#if ENABLE_ASH_ALIAS
9335 sp->ap = ap;
9336 if (ap) {
9337 ap->flag |= ALIASINUSE;
9338 sp->string = s;
9339 }
9340#endif
9341 g_parsefile->next_to_pgetc = s;
9342 g_parsefile->left_in_line = len;
9343 INT_ON;
9344}
9345
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009346static void
9347popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009348{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009349 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009350
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009351 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009352#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009353 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009354 if (g_parsefile->next_to_pgetc[-1] == ' '
9355 || g_parsefile->next_to_pgetc[-1] == '\t'
9356 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009357 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009358 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009359 if (sp->string != sp->ap->val) {
9360 free(sp->string);
9361 }
9362 sp->ap->flag &= ~ALIASINUSE;
9363 if (sp->ap->flag & ALIASDEAD) {
9364 unalias(sp->ap->name);
9365 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009366 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009367#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009368 g_parsefile->next_to_pgetc = sp->prev_string;
9369 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009370 g_parsefile->strpush = sp->prev;
9371 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009372 free(sp);
9373 INT_ON;
9374}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009375
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009376//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9377//it peeks whether it is &>, and then pushes back both chars.
9378//This function needs to save last *next_to_pgetc to buf[0]
9379//to make two pungetc() reliable. Currently,
9380// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009381static int
9382preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009383{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009384 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009385 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009386
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009387 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009388#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009389 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009390 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009391 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009392 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009393#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009394 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009395#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009396 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9397 if (nr == 0) {
9398 /* Ctrl+C pressed */
9399 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009400 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009401 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009402 raise(SIGINT);
9403 return 1;
9404 }
Eric Andersenc470f442003-07-28 09:56:35 +00009405 goto retry;
9406 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009407 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009408 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009409 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009410 }
Eric Andersencb57d552001-06-28 07:25:16 +00009411 }
9412#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009413 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009414#endif
9415
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009416#if 0
9417/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009418 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009419 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009420 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009421 if (flags >= 0 && (flags & O_NONBLOCK)) {
9422 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009423 if (fcntl(0, F_SETFL, flags) >= 0) {
9424 out2str("sh: turning off NDELAY mode\n");
9425 goto retry;
9426 }
9427 }
9428 }
9429 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009430#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009431 return nr;
9432}
9433
9434/*
9435 * Refill the input buffer and return the next input character:
9436 *
9437 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009438 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9439 * or we are reading from a string so we can't refill the buffer,
9440 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009441 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009442 * 4) Process input up to the next newline, deleting nul characters.
9443 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009444//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9445#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009446static int
Eric Andersenc470f442003-07-28 09:56:35 +00009447preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009448{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009449 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009450 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009451
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009452 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009453#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009454 if (g_parsefile->left_in_line == -1
9455 && g_parsefile->strpush->ap
9456 && g_parsefile->next_to_pgetc[-1] != ' '
9457 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009458 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009459 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009460 return PEOA;
9461 }
Eric Andersen2870d962001-07-02 17:27:21 +00009462#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009463 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009464 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009465 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9466 g_parsefile->left_in_line,
9467 g_parsefile->next_to_pgetc,
9468 g_parsefile->next_to_pgetc);
9469 if (--g_parsefile->left_in_line >= 0)
9470 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009471 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009472 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009473 * "pgetc" needs refilling.
9474 */
9475
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009476 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009477 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009478 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009479 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009480 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009481 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009482 /* even in failure keep left_in_line and next_to_pgetc
9483 * in lock step, for correct multi-layer pungetc.
9484 * left_in_line was decremented before preadbuffer(),
9485 * must inc next_to_pgetc: */
9486 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009487 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009488 }
Eric Andersencb57d552001-06-28 07:25:16 +00009489
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009490 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009491 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009492 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009493 again:
9494 more = preadfd();
9495 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 /* don't try reading again */
9497 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009498 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009499 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009500 return PEOF;
9501 }
9502 }
9503
Denis Vlasenko727752d2008-11-28 03:41:47 +00009504 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009505 * Set g_parsefile->left_in_line
9506 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 * NUL chars are deleted.
9508 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009509 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009510 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009511 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009512
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009513 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009514
Denis Vlasenko727752d2008-11-28 03:41:47 +00009515 c = *q;
9516 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009517 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009518 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009519 q++;
9520 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009521 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009522 break;
9523 }
Eric Andersencb57d552001-06-28 07:25:16 +00009524 }
9525
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009526 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009527 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9528 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009529 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009530 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009531 }
9532 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009533 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009534
Eric Andersencb57d552001-06-28 07:25:16 +00009535 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009536 char save = *q;
9537 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009538 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009539 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009540 }
9541
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009542 pgetc_debug("preadbuffer at %d:%p'%s'",
9543 g_parsefile->left_in_line,
9544 g_parsefile->next_to_pgetc,
9545 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009546 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009547}
9548
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009549#define pgetc_as_macro() \
9550 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009551 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552 : preadbuffer() \
9553 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009554
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009555static int
9556pgetc(void)
9557{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009558 pgetc_debug("pgetc_fast at %d:%p'%s'",
9559 g_parsefile->left_in_line,
9560 g_parsefile->next_to_pgetc,
9561 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009562 return pgetc_as_macro();
9563}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009564
9565#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009566# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009567#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009568# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009569#endif
9570
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009571#if ENABLE_ASH_ALIAS
9572static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009573pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009574{
9575 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009576 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009577 pgetc_debug("pgetc_fast at %d:%p'%s'",
9578 g_parsefile->left_in_line,
9579 g_parsefile->next_to_pgetc,
9580 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009581 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009582 } while (c == PEOA);
9583 return c;
9584}
9585#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009586# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009587#endif
9588
9589/*
9590 * Read a line from the script.
9591 */
9592static char *
9593pfgets(char *line, int len)
9594{
9595 char *p = line;
9596 int nleft = len;
9597 int c;
9598
9599 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009600 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009601 if (c == PEOF) {
9602 if (p == line)
9603 return NULL;
9604 break;
9605 }
9606 *p++ = c;
9607 if (c == '\n')
9608 break;
9609 }
9610 *p = '\0';
9611 return line;
9612}
9613
Eric Andersenc470f442003-07-28 09:56:35 +00009614/*
9615 * Undo the last call to pgetc. Only one character may be pushed back.
9616 * PEOF may be pushed back.
9617 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009618static void
Eric Andersenc470f442003-07-28 09:56:35 +00009619pungetc(void)
9620{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009621 g_parsefile->left_in_line++;
9622 g_parsefile->next_to_pgetc--;
9623 pgetc_debug("pushed back to %d:%p'%s'",
9624 g_parsefile->left_in_line,
9625 g_parsefile->next_to_pgetc,
9626 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009627}
9628
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009629/*
9630 * To handle the "." command, a stack of input files is used. Pushfile
9631 * adds a new entry to the stack and popfile restores the previous level.
9632 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009633static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009634pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009635{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009636 struct parsefile *pf;
9637
Denis Vlasenko597906c2008-02-20 16:38:54 +00009638 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009639 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009640 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009641 /*pf->strpush = NULL; - ckzalloc did it */
9642 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009643 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009644}
9645
9646static void
9647popfile(void)
9648{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009649 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009650
Denis Vlasenkob012b102007-02-19 22:43:01 +00009651 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009652 if (pf->fd >= 0)
9653 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009654 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009655 while (pf->strpush)
9656 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009657 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009658 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009659 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009660}
9661
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009662/*
9663 * Return to top level.
9664 */
9665static void
9666popallfiles(void)
9667{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009668 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009669 popfile();
9670}
9671
9672/*
9673 * Close the file(s) that the shell is reading commands from. Called
9674 * after a fork is done.
9675 */
9676static void
9677closescript(void)
9678{
9679 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009680 if (g_parsefile->fd > 0) {
9681 close(g_parsefile->fd);
9682 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009683 }
9684}
9685
9686/*
9687 * Like setinputfile, but takes an open file descriptor. Call this with
9688 * interrupts off.
9689 */
9690static void
9691setinputfd(int fd, int push)
9692{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009693 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009694 if (push) {
9695 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009696 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009697 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009698 g_parsefile->fd = fd;
9699 if (g_parsefile->buf == NULL)
9700 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009701 g_parsefile->left_in_buffer = 0;
9702 g_parsefile->left_in_line = 0;
9703 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009704}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009705
Eric Andersenc470f442003-07-28 09:56:35 +00009706/*
9707 * Set the input to take input from a file. If push is set, push the
9708 * old input onto the stack first.
9709 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009710static int
9711setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009712{
9713 int fd;
9714 int fd2;
9715
Denis Vlasenkob012b102007-02-19 22:43:01 +00009716 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009717 fd = open(fname, O_RDONLY);
9718 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009719 if (flags & INPUT_NOFILE_OK)
9720 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009721 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009722 }
Eric Andersenc470f442003-07-28 09:56:35 +00009723 if (fd < 10) {
9724 fd2 = copyfd(fd, 10);
9725 close(fd);
9726 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009727 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009728 fd = fd2;
9729 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009730 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009731 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009732 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009733 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009734}
9735
Eric Andersencb57d552001-06-28 07:25:16 +00009736/*
9737 * Like setinputfile, but takes input from a string.
9738 */
Eric Andersenc470f442003-07-28 09:56:35 +00009739static void
9740setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009741{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009742 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009743 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009744 g_parsefile->next_to_pgetc = string;
9745 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009746 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009747 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009748 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009749}
9750
9751
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009752/* ============ mail.c
9753 *
9754 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009755 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009756
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009757#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009758
Eric Andersencb57d552001-06-28 07:25:16 +00009759#define MAXMBOXES 10
9760
Eric Andersenc470f442003-07-28 09:56:35 +00009761/* times of mailboxes */
9762static time_t mailtime[MAXMBOXES];
9763/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009764static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009765
Eric Andersencb57d552001-06-28 07:25:16 +00009766/*
Eric Andersenc470f442003-07-28 09:56:35 +00009767 * Print appropriate message(s) if mail has arrived.
9768 * If mail_var_path_changed is set,
9769 * then the value of MAIL has mail_var_path_changed,
9770 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009771 */
Eric Andersenc470f442003-07-28 09:56:35 +00009772static void
9773chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009774{
Eric Andersencb57d552001-06-28 07:25:16 +00009775 const char *mpath;
9776 char *p;
9777 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009778 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009779 struct stackmark smark;
9780 struct stat statb;
9781
Eric Andersencb57d552001-06-28 07:25:16 +00009782 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009783 mpath = mpathset() ? mpathval() : mailval();
9784 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009785 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009786 if (p == NULL)
9787 break;
9788 if (*p == '\0')
9789 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009790 for (q = p; *q; q++)
9791 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009792#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009793 if (q[-1] != '/')
9794 abort();
9795#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009796 q[-1] = '\0'; /* delete trailing '/' */
9797 if (stat(p, &statb) < 0) {
9798 *mtp = 0;
9799 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009800 }
Eric Andersenc470f442003-07-28 09:56:35 +00009801 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9802 fprintf(
9803 stderr, snlfmt,
9804 pathopt ? pathopt : "you have mail"
9805 );
9806 }
9807 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009808 }
Eric Andersenc470f442003-07-28 09:56:35 +00009809 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009810 popstackmark(&smark);
9811}
Eric Andersencb57d552001-06-28 07:25:16 +00009812
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009813static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009814changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009815{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009816 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009817}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009818
Denis Vlasenko131ae172007-02-18 13:00:19 +00009819#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009820
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009821
9822/* ============ ??? */
9823
Eric Andersencb57d552001-06-28 07:25:16 +00009824/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009825 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009826 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009827static void
9828setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009829{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009830 char **newparam;
9831 char **ap;
9832 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009833
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009834 for (nparam = 0; argv[nparam]; nparam++)
9835 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009836 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9837 while (*argv) {
9838 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009839 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009840 *ap = NULL;
9841 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009842 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009843 shellparam.nparam = nparam;
9844 shellparam.p = newparam;
9845#if ENABLE_ASH_GETOPTS
9846 shellparam.optind = 1;
9847 shellparam.optoff = -1;
9848#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009849}
9850
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009851/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009852 * Process shell options. The global variable argptr contains a pointer
9853 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009854 *
9855 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9856 * For a non-interactive shell, an error condition encountered
9857 * by a special built-in ... shall cause the shell to write a diagnostic message
9858 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009859 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009860 * ...
9861 * Utility syntax error (option or operand error) Shall exit
9862 * ...
9863 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9864 * we see that bash does not do that (set "finishes" with error code 1 instead,
9865 * and shell continues), and people rely on this behavior!
9866 * Testcase:
9867 * set -o barfoo 2>/dev/null
9868 * echo $?
9869 *
9870 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009871 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009872static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009873plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009874{
9875 int i;
9876
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009877 if (name) {
9878 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009879 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009880 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009881 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009882 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009883 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009884 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009885 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009886 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009887 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009888 if (val) {
9889 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9890 } else {
9891 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9892 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009893 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009894 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009895}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009896static void
9897setoption(int flag, int val)
9898{
9899 int i;
9900
9901 for (i = 0; i < NOPTS; i++) {
9902 if (optletters(i) == flag) {
9903 optlist[i] = val;
9904 return;
9905 }
9906 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009907 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009908 /* NOTREACHED */
9909}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009910static int
Eric Andersenc470f442003-07-28 09:56:35 +00009911options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009912{
9913 char *p;
9914 int val;
9915 int c;
9916
9917 if (cmdline)
9918 minusc = NULL;
9919 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009920 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009921 if (c != '-' && c != '+')
9922 break;
9923 argptr++;
9924 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009925 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009926 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009927 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009928 if (!cmdline) {
9929 /* "-" means turn off -x and -v */
9930 if (p[0] == '\0')
9931 xflag = vflag = 0;
9932 /* "--" means reset params */
9933 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009934 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009935 }
Eric Andersenc470f442003-07-28 09:56:35 +00009936 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009937 }
Eric Andersencb57d552001-06-28 07:25:16 +00009938 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009939 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009940 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009941 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009942 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009943 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009944 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009945 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009946 /* it already printed err message */
9947 return 1; /* error */
9948 }
Eric Andersencb57d552001-06-28 07:25:16 +00009949 if (*argptr)
9950 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009951 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9952 isloginsh = 1;
9953 /* bash does not accept +-login, we also won't */
9954 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009955 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009956 isloginsh = 1;
9957 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009958 } else {
9959 setoption(c, val);
9960 }
9961 }
9962 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009963 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009964}
9965
Eric Andersencb57d552001-06-28 07:25:16 +00009966/*
Eric Andersencb57d552001-06-28 07:25:16 +00009967 * The shift builtin command.
9968 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009969static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009970shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009971{
9972 int n;
9973 char **ap1, **ap2;
9974
9975 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009976 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009977 n = number(argv[1]);
9978 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009979 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009980 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009981 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009982 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009983 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009984 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009985 }
9986 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009987 while ((*ap2++ = *ap1++) != NULL)
9988 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009989#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009990 shellparam.optind = 1;
9991 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009992#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009993 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009994 return 0;
9995}
9996
Eric Andersencb57d552001-06-28 07:25:16 +00009997/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009998 * POSIX requires that 'set' (but not export or readonly) output the
9999 * variables in lexicographic order - by the locale's collating order (sigh).
10000 * Maybe we could keep them in an ordered balanced binary tree
10001 * instead of hashed lists.
10002 * For now just roll 'em through qsort for printing...
10003 */
10004static int
10005showvars(const char *sep_prefix, int on, int off)
10006{
10007 const char *sep;
10008 char **ep, **epend;
10009
10010 ep = listvars(on, off, &epend);
10011 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10012
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010013 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010014
10015 for (; ep < epend; ep++) {
10016 const char *p;
10017 const char *q;
10018
10019 p = strchrnul(*ep, '=');
10020 q = nullstr;
10021 if (*p)
10022 q = single_quote(++p);
10023 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10024 }
10025 return 0;
10026}
10027
10028/*
Eric Andersencb57d552001-06-28 07:25:16 +000010029 * The set command builtin.
10030 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010031static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010032setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010033{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010034 int retval;
10035
Denis Vlasenko68404f12008-03-17 09:00:54 +000010036 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010037 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010038 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010039 retval = 1;
10040 if (!options(0)) { /* if no parse error... */
10041 retval = 0;
10042 optschanged();
10043 if (*argptr != NULL) {
10044 setparam(argptr);
10045 }
Eric Andersencb57d552001-06-28 07:25:16 +000010046 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010047 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010048 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010049}
10050
Denis Vlasenko131ae172007-02-18 13:00:19 +000010051#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010052static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010053change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010054{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010055 uint32_t t;
10056
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010057 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010058 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010059 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010060 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010061 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010062 vrandom.flags &= ~VNOFUNC;
10063 } else {
10064 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010065 t = strtoul(value, NULL, 10);
10066 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010067 }
Eric Andersenef02f822004-03-11 13:34:24 +000010068}
Eric Andersen16767e22004-03-16 05:14:10 +000010069#endif
10070
Denis Vlasenko131ae172007-02-18 13:00:19 +000010071#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010072static int
Eric Andersenc470f442003-07-28 09:56:35 +000010073getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010074{
10075 char *p, *q;
10076 char c = '?';
10077 int done = 0;
10078 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010079 char s[12];
10080 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010081
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010082 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010083 return 1;
10084 optnext = optfirst + *param_optind - 1;
10085
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010086 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010087 p = NULL;
10088 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010089 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010090 if (p == NULL || *p == '\0') {
10091 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010092 p = *optnext;
10093 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010094 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010095 p = NULL;
10096 done = 1;
10097 goto out;
10098 }
10099 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010100 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010101 goto atend;
10102 }
10103
10104 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010105 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010106 if (*q == '\0') {
10107 if (optstr[0] == ':') {
10108 s[0] = c;
10109 s[1] = '\0';
10110 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010111 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010112 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010113 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010114 }
10115 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010116 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010117 }
10118 if (*++q == ':')
10119 q++;
10120 }
10121
10122 if (*++q == ':') {
10123 if (*p == '\0' && (p = *optnext) == NULL) {
10124 if (optstr[0] == ':') {
10125 s[0] = c;
10126 s[1] = '\0';
10127 err |= setvarsafe("OPTARG", s, 0);
10128 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010129 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010130 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010131 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010132 c = '?';
10133 }
Eric Andersenc470f442003-07-28 09:56:35 +000010134 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010135 }
10136
10137 if (p == *optnext)
10138 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010139 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010140 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010141 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010142 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010143 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010144 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010145 *param_optind = optnext - optfirst + 1;
10146 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010147 err |= setvarsafe("OPTIND", s, VNOFUNC);
10148 s[0] = c;
10149 s[1] = '\0';
10150 err |= setvarsafe(optvar, s, 0);
10151 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010152 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010153 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010154 flush_stdout_stderr();
10155 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010156 }
10157 return done;
10158}
Eric Andersenc470f442003-07-28 09:56:35 +000010159
10160/*
10161 * The getopts builtin. Shellparam.optnext points to the next argument
10162 * to be processed. Shellparam.optptr points to the next character to
10163 * be processed in the current argument. If shellparam.optnext is NULL,
10164 * then it's the first time getopts has been called.
10165 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010166static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010167getoptscmd(int argc, char **argv)
10168{
10169 char **optbase;
10170
10171 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010172 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010173 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010174 optbase = shellparam.p;
10175 if (shellparam.optind > shellparam.nparam + 1) {
10176 shellparam.optind = 1;
10177 shellparam.optoff = -1;
10178 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010179 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010180 optbase = &argv[3];
10181 if (shellparam.optind > argc - 2) {
10182 shellparam.optind = 1;
10183 shellparam.optoff = -1;
10184 }
10185 }
10186
10187 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010188 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010189}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010190#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010191
Eric Andersencb57d552001-06-28 07:25:16 +000010192
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010193/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010194
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010195struct heredoc {
10196 struct heredoc *next; /* next here document in list */
10197 union node *here; /* redirection node */
10198 char *eofmark; /* string indicating end of input */
10199 smallint striptabs; /* if set, strip leading tabs */
10200};
10201
10202static smallint tokpushback; /* last token pushed back */
10203static smallint parsebackquote; /* nonzero if we are inside backquotes */
10204static smallint quoteflag; /* set if (part of) last token was quoted */
10205static token_id_t lasttoken; /* last token read (integer id Txxx) */
10206static struct heredoc *heredoclist; /* list of here documents to read */
10207static char *wordtext; /* text of last word returned by readtoken */
10208static struct nodelist *backquotelist;
10209static union node *redirnode;
10210static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010211
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010212/*
10213 * Called when an unexpected token is read during the parse. The argument
10214 * is the token that is expected, or -1 if more than one type of token can
10215 * occur at this point.
10216 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010217static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010218static void
10219raise_error_unexpected_syntax(int token)
10220{
10221 char msg[64];
10222 int l;
10223
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010224 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010225 if (token >= 0)
10226 sprintf(msg + l, " (expecting %s)", tokname(token));
10227 raise_error_syntax(msg);
10228 /* NOTREACHED */
10229}
Eric Andersencb57d552001-06-28 07:25:16 +000010230
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010231#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010232
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010233/* parsing is heavily cross-recursive, need these forward decls */
10234static union node *andor(void);
10235static union node *pipeline(void);
10236static union node *parse_command(void);
10237static void parseheredoc(void);
10238static char peektoken(void);
10239static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010240
Eric Andersenc470f442003-07-28 09:56:35 +000010241static union node *
10242list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010243{
10244 union node *n1, *n2, *n3;
10245 int tok;
10246
Eric Andersenc470f442003-07-28 09:56:35 +000010247 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10248 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010249 return NULL;
10250 n1 = NULL;
10251 for (;;) {
10252 n2 = andor();
10253 tok = readtoken();
10254 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010255 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010256 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010257 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010258 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010259 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010260 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010261 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010262 n2 = n3;
10263 }
10264 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010265 }
10266 }
10267 if (n1 == NULL) {
10268 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010269 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010270 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010271 n3->type = NSEMI;
10272 n3->nbinary.ch1 = n1;
10273 n3->nbinary.ch2 = n2;
10274 n1 = n3;
10275 }
10276 switch (tok) {
10277 case TBACKGND:
10278 case TSEMI:
10279 tok = readtoken();
10280 /* fall through */
10281 case TNL:
10282 if (tok == TNL) {
10283 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010284 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010285 return n1;
10286 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010287 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010288 }
Eric Andersenc470f442003-07-28 09:56:35 +000010289 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010290 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010291 return n1;
10292 break;
10293 case TEOF:
10294 if (heredoclist)
10295 parseheredoc();
10296 else
Eric Andersenc470f442003-07-28 09:56:35 +000010297 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010298 return n1;
10299 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010300 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010301 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010302 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010303 return n1;
10304 }
10305 }
10306}
10307
Eric Andersenc470f442003-07-28 09:56:35 +000010308static union node *
10309andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010310{
Eric Andersencb57d552001-06-28 07:25:16 +000010311 union node *n1, *n2, *n3;
10312 int t;
10313
Eric Andersencb57d552001-06-28 07:25:16 +000010314 n1 = pipeline();
10315 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010316 t = readtoken();
10317 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010318 t = NAND;
10319 } else if (t == TOR) {
10320 t = NOR;
10321 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010322 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010323 return n1;
10324 }
Eric Andersenc470f442003-07-28 09:56:35 +000010325 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010326 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010327 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010328 n3->type = t;
10329 n3->nbinary.ch1 = n1;
10330 n3->nbinary.ch2 = n2;
10331 n1 = n3;
10332 }
10333}
10334
Eric Andersenc470f442003-07-28 09:56:35 +000010335static union node *
10336pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010337{
Eric Andersencb57d552001-06-28 07:25:16 +000010338 union node *n1, *n2, *pipenode;
10339 struct nodelist *lp, *prev;
10340 int negate;
10341
10342 negate = 0;
10343 TRACE(("pipeline: entered\n"));
10344 if (readtoken() == TNOT) {
10345 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010346 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010347 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010348 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010349 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010350 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010351 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010352 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010353 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010354 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010355 pipenode->npipe.cmdlist = lp;
10356 lp->n = n1;
10357 do {
10358 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010359 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010360 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010361 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010362 prev->next = lp;
10363 } while (readtoken() == TPIPE);
10364 lp->next = NULL;
10365 n1 = pipenode;
10366 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010367 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010368 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010369 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010370 n2->type = NNOT;
10371 n2->nnot.com = n1;
10372 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010373 }
10374 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010375}
10376
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010377static union node *
10378makename(void)
10379{
10380 union node *n;
10381
Denis Vlasenko597906c2008-02-20 16:38:54 +000010382 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010383 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010384 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010385 n->narg.text = wordtext;
10386 n->narg.backquote = backquotelist;
10387 return n;
10388}
10389
10390static void
10391fixredir(union node *n, const char *text, int err)
10392{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010393 int fd;
10394
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010395 TRACE(("Fix redir %s %d\n", text, err));
10396 if (!err)
10397 n->ndup.vname = NULL;
10398
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010399 fd = bb_strtou(text, NULL, 10);
10400 if (!errno && fd >= 0)
10401 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010402 else if (LONE_DASH(text))
10403 n->ndup.dupfd = -1;
10404 else {
10405 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010406 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010407 n->ndup.vname = makename();
10408 }
10409}
10410
10411/*
10412 * Returns true if the text contains nothing to expand (no dollar signs
10413 * or backquotes).
10414 */
10415static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010416noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010417{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010418 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010419
Denys Vlasenkocd716832009-11-28 22:14:02 +010010420 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010421 if (c == CTLQUOTEMARK)
10422 continue;
10423 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010424 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010425 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010426 return 0;
10427 }
10428 return 1;
10429}
10430
10431static void
10432parsefname(void)
10433{
10434 union node *n = redirnode;
10435
10436 if (readtoken() != TWORD)
10437 raise_error_unexpected_syntax(-1);
10438 if (n->type == NHERE) {
10439 struct heredoc *here = heredoc;
10440 struct heredoc *p;
10441 int i;
10442
10443 if (quoteflag == 0)
10444 n->type = NXHERE;
10445 TRACE(("Here document %d\n", n->type));
10446 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010447 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010448 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010449 here->eofmark = wordtext;
10450 here->next = NULL;
10451 if (heredoclist == NULL)
10452 heredoclist = here;
10453 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010454 for (p = heredoclist; p->next; p = p->next)
10455 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010456 p->next = here;
10457 }
10458 } else if (n->type == NTOFD || n->type == NFROMFD) {
10459 fixredir(n, wordtext, 0);
10460 } else {
10461 n->nfile.fname = makename();
10462 }
10463}
Eric Andersencb57d552001-06-28 07:25:16 +000010464
Eric Andersenc470f442003-07-28 09:56:35 +000010465static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010466simplecmd(void)
10467{
10468 union node *args, **app;
10469 union node *n = NULL;
10470 union node *vars, **vpp;
10471 union node **rpp, *redir;
10472 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010473#if ENABLE_ASH_BASH_COMPAT
10474 smallint double_brackets_flag = 0;
10475#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010476
10477 args = NULL;
10478 app = &args;
10479 vars = NULL;
10480 vpp = &vars;
10481 redir = NULL;
10482 rpp = &redir;
10483
10484 savecheckkwd = CHKALIAS;
10485 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010486 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010487 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010488 t = readtoken();
10489 switch (t) {
10490#if ENABLE_ASH_BASH_COMPAT
10491 case TAND: /* "&&" */
10492 case TOR: /* "||" */
10493 if (!double_brackets_flag) {
10494 tokpushback = 1;
10495 goto out;
10496 }
10497 wordtext = (char *) (t == TAND ? "-a" : "-o");
10498#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010500 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010501 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010502 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010503 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010504#if ENABLE_ASH_BASH_COMPAT
10505 if (strcmp("[[", wordtext) == 0)
10506 double_brackets_flag = 1;
10507 else if (strcmp("]]", wordtext) == 0)
10508 double_brackets_flag = 0;
10509#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010510 n->narg.backquote = backquotelist;
10511 if (savecheckkwd && isassignment(wordtext)) {
10512 *vpp = n;
10513 vpp = &n->narg.next;
10514 } else {
10515 *app = n;
10516 app = &n->narg.next;
10517 savecheckkwd = 0;
10518 }
10519 break;
10520 case TREDIR:
10521 *rpp = n = redirnode;
10522 rpp = &n->nfile.next;
10523 parsefname(); /* read name of redirection file */
10524 break;
10525 case TLP:
10526 if (args && app == &args->narg.next
10527 && !vars && !redir
10528 ) {
10529 struct builtincmd *bcmd;
10530 const char *name;
10531
10532 /* We have a function */
10533 if (readtoken() != TRP)
10534 raise_error_unexpected_syntax(TRP);
10535 name = n->narg.text;
10536 if (!goodname(name)
10537 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10538 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010539 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010540 }
10541 n->type = NDEFUN;
10542 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10543 n->narg.next = parse_command();
10544 return n;
10545 }
10546 /* fall through */
10547 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010548 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010549 goto out;
10550 }
10551 }
10552 out:
10553 *app = NULL;
10554 *vpp = NULL;
10555 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010556 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010557 n->type = NCMD;
10558 n->ncmd.args = args;
10559 n->ncmd.assign = vars;
10560 n->ncmd.redirect = redir;
10561 return n;
10562}
10563
10564static union node *
10565parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010566{
Eric Andersencb57d552001-06-28 07:25:16 +000010567 union node *n1, *n2;
10568 union node *ap, **app;
10569 union node *cp, **cpp;
10570 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010571 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010572 int t;
10573
10574 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010575 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010576
Eric Andersencb57d552001-06-28 07:25:16 +000010577 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010578 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010579 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010580 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010581 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010582 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010583 n1->type = NIF;
10584 n1->nif.test = list(0);
10585 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010586 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010587 n1->nif.ifpart = list(0);
10588 n2 = n1;
10589 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010590 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010591 n2 = n2->nif.elsepart;
10592 n2->type = NIF;
10593 n2->nif.test = list(0);
10594 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010595 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010596 n2->nif.ifpart = list(0);
10597 }
10598 if (lasttoken == TELSE)
10599 n2->nif.elsepart = list(0);
10600 else {
10601 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010602 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010603 }
Eric Andersenc470f442003-07-28 09:56:35 +000010604 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010605 break;
10606 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010607 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010608 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010609 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010610 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010611 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010612 got = readtoken();
10613 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010614 TRACE(("expecting DO got %s %s\n", tokname(got),
10615 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010616 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010617 }
10618 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010619 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010620 break;
10621 }
10622 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010623 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010624 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010625 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010626 n1->type = NFOR;
10627 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010628 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010629 if (readtoken() == TIN) {
10630 app = &ap;
10631 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010632 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010633 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010634 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010635 n2->narg.text = wordtext;
10636 n2->narg.backquote = backquotelist;
10637 *app = n2;
10638 app = &n2->narg.next;
10639 }
10640 *app = NULL;
10641 n1->nfor.args = ap;
10642 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010643 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010644 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010645 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010646 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010647 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010648 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010649 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010650 n1->nfor.args = n2;
10651 /*
10652 * Newline or semicolon here is optional (but note
10653 * that the original Bourne shell only allowed NL).
10654 */
10655 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010656 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010657 }
Eric Andersenc470f442003-07-28 09:56:35 +000010658 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010659 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010660 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010661 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010662 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010663 break;
10664 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010665 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010666 n1->type = NCASE;
10667 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010668 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010669 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010670 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010671 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010672 n2->narg.text = wordtext;
10673 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010674 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010675 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 } while (readtoken() == TNL);
10677 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010678 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010679 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010680 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010681 checkkwd = CHKNL | CHKKWD;
10682 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010683 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010684 if (lasttoken == TLP)
10685 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010686 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010687 cp->type = NCLIST;
10688 app = &cp->nclist.pattern;
10689 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010690 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010691 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010692 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010693 ap->narg.text = wordtext;
10694 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010695 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010696 break;
10697 app = &ap->narg.next;
10698 readtoken();
10699 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010700 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010701 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010702 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010703 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010704
Eric Andersenc470f442003-07-28 09:56:35 +000010705 cpp = &cp->nclist.next;
10706
10707 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010708 t = readtoken();
10709 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010710 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010711 raise_error_unexpected_syntax(TENDCASE);
10712 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010713 }
Eric Andersenc470f442003-07-28 09:56:35 +000010714 }
Eric Andersencb57d552001-06-28 07:25:16 +000010715 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010716 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010717 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010718 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010719 n1->type = NSUBSHELL;
10720 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010721 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010722 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010723 break;
10724 case TBEGIN:
10725 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010726 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010727 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010728 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010729 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010730 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010731 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010732 }
10733
Eric Andersenc470f442003-07-28 09:56:35 +000010734 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010735 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010736
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010737 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010738 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010739 checkkwd = CHKKWD | CHKALIAS;
10740 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010741 while (readtoken() == TREDIR) {
10742 *rpp = n2 = redirnode;
10743 rpp = &n2->nfile.next;
10744 parsefname();
10745 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010746 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010747 *rpp = NULL;
10748 if (redir) {
10749 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010750 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010751 n2->type = NREDIR;
10752 n2->nredir.n = n1;
10753 n1 = n2;
10754 }
10755 n1->nredir.redirect = redir;
10756 }
Eric Andersencb57d552001-06-28 07:25:16 +000010757 return n1;
10758}
10759
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010760#if ENABLE_ASH_BASH_COMPAT
10761static int decode_dollar_squote(void)
10762{
10763 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10764 int c, cnt;
10765 char *p;
10766 char buf[4];
10767
10768 c = pgetc();
10769 p = strchr(C_escapes, c);
10770 if (p) {
10771 buf[0] = c;
10772 p = buf;
10773 cnt = 3;
10774 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10775 do {
10776 c = pgetc();
10777 *++p = c;
10778 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10779 pungetc();
10780 } else if (c == 'x') { /* \xHH */
10781 do {
10782 c = pgetc();
10783 *++p = c;
10784 } while (isxdigit(c) && --cnt);
10785 pungetc();
10786 if (cnt == 3) { /* \x but next char is "bad" */
10787 c = 'x';
10788 goto unrecognized;
10789 }
10790 } else { /* simple seq like \\ or \t */
10791 p++;
10792 }
10793 *p = '\0';
10794 p = buf;
10795 c = bb_process_escape_sequence((void*)&p);
10796 } else { /* unrecognized "\z": print both chars unless ' or " */
10797 if (c != '\'' && c != '"') {
10798 unrecognized:
10799 c |= 0x100; /* "please encode \, then me" */
10800 }
10801 }
10802 return c;
10803}
10804#endif
10805
Eric Andersencb57d552001-06-28 07:25:16 +000010806/*
10807 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10808 * is not NULL, read a here document. In the latter case, eofmark is the
10809 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010810 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010811 * is the first character of the input token or document.
10812 *
10813 * Because C does not have internal subroutines, I have simulated them
10814 * using goto's to implement the subroutine linkage. The following macros
10815 * will run code that appears at the end of readtoken1.
10816 */
Eric Andersen2870d962001-07-02 17:27:21 +000010817#define CHECKEND() {goto checkend; checkend_return:;}
10818#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10819#define PARSESUB() {goto parsesub; parsesub_return:;}
10820#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10821#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10822#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010823static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010824readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010825{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010826 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010827 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010828 char *out;
10829 int len;
10830 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010831 struct nodelist *bqlist;
10832 smallint quotef;
10833 smallint dblquote;
10834 smallint oldstyle;
10835 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010836#if ENABLE_ASH_EXPAND_PRMT
10837 smallint pssyntax; /* we are expanding a prompt string */
10838#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010839 int varnest; /* levels of variables expansion */
10840 int arinest; /* levels of arithmetic expansion */
10841 int parenlevel; /* levels of parens in arithmetic */
10842 int dqvarnest; /* levels of variables expansion within double quotes */
10843
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010844 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010845
Eric Andersencb57d552001-06-28 07:25:16 +000010846#if __GNUC__
10847 /* Avoid longjmp clobbering */
10848 (void) &out;
10849 (void) &quotef;
10850 (void) &dblquote;
10851 (void) &varnest;
10852 (void) &arinest;
10853 (void) &parenlevel;
10854 (void) &dqvarnest;
10855 (void) &oldstyle;
10856 (void) &prevsyntax;
10857 (void) &syntax;
10858#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010859 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010860 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010861 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010862 oldstyle = 0;
10863 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010864#if ENABLE_ASH_EXPAND_PRMT
10865 pssyntax = (syntax == PSSYNTAX);
10866 if (pssyntax)
10867 syntax = DQSYNTAX;
10868#endif
10869 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010870 varnest = 0;
10871 arinest = 0;
10872 parenlevel = 0;
10873 dqvarnest = 0;
10874
10875 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010876 loop:
10877 /* For each line, until end of word */
10878 {
Eric Andersenc470f442003-07-28 09:56:35 +000010879 CHECKEND(); /* set c to PEOF if at end of here document */
10880 for (;;) { /* until end of line or end of word */
10881 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010882 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010883 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010884 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010885 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010886 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010887 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010888 if (doprompt)
10889 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010890 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010891 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010892 case CWORD:
10893 USTPUTC(c, out);
10894 break;
10895 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010896 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010897 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010898#if ENABLE_ASH_BASH_COMPAT
10899 if (c == '\\' && bash_dollar_squote) {
10900 c = decode_dollar_squote();
10901 if (c & 0x100) {
10902 USTPUTC('\\', out);
10903 c = (unsigned char)c;
10904 }
10905 }
10906#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010907 USTPUTC(c, out);
10908 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010909 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010910 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010911 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010912 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010913 USTPUTC('\\', out);
10914 pungetc();
10915 } else if (c == '\n') {
10916 if (doprompt)
10917 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010918 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010919#if ENABLE_ASH_EXPAND_PRMT
10920 if (c == '$' && pssyntax) {
10921 USTPUTC(CTLESC, out);
10922 USTPUTC('\\', out);
10923 }
10924#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010925 if (dblquote && c != '\\'
10926 && c != '`' && c != '$'
10927 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010928 ) {
10929 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010930 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010931 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010932 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010933 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010934 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010935 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010936 }
10937 break;
10938 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010939 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010940 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010941 if (eofmark == NULL) {
10942 USTPUTC(CTLQUOTEMARK, out);
10943 }
Eric Andersencb57d552001-06-28 07:25:16 +000010944 break;
10945 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010946 syntax = DQSYNTAX;
10947 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010948 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010949 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010950 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010951 if (eofmark != NULL && arinest == 0
10952 && varnest == 0
10953 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010954 USTPUTC(c, out);
10955 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010956 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010957 syntax = BASESYNTAX;
10958 dblquote = 0;
10959 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010960 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010961 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010962 }
10963 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010964 case CVAR: /* '$' */
10965 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010966 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010967 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010968 if (varnest > 0) {
10969 varnest--;
10970 if (dqvarnest > 0) {
10971 dqvarnest--;
10972 }
10973 USTPUTC(CTLENDVAR, out);
10974 } else {
10975 USTPUTC(c, out);
10976 }
10977 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010978#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010979 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010980 parenlevel++;
10981 USTPUTC(c, out);
10982 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010983 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010984 if (parenlevel > 0) {
10985 USTPUTC(c, out);
10986 --parenlevel;
10987 } else {
10988 if (pgetc() == ')') {
10989 if (--arinest == 0) {
10990 USTPUTC(CTLENDARI, out);
10991 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010992 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010993 } else
10994 USTPUTC(')', out);
10995 } else {
10996 /*
10997 * unbalanced parens
10998 * (don't 2nd guess - no error)
10999 */
11000 pungetc();
11001 USTPUTC(')', out);
11002 }
11003 }
11004 break;
11005#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011006 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011007 PARSEBACKQOLD();
11008 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011009 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011010 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011011 case CIGN:
11012 break;
11013 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011014 if (varnest == 0) {
11015#if ENABLE_ASH_BASH_COMPAT
11016 if (c == '&') {
11017 if (pgetc() == '>')
11018 c = 0x100 + '>'; /* flag &> */
11019 pungetc();
11020 }
11021#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011022 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011023 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011024 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011025 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011026
Eric Andersencb57d552001-06-28 07:25:16 +000011027 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011028 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011029 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011030 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011031 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011032#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011033 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011034 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011035#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011036 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011037 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011038 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011039 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011040 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011041 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011042 }
11043 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011044 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011045 out = stackblock();
11046 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011047 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011048 && quotef == 0
11049 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011050 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011051 PARSEREDIR(); /* passed as params: out, c */
11052 lasttoken = TREDIR;
11053 return lasttoken;
11054 }
11055 /* else: non-number X seen, interpret it
11056 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011057 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011058 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011059 }
11060 quoteflag = quotef;
11061 backquotelist = bqlist;
11062 grabstackblock(len);
11063 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011064 lasttoken = TWORD;
11065 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011066/* end of readtoken routine */
11067
Eric Andersencb57d552001-06-28 07:25:16 +000011068/*
11069 * Check to see whether we are at the end of the here document. When this
11070 * is called, c is set to the first character of the next input line. If
11071 * we are at the end of the here document, this routine sets the c to PEOF.
11072 */
Eric Andersenc470f442003-07-28 09:56:35 +000011073checkend: {
11074 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011075#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011076 if (c == PEOA)
11077 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011078#endif
11079 if (striptabs) {
11080 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011081 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011082 }
Eric Andersenc470f442003-07-28 09:56:35 +000011083 }
11084 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011085 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011086 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011087
Eric Andersenc470f442003-07-28 09:56:35 +000011088 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011089 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11090 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011091 if (*p == '\n' && *q == '\0') {
11092 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011093 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011094 needprompt = doprompt;
11095 } else {
11096 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011097 }
11098 }
11099 }
11100 }
Eric Andersenc470f442003-07-28 09:56:35 +000011101 goto checkend_return;
11102}
Eric Andersencb57d552001-06-28 07:25:16 +000011103
Eric Andersencb57d552001-06-28 07:25:16 +000011104/*
11105 * Parse a redirection operator. The variable "out" points to a string
11106 * specifying the fd to be redirected. The variable "c" contains the
11107 * first character of the redirection operator.
11108 */
Eric Andersenc470f442003-07-28 09:56:35 +000011109parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011110 /* out is already checked to be a valid number or "" */
11111 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011112 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011113
Denis Vlasenko597906c2008-02-20 16:38:54 +000011114 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011115 if (c == '>') {
11116 np->nfile.fd = 1;
11117 c = pgetc();
11118 if (c == '>')
11119 np->type = NAPPEND;
11120 else if (c == '|')
11121 np->type = NCLOBBER;
11122 else if (c == '&')
11123 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011124 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011125 else {
11126 np->type = NTO;
11127 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011128 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011129 }
11130#if ENABLE_ASH_BASH_COMPAT
11131 else if (c == 0x100 + '>') { /* this flags &> redirection */
11132 np->nfile.fd = 1;
11133 pgetc(); /* this is '>', no need to check */
11134 np->type = NTO2;
11135 }
11136#endif
11137 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011138 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011139 c = pgetc();
11140 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011141 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011142 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011143 np = stzalloc(sizeof(struct nhere));
11144 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011145 }
11146 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011147 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011148 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011149 c = pgetc();
11150 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011151 heredoc->striptabs = 1;
11152 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011153 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011154 pungetc();
11155 }
11156 break;
11157
11158 case '&':
11159 np->type = NFROMFD;
11160 break;
11161
11162 case '>':
11163 np->type = NFROMTO;
11164 break;
11165
11166 default:
11167 np->type = NFROM;
11168 pungetc();
11169 break;
11170 }
Eric Andersencb57d552001-06-28 07:25:16 +000011171 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011172 if (fd >= 0)
11173 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011174 redirnode = np;
11175 goto parseredir_return;
11176}
Eric Andersencb57d552001-06-28 07:25:16 +000011177
Eric Andersencb57d552001-06-28 07:25:16 +000011178/*
11179 * Parse a substitution. At this point, we have read the dollar sign
11180 * and nothing else.
11181 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011182
11183/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11184 * (assuming ascii char codes, as the original implementation did) */
11185#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011186 (((unsigned)(c) - 33 < 32) \
11187 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011188parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011189 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011190 int typeloc;
11191 int flags;
11192 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011193 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011194
Eric Andersenc470f442003-07-28 09:56:35 +000011195 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011196 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011197 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011198 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011199#if ENABLE_ASH_BASH_COMPAT
11200 if (c == '\'')
11201 bash_dollar_squote = 1;
11202 else
11203#endif
11204 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011205 pungetc();
11206 } else if (c == '(') { /* $(command) or $((arith)) */
11207 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011208#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011209 PARSEARITH();
11210#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011211 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011212#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011213 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011214 pungetc();
11215 PARSEBACKQNEW();
11216 }
11217 } else {
11218 USTPUTC(CTLVAR, out);
11219 typeloc = out - (char *)stackblock();
11220 USTPUTC(VSNORMAL, out);
11221 subtype = VSNORMAL;
11222 if (c == '{') {
11223 c = pgetc();
11224 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011225 c = pgetc();
11226 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011227 c = '#';
11228 else
11229 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011230 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011231 subtype = 0;
11232 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011233 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011234 do {
11235 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011236 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011237 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011238 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011239 do {
11240 STPUTC(c, out);
11241 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011242 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011243 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011244 USTPUTC(c, out);
11245 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011246 } else {
11247 badsub:
11248 raise_error_syntax("bad substitution");
11249 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011250 if (c != '}' && subtype == VSLENGTH)
11251 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011252
Eric Andersenc470f442003-07-28 09:56:35 +000011253 STPUTC('=', out);
11254 flags = 0;
11255 if (subtype == 0) {
11256 switch (c) {
11257 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011258 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011259#if ENABLE_ASH_BASH_COMPAT
11260 if (c == ':' || c == '$' || isdigit(c)) {
11261 pungetc();
11262 subtype = VSSUBSTR;
11263 break;
11264 }
11265#endif
11266 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011267 /*FALLTHROUGH*/
11268 default:
11269 p = strchr(types, c);
11270 if (p == NULL)
11271 goto badsub;
11272 subtype = p - types + VSNORMAL;
11273 break;
11274 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011275 case '#': {
11276 int cc = c;
11277 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11278 c = pgetc();
11279 if (c == cc)
11280 subtype++;
11281 else
11282 pungetc();
11283 break;
11284 }
11285#if ENABLE_ASH_BASH_COMPAT
11286 case '/':
11287 subtype = VSREPLACE;
11288 c = pgetc();
11289 if (c == '/')
11290 subtype++; /* VSREPLACEALL */
11291 else
11292 pungetc();
11293 break;
11294#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011295 }
Eric Andersenc470f442003-07-28 09:56:35 +000011296 } else {
11297 pungetc();
11298 }
11299 if (dblquote || arinest)
11300 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011301 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011302 if (subtype != VSNORMAL) {
11303 varnest++;
11304 if (dblquote || arinest) {
11305 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011306 }
11307 }
11308 }
Eric Andersenc470f442003-07-28 09:56:35 +000011309 goto parsesub_return;
11310}
Eric Andersencb57d552001-06-28 07:25:16 +000011311
Eric Andersencb57d552001-06-28 07:25:16 +000011312/*
11313 * Called to parse command substitutions. Newstyle is set if the command
11314 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11315 * list of commands (passed by reference), and savelen is the number of
11316 * characters on the top of the stack which must be preserved.
11317 */
Eric Andersenc470f442003-07-28 09:56:35 +000011318parsebackq: {
11319 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011320 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011321 union node *n;
11322 char *volatile str;
11323 struct jmploc jmploc;
11324 struct jmploc *volatile savehandler;
11325 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011326 smallint saveprompt = 0;
11327
Eric Andersencb57d552001-06-28 07:25:16 +000011328#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011329 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011330#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011331 savepbq = parsebackquote;
11332 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011333 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011334 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011335 exception_handler = savehandler;
11336 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011337 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011338 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011339 str = NULL;
11340 savelen = out - (char *)stackblock();
11341 if (savelen > 0) {
11342 str = ckmalloc(savelen);
11343 memcpy(str, stackblock(), savelen);
11344 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011345 savehandler = exception_handler;
11346 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011347 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011348 if (oldstyle) {
11349 /* We must read until the closing backquote, giving special
11350 treatment to some slashes, and then push the string and
11351 reread it as input, interpreting it normally. */
11352 char *pout;
11353 int pc;
11354 size_t psavelen;
11355 char *pstr;
11356
11357
11358 STARTSTACKSTR(pout);
11359 for (;;) {
11360 if (needprompt) {
11361 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011362 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011363 pc = pgetc();
11364 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011365 case '`':
11366 goto done;
11367
11368 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011369 pc = pgetc();
11370 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011371 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011372 if (doprompt)
11373 setprompt(2);
11374 /*
11375 * If eating a newline, avoid putting
11376 * the newline into the new character
11377 * stream (via the STPUTC after the
11378 * switch).
11379 */
11380 continue;
11381 }
11382 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011383 && (!dblquote || pc != '"')
11384 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011385 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011386 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011387 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011388 break;
11389 }
11390 /* fall through */
11391
11392 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011393 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011394 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011395 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011396
11397 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011398 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011399 needprompt = doprompt;
11400 break;
11401
11402 default:
11403 break;
11404 }
11405 STPUTC(pc, pout);
11406 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011407 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011408 STPUTC('\0', pout);
11409 psavelen = pout - (char *)stackblock();
11410 if (psavelen > 0) {
11411 pstr = grabstackstr(pout);
11412 setinputstring(pstr);
11413 }
11414 }
11415 nlpp = &bqlist;
11416 while (*nlpp)
11417 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011418 *nlpp = stzalloc(sizeof(**nlpp));
11419 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011420 parsebackquote = oldstyle;
11421
11422 if (oldstyle) {
11423 saveprompt = doprompt;
11424 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011425 }
11426
Eric Andersenc470f442003-07-28 09:56:35 +000011427 n = list(2);
11428
11429 if (oldstyle)
11430 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011431 else if (readtoken() != TRP)
11432 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011433
11434 (*nlpp)->n = n;
11435 if (oldstyle) {
11436 /*
11437 * Start reading from old file again, ignoring any pushed back
11438 * tokens left from the backquote parsing
11439 */
11440 popfile();
11441 tokpushback = 0;
11442 }
11443 while (stackblocksize() <= savelen)
11444 growstackblock();
11445 STARTSTACKSTR(out);
11446 if (str) {
11447 memcpy(out, str, savelen);
11448 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011449 INT_OFF;
11450 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011451 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011452 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011453 }
11454 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011455 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011456 if (arinest || dblquote)
11457 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11458 else
11459 USTPUTC(CTLBACKQ, out);
11460 if (oldstyle)
11461 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011462 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011463}
11464
Mike Frysinger98c52642009-04-02 10:02:37 +000011465#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011466/*
11467 * Parse an arithmetic expansion (indicate start of one and set state)
11468 */
Eric Andersenc470f442003-07-28 09:56:35 +000011469parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011470 if (++arinest == 1) {
11471 prevsyntax = syntax;
11472 syntax = ARISYNTAX;
11473 USTPUTC(CTLARI, out);
11474 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011475 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011476 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011477 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011478 } else {
11479 /*
11480 * we collapse embedded arithmetic expansion to
11481 * parenthesis, which should be equivalent
11482 */
11483 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011484 }
Eric Andersenc470f442003-07-28 09:56:35 +000011485 goto parsearith_return;
11486}
11487#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011488
Eric Andersenc470f442003-07-28 09:56:35 +000011489} /* end of readtoken */
11490
Eric Andersencb57d552001-06-28 07:25:16 +000011491/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011492 * Read the next input token.
11493 * If the token is a word, we set backquotelist to the list of cmds in
11494 * backquotes. We set quoteflag to true if any part of the word was
11495 * quoted.
11496 * If the token is TREDIR, then we set redirnode to a structure containing
11497 * the redirection.
11498 * In all cases, the variable startlinno is set to the number of the line
11499 * on which the token starts.
11500 *
11501 * [Change comment: here documents and internal procedures]
11502 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11503 * word parsing code into a separate routine. In this case, readtoken
11504 * doesn't need to have any internal procedures, but parseword does.
11505 * We could also make parseoperator in essence the main routine, and
11506 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011507 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011508#define NEW_xxreadtoken
11509#ifdef NEW_xxreadtoken
11510/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011511static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011512 '\n', '(', ')', /* singles */
11513 '&', '|', ';', /* doubles */
11514 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011515};
Eric Andersencb57d552001-06-28 07:25:16 +000011516
Denis Vlasenko834dee72008-10-07 09:18:30 +000011517#define xxreadtoken_singles 3
11518#define xxreadtoken_doubles 3
11519
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011520static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011521 TNL, TLP, TRP, /* only single occurrence allowed */
11522 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11523 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011524 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011525};
11526
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011527static int
11528xxreadtoken(void)
11529{
11530 int c;
11531
11532 if (tokpushback) {
11533 tokpushback = 0;
11534 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011535 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011536 if (needprompt) {
11537 setprompt(2);
11538 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011539 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011540 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011541 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011542 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011543 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011544
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011545 if (c == '#') {
11546 while ((c = pgetc()) != '\n' && c != PEOF)
11547 continue;
11548 pungetc();
11549 } else if (c == '\\') {
11550 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011551 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011552 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011553 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011554 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011555 if (doprompt)
11556 setprompt(2);
11557 } else {
11558 const char *p;
11559
11560 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11561 if (c != PEOF) {
11562 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011563 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011564 needprompt = doprompt;
11565 }
11566
11567 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011568 if (p == NULL)
11569 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011570
Denis Vlasenko834dee72008-10-07 09:18:30 +000011571 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11572 int cc = pgetc();
11573 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011574 p += xxreadtoken_doubles + 1;
11575 } else {
11576 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011577#if ENABLE_ASH_BASH_COMPAT
11578 if (c == '&' && cc == '>') /* &> */
11579 break; /* return readtoken1(...) */
11580#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011581 }
11582 }
11583 }
11584 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11585 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011586 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011587 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011588
11589 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011590}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011591#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011592#define RETURN(token) return lasttoken = token
11593static int
11594xxreadtoken(void)
11595{
11596 int c;
11597
11598 if (tokpushback) {
11599 tokpushback = 0;
11600 return lasttoken;
11601 }
11602 if (needprompt) {
11603 setprompt(2);
11604 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011605 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011606 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011607 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011608 switch (c) {
11609 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011610 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011611 continue;
11612 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011613 while ((c = pgetc()) != '\n' && c != PEOF)
11614 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011615 pungetc();
11616 continue;
11617 case '\\':
11618 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011619 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011620 if (doprompt)
11621 setprompt(2);
11622 continue;
11623 }
11624 pungetc();
11625 goto breakloop;
11626 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011627 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011628 needprompt = doprompt;
11629 RETURN(TNL);
11630 case PEOF:
11631 RETURN(TEOF);
11632 case '&':
11633 if (pgetc() == '&')
11634 RETURN(TAND);
11635 pungetc();
11636 RETURN(TBACKGND);
11637 case '|':
11638 if (pgetc() == '|')
11639 RETURN(TOR);
11640 pungetc();
11641 RETURN(TPIPE);
11642 case ';':
11643 if (pgetc() == ';')
11644 RETURN(TENDCASE);
11645 pungetc();
11646 RETURN(TSEMI);
11647 case '(':
11648 RETURN(TLP);
11649 case ')':
11650 RETURN(TRP);
11651 default:
11652 goto breakloop;
11653 }
11654 }
11655 breakloop:
11656 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11657#undef RETURN
11658}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011659#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011660
11661static int
11662readtoken(void)
11663{
11664 int t;
11665#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011666 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011667#endif
11668
11669#if ENABLE_ASH_ALIAS
11670 top:
11671#endif
11672
11673 t = xxreadtoken();
11674
11675 /*
11676 * eat newlines
11677 */
11678 if (checkkwd & CHKNL) {
11679 while (t == TNL) {
11680 parseheredoc();
11681 t = xxreadtoken();
11682 }
11683 }
11684
11685 if (t != TWORD || quoteflag) {
11686 goto out;
11687 }
11688
11689 /*
11690 * check for keywords
11691 */
11692 if (checkkwd & CHKKWD) {
11693 const char *const *pp;
11694
11695 pp = findkwd(wordtext);
11696 if (pp) {
11697 lasttoken = t = pp - tokname_array;
11698 TRACE(("keyword %s recognized\n", tokname(t)));
11699 goto out;
11700 }
11701 }
11702
11703 if (checkkwd & CHKALIAS) {
11704#if ENABLE_ASH_ALIAS
11705 struct alias *ap;
11706 ap = lookupalias(wordtext, 1);
11707 if (ap != NULL) {
11708 if (*ap->val) {
11709 pushstring(ap->val, ap);
11710 }
11711 goto top;
11712 }
11713#endif
11714 }
11715 out:
11716 checkkwd = 0;
11717#if DEBUG
11718 if (!alreadyseen)
11719 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11720 else
11721 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11722#endif
11723 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011724}
11725
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011726static char
11727peektoken(void)
11728{
11729 int t;
11730
11731 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011732 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011733 return tokname_array[t][0];
11734}
Eric Andersencb57d552001-06-28 07:25:16 +000011735
11736/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011737 * Read and parse a command. Returns NODE_EOF on end of file.
11738 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011739 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011740static union node *
11741parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011742{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011743 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011744
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011745 tokpushback = 0;
11746 doprompt = interact;
11747 if (doprompt)
11748 setprompt(doprompt);
11749 needprompt = 0;
11750 t = readtoken();
11751 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011752 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011753 if (t == TNL)
11754 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011755 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011756 return list(1);
11757}
11758
11759/*
11760 * Input any here documents.
11761 */
11762static void
11763parseheredoc(void)
11764{
11765 struct heredoc *here;
11766 union node *n;
11767
11768 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011769 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011770
11771 while (here) {
11772 if (needprompt) {
11773 setprompt(2);
11774 }
11775 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11776 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011777 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011778 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011779 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011780 n->narg.text = wordtext;
11781 n->narg.backquote = backquotelist;
11782 here->here->nhere.doc = n;
11783 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011784 }
Eric Andersencb57d552001-06-28 07:25:16 +000011785}
11786
11787
11788/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011789 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011790 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011791#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011792static const char *
11793expandstr(const char *ps)
11794{
11795 union node n;
11796
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011797 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11798 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011799 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011800 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011801 popfile();
11802
11803 n.narg.type = NARG;
11804 n.narg.next = NULL;
11805 n.narg.text = wordtext;
11806 n.narg.backquote = backquotelist;
11807
11808 expandarg(&n, NULL, 0);
11809 return stackblock();
11810}
11811#endif
11812
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011813/*
11814 * Execute a command or commands contained in a string.
11815 */
11816static int
11817evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011818{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011819 union node *n;
11820 struct stackmark smark;
11821 int skip;
11822
11823 setinputstring(s);
11824 setstackmark(&smark);
11825
11826 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011827 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011828 evaltree(n, 0);
11829 popstackmark(&smark);
11830 skip = evalskip;
11831 if (skip)
11832 break;
11833 }
11834 popfile();
11835
11836 skip &= mask;
11837 evalskip = skip;
11838 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011839}
11840
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011841/*
11842 * The eval command.
11843 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011844static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011845evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011846{
11847 char *p;
11848 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011849
Denis Vlasenko68404f12008-03-17 09:00:54 +000011850 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011851 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011852 argv += 2;
11853 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011854 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011855 for (;;) {
11856 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011857 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011858 if (p == NULL)
11859 break;
11860 STPUTC(' ', concat);
11861 }
11862 STPUTC('\0', concat);
11863 p = grabstackstr(concat);
11864 }
11865 evalstring(p, ~SKIPEVAL);
11866
11867 }
11868 return exitstatus;
11869}
11870
11871/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011872 * Read and execute commands.
11873 * "Top" is nonzero for the top level command loop;
11874 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011875 */
11876static int
11877cmdloop(int top)
11878{
11879 union node *n;
11880 struct stackmark smark;
11881 int inter;
11882 int numeof = 0;
11883
11884 TRACE(("cmdloop(%d) called\n", top));
11885 for (;;) {
11886 int skip;
11887
11888 setstackmark(&smark);
11889#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011890 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011891 showjobs(stderr, SHOW_CHANGED);
11892#endif
11893 inter = 0;
11894 if (iflag && top) {
11895 inter++;
11896#if ENABLE_ASH_MAIL
11897 chkmail();
11898#endif
11899 }
11900 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011901#if DEBUG
11902 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011903 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011904#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011905 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011906 if (!top || numeof >= 50)
11907 break;
11908 if (!stoppedjobs()) {
11909 if (!Iflag)
11910 break;
11911 out2str("\nUse \"exit\" to leave shell.\n");
11912 }
11913 numeof++;
11914 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011915 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11916 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011917 numeof = 0;
11918 evaltree(n, 0);
11919 }
11920 popstackmark(&smark);
11921 skip = evalskip;
11922
11923 if (skip) {
11924 evalskip = 0;
11925 return skip & SKIPEVAL;
11926 }
11927 }
11928 return 0;
11929}
11930
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011931/*
11932 * Take commands from a file. To be compatible we should do a path
11933 * search for the file, which is necessary to find sub-commands.
11934 */
11935static char *
11936find_dot_file(char *name)
11937{
11938 char *fullname;
11939 const char *path = pathval();
11940 struct stat statb;
11941
11942 /* don't try this for absolute or relative paths */
11943 if (strchr(name, '/'))
11944 return name;
11945
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011946 /* IIRC standards do not say whether . is to be searched.
11947 * And it is even smaller this way, making it unconditional for now:
11948 */
11949 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11950 fullname = name;
11951 goto try_cur_dir;
11952 }
11953
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011954 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011955 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011956 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11957 /*
11958 * Don't bother freeing here, since it will
11959 * be freed by the caller.
11960 */
11961 return fullname;
11962 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011963 if (fullname != name)
11964 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011965 }
11966
11967 /* not found in the PATH */
11968 ash_msg_and_raise_error("%s: not found", name);
11969 /* NOTREACHED */
11970}
11971
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011972static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011973dotcmd(int argc, char **argv)
11974{
11975 struct strlist *sp;
11976 volatile struct shparam saveparam;
11977 int status = 0;
11978
11979 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011980 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011981
Denis Vlasenko68404f12008-03-17 09:00:54 +000011982 if (argv[1]) { /* That's what SVR2 does */
11983 char *fullname = find_dot_file(argv[1]);
11984 argv += 2;
11985 argc -= 2;
11986 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011987 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011988 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011989 shellparam.nparam = argc;
11990 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011991 };
11992
11993 setinputfile(fullname, INPUT_PUSH_FILE);
11994 commandname = fullname;
11995 cmdloop(0);
11996 popfile();
11997
Denis Vlasenko68404f12008-03-17 09:00:54 +000011998 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011999 freeparam(&shellparam);
12000 shellparam = saveparam;
12001 };
12002 status = exitstatus;
12003 }
12004 return status;
12005}
12006
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012007static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012008exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012009{
12010 if (stoppedjobs())
12011 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012012 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012013 exitstatus = number(argv[1]);
12014 raise_exception(EXEXIT);
12015 /* NOTREACHED */
12016}
12017
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012018/*
12019 * Read a file containing shell functions.
12020 */
12021static void
12022readcmdfile(char *name)
12023{
12024 setinputfile(name, INPUT_PUSH_FILE);
12025 cmdloop(0);
12026 popfile();
12027}
12028
12029
Denis Vlasenkocc571512007-02-23 21:10:35 +000012030/* ============ find_command inplementation */
12031
12032/*
12033 * Resolve a command name. If you change this routine, you may have to
12034 * change the shellexec routine as well.
12035 */
12036static void
12037find_command(char *name, struct cmdentry *entry, int act, const char *path)
12038{
12039 struct tblentry *cmdp;
12040 int idx;
12041 int prev;
12042 char *fullname;
12043 struct stat statb;
12044 int e;
12045 int updatetbl;
12046 struct builtincmd *bcmd;
12047
12048 /* If name contains a slash, don't use PATH or hash table */
12049 if (strchr(name, '/') != NULL) {
12050 entry->u.index = -1;
12051 if (act & DO_ABS) {
12052 while (stat(name, &statb) < 0) {
12053#ifdef SYSV
12054 if (errno == EINTR)
12055 continue;
12056#endif
12057 entry->cmdtype = CMDUNKNOWN;
12058 return;
12059 }
12060 }
12061 entry->cmdtype = CMDNORMAL;
12062 return;
12063 }
12064
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012065/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012066
12067 updatetbl = (path == pathval());
12068 if (!updatetbl) {
12069 act |= DO_ALTPATH;
12070 if (strstr(path, "%builtin") != NULL)
12071 act |= DO_ALTBLTIN;
12072 }
12073
12074 /* If name is in the table, check answer will be ok */
12075 cmdp = cmdlookup(name, 0);
12076 if (cmdp != NULL) {
12077 int bit;
12078
12079 switch (cmdp->cmdtype) {
12080 default:
12081#if DEBUG
12082 abort();
12083#endif
12084 case CMDNORMAL:
12085 bit = DO_ALTPATH;
12086 break;
12087 case CMDFUNCTION:
12088 bit = DO_NOFUNC;
12089 break;
12090 case CMDBUILTIN:
12091 bit = DO_ALTBLTIN;
12092 break;
12093 }
12094 if (act & bit) {
12095 updatetbl = 0;
12096 cmdp = NULL;
12097 } else if (cmdp->rehash == 0)
12098 /* if not invalidated by cd, we're done */
12099 goto success;
12100 }
12101
12102 /* If %builtin not in path, check for builtin next */
12103 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012104 if (bcmd) {
12105 if (IS_BUILTIN_REGULAR(bcmd))
12106 goto builtin_success;
12107 if (act & DO_ALTPATH) {
12108 if (!(act & DO_ALTBLTIN))
12109 goto builtin_success;
12110 } else if (builtinloc <= 0) {
12111 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012112 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012113 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012114
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012115#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012116 {
12117 int applet_no = find_applet_by_name(name);
12118 if (applet_no >= 0) {
12119 entry->cmdtype = CMDNORMAL;
12120 entry->u.index = -2 - applet_no;
12121 return;
12122 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012123 }
12124#endif
12125
Denis Vlasenkocc571512007-02-23 21:10:35 +000012126 /* We have to search path. */
12127 prev = -1; /* where to start */
12128 if (cmdp && cmdp->rehash) { /* doing a rehash */
12129 if (cmdp->cmdtype == CMDBUILTIN)
12130 prev = builtinloc;
12131 else
12132 prev = cmdp->param.index;
12133 }
12134
12135 e = ENOENT;
12136 idx = -1;
12137 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012138 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012139 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012140 /* NB: code below will still use fullname
12141 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012142 idx++;
12143 if (pathopt) {
12144 if (prefix(pathopt, "builtin")) {
12145 if (bcmd)
12146 goto builtin_success;
12147 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012148 }
12149 if ((act & DO_NOFUNC)
12150 || !prefix(pathopt, "func")
12151 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012152 continue;
12153 }
12154 }
12155 /* if rehash, don't redo absolute path names */
12156 if (fullname[0] == '/' && idx <= prev) {
12157 if (idx < prev)
12158 continue;
12159 TRACE(("searchexec \"%s\": no change\n", name));
12160 goto success;
12161 }
12162 while (stat(fullname, &statb) < 0) {
12163#ifdef SYSV
12164 if (errno == EINTR)
12165 continue;
12166#endif
12167 if (errno != ENOENT && errno != ENOTDIR)
12168 e = errno;
12169 goto loop;
12170 }
12171 e = EACCES; /* if we fail, this will be the error */
12172 if (!S_ISREG(statb.st_mode))
12173 continue;
12174 if (pathopt) { /* this is a %func directory */
12175 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012176 /* NB: stalloc will return space pointed by fullname
12177 * (because we don't have any intervening allocations
12178 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012179 readcmdfile(fullname);
12180 cmdp = cmdlookup(name, 0);
12181 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12182 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12183 stunalloc(fullname);
12184 goto success;
12185 }
12186 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12187 if (!updatetbl) {
12188 entry->cmdtype = CMDNORMAL;
12189 entry->u.index = idx;
12190 return;
12191 }
12192 INT_OFF;
12193 cmdp = cmdlookup(name, 1);
12194 cmdp->cmdtype = CMDNORMAL;
12195 cmdp->param.index = idx;
12196 INT_ON;
12197 goto success;
12198 }
12199
12200 /* We failed. If there was an entry for this command, delete it */
12201 if (cmdp && updatetbl)
12202 delete_cmd_entry();
12203 if (act & DO_ERR)
12204 ash_msg("%s: %s", name, errmsg(e, "not found"));
12205 entry->cmdtype = CMDUNKNOWN;
12206 return;
12207
12208 builtin_success:
12209 if (!updatetbl) {
12210 entry->cmdtype = CMDBUILTIN;
12211 entry->u.cmd = bcmd;
12212 return;
12213 }
12214 INT_OFF;
12215 cmdp = cmdlookup(name, 1);
12216 cmdp->cmdtype = CMDBUILTIN;
12217 cmdp->param.cmd = bcmd;
12218 INT_ON;
12219 success:
12220 cmdp->rehash = 0;
12221 entry->cmdtype = cmdp->cmdtype;
12222 entry->u = cmdp->param;
12223}
12224
12225
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012226/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012227
Eric Andersencb57d552001-06-28 07:25:16 +000012228/*
Eric Andersencb57d552001-06-28 07:25:16 +000012229 * The trap builtin.
12230 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012231static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012232trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012233{
12234 char *action;
12235 char **ap;
12236 int signo;
12237
Eric Andersenc470f442003-07-28 09:56:35 +000012238 nextopt(nullstr);
12239 ap = argptr;
12240 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012241 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012242 char *tr = trap_ptr[signo];
12243 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012244 /* note: bash adds "SIG", but only if invoked
12245 * as "bash". If called as "sh", or if set -o posix,
12246 * then it prints short signal names.
12247 * We are printing short names: */
12248 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012249 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012250 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012251 /* trap_ptr != trap only if we are in special-cased `trap` code.
12252 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012253 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012254 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012255 }
12256 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012257 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012258 if (trap_ptr != trap) {
12259 free(trap_ptr);
12260 trap_ptr = trap;
12261 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012262 */
Eric Andersencb57d552001-06-28 07:25:16 +000012263 return 0;
12264 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012265
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012266 action = NULL;
12267 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012268 action = *ap++;
12269 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012270 signo = get_signum(*ap);
12271 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012272 ash_msg_and_raise_error("%s: bad trap", *ap);
12273 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012274 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012275 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012276 action = NULL;
12277 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012278 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012279 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012280 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012281 trap[signo] = action;
12282 if (signo != 0)
12283 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012284 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012285 ap++;
12286 }
12287 return 0;
12288}
12289
Eric Andersenc470f442003-07-28 09:56:35 +000012290
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012291/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012292
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012293#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012294/*
12295 * Lists available builtins
12296 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012297static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012298helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012299{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012300 unsigned col;
12301 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012302
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012303 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012304 "Built-in commands:\n"
12305 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012306 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012307 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012308 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012309 if (col > 60) {
12310 out1fmt("\n");
12311 col = 0;
12312 }
12313 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012314#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012315 {
12316 const char *a = applet_names;
12317 while (*a) {
12318 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12319 if (col > 60) {
12320 out1fmt("\n");
12321 col = 0;
12322 }
12323 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012324 }
12325 }
12326#endif
12327 out1fmt("\n\n");
12328 return EXIT_SUCCESS;
12329}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012330#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012331
Eric Andersencb57d552001-06-28 07:25:16 +000012332/*
Eric Andersencb57d552001-06-28 07:25:16 +000012333 * The export and readonly commands.
12334 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012335static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012336exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012337{
12338 struct var *vp;
12339 char *name;
12340 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012341 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012342 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012343
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012344 if (nextopt("p") != 'p') {
12345 aptr = argptr;
12346 name = *aptr;
12347 if (name) {
12348 do {
12349 p = strchr(name, '=');
12350 if (p != NULL) {
12351 p++;
12352 } else {
12353 vp = *findvar(hashvar(name), name);
12354 if (vp) {
12355 vp->flags |= flag;
12356 continue;
12357 }
Eric Andersencb57d552001-06-28 07:25:16 +000012358 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012359 setvar(name, p, flag);
12360 } while ((name = *++aptr) != NULL);
12361 return 0;
12362 }
Eric Andersencb57d552001-06-28 07:25:16 +000012363 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012364 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012365 return 0;
12366}
12367
Eric Andersencb57d552001-06-28 07:25:16 +000012368/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012369 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012370 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012371static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012372unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012373{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012374 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012375
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012376 cmdp = cmdlookup(name, 0);
12377 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12378 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012379}
12380
Eric Andersencb57d552001-06-28 07:25:16 +000012381/*
Eric Andersencb57d552001-06-28 07:25:16 +000012382 * The unset builtin command. We unset the function before we unset the
12383 * variable to allow a function to be unset when there is a readonly variable
12384 * with the same name.
12385 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012386static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012387unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012388{
12389 char **ap;
12390 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012391 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012392 int ret = 0;
12393
12394 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012395 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012396 }
Eric Andersencb57d552001-06-28 07:25:16 +000012397
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012398 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012399 if (flag != 'f') {
12400 i = unsetvar(*ap);
12401 ret |= i;
12402 if (!(i & 2))
12403 continue;
12404 }
12405 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012406 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012407 }
Eric Andersenc470f442003-07-28 09:56:35 +000012408 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012409}
12410
12411
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012412/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012413
Eric Andersenc470f442003-07-28 09:56:35 +000012414#include <sys/times.h>
12415
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012416static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012417 ' ', offsetof(struct tms, tms_utime),
12418 '\n', offsetof(struct tms, tms_stime),
12419 ' ', offsetof(struct tms, tms_cutime),
12420 '\n', offsetof(struct tms, tms_cstime),
12421 0
12422};
Eric Andersencb57d552001-06-28 07:25:16 +000012423
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012424static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012425timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012426{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012427 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012428 const unsigned char *p;
12429 struct tms buf;
12430
12431 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012432 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012433
12434 p = timescmd_str;
12435 do {
12436 t = *(clock_t *)(((char *) &buf) + p[1]);
12437 s = t / clk_tck;
12438 out1fmt("%ldm%ld.%.3lds%c",
12439 s/60, s%60,
12440 ((t - s * clk_tck) * 1000) / clk_tck,
12441 p[0]);
12442 } while (*(p += 2));
12443
Eric Andersencb57d552001-06-28 07:25:16 +000012444 return 0;
12445}
12446
Mike Frysinger98c52642009-04-02 10:02:37 +000012447#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012448/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012449 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12450 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012451 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012452 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012453 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012454static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012455letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012456{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012457 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012458
Denis Vlasenko68404f12008-03-17 09:00:54 +000012459 argv++;
12460 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012461 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012462 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012463 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012464 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012465
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012466 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012467}
Mike Frysinger98c52642009-04-02 10:02:37 +000012468#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012469
Eric Andersenc470f442003-07-28 09:56:35 +000012470
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012471/* ============ miscbltin.c
12472 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012473 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012474 */
12475
12476#undef rflag
12477
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012478#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012479typedef enum __rlimit_resource rlim_t;
12480#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012481
Eric Andersenc470f442003-07-28 09:56:35 +000012482/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012483 * The read builtin. Options:
12484 * -r Do not interpret '\' specially
12485 * -s Turn off echo (tty only)
12486 * -n NCHARS Read NCHARS max
12487 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12488 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12489 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012490 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012491 * TODO: bash also has:
12492 * -a ARRAY Read into array[0],[1],etc
12493 * -d DELIM End on DELIM char, not newline
12494 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012495 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012496static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012497readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012498{
Denys Vlasenko73067272010-01-12 22:11:24 +010012499 char *opt_n = NULL;
12500 char *opt_p = NULL;
12501 char *opt_t = NULL;
12502 char *opt_u = NULL;
12503 int read_flags = 0;
12504 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012505 int i;
12506
Denys Vlasenko73067272010-01-12 22:11:24 +010012507 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012508 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012509 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012510 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012511 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012512 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012513 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012514 break;
12515 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012516 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012517 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012518 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012519 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012520 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012521 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012522 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012523 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012524 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012525 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012526 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012527 default:
12528 break;
12529 }
Eric Andersenc470f442003-07-28 09:56:35 +000012530 }
Paul Fox02eb9342005-09-07 16:56:02 +000012531
Denys Vlasenko03dad222010-01-12 23:29:57 +010012532 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012533 argptr,
12534 bltinlookup("IFS"), /* can be NULL */
12535 read_flags,
12536 opt_n,
12537 opt_p,
12538 opt_t,
12539 opt_u
12540 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012541
Denys Vlasenko73067272010-01-12 22:11:24 +010012542 if ((uintptr_t)r > 1)
12543 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012544
Denys Vlasenko73067272010-01-12 22:11:24 +010012545 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012546}
12547
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012548static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012549umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012550{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012551 static const char permuser[3] ALIGN1 = "ugo";
12552 static const char permmode[3] ALIGN1 = "rwx";
12553 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012554 S_IRUSR, S_IWUSR, S_IXUSR,
12555 S_IRGRP, S_IWGRP, S_IXGRP,
12556 S_IROTH, S_IWOTH, S_IXOTH
12557 };
12558
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012559 /* TODO: use bb_parse_mode() instead */
12560
Eric Andersenc470f442003-07-28 09:56:35 +000012561 char *ap;
12562 mode_t mask;
12563 int i;
12564 int symbolic_mode = 0;
12565
12566 while (nextopt("S") != '\0') {
12567 symbolic_mode = 1;
12568 }
12569
Denis Vlasenkob012b102007-02-19 22:43:01 +000012570 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012571 mask = umask(0);
12572 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012573 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012574
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012575 ap = *argptr;
12576 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012577 if (symbolic_mode) {
12578 char buf[18];
12579 char *p = buf;
12580
12581 for (i = 0; i < 3; i++) {
12582 int j;
12583
12584 *p++ = permuser[i];
12585 *p++ = '=';
12586 for (j = 0; j < 3; j++) {
12587 if ((mask & permmask[3 * i + j]) == 0) {
12588 *p++ = permmode[j];
12589 }
12590 }
12591 *p++ = ',';
12592 }
12593 *--p = 0;
12594 puts(buf);
12595 } else {
12596 out1fmt("%.4o\n", mask);
12597 }
12598 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012599 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012600 mask = 0;
12601 do {
12602 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012603 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012604 mask = (mask << 3) + (*ap - '0');
12605 } while (*++ap != '\0');
12606 umask(mask);
12607 } else {
12608 mask = ~mask & 0777;
12609 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012610 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012611 }
12612 umask(~mask & 0777);
12613 }
12614 }
12615 return 0;
12616}
12617
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012618static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012619ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012620{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012621 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012622}
12623
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012624/* ============ main() and helpers */
12625
12626/*
12627 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012628 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012629static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012630static void
12631exitshell(void)
12632{
12633 struct jmploc loc;
12634 char *p;
12635 int status;
12636
12637 status = exitstatus;
12638 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12639 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012640 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012641/* dash bug: it just does _exit(exitstatus) here
12642 * but we have to do setjobctl(0) first!
12643 * (bug is still not fixed in dash-0.5.3 - if you run dash
12644 * under Midnight Commander, on exit from dash MC is backgrounded) */
12645 status = exitstatus;
12646 goto out;
12647 }
12648 exception_handler = &loc;
12649 p = trap[0];
12650 if (p) {
12651 trap[0] = NULL;
12652 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012653 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012654 }
12655 flush_stdout_stderr();
12656 out:
12657 setjobctl(0);
12658 _exit(status);
12659 /* NOTREACHED */
12660}
12661
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012662static void
12663init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012664{
12665 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012666 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012667
12668 /* from trap.c: */
12669 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012670 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12671 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12672 */
12673 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012674
12675 /* from var.c: */
12676 {
12677 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012678 const char *p;
12679 struct stat st1, st2;
12680
12681 initvar();
12682 for (envp = environ; envp && *envp; envp++) {
12683 if (strchr(*envp, '=')) {
12684 setvareq(*envp, VEXPORT|VTEXTFIXED);
12685 }
12686 }
12687
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012688 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012689
12690 p = lookupvar("PWD");
12691 if (p)
12692 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12693 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12694 p = '\0';
12695 setpwd(p, 0);
12696 }
12697}
12698
12699/*
12700 * Process the shell command line arguments.
12701 */
12702static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012703procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012704{
12705 int i;
12706 const char *xminusc;
12707 char **xargv;
12708
12709 xargv = argv;
12710 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012711 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012712 xargv++;
12713 for (i = 0; i < NOPTS; i++)
12714 optlist[i] = 2;
12715 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012716 if (options(1)) {
12717 /* it already printed err message */
12718 raise_exception(EXERROR);
12719 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012720 xargv = argptr;
12721 xminusc = minusc;
12722 if (*xargv == NULL) {
12723 if (xminusc)
12724 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12725 sflag = 1;
12726 }
12727 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12728 iflag = 1;
12729 if (mflag == 2)
12730 mflag = iflag;
12731 for (i = 0; i < NOPTS; i++)
12732 if (optlist[i] == 2)
12733 optlist[i] = 0;
12734#if DEBUG == 2
12735 debug = 1;
12736#endif
12737 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12738 if (xminusc) {
12739 minusc = *xargv++;
12740 if (*xargv)
12741 goto setarg0;
12742 } else if (!sflag) {
12743 setinputfile(*xargv, 0);
12744 setarg0:
12745 arg0 = *xargv++;
12746 commandname = arg0;
12747 }
12748
12749 shellparam.p = xargv;
12750#if ENABLE_ASH_GETOPTS
12751 shellparam.optind = 1;
12752 shellparam.optoff = -1;
12753#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012754 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012755 while (*xargv) {
12756 shellparam.nparam++;
12757 xargv++;
12758 }
12759 optschanged();
12760}
12761
12762/*
12763 * Read /etc/profile or .profile.
12764 */
12765static void
12766read_profile(const char *name)
12767{
12768 int skip;
12769
12770 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12771 return;
12772 skip = cmdloop(0);
12773 popfile();
12774 if (skip)
12775 exitshell();
12776}
12777
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012778/*
12779 * This routine is called when an error or an interrupt occurs in an
12780 * interactive shell and control is returned to the main command loop.
12781 */
12782static void
12783reset(void)
12784{
12785 /* from eval.c: */
12786 evalskip = 0;
12787 loopnest = 0;
12788 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012789 g_parsefile->left_in_buffer = 0;
12790 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012791 popallfiles();
12792 /* from parser.c: */
12793 tokpushback = 0;
12794 checkkwd = 0;
12795 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012796 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012797}
12798
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012799#if PROFILE
12800static short profile_buf[16384];
12801extern int etext();
12802#endif
12803
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012804/*
12805 * Main routine. We initialize things, parse the arguments, execute
12806 * profiles if we're a login shell, and then call cmdloop to execute
12807 * commands. The setjmp call sets up the location to jump to when an
12808 * exception occurs. When an exception occurs the variable "state"
12809 * is used to figure out how far we had gotten.
12810 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012811int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012812int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012813{
Mike Frysinger98c52642009-04-02 10:02:37 +000012814 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012815 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012816 struct jmploc jmploc;
12817 struct stackmark smark;
12818
Denis Vlasenko01631112007-12-16 17:20:38 +000012819 /* Initialize global data */
12820 INIT_G_misc();
12821 INIT_G_memstack();
12822 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012823#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012824 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012825#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012826 INIT_G_cmdtable();
12827
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012828#if PROFILE
12829 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12830#endif
12831
12832#if ENABLE_FEATURE_EDITING
12833 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12834#endif
12835 state = 0;
12836 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012837 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012838 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012839
12840 reset();
12841
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012842 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012843 if (e == EXERROR)
12844 exitstatus = 2;
12845 s = state;
12846 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12847 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012848 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012849 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012850
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012851 popstackmark(&smark);
12852 FORCE_INT_ON; /* enable interrupts */
12853 if (s == 1)
12854 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012855 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012856 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012857 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012858 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012859 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012860 }
12861 exception_handler = &jmploc;
12862#if DEBUG
12863 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012864 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012865 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012866#endif
12867 rootpid = getpid();
12868
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012869 init();
12870 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012871 procargs(argv);
12872
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012873#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12874 if (iflag) {
12875 const char *hp = lookupvar("HISTFILE");
12876
12877 if (hp == NULL) {
12878 hp = lookupvar("HOME");
12879 if (hp != NULL) {
12880 char *defhp = concat_path_file(hp, ".ash_history");
12881 setvar("HISTFILE", defhp, 0);
12882 free(defhp);
12883 }
12884 }
12885 }
12886#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012887 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012888 isloginsh = 1;
12889 if (isloginsh) {
12890 state = 1;
12891 read_profile("/etc/profile");
12892 state1:
12893 state = 2;
12894 read_profile(".profile");
12895 }
12896 state2:
12897 state = 3;
12898 if (
12899#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012900 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012901#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012902 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012903 ) {
12904 shinit = lookupvar("ENV");
12905 if (shinit != NULL && *shinit != '\0') {
12906 read_profile(shinit);
12907 }
12908 }
12909 state3:
12910 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012911 if (minusc) {
12912 /* evalstring pushes parsefile stack.
12913 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012914 * is one of stacked source fds.
12915 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012916 if (!sflag)
12917 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012918 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012919 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012920
12921 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010012922#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000012923 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012924 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012925 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012926 line_input_state->hist_file = hp;
12927 }
12928#endif
12929 state4: /* XXX ??? - why isn't this before the "if" statement */
12930 cmdloop(1);
12931 }
12932#if PROFILE
12933 monitor(0);
12934#endif
12935#ifdef GPROF
12936 {
12937 extern void _mcleanup(void);
12938 _mcleanup();
12939 }
12940#endif
12941 exitshell();
12942 /* NOTREACHED */
12943}
12944
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012945
Eric Andersendf82f612001-06-28 07:46:40 +000012946/*-
12947 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000012948 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000012949 *
12950 * This code is derived from software contributed to Berkeley by
12951 * Kenneth Almquist.
12952 *
12953 * Redistribution and use in source and binary forms, with or without
12954 * modification, are permitted provided that the following conditions
12955 * are met:
12956 * 1. Redistributions of source code must retain the above copyright
12957 * notice, this list of conditions and the following disclaimer.
12958 * 2. Redistributions in binary form must reproduce the above copyright
12959 * notice, this list of conditions and the following disclaimer in the
12960 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000012961 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000012962 * may be used to endorse or promote products derived from this software
12963 * without specific prior written permission.
12964 *
12965 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12966 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12967 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12968 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12969 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12970 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12971 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12972 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12973 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12974 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
12975 * SUCH DAMAGE.
12976 */