blob: 613a66dbcd092c433d001dbbb7435773f454463e [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
5 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +00006 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +00007 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +00008 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +00009 * was re-ported from NetBSD and debianized.
10 *
Eric Andersencb57d552001-06-28 07:25:16 +000011 * This code is derived from software contributed to Berkeley by
12 * Kenneth Almquist.
13 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000014 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersendf82f612001-06-28 07:46:40 +000015 *
Eric Andersen81fe1232003-07-29 06:38:40 +000016 * Original BSD copyright notice is retained at the end of this file.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
37#define IFS_BROKEN
38
39#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000040
Denis Vlasenkob012b102007-02-19 22:43:01 +000041#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000042# ifndef _GNU_SOURCE
43# define _GNU_SOURCE
44# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000045#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000046
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000047#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000048//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000050#include <paths.h>
51#include <setjmp.h>
52#include <fnmatch.h>
Mike Frysinger98c52642009-04-02 10:02:37 +000053#include "math.h"
Denis Vlasenko61befda2008-11-25 01:36:03 +000054
55#if defined SINGLE_APPLET_MAIN
56/* STANDALONE does not make sense, and won't compile */
57#undef CONFIG_FEATURE_SH_STANDALONE
58#undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000059#undef IF_FEATURE_SH_STANDALONE
60#undef IF_NOT_FEATURE_SH_STANDALONE(...)
Denis Vlasenko61befda2008-11-25 01:36:03 +000061#define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000062#define IF_FEATURE_SH_STANDALONE(...)
63#define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000064#endif
65
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000066#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000067# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000068#endif
69
Denis Vlasenkob012b102007-02-19 22:43:01 +000070#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000071# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000072#endif
73
Denis Vlasenkob012b102007-02-19 22:43:01 +000074
Denis Vlasenko01631112007-12-16 17:20:38 +000075/* ============ Hash table sizes. Configurable. */
76
77#define VTABSIZE 39
78#define ATABSIZE 39
79#define CMDTABLESIZE 31 /* should be prime */
80
81
Denis Vlasenkob012b102007-02-19 22:43:01 +000082/* ============ Shell options */
83
84static const char *const optletters_optnames[] = {
85 "e" "errexit",
86 "f" "noglob",
87 "I" "ignoreeof",
88 "i" "interactive",
89 "m" "monitor",
90 "n" "noexec",
91 "s" "stdin",
92 "x" "xtrace",
93 "v" "verbose",
94 "C" "noclobber",
95 "a" "allexport",
96 "b" "notify",
97 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000098 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +000099#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000100 ,"\0" "nolog"
101 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000102#endif
103};
104
105#define optletters(n) optletters_optnames[(n)][0]
106#define optnames(n) (&optletters_optnames[(n)][1])
107
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000108enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109
Eric Andersenc470f442003-07-28 09:56:35 +0000110
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000112
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000113static const char homestr[] ALIGN1 = "HOME";
114static const char snlfmt[] ALIGN1 = "%s\n";
115static const char illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000116
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000117/*
Eric Andersenc470f442003-07-28 09:56:35 +0000118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000120 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000121 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
125 */
Eric Andersenc470f442003-07-28 09:56:35 +0000126struct jmploc {
127 jmp_buf loc;
128};
Denis Vlasenko01631112007-12-16 17:20:38 +0000129
130struct globals_misc {
131 /* pid of main shell */
132 int rootpid;
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
134 int shlvl;
135#define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
137
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
140
141 char *arg0; /* value of $0 */
142
143 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000144
145// disabled by vda: cannot understand how it was supposed to work -
146// cannot fix bugs. That's why you have to explain your non-trivial designs!
147// /* do we generate EXSIG events */
148// int exsig; /* counter */
149 volatile int suppressint; /* counter */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000150// TODO: rename
151// pendingsig -> pending_sig
152// intpending -> pending_int
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000153 volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
154 /* last pending signal */
155 volatile /*sig_atomic_t*/ smallint pendingsig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000156 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000157 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000158#define EXINT 0 /* SIGINT received */
159#define EXERROR 1 /* a generic error */
160#define EXSHELLPROC 2 /* execute a shell procedure */
161#define EXEXEC 3 /* command execution failed */
162#define EXEXIT 4 /* exit the shell */
163#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000164
Denis Vlasenko01631112007-12-16 17:20:38 +0000165 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000166 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000167
168 char optlist[NOPTS];
169#define eflag optlist[0]
170#define fflag optlist[1]
171#define Iflag optlist[2]
172#define iflag optlist[3]
173#define mflag optlist[4]
174#define nflag optlist[5]
175#define sflag optlist[6]
176#define xflag optlist[7]
177#define vflag optlist[8]
178#define Cflag optlist[9]
179#define aflag optlist[10]
180#define bflag optlist[11]
181#define uflag optlist[12]
182#define viflag optlist[13]
183#if DEBUG
184#define nolog optlist[14]
185#define debug optlist[15]
186#endif
187
188 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000189 /*
190 * Sigmode records the current value of the signal handlers for the various
191 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000192 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000193 */
194 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000195#define S_DFL 1 /* default signal handling (SIG_DFL) */
196#define S_CATCH 2 /* signal is caught */
197#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000198#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000199
Denis Vlasenko01631112007-12-16 17:20:38 +0000200 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000201 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000202 char *trap[NSIG];
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000203
204 /* Rarely referenced stuff */
205#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000206 /* Random number generators */
207 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
208 uint32_t random_LCG; /* LCG (fast but weak) */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000209#endif
210 pid_t backgndpid; /* pid of last background process */
211 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000212};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000213extern struct globals_misc *const ash_ptr_to_globals_misc;
214#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000215#define rootpid (G_misc.rootpid )
216#define shlvl (G_misc.shlvl )
217#define minusc (G_misc.minusc )
218#define curdir (G_misc.curdir )
219#define physdir (G_misc.physdir )
220#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000221#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000222#define exception_type (G_misc.exception_type )
Denis Vlasenko01631112007-12-16 17:20:38 +0000223#define suppressint (G_misc.suppressint )
224#define intpending (G_misc.intpending )
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000225//#define exsig (G_misc.exsig )
Denis Vlasenko01631112007-12-16 17:20:38 +0000226#define pendingsig (G_misc.pendingsig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000227#define isloginsh (G_misc.isloginsh )
228#define nullstr (G_misc.nullstr )
229#define optlist (G_misc.optlist )
230#define sigmode (G_misc.sigmode )
231#define gotsig (G_misc.gotsig )
232#define trap (G_misc.trap )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000233#define random_galois_LFSR (G_misc.random_galois_LFSR)
234#define random_LCG (G_misc.random_LCG )
235#define backgndpid (G_misc.backgndpid )
236#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000237#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000238 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
239 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000240 curdir = nullstr; \
241 physdir = nullstr; \
242} while (0)
243
244
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000245/* ============ DEBUG */
246#if DEBUG
247static void trace_printf(const char *fmt, ...);
248static void trace_vprintf(const char *fmt, va_list va);
249# define TRACE(param) trace_printf param
250# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000251# define close(fd) do { \
252 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000253 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200254 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000255 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000256} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000257#else
258# define TRACE(param)
259# define TRACEV(param)
260#endif
261
262
Denis Vlasenko559691a2008-10-05 18:39:31 +0000263/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
265
266/* C99 say: "char" declaration may be signed or unsigned by default */
267#define signed_char2int(sc) ((int)(signed char)(sc))
268
Denis Vlasenko559691a2008-10-05 18:39:31 +0000269static int isdigit_str9(const char *str)
270{
271 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
272 while (--maxlen && isdigit(*str))
273 str++;
274 return (*str == '\0');
275}
Denis Vlasenko01631112007-12-16 17:20:38 +0000276
Denis Vlasenko559691a2008-10-05 18:39:31 +0000277
278/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000279/*
Eric Andersen2870d962001-07-02 17:27:21 +0000280 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000281 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000282 * much more efficient and portable. (But hacking the kernel is so much
283 * more fun than worrying about efficiency and portability. :-))
284 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000285#define INT_OFF do { \
286 suppressint++; \
287 xbarrier(); \
288} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000289
290/*
291 * Called to raise an exception. Since C doesn't include exceptions, we
292 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000293 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000294 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000295static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000296static void
297raise_exception(int e)
298{
299#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000300 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301 abort();
302#endif
303 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000304 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000305 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000306}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000307#if DEBUG
308#define raise_exception(e) do { \
309 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
310 raise_exception(e); \
311} while (0)
312#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000313
314/*
315 * Called from trap.c when a SIGINT is received. (If the user specifies
316 * that SIGINT is to be trapped or ignored using the trap builtin, then
317 * this routine is not called.) Suppressint is nonzero when interrupts
318 * are held using the INT_OFF macro. (The test for iflag is just
319 * defensive programming.)
320 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000321static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000322static void
323raise_interrupt(void)
324{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000325 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000326
327 intpending = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000328 /* Signal is not automatically unmasked after it is raised,
329 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000330 sigprocmask_allsigs(SIG_UNBLOCK);
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000331 /* pendingsig = 0; - now done in onsig() */
332
Denis Vlasenko4b875702009-03-19 13:30:04 +0000333 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000334 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
335 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000336 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000337 signal(SIGINT, SIG_DFL);
338 raise(SIGINT);
339 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000340 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000341 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000342 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000343 /* NOTREACHED */
344}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000345#if DEBUG
346#define raise_interrupt() do { \
347 TRACE(("raising interrupt on line %d\n", __LINE__)); \
348 raise_interrupt(); \
349} while (0)
350#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000351
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000352static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000353int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000354{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000355 xbarrier();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000356 if (--suppressint == 0 && intpending) {
357 raise_interrupt();
358 }
359}
360#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000361static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000362force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000363{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000364 xbarrier();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000365 suppressint = 0;
366 if (intpending)
367 raise_interrupt();
368}
369#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000370
Denis Vlasenkob012b102007-02-19 22:43:01 +0000371#define SAVE_INT(v) ((v) = suppressint)
372
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000373#define RESTORE_INT(v) do { \
374 xbarrier(); \
375 suppressint = (v); \
376 if (suppressint == 0 && intpending) \
377 raise_interrupt(); \
378} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000380
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000381/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000382
Eric Andersenc470f442003-07-28 09:56:35 +0000383static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000384outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000385{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000386 INT_OFF;
387 fputs(p, file);
388 INT_ON;
389}
390
391static void
392flush_stdout_stderr(void)
393{
394 INT_OFF;
395 fflush(stdout);
396 fflush(stderr);
397 INT_ON;
398}
399
400static void
401flush_stderr(void)
402{
403 INT_OFF;
404 fflush(stderr);
405 INT_ON;
406}
407
408static void
409outcslow(int c, FILE *dest)
410{
411 INT_OFF;
412 putc(c, dest);
413 fflush(dest);
414 INT_ON;
415}
416
417static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
418static int
419out1fmt(const char *fmt, ...)
420{
421 va_list ap;
422 int r;
423
424 INT_OFF;
425 va_start(ap, fmt);
426 r = vprintf(fmt, ap);
427 va_end(ap);
428 INT_ON;
429 return r;
430}
431
432static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
433static int
434fmtstr(char *outbuf, size_t length, const char *fmt, ...)
435{
436 va_list ap;
437 int ret;
438
439 va_start(ap, fmt);
440 INT_OFF;
441 ret = vsnprintf(outbuf, length, fmt, ap);
442 va_end(ap);
443 INT_ON;
444 return ret;
445}
446
447static void
448out1str(const char *p)
449{
450 outstr(p, stdout);
451}
452
453static void
454out2str(const char *p)
455{
456 outstr(p, stderr);
457 flush_stderr();
458}
459
460
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000461/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000462
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000463/* control characters in argument strings */
464#define CTLESC '\201' /* escape next character */
465#define CTLVAR '\202' /* variable defn */
466#define CTLENDVAR '\203'
467#define CTLBACKQ '\204'
468#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
469/* CTLBACKQ | CTLQUOTE == '\205' */
470#define CTLARI '\206' /* arithmetic expression */
471#define CTLENDARI '\207'
472#define CTLQUOTEMARK '\210'
473
474/* variable substitution byte (follows CTLVAR) */
475#define VSTYPE 0x0f /* type of variable substitution */
476#define VSNUL 0x10 /* colon--treat the empty string as unset */
477#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
478
479/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000480#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
481#define VSMINUS 0x2 /* ${var-text} */
482#define VSPLUS 0x3 /* ${var+text} */
483#define VSQUESTION 0x4 /* ${var?message} */
484#define VSASSIGN 0x5 /* ${var=text} */
485#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
486#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
487#define VSTRIMLEFT 0x8 /* ${var#pattern} */
488#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
489#define VSLENGTH 0xa /* ${#var} */
490#if ENABLE_ASH_BASH_COMPAT
491#define VSSUBSTR 0xc /* ${var:position:length} */
492#define VSREPLACE 0xd /* ${var/pattern/replacement} */
493#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
494#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000495
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000496static const char dolatstr[] ALIGN1 = {
497 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
498};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000499
Denis Vlasenko559691a2008-10-05 18:39:31 +0000500#define NCMD 0
501#define NPIPE 1
502#define NREDIR 2
503#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000504#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000505#define NAND 5
506#define NOR 6
507#define NSEMI 7
508#define NIF 8
509#define NWHILE 9
510#define NUNTIL 10
511#define NFOR 11
512#define NCASE 12
513#define NCLIST 13
514#define NDEFUN 14
515#define NARG 15
516#define NTO 16
517#if ENABLE_ASH_BASH_COMPAT
518#define NTO2 17
519#endif
520#define NCLOBBER 18
521#define NFROM 19
522#define NFROMTO 20
523#define NAPPEND 21
524#define NTOFD 22
525#define NFROMFD 23
526#define NHERE 24
527#define NXHERE 25
528#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000529#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530
531union node;
532
533struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000534 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535 union node *assign;
536 union node *args;
537 union node *redirect;
538};
539
540struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000541 smallint type;
542 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000543 struct nodelist *cmdlist;
544};
545
546struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000547 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 union node *n;
549 union node *redirect;
550};
551
552struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000553 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000554 union node *ch1;
555 union node *ch2;
556};
557
558struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000559 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000560 union node *test;
561 union node *ifpart;
562 union node *elsepart;
563};
564
565struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000566 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000567 union node *args;
568 union node *body;
569 char *var;
570};
571
572struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000573 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000574 union node *expr;
575 union node *cases;
576};
577
578struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000579 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000580 union node *next;
581 union node *pattern;
582 union node *body;
583};
584
585struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000586 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000587 union node *next;
588 char *text;
589 struct nodelist *backquote;
590};
591
Denis Vlasenko559691a2008-10-05 18:39:31 +0000592/* nfile and ndup layout must match!
593 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
594 * that it is actually NTO2 (>&file), and change its type.
595 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000597 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *next;
599 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000600 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601 union node *fname;
602 char *expfname;
603};
604
605struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000606 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000607 union node *next;
608 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609 int dupfd;
610 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000611 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000612};
613
614struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000615 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000616 union node *next;
617 int fd;
618 union node *doc;
619};
620
621struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000622 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000623 union node *com;
624};
625
626union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000627 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000628 struct ncmd ncmd;
629 struct npipe npipe;
630 struct nredir nredir;
631 struct nbinary nbinary;
632 struct nif nif;
633 struct nfor nfor;
634 struct ncase ncase;
635 struct nclist nclist;
636 struct narg narg;
637 struct nfile nfile;
638 struct ndup ndup;
639 struct nhere nhere;
640 struct nnot nnot;
641};
642
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200643/*
644 * NODE_EOF is returned by parsecmd when it encounters an end of file.
645 * It must be distinct from NULL.
646 */
647#define NODE_EOF ((union node *) -1L)
648
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000649struct nodelist {
650 struct nodelist *next;
651 union node *n;
652};
653
654struct funcnode {
655 int count;
656 union node n;
657};
658
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000659/*
660 * Free a parse tree.
661 */
662static void
663freefunc(struct funcnode *f)
664{
665 if (f && --f->count < 0)
666 free(f);
667}
668
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000669
670/* ============ Debugging output */
671
672#if DEBUG
673
674static FILE *tracefile;
675
676static void
677trace_printf(const char *fmt, ...)
678{
679 va_list va;
680
681 if (debug != 1)
682 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000683 if (DEBUG_TIME)
684 fprintf(tracefile, "%u ", (int) time(NULL));
685 if (DEBUG_PID)
686 fprintf(tracefile, "[%u] ", (int) getpid());
687 if (DEBUG_SIG)
688 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000689 va_start(va, fmt);
690 vfprintf(tracefile, fmt, va);
691 va_end(va);
692}
693
694static void
695trace_vprintf(const char *fmt, va_list va)
696{
697 if (debug != 1)
698 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000699 if (DEBUG_TIME)
700 fprintf(tracefile, "%u ", (int) time(NULL));
701 if (DEBUG_PID)
702 fprintf(tracefile, "[%u] ", (int) getpid());
703 if (DEBUG_SIG)
704 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000705 vfprintf(tracefile, fmt, va);
706}
707
708static void
709trace_puts(const char *s)
710{
711 if (debug != 1)
712 return;
713 fputs(s, tracefile);
714}
715
716static void
717trace_puts_quoted(char *s)
718{
719 char *p;
720 char c;
721
722 if (debug != 1)
723 return;
724 putc('"', tracefile);
725 for (p = s; *p; p++) {
726 switch (*p) {
727 case '\n': c = 'n'; goto backslash;
728 case '\t': c = 't'; goto backslash;
729 case '\r': c = 'r'; goto backslash;
730 case '"': c = '"'; goto backslash;
731 case '\\': c = '\\'; goto backslash;
732 case CTLESC: c = 'e'; goto backslash;
733 case CTLVAR: c = 'v'; goto backslash;
734 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
735 case CTLBACKQ: c = 'q'; goto backslash;
736 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
737 backslash:
738 putc('\\', tracefile);
739 putc(c, tracefile);
740 break;
741 default:
742 if (*p >= ' ' && *p <= '~')
743 putc(*p, tracefile);
744 else {
745 putc('\\', tracefile);
746 putc(*p >> 6 & 03, tracefile);
747 putc(*p >> 3 & 07, tracefile);
748 putc(*p & 07, tracefile);
749 }
750 break;
751 }
752 }
753 putc('"', tracefile);
754}
755
756static void
757trace_puts_args(char **ap)
758{
759 if (debug != 1)
760 return;
761 if (!*ap)
762 return;
763 while (1) {
764 trace_puts_quoted(*ap);
765 if (!*++ap) {
766 putc('\n', tracefile);
767 break;
768 }
769 putc(' ', tracefile);
770 }
771}
772
773static void
774opentrace(void)
775{
776 char s[100];
777#ifdef O_APPEND
778 int flags;
779#endif
780
781 if (debug != 1) {
782 if (tracefile)
783 fflush(tracefile);
784 /* leave open because libedit might be using it */
785 return;
786 }
787 strcpy(s, "./trace");
788 if (tracefile) {
789 if (!freopen(s, "a", tracefile)) {
790 fprintf(stderr, "Can't re-open %s\n", s);
791 debug = 0;
792 return;
793 }
794 } else {
795 tracefile = fopen(s, "a");
796 if (tracefile == NULL) {
797 fprintf(stderr, "Can't open %s\n", s);
798 debug = 0;
799 return;
800 }
801 }
802#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000803 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000804 if (flags >= 0)
805 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
806#endif
807 setlinebuf(tracefile);
808 fputs("\nTracing started.\n", tracefile);
809}
810
811static void
812indent(int amount, char *pfx, FILE *fp)
813{
814 int i;
815
816 for (i = 0; i < amount; i++) {
817 if (pfx && i == amount - 1)
818 fputs(pfx, fp);
819 putc('\t', fp);
820 }
821}
822
823/* little circular references here... */
824static void shtree(union node *n, int ind, char *pfx, FILE *fp);
825
826static void
827sharg(union node *arg, FILE *fp)
828{
829 char *p;
830 struct nodelist *bqlist;
831 int subtype;
832
833 if (arg->type != NARG) {
834 out1fmt("<node type %d>\n", arg->type);
835 abort();
836 }
837 bqlist = arg->narg.backquote;
838 for (p = arg->narg.text; *p; p++) {
839 switch (*p) {
840 case CTLESC:
841 putc(*++p, fp);
842 break;
843 case CTLVAR:
844 putc('$', fp);
845 putc('{', fp);
846 subtype = *++p;
847 if (subtype == VSLENGTH)
848 putc('#', fp);
849
850 while (*p != '=')
851 putc(*p++, fp);
852
853 if (subtype & VSNUL)
854 putc(':', fp);
855
856 switch (subtype & VSTYPE) {
857 case VSNORMAL:
858 putc('}', fp);
859 break;
860 case VSMINUS:
861 putc('-', fp);
862 break;
863 case VSPLUS:
864 putc('+', fp);
865 break;
866 case VSQUESTION:
867 putc('?', fp);
868 break;
869 case VSASSIGN:
870 putc('=', fp);
871 break;
872 case VSTRIMLEFT:
873 putc('#', fp);
874 break;
875 case VSTRIMLEFTMAX:
876 putc('#', fp);
877 putc('#', fp);
878 break;
879 case VSTRIMRIGHT:
880 putc('%', fp);
881 break;
882 case VSTRIMRIGHTMAX:
883 putc('%', fp);
884 putc('%', fp);
885 break;
886 case VSLENGTH:
887 break;
888 default:
889 out1fmt("<subtype %d>", subtype);
890 }
891 break;
892 case CTLENDVAR:
893 putc('}', fp);
894 break;
895 case CTLBACKQ:
896 case CTLBACKQ|CTLQUOTE:
897 putc('$', fp);
898 putc('(', fp);
899 shtree(bqlist->n, -1, NULL, fp);
900 putc(')', fp);
901 break;
902 default:
903 putc(*p, fp);
904 break;
905 }
906 }
907}
908
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200909static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000910shcmd(union node *cmd, FILE *fp)
911{
912 union node *np;
913 int first;
914 const char *s;
915 int dftfd;
916
917 first = 1;
918 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000919 if (!first)
920 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000921 sharg(np, fp);
922 first = 0;
923 }
924 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000925 if (!first)
926 putc(' ', fp);
927 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000928 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000929 case NTO: s = ">>"+1; dftfd = 1; break;
930 case NCLOBBER: s = ">|"; dftfd = 1; break;
931 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000932#if ENABLE_ASH_BASH_COMPAT
933 case NTO2:
934#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000935 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000936 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000937 case NFROMFD: s = "<&"; break;
938 case NFROMTO: s = "<>"; break;
939 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000940 }
941 if (np->nfile.fd != dftfd)
942 fprintf(fp, "%d", np->nfile.fd);
943 fputs(s, fp);
944 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
945 fprintf(fp, "%d", np->ndup.dupfd);
946 } else {
947 sharg(np->nfile.fname, fp);
948 }
949 first = 0;
950 }
951}
952
953static void
954shtree(union node *n, int ind, char *pfx, FILE *fp)
955{
956 struct nodelist *lp;
957 const char *s;
958
959 if (n == NULL)
960 return;
961
962 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200963
964 if (n == NODE_EOF) {
965 fputs("<EOF>", fp);
966 return;
967 }
968
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000969 switch (n->type) {
970 case NSEMI:
971 s = "; ";
972 goto binop;
973 case NAND:
974 s = " && ";
975 goto binop;
976 case NOR:
977 s = " || ";
978 binop:
979 shtree(n->nbinary.ch1, ind, NULL, fp);
980 /* if (ind < 0) */
981 fputs(s, fp);
982 shtree(n->nbinary.ch2, ind, NULL, fp);
983 break;
984 case NCMD:
985 shcmd(n, fp);
986 if (ind >= 0)
987 putc('\n', fp);
988 break;
989 case NPIPE:
990 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
991 shcmd(lp->n, fp);
992 if (lp->next)
993 fputs(" | ", fp);
994 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000995 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000996 fputs(" &", fp);
997 if (ind >= 0)
998 putc('\n', fp);
999 break;
1000 default:
1001 fprintf(fp, "<node type %d>", n->type);
1002 if (ind >= 0)
1003 putc('\n', fp);
1004 break;
1005 }
1006}
1007
1008static void
1009showtree(union node *n)
1010{
1011 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001012 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001013}
1014
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001015#endif /* DEBUG */
1016
1017
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001018/* ============ Parser data */
1019
1020/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001021 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1022 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001023struct strlist {
1024 struct strlist *next;
1025 char *text;
1026};
1027
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001028struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001029
Denis Vlasenkob012b102007-02-19 22:43:01 +00001030struct strpush {
1031 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001032 char *prev_string;
1033 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034#if ENABLE_ASH_ALIAS
1035 struct alias *ap; /* if push was associated with an alias */
1036#endif
1037 char *string; /* remember the string since it may change */
1038};
1039
1040struct parsefile {
1041 struct parsefile *prev; /* preceding file on stack */
1042 int linno; /* current line */
1043 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001044 int left_in_line; /* number of chars left in this line */
1045 int left_in_buffer; /* number of chars left in this buffer past the line */
1046 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001047 char *buf; /* input buffer */
1048 struct strpush *strpush; /* for pushing strings at this level */
1049 struct strpush basestrpush; /* so pushing one is fast */
1050};
1051
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001052static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001053static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001054static int startlinno; /* line # where last token started */
1055static char *commandname; /* currently executing command */
1056static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001057static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001058
1059
1060/* ============ Message printing */
1061
1062static void
1063ash_vmsg(const char *msg, va_list ap)
1064{
1065 fprintf(stderr, "%s: ", arg0);
1066 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 if (strcmp(arg0, commandname))
1068 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001069 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001070 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001071 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072 vfprintf(stderr, msg, ap);
1073 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001074}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001075
1076/*
1077 * Exverror is called to raise the error exception. If the second argument
1078 * is not NULL then error prints an error message using printf style
1079 * formatting. It then raises the error exception.
1080 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001081static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082static void
1083ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001084{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001085#if DEBUG
1086 if (msg) {
1087 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1088 TRACEV((msg, ap));
1089 TRACE(("\") pid=%d\n", getpid()));
1090 } else
1091 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1092 if (msg)
1093#endif
1094 ash_vmsg(msg, ap);
1095
1096 flush_stdout_stderr();
1097 raise_exception(cond);
1098 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001099}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001100
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001101static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001102static void
1103ash_msg_and_raise_error(const char *msg, ...)
1104{
1105 va_list ap;
1106
1107 va_start(ap, msg);
1108 ash_vmsg_and_raise(EXERROR, msg, ap);
1109 /* NOTREACHED */
1110 va_end(ap);
1111}
1112
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001113static void raise_error_syntax(const char *) NORETURN;
1114static void
1115raise_error_syntax(const char *msg)
1116{
1117 ash_msg_and_raise_error("syntax error: %s", msg);
1118 /* NOTREACHED */
1119}
1120
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001121static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001122static void
1123ash_msg_and_raise(int cond, const char *msg, ...)
1124{
1125 va_list ap;
1126
1127 va_start(ap, msg);
1128 ash_vmsg_and_raise(cond, msg, ap);
1129 /* NOTREACHED */
1130 va_end(ap);
1131}
1132
1133/*
1134 * error/warning routines for external builtins
1135 */
1136static void
1137ash_msg(const char *fmt, ...)
1138{
1139 va_list ap;
1140
1141 va_start(ap, fmt);
1142 ash_vmsg(fmt, ap);
1143 va_end(ap);
1144}
1145
1146/*
1147 * Return a string describing an error. The returned string may be a
1148 * pointer to a static buffer that will be overwritten on the next call.
1149 * Action describes the operation that got the error.
1150 */
1151static const char *
1152errmsg(int e, const char *em)
1153{
1154 if (e == ENOENT || e == ENOTDIR) {
1155 return em;
1156 }
1157 return strerror(e);
1158}
1159
1160
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001161/* ============ Memory allocation */
1162
1163/*
1164 * It appears that grabstackstr() will barf with such alignments
1165 * because stalloc() will return a string allocated in a new stackblock.
1166 */
1167#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1168enum {
1169 /* Most machines require the value returned from malloc to be aligned
1170 * in some way. The following macro will get this right
1171 * on many machines. */
1172 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1173 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001174 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001175};
1176
1177struct stack_block {
1178 struct stack_block *prev;
1179 char space[MINSIZE];
1180};
1181
1182struct stackmark {
1183 struct stack_block *stackp;
1184 char *stacknxt;
1185 size_t stacknleft;
1186 struct stackmark *marknext;
1187};
1188
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001189
Denis Vlasenko01631112007-12-16 17:20:38 +00001190struct globals_memstack {
1191 struct stack_block *g_stackp; // = &stackbase;
1192 struct stackmark *markp;
1193 char *g_stacknxt; // = stackbase.space;
1194 char *sstrend; // = stackbase.space + MINSIZE;
1195 size_t g_stacknleft; // = MINSIZE;
1196 int herefd; // = -1;
1197 struct stack_block stackbase;
1198};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001199extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1200#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001201#define g_stackp (G_memstack.g_stackp )
1202#define markp (G_memstack.markp )
1203#define g_stacknxt (G_memstack.g_stacknxt )
1204#define sstrend (G_memstack.sstrend )
1205#define g_stacknleft (G_memstack.g_stacknleft)
1206#define herefd (G_memstack.herefd )
1207#define stackbase (G_memstack.stackbase )
1208#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001209 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1210 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001211 g_stackp = &stackbase; \
1212 g_stacknxt = stackbase.space; \
1213 g_stacknleft = MINSIZE; \
1214 sstrend = stackbase.space + MINSIZE; \
1215 herefd = -1; \
1216} while (0)
1217
1218#define stackblock() ((void *)g_stacknxt)
1219#define stackblocksize() g_stacknleft
1220
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001221
1222static void *
1223ckrealloc(void * p, size_t nbytes)
1224{
1225 p = realloc(p, nbytes);
1226 if (!p)
1227 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1228 return p;
1229}
1230
1231static void *
1232ckmalloc(size_t nbytes)
1233{
1234 return ckrealloc(NULL, nbytes);
1235}
1236
Denis Vlasenko597906c2008-02-20 16:38:54 +00001237static void *
1238ckzalloc(size_t nbytes)
1239{
1240 return memset(ckmalloc(nbytes), 0, nbytes);
1241}
1242
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001243/*
1244 * Make a copy of a string in safe storage.
1245 */
1246static char *
1247ckstrdup(const char *s)
1248{
1249 char *p = strdup(s);
1250 if (!p)
1251 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1252 return p;
1253}
1254
1255/*
1256 * Parse trees for commands are allocated in lifo order, so we use a stack
1257 * to make this more efficient, and also to avoid all sorts of exception
1258 * handling code to handle interrupts in the middle of a parse.
1259 *
1260 * The size 504 was chosen because the Ultrix malloc handles that size
1261 * well.
1262 */
1263static void *
1264stalloc(size_t nbytes)
1265{
1266 char *p;
1267 size_t aligned;
1268
1269 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001270 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001271 size_t len;
1272 size_t blocksize;
1273 struct stack_block *sp;
1274
1275 blocksize = aligned;
1276 if (blocksize < MINSIZE)
1277 blocksize = MINSIZE;
1278 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1279 if (len < blocksize)
1280 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1281 INT_OFF;
1282 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001283 sp->prev = g_stackp;
1284 g_stacknxt = sp->space;
1285 g_stacknleft = blocksize;
1286 sstrend = g_stacknxt + blocksize;
1287 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001288 INT_ON;
1289 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001290 p = g_stacknxt;
1291 g_stacknxt += aligned;
1292 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001293 return p;
1294}
1295
Denis Vlasenko597906c2008-02-20 16:38:54 +00001296static void *
1297stzalloc(size_t nbytes)
1298{
1299 return memset(stalloc(nbytes), 0, nbytes);
1300}
1301
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001302static void
1303stunalloc(void *p)
1304{
1305#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001306 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001307 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001308 abort();
1309 }
1310#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001311 g_stacknleft += g_stacknxt - (char *)p;
1312 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001313}
1314
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001315/*
1316 * Like strdup but works with the ash stack.
1317 */
1318static char *
1319ststrdup(const char *p)
1320{
1321 size_t len = strlen(p) + 1;
1322 return memcpy(stalloc(len), p, len);
1323}
1324
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001325static void
1326setstackmark(struct stackmark *mark)
1327{
Denis Vlasenko01631112007-12-16 17:20:38 +00001328 mark->stackp = g_stackp;
1329 mark->stacknxt = g_stacknxt;
1330 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001331 mark->marknext = markp;
1332 markp = mark;
1333}
1334
1335static void
1336popstackmark(struct stackmark *mark)
1337{
1338 struct stack_block *sp;
1339
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001340 if (!mark->stackp)
1341 return;
1342
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001343 INT_OFF;
1344 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001345 while (g_stackp != mark->stackp) {
1346 sp = g_stackp;
1347 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001348 free(sp);
1349 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001350 g_stacknxt = mark->stacknxt;
1351 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001352 sstrend = mark->stacknxt + mark->stacknleft;
1353 INT_ON;
1354}
1355
1356/*
1357 * When the parser reads in a string, it wants to stick the string on the
1358 * stack and only adjust the stack pointer when it knows how big the
1359 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1360 * of space on top of the stack and stackblocklen returns the length of
1361 * this block. Growstackblock will grow this space by at least one byte,
1362 * possibly moving it (like realloc). Grabstackblock actually allocates the
1363 * part of the block that has been used.
1364 */
1365static void
1366growstackblock(void)
1367{
1368 size_t newlen;
1369
Denis Vlasenko01631112007-12-16 17:20:38 +00001370 newlen = g_stacknleft * 2;
1371 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001372 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1373 if (newlen < 128)
1374 newlen += 128;
1375
Denis Vlasenko01631112007-12-16 17:20:38 +00001376 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001377 struct stack_block *oldstackp;
1378 struct stackmark *xmark;
1379 struct stack_block *sp;
1380 struct stack_block *prevstackp;
1381 size_t grosslen;
1382
1383 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001384 oldstackp = g_stackp;
1385 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001386 prevstackp = sp->prev;
1387 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1388 sp = ckrealloc(sp, grosslen);
1389 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001390 g_stackp = sp;
1391 g_stacknxt = sp->space;
1392 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001393 sstrend = sp->space + newlen;
1394
1395 /*
1396 * Stack marks pointing to the start of the old block
1397 * must be relocated to point to the new block
1398 */
1399 xmark = markp;
1400 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001401 xmark->stackp = g_stackp;
1402 xmark->stacknxt = g_stacknxt;
1403 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001404 xmark = xmark->marknext;
1405 }
1406 INT_ON;
1407 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001409 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001410 char *p = stalloc(newlen);
1411
1412 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001413 g_stacknxt = memcpy(p, oldspace, oldlen);
1414 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001415 }
1416}
1417
1418static void
1419grabstackblock(size_t len)
1420{
1421 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001422 g_stacknxt += len;
1423 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001424}
1425
1426/*
1427 * The following routines are somewhat easier to use than the above.
1428 * The user declares a variable of type STACKSTR, which may be declared
1429 * to be a register. The macro STARTSTACKSTR initializes things. Then
1430 * the user uses the macro STPUTC to add characters to the string. In
1431 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1432 * grown as necessary. When the user is done, she can just leave the
1433 * string there and refer to it using stackblock(). Or she can allocate
1434 * the space for it using grabstackstr(). If it is necessary to allow
1435 * someone else to use the stack temporarily and then continue to grow
1436 * the string, the user should use grabstack to allocate the space, and
1437 * then call ungrabstr(p) to return to the previous mode of operation.
1438 *
1439 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1440 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1441 * is space for at least one character.
1442 */
1443static void *
1444growstackstr(void)
1445{
1446 size_t len = stackblocksize();
1447 if (herefd >= 0 && len >= 1024) {
1448 full_write(herefd, stackblock(), len);
1449 return stackblock();
1450 }
1451 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001452 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001453}
1454
1455/*
1456 * Called from CHECKSTRSPACE.
1457 */
1458static char *
1459makestrspace(size_t newlen, char *p)
1460{
Denis Vlasenko01631112007-12-16 17:20:38 +00001461 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001462 size_t size = stackblocksize();
1463
1464 for (;;) {
1465 size_t nleft;
1466
1467 size = stackblocksize();
1468 nleft = size - len;
1469 if (nleft >= newlen)
1470 break;
1471 growstackblock();
1472 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001473 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001474}
1475
1476static char *
1477stack_nputstr(const char *s, size_t n, char *p)
1478{
1479 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001480 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001481 return p;
1482}
1483
1484static char *
1485stack_putstr(const char *s, char *p)
1486{
1487 return stack_nputstr(s, strlen(s), p);
1488}
1489
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001490static char *
1491_STPUTC(int c, char *p)
1492{
1493 if (p == sstrend)
1494 p = growstackstr();
1495 *p++ = c;
1496 return p;
1497}
1498
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001499#define STARTSTACKSTR(p) ((p) = stackblock())
1500#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001501#define CHECKSTRSPACE(n, p) do { \
1502 char *q = (p); \
1503 size_t l = (n); \
1504 size_t m = sstrend - q; \
1505 if (l > m) \
1506 (p) = makestrspace(l, q); \
1507} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001508#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001509#define STACKSTRNUL(p) do { \
1510 if ((p) == sstrend) \
1511 (p) = growstackstr(); \
1512 *(p) = '\0'; \
1513} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001514#define STUNPUTC(p) (--(p))
1515#define STTOPC(p) ((p)[-1])
1516#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001517
1518#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001519#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001520#define stackstrend() ((void *)sstrend)
1521
1522
1523/* ============ String helpers */
1524
1525/*
1526 * prefix -- see if pfx is a prefix of string.
1527 */
1528static char *
1529prefix(const char *string, const char *pfx)
1530{
1531 while (*pfx) {
1532 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001533 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001534 }
1535 return (char *) string;
1536}
1537
1538/*
1539 * Check for a valid number. This should be elsewhere.
1540 */
1541static int
1542is_number(const char *p)
1543{
1544 do {
1545 if (!isdigit(*p))
1546 return 0;
1547 } while (*++p != '\0');
1548 return 1;
1549}
1550
1551/*
1552 * Convert a string of digits to an integer, printing an error message on
1553 * failure.
1554 */
1555static int
1556number(const char *s)
1557{
1558 if (!is_number(s))
1559 ash_msg_and_raise_error(illnum, s);
1560 return atoi(s);
1561}
1562
1563/*
1564 * Produce a possibly single quoted string suitable as input to the shell.
1565 * The return string is allocated on the stack.
1566 */
1567static char *
1568single_quote(const char *s)
1569{
1570 char *p;
1571
1572 STARTSTACKSTR(p);
1573
1574 do {
1575 char *q;
1576 size_t len;
1577
1578 len = strchrnul(s, '\'') - s;
1579
1580 q = p = makestrspace(len + 3, p);
1581
1582 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001583 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001584 *q++ = '\'';
1585 s += len;
1586
1587 STADJUST(q - p, p);
1588
1589 len = strspn(s, "'");
1590 if (!len)
1591 break;
1592
1593 q = p = makestrspace(len + 3, p);
1594
1595 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001596 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001597 *q++ = '"';
1598 s += len;
1599
1600 STADJUST(q - p, p);
1601 } while (*s);
1602
1603 USTPUTC(0, p);
1604
1605 return stackblock();
1606}
1607
1608
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001609/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001610
1611static char **argptr; /* argument list for builtin commands */
1612static char *optionarg; /* set by nextopt (like getopt) */
1613static char *optptr; /* used by nextopt */
1614
1615/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001616 * XXX - should get rid of. Have all builtins use getopt(3).
1617 * The library getopt must have the BSD extension static variable
1618 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001619 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001620 * Standard option processing (a la getopt) for builtin routines.
1621 * The only argument that is passed to nextopt is the option string;
1622 * the other arguments are unnecessary. It returns the character,
1623 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001624 */
1625static int
1626nextopt(const char *optstring)
1627{
1628 char *p;
1629 const char *q;
1630 char c;
1631
1632 p = optptr;
1633 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001634 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001635 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001636 if (p == NULL)
1637 return '\0';
1638 if (*p != '-')
1639 return '\0';
1640 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001641 return '\0';
1642 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001644 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001645 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001646 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001647 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001649 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001651 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001652 if (*++q == ':')
1653 q++;
1654 }
1655 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001656 if (*p == '\0') {
1657 p = *argptr++;
1658 if (p == NULL)
1659 ash_msg_and_raise_error("no arg for -%c option", c);
1660 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001661 optionarg = p;
1662 p = NULL;
1663 }
1664 optptr = p;
1665 return c;
1666}
1667
1668
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001669/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001670
Denis Vlasenko01631112007-12-16 17:20:38 +00001671/*
1672 * The parsefile structure pointed to by the global variable parsefile
1673 * contains information about the current file being read.
1674 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001675struct shparam {
1676 int nparam; /* # of positional parameters (without $0) */
1677#if ENABLE_ASH_GETOPTS
1678 int optind; /* next parameter to be processed by getopts */
1679 int optoff; /* used by getopts */
1680#endif
1681 unsigned char malloced; /* if parameter list dynamically allocated */
1682 char **p; /* parameter list */
1683};
1684
1685/*
1686 * Free the list of positional parameters.
1687 */
1688static void
1689freeparam(volatile struct shparam *param)
1690{
Denis Vlasenko01631112007-12-16 17:20:38 +00001691 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001692 char **ap, **ap1;
1693 ap = ap1 = param->p;
1694 while (*ap)
1695 free(*ap++);
1696 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001697 }
1698}
1699
1700#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001701static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001702#endif
1703
1704struct var {
1705 struct var *next; /* next entry in hash list */
1706 int flags; /* flags are defined above */
1707 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001708 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001709 /* the variable gets set/unset */
1710};
1711
1712struct localvar {
1713 struct localvar *next; /* next local variable in list */
1714 struct var *vp; /* the variable that was made local */
1715 int flags; /* saved flags */
1716 const char *text; /* saved text */
1717};
1718
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001719/* flags */
1720#define VEXPORT 0x01 /* variable is exported */
1721#define VREADONLY 0x02 /* variable cannot be modified */
1722#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1723#define VTEXTFIXED 0x08 /* text is statically allocated */
1724#define VSTACK 0x10 /* text is allocated on the stack */
1725#define VUNSET 0x20 /* the variable is not set */
1726#define VNOFUNC 0x40 /* don't call the callback function */
1727#define VNOSET 0x80 /* do not set variable - just readonly test */
1728#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001729#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001730# define VDYNAMIC 0x200 /* dynamic variable */
1731#else
1732# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001733#endif
1734
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001735#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001736static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001737#define defifs (defifsvar + 4)
1738#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001739static const char defifs[] ALIGN1 = " \t\n";
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 Vlasenkoaa744452007-02-23 01:04:22 +00001772#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001773 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001775 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1779 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001780#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001781 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1782 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1784 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001786 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001787#endif
1788#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001789 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#endif
1791#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1793 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001796 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001797#endif
1798};
1799
Denis Vlasenko0b769642008-07-24 07:54:57 +00001800struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001801
1802struct globals_var {
1803 struct shparam shellparam; /* $@ current positional parameters */
1804 struct redirtab *redirlist;
1805 int g_nullredirs;
1806 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1807 struct var *vartab[VTABSIZE];
1808 struct var varinit[ARRAY_SIZE(varinit_data)];
1809};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001810extern struct globals_var *const ash_ptr_to_globals_var;
1811#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001812#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001813//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001814#define g_nullredirs (G_var.g_nullredirs )
1815#define preverrout_fd (G_var.preverrout_fd)
1816#define vartab (G_var.vartab )
1817#define varinit (G_var.varinit )
1818#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001819 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001820 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1821 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001822 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1823 varinit[i].flags = varinit_data[i].flags; \
1824 varinit[i].text = varinit_data[i].text; \
1825 varinit[i].func = varinit_data[i].func; \
1826 } \
1827} while (0)
1828
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001829#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001830#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001831# define vmail (&vifs)[1]
1832# define vmpath (&vmail)[1]
1833# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001835# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001836#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001837#define vps1 (&vpath)[1]
1838#define vps2 (&vps1)[1]
1839#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001840#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001841# define voptind (&vps4)[1]
1842# if ENABLE_ASH_RANDOM_SUPPORT
1843# define vrandom (&voptind)[1]
1844# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001846# if ENABLE_ASH_RANDOM_SUPPORT
1847# define vrandom (&vps4)[1]
1848# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001850
1851/*
1852 * The following macros access the values of the above variables.
1853 * They have to skip over the name. They return the null string
1854 * for unset variables.
1855 */
1856#define ifsval() (vifs.text + 4)
1857#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001858#if ENABLE_ASH_MAIL
1859# define mailval() (vmail.text + 5)
1860# define mpathval() (vmpath.text + 9)
1861# define mpathset() ((vmpath.flags & VUNSET) == 0)
1862#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001863#define pathval() (vpath.text + 5)
1864#define ps1val() (vps1.text + 4)
1865#define ps2val() (vps2.text + 4)
1866#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001867#if ENABLE_ASH_GETOPTS
1868# define optindval() (voptind.text + 7)
1869#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001871
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001872#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1873#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1874
Denis Vlasenko01631112007-12-16 17:20:38 +00001875#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001876static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001877getoptsreset(const char *value)
1878{
1879 shellparam.optind = number(value);
1880 shellparam.optoff = -1;
1881}
1882#endif
1883
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001884/*
1885 * Return of a legal variable name (a letter or underscore followed by zero or
1886 * more letters, underscores, and digits).
1887 */
1888static char *
1889endofname(const char *name)
1890{
1891 char *p;
1892
1893 p = (char *) name;
1894 if (!is_name(*p))
1895 return p;
1896 while (*++p) {
1897 if (!is_in_name(*p))
1898 break;
1899 }
1900 return p;
1901}
1902
1903/*
1904 * Compares two strings up to the first = or '\0'. The first
1905 * string must be terminated by '='; the second may be terminated by
1906 * either '=' or '\0'.
1907 */
1908static int
1909varcmp(const char *p, const char *q)
1910{
1911 int c, d;
1912
1913 while ((c = *p) == (d = *q)) {
1914 if (!c || c == '=')
1915 goto out;
1916 p++;
1917 q++;
1918 }
1919 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001920 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001921 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001922 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001923 out:
1924 return c - d;
1925}
1926
1927static int
1928varequal(const char *a, const char *b)
1929{
1930 return !varcmp(a, b);
1931}
1932
1933/*
1934 * Find the appropriate entry in the hash table from the name.
1935 */
1936static struct var **
1937hashvar(const char *p)
1938{
1939 unsigned hashval;
1940
1941 hashval = ((unsigned char) *p) << 4;
1942 while (*p && *p != '=')
1943 hashval += (unsigned char) *p++;
1944 return &vartab[hashval % VTABSIZE];
1945}
1946
1947static int
1948vpcmp(const void *a, const void *b)
1949{
1950 return varcmp(*(const char **)a, *(const char **)b);
1951}
1952
1953/*
1954 * This routine initializes the builtin variables.
1955 */
1956static void
1957initvar(void)
1958{
1959 struct var *vp;
1960 struct var *end;
1961 struct var **vpp;
1962
1963 /*
1964 * PS1 depends on uid
1965 */
1966#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1967 vps1.text = "PS1=\\w \\$ ";
1968#else
1969 if (!geteuid())
1970 vps1.text = "PS1=# ";
1971#endif
1972 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001973 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001974 do {
1975 vpp = hashvar(vp->text);
1976 vp->next = *vpp;
1977 *vpp = vp;
1978 } while (++vp < end);
1979}
1980
1981static struct var **
1982findvar(struct var **vpp, const char *name)
1983{
1984 for (; *vpp; vpp = &(*vpp)->next) {
1985 if (varequal((*vpp)->text, name)) {
1986 break;
1987 }
1988 }
1989 return vpp;
1990}
1991
1992/*
1993 * Find the value of a variable. Returns NULL if not set.
1994 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001995static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001996lookupvar(const char *name)
1997{
1998 struct var *v;
1999
2000 v = *findvar(hashvar(name), name);
2001 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002002#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002003 /*
2004 * Dynamic variables are implemented roughly the same way they are
2005 * in bash. Namely, they're "special" so long as they aren't unset.
2006 * As soon as they're unset, they're no longer dynamic, and dynamic
2007 * lookup will no longer happen at that point. -- PFM.
2008 */
2009 if ((v->flags & VDYNAMIC))
2010 (*v->func)(NULL);
2011#endif
2012 if (!(v->flags & VUNSET))
2013 return strchrnul(v->text, '=') + 1;
2014 }
2015 return NULL;
2016}
2017
2018/*
2019 * Search the environment of a builtin command.
2020 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002021static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002022bltinlookup(const char *name)
2023{
2024 struct strlist *sp;
2025
2026 for (sp = cmdenviron; sp; sp = sp->next) {
2027 if (varequal(sp->text, name))
2028 return strchrnul(sp->text, '=') + 1;
2029 }
2030 return lookupvar(name);
2031}
2032
2033/*
2034 * Same as setvar except that the variable and value are passed in
2035 * the first argument as name=value. Since the first argument will
2036 * be actually stored in the table, it should not be a string that
2037 * will go away.
2038 * Called with interrupts off.
2039 */
2040static void
2041setvareq(char *s, int flags)
2042{
2043 struct var *vp, **vpp;
2044
2045 vpp = hashvar(s);
2046 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2047 vp = *findvar(vpp, s);
2048 if (vp) {
2049 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2050 const char *n;
2051
2052 if (flags & VNOSAVE)
2053 free(s);
2054 n = vp->text;
2055 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2056 }
2057
2058 if (flags & VNOSET)
2059 return;
2060
2061 if (vp->func && (flags & VNOFUNC) == 0)
2062 (*vp->func)(strchrnul(s, '=') + 1);
2063
2064 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2065 free((char*)vp->text);
2066
2067 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2068 } else {
2069 if (flags & VNOSET)
2070 return;
2071 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002072 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002073 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002074 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002075 *vpp = vp;
2076 }
2077 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2078 s = ckstrdup(s);
2079 vp->text = s;
2080 vp->flags = flags;
2081}
2082
2083/*
2084 * Set the value of a variable. The flags argument is ored with the
2085 * flags of the variable. If val is NULL, the variable is unset.
2086 */
2087static void
2088setvar(const char *name, const char *val, int flags)
2089{
2090 char *p, *q;
2091 size_t namelen;
2092 char *nameeq;
2093 size_t vallen;
2094
2095 q = endofname(name);
2096 p = strchrnul(q, '=');
2097 namelen = p - name;
2098 if (!namelen || p != q)
2099 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2100 vallen = 0;
2101 if (val == NULL) {
2102 flags |= VUNSET;
2103 } else {
2104 vallen = strlen(val);
2105 }
2106 INT_OFF;
2107 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002108 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002109 if (val) {
2110 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002111 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002112 }
2113 *p = '\0';
2114 setvareq(nameeq, flags | VNOSAVE);
2115 INT_ON;
2116}
2117
2118#if ENABLE_ASH_GETOPTS
2119/*
2120 * Safe version of setvar, returns 1 on success 0 on failure.
2121 */
2122static int
2123setvarsafe(const char *name, const char *val, int flags)
2124{
2125 int err;
2126 volatile int saveint;
2127 struct jmploc *volatile savehandler = exception_handler;
2128 struct jmploc jmploc;
2129
2130 SAVE_INT(saveint);
2131 if (setjmp(jmploc.loc))
2132 err = 1;
2133 else {
2134 exception_handler = &jmploc;
2135 setvar(name, val, flags);
2136 err = 0;
2137 }
2138 exception_handler = savehandler;
2139 RESTORE_INT(saveint);
2140 return err;
2141}
2142#endif
2143
2144/*
2145 * Unset the specified variable.
2146 */
2147static int
2148unsetvar(const char *s)
2149{
2150 struct var **vpp;
2151 struct var *vp;
2152 int retval;
2153
2154 vpp = findvar(hashvar(s), s);
2155 vp = *vpp;
2156 retval = 2;
2157 if (vp) {
2158 int flags = vp->flags;
2159
2160 retval = 1;
2161 if (flags & VREADONLY)
2162 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002163#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002164 vp->flags &= ~VDYNAMIC;
2165#endif
2166 if (flags & VUNSET)
2167 goto ok;
2168 if ((flags & VSTRFIXED) == 0) {
2169 INT_OFF;
2170 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2171 free((char*)vp->text);
2172 *vpp = vp->next;
2173 free(vp);
2174 INT_ON;
2175 } else {
2176 setvar(s, 0, 0);
2177 vp->flags &= ~VEXPORT;
2178 }
2179 ok:
2180 retval = 0;
2181 }
2182 out:
2183 return retval;
2184}
2185
2186/*
2187 * Process a linked list of variable assignments.
2188 */
2189static void
2190listsetvar(struct strlist *list_set_var, int flags)
2191{
2192 struct strlist *lp = list_set_var;
2193
2194 if (!lp)
2195 return;
2196 INT_OFF;
2197 do {
2198 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002199 lp = lp->next;
2200 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002201 INT_ON;
2202}
2203
2204/*
2205 * Generate a list of variables satisfying the given conditions.
2206 */
2207static char **
2208listvars(int on, int off, char ***end)
2209{
2210 struct var **vpp;
2211 struct var *vp;
2212 char **ep;
2213 int mask;
2214
2215 STARTSTACKSTR(ep);
2216 vpp = vartab;
2217 mask = on | off;
2218 do {
2219 for (vp = *vpp; vp; vp = vp->next) {
2220 if ((vp->flags & mask) == on) {
2221 if (ep == stackstrend())
2222 ep = growstackstr();
2223 *ep++ = (char *) vp->text;
2224 }
2225 }
2226 } while (++vpp < vartab + VTABSIZE);
2227 if (ep == stackstrend())
2228 ep = growstackstr();
2229 if (end)
2230 *end = ep;
2231 *ep++ = NULL;
2232 return grabstackstr(ep);
2233}
2234
2235
2236/* ============ Path search helper
2237 *
2238 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002239 * of the path before the first call; path_advance will update
2240 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002241 * the possible path expansions in sequence. If an option (indicated by
2242 * a percent sign) appears in the path entry then the global variable
2243 * pathopt will be set to point to it; otherwise pathopt will be set to
2244 * NULL.
2245 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002246static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002247
2248static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002249path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002250{
2251 const char *p;
2252 char *q;
2253 const char *start;
2254 size_t len;
2255
2256 if (*path == NULL)
2257 return NULL;
2258 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002259 for (p = start; *p && *p != ':' && *p != '%'; p++)
2260 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002261 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2262 while (stackblocksize() < len)
2263 growstackblock();
2264 q = stackblock();
2265 if (p != start) {
2266 memcpy(q, start, p - start);
2267 q += p - start;
2268 *q++ = '/';
2269 }
2270 strcpy(q, name);
2271 pathopt = NULL;
2272 if (*p == '%') {
2273 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002274 while (*p && *p != ':')
2275 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002276 }
2277 if (*p == ':')
2278 *path = p + 1;
2279 else
2280 *path = NULL;
2281 return stalloc(len);
2282}
2283
2284
2285/* ============ Prompt */
2286
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002287static smallint doprompt; /* if set, prompt the user */
2288static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002289
2290#if ENABLE_FEATURE_EDITING
2291static line_input_t *line_input_state;
2292static const char *cmdedit_prompt;
2293static void
2294putprompt(const char *s)
2295{
2296 if (ENABLE_ASH_EXPAND_PRMT) {
2297 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002298 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002299 return;
2300 }
2301 cmdedit_prompt = s;
2302}
2303#else
2304static void
2305putprompt(const char *s)
2306{
2307 out2str(s);
2308}
2309#endif
2310
2311#if ENABLE_ASH_EXPAND_PRMT
2312/* expandstr() needs parsing machinery, so it is far away ahead... */
2313static const char *expandstr(const char *ps);
2314#else
2315#define expandstr(s) s
2316#endif
2317
2318static void
2319setprompt(int whichprompt)
2320{
2321 const char *prompt;
2322#if ENABLE_ASH_EXPAND_PRMT
2323 struct stackmark smark;
2324#endif
2325
2326 needprompt = 0;
2327
2328 switch (whichprompt) {
2329 case 1:
2330 prompt = ps1val();
2331 break;
2332 case 2:
2333 prompt = ps2val();
2334 break;
2335 default: /* 0 */
2336 prompt = nullstr;
2337 }
2338#if ENABLE_ASH_EXPAND_PRMT
2339 setstackmark(&smark);
2340 stalloc(stackblocksize());
2341#endif
2342 putprompt(expandstr(prompt));
2343#if ENABLE_ASH_EXPAND_PRMT
2344 popstackmark(&smark);
2345#endif
2346}
2347
2348
2349/* ============ The cd and pwd commands */
2350
2351#define CD_PHYSICAL 1
2352#define CD_PRINT 2
2353
2354static int docd(const char *, int);
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';
2363 while ((i = nextopt("LP"))) {
2364 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{
2486 const char *dir = 0;
2487 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
Denis Vlasenko131ae172007-02-18 13:00:19 +00002612#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002613#define SYNBASE 130
2614#define PEOF -130
2615#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002616#define PEOA_OR_PEOF PEOA
2617#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002618#define SYNBASE 129
2619#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002620#define PEOA_OR_PEOF PEOF
2621#endif
2622
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002623/* number syntax index */
2624#define BASESYNTAX 0 /* not in quotes */
2625#define DQSYNTAX 1 /* in double quotes */
2626#define SQSYNTAX 2 /* in single quotes */
2627#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002628#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002629
Denis Vlasenko131ae172007-02-18 13:00:19 +00002630#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002631#define USE_SIT_FUNCTION
2632#endif
2633
Mike Frysinger98c52642009-04-02 10:02:37 +00002634#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002635static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002636#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002637 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002638#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002639 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2640 { CNL, CNL, CNL, CNL }, /* 2, \n */
2641 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2642 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2643 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2644 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2645 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2646 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2647 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2648 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2649 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002650#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002651 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2652 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2653 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002654#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002655};
Eric Andersenc470f442003-07-28 09:56:35 +00002656#else
2657static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002658#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002659 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002660#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002661 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2662 { CNL, CNL, CNL }, /* 2, \n */
2663 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2664 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2665 { CVAR, CVAR, CWORD }, /* 5, $ */
2666 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2667 { CSPCL, CWORD, CWORD }, /* 7, ( */
2668 { CSPCL, CWORD, CWORD }, /* 8, ) */
2669 { CBACK, CBACK, CCTL }, /* 9, \ */
2670 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2671 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002672#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002673 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2674 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2675 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002676#endif
2677};
Mike Frysinger98c52642009-04-02 10:02:37 +00002678#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002679
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002680#ifdef USE_SIT_FUNCTION
2681
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002682static int
2683SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002684{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002685 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002686#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002687 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002688 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2689 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2690 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2691 11, 3 /* "}~" */
2692 };
2693#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002694 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002695 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2696 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2697 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2698 10, 2 /* "}~" */
2699 };
2700#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002701 const char *s;
2702 int indx;
2703
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002704 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002705 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002706 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002707#if ENABLE_ASH_ALIAS
2708 if (c == PEOA) { /* 2^8+1 */
2709 indx = 0;
2710 } else
2711#endif
2712 {
2713 if ((unsigned char)c >= (unsigned char)(CTLESC)
2714 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2715 ) {
2716 return CCTL;
2717 }
2718 s = strchrnul(spec_symbls, c);
2719 if (*s == '\0') {
2720 return CWORD;
2721 }
2722 indx = syntax_index_table[s - spec_symbls];
2723 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002724 return S_I_T[indx][syntax];
2725}
2726
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002727#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002728
Denis Vlasenko131ae172007-02-18 13:00:19 +00002729#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002730#define CSPCL_CIGN_CIGN_CIGN 0
2731#define CSPCL_CWORD_CWORD_CWORD 1
2732#define CNL_CNL_CNL_CNL 2
2733#define CWORD_CCTL_CCTL_CWORD 3
2734#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2735#define CVAR_CVAR_CWORD_CVAR 5
2736#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2737#define CSPCL_CWORD_CWORD_CLP 7
2738#define CSPCL_CWORD_CWORD_CRP 8
2739#define CBACK_CBACK_CCTL_CBACK 9
2740#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2741#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2742#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2743#define CWORD_CWORD_CWORD_CWORD 13
2744#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002745#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002746#define CSPCL_CWORD_CWORD_CWORD 0
2747#define CNL_CNL_CNL_CNL 1
2748#define CWORD_CCTL_CCTL_CWORD 2
2749#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2750#define CVAR_CVAR_CWORD_CVAR 4
2751#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2752#define CSPCL_CWORD_CWORD_CLP 6
2753#define CSPCL_CWORD_CWORD_CRP 7
2754#define CBACK_CBACK_CCTL_CBACK 8
2755#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2756#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2757#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2758#define CWORD_CWORD_CWORD_CWORD 12
2759#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002760#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002761
2762static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002763 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002764 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002765#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002766 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2767#endif
2768 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2770 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2771 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2772 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2773 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2774 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2775 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2776 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002777 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2907 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002930 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002931 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2933 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002935 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002936 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2937 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2938 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2941 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2943 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2955 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2956 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2957 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2959 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2960 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2988 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2989 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2990 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2993 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3021 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3022 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3023 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003024};
3025
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003026#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003027
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003028#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003029
Eric Andersen2870d962001-07-02 17:27:21 +00003030
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003031/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003032
Denis Vlasenko131ae172007-02-18 13:00:19 +00003033#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003034
3035#define ALIASINUSE 1
3036#define ALIASDEAD 2
3037
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003038struct alias {
3039 struct alias *next;
3040 char *name;
3041 char *val;
3042 int flag;
3043};
3044
Denis Vlasenko01631112007-12-16 17:20:38 +00003045
3046static struct alias **atab; // [ATABSIZE];
3047#define INIT_G_alias() do { \
3048 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3049} while (0)
3050
Eric Andersen2870d962001-07-02 17:27:21 +00003051
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003052static struct alias **
3053__lookupalias(const char *name) {
3054 unsigned int hashval;
3055 struct alias **app;
3056 const char *p;
3057 unsigned int ch;
3058
3059 p = name;
3060
3061 ch = (unsigned char)*p;
3062 hashval = ch << 4;
3063 while (ch) {
3064 hashval += ch;
3065 ch = (unsigned char)*++p;
3066 }
3067 app = &atab[hashval % ATABSIZE];
3068
3069 for (; *app; app = &(*app)->next) {
3070 if (strcmp(name, (*app)->name) == 0) {
3071 break;
3072 }
3073 }
3074
3075 return app;
3076}
3077
3078static struct alias *
3079lookupalias(const char *name, int check)
3080{
3081 struct alias *ap = *__lookupalias(name);
3082
3083 if (check && ap && (ap->flag & ALIASINUSE))
3084 return NULL;
3085 return ap;
3086}
3087
3088static struct alias *
3089freealias(struct alias *ap)
3090{
3091 struct alias *next;
3092
3093 if (ap->flag & ALIASINUSE) {
3094 ap->flag |= ALIASDEAD;
3095 return ap;
3096 }
3097
3098 next = ap->next;
3099 free(ap->name);
3100 free(ap->val);
3101 free(ap);
3102 return next;
3103}
Eric Andersencb57d552001-06-28 07:25:16 +00003104
Eric Andersenc470f442003-07-28 09:56:35 +00003105static void
3106setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003107{
3108 struct alias *ap, **app;
3109
3110 app = __lookupalias(name);
3111 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003112 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003113 if (ap) {
3114 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003115 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003116 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003117 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003118 ap->flag &= ~ALIASDEAD;
3119 } else {
3120 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003121 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003122 ap->name = ckstrdup(name);
3123 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003124 /*ap->flag = 0; - ckzalloc did it */
3125 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003126 *app = ap;
3127 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003128 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003129}
3130
Eric Andersenc470f442003-07-28 09:56:35 +00003131static int
3132unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003133{
Eric Andersencb57d552001-06-28 07:25:16 +00003134 struct alias **app;
3135
3136 app = __lookupalias(name);
3137
3138 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003139 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003140 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003141 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003142 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003143 }
3144
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003145 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003146}
3147
Eric Andersenc470f442003-07-28 09:56:35 +00003148static void
3149rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003150{
Eric Andersencb57d552001-06-28 07:25:16 +00003151 struct alias *ap, **app;
3152 int i;
3153
Denis Vlasenkob012b102007-02-19 22:43:01 +00003154 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003155 for (i = 0; i < ATABSIZE; i++) {
3156 app = &atab[i];
3157 for (ap = *app; ap; ap = *app) {
3158 *app = freealias(*app);
3159 if (ap == *app) {
3160 app = &ap->next;
3161 }
3162 }
3163 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003164 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003165}
3166
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003167static void
3168printalias(const struct alias *ap)
3169{
3170 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3171}
3172
Eric Andersencb57d552001-06-28 07:25:16 +00003173/*
3174 * TODO - sort output
3175 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003176static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003177aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003178{
3179 char *n, *v;
3180 int ret = 0;
3181 struct alias *ap;
3182
Denis Vlasenko68404f12008-03-17 09:00:54 +00003183 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003184 int i;
3185
Denis Vlasenko68404f12008-03-17 09:00:54 +00003186 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003187 for (ap = atab[i]; ap; ap = ap->next) {
3188 printalias(ap);
3189 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003190 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003191 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003192 }
3193 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003194 v = strchr(n+1, '=');
3195 if (v == NULL) { /* n+1: funny ksh stuff */
3196 ap = *__lookupalias(n);
3197 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003198 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003199 ret = 1;
3200 } else
3201 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003202 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003203 *v++ = '\0';
3204 setalias(n, v);
3205 }
3206 }
3207
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003208 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003209}
3210
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003211static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003212unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003213{
3214 int i;
3215
3216 while ((i = nextopt("a")) != '\0') {
3217 if (i == 'a') {
3218 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003219 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003220 }
3221 }
3222 for (i = 0; *argptr; argptr++) {
3223 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003224 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003225 i = 1;
3226 }
3227 }
3228
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003229 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003230}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003231
Denis Vlasenko131ae172007-02-18 13:00:19 +00003232#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003233
Eric Andersenc470f442003-07-28 09:56:35 +00003234
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003235/* ============ jobs.c */
3236
3237/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3238#define FORK_FG 0
3239#define FORK_BG 1
3240#define FORK_NOJOB 2
3241
3242/* mode flags for showjob(s) */
3243#define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3244#define SHOW_PID 0x04 /* include process pid */
3245#define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3246
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003247/*
3248 * A job structure contains information about a job. A job is either a
3249 * single process or a set of processes contained in a pipeline. In the
3250 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3251 * array of pids.
3252 */
3253
3254struct procstat {
3255 pid_t pid; /* process id */
3256 int status; /* last process status from wait() */
3257 char *cmd; /* text of command being run */
3258};
3259
3260struct job {
3261 struct procstat ps0; /* status of process */
3262 struct procstat *ps; /* status or processes when more than one */
3263#if JOBS
3264 int stopstatus; /* status of a stopped job */
3265#endif
3266 uint32_t
3267 nprocs: 16, /* number of processes */
3268 state: 8,
3269#define JOBRUNNING 0 /* at least one proc running */
3270#define JOBSTOPPED 1 /* all procs are stopped */
3271#define JOBDONE 2 /* all procs are completed */
3272#if JOBS
3273 sigint: 1, /* job was killed by SIGINT */
3274 jobctl: 1, /* job running under job control */
3275#endif
3276 waited: 1, /* true if this entry has been waited for */
3277 used: 1, /* true if this entry is in used */
3278 changed: 1; /* true if status has changed */
3279 struct job *prev_job; /* previous job */
3280};
3281
Denis Vlasenko68404f12008-03-17 09:00:54 +00003282static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003283#if !JOBS
3284#define forkshell(job, node, mode) forkshell(job, mode)
3285#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003286static int forkshell(struct job *, union node *, int);
3287static int waitforjob(struct job *);
3288
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003289#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003290enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003291#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003292#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003293static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003294static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003295#endif
3296
3297/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003298 * Ignore a signal.
3299 */
3300static void
3301ignoresig(int signo)
3302{
3303 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3304 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3305 /* No, need to do it */
3306 signal(signo, SIG_IGN);
3307 }
3308 sigmode[signo - 1] = S_HARD_IGN;
3309}
3310
3311/*
3312 * Signal handler. Only one usage site - in setsignal()
3313 */
3314static void
3315onsig(int signo)
3316{
3317 gotsig[signo - 1] = 1;
3318
3319 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3320 if (!suppressint) {
3321 pendingsig = 0;
3322 raise_interrupt(); /* does not return */
3323 }
3324 intpending = 1;
3325 } else {
3326 pendingsig = signo;
3327 }
3328}
3329
3330/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 * Set the signal handler for the specified signal. The routine figures
3332 * out what it should be set to.
3333 */
3334static void
3335setsignal(int signo)
3336{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003337 char *t;
3338 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 struct sigaction act;
3340
3341 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003342 new_act = S_DFL;
3343 if (t != NULL) { /* trap for this sig is set */
3344 new_act = S_CATCH;
3345 if (t[0] == '\0') /* trap is "": ignore this sig */
3346 new_act = S_IGN;
3347 }
3348
3349 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003350 switch (signo) {
3351 case SIGINT:
3352 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003353 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003354 break;
3355 case SIGQUIT:
3356#if DEBUG
3357 if (debug)
3358 break;
3359#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 /* man bash:
3361 * "In all cases, bash ignores SIGQUIT. Non-builtin
3362 * commands run by bash have signal handlers
3363 * set to the values inherited by the shell
3364 * from its parent". */
3365 new_act = S_IGN;
3366 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003367 case SIGTERM:
3368 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003369 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003370 break;
3371#if JOBS
3372 case SIGTSTP:
3373 case SIGTTOU:
3374 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003375 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003376 break;
3377#endif
3378 }
3379 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003380//TODO: if !rootshell, we reset SIGQUIT to DFL,
3381//whereas we have to restore it to what shell got on entry
3382//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003383
3384 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003385 cur_act = *t;
3386 if (cur_act == 0) {
3387 /* current setting is not yet known */
3388 if (sigaction(signo, NULL, &act)) {
3389 /* pretend it worked; maybe we should give a warning,
3390 * but other shells don't. We don't alter sigmode,
3391 * so we retry every time.
3392 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003393 return;
3394 }
3395 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003396 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397 if (mflag
3398 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3399 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003400 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003401 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402 }
3403 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003404 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003406
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003407 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003408 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003409 case S_CATCH:
3410 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003411 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3412 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003413 break;
3414 case S_IGN:
3415 act.sa_handler = SIG_IGN;
3416 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003417 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003418 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003419
3420 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003421}
3422
3423/* mode flags for set_curjob */
3424#define CUR_DELETE 2
3425#define CUR_RUNNING 1
3426#define CUR_STOPPED 0
3427
3428/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003429#define DOWAIT_NONBLOCK WNOHANG
3430#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003431
3432#if JOBS
3433/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003434static int initialpgrp; //references:2
3435static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003436#endif
3437/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003438static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003439/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003440static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003441/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003442static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003443/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003444static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003445
3446static void
3447set_curjob(struct job *jp, unsigned mode)
3448{
3449 struct job *jp1;
3450 struct job **jpp, **curp;
3451
3452 /* first remove from list */
3453 jpp = curp = &curjob;
3454 do {
3455 jp1 = *jpp;
3456 if (jp1 == jp)
3457 break;
3458 jpp = &jp1->prev_job;
3459 } while (1);
3460 *jpp = jp1->prev_job;
3461
3462 /* Then re-insert in correct position */
3463 jpp = curp;
3464 switch (mode) {
3465 default:
3466#if DEBUG
3467 abort();
3468#endif
3469 case CUR_DELETE:
3470 /* job being deleted */
3471 break;
3472 case CUR_RUNNING:
3473 /* newly created job or backgrounded job,
3474 put after all stopped jobs. */
3475 do {
3476 jp1 = *jpp;
3477#if JOBS
3478 if (!jp1 || jp1->state != JOBSTOPPED)
3479#endif
3480 break;
3481 jpp = &jp1->prev_job;
3482 } while (1);
3483 /* FALLTHROUGH */
3484#if JOBS
3485 case CUR_STOPPED:
3486#endif
3487 /* newly stopped job - becomes curjob */
3488 jp->prev_job = *jpp;
3489 *jpp = jp;
3490 break;
3491 }
3492}
3493
3494#if JOBS || DEBUG
3495static int
3496jobno(const struct job *jp)
3497{
3498 return jp - jobtab + 1;
3499}
3500#endif
3501
3502/*
3503 * Convert a job name to a job structure.
3504 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003505#if !JOBS
3506#define getjob(name, getctl) getjob(name)
3507#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003508static struct job *
3509getjob(const char *name, int getctl)
3510{
3511 struct job *jp;
3512 struct job *found;
3513 const char *err_msg = "No such job: %s";
3514 unsigned num;
3515 int c;
3516 const char *p;
3517 char *(*match)(const char *, const char *);
3518
3519 jp = curjob;
3520 p = name;
3521 if (!p)
3522 goto currentjob;
3523
3524 if (*p != '%')
3525 goto err;
3526
3527 c = *++p;
3528 if (!c)
3529 goto currentjob;
3530
3531 if (!p[1]) {
3532 if (c == '+' || c == '%') {
3533 currentjob:
3534 err_msg = "No current job";
3535 goto check;
3536 }
3537 if (c == '-') {
3538 if (jp)
3539 jp = jp->prev_job;
3540 err_msg = "No previous job";
3541 check:
3542 if (!jp)
3543 goto err;
3544 goto gotit;
3545 }
3546 }
3547
3548 if (is_number(p)) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00003549// TODO: number() instead? It does error checking...
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003550 num = atoi(p);
3551 if (num < njobs) {
3552 jp = jobtab + num - 1;
3553 if (jp->used)
3554 goto gotit;
3555 goto err;
3556 }
3557 }
3558
3559 match = prefix;
3560 if (*p == '?') {
3561 match = strstr;
3562 p++;
3563 }
3564
3565 found = 0;
3566 while (1) {
3567 if (!jp)
3568 goto err;
3569 if (match(jp->ps[0].cmd, p)) {
3570 if (found)
3571 goto err;
3572 found = jp;
3573 err_msg = "%s: ambiguous";
3574 }
3575 jp = jp->prev_job;
3576 }
3577
3578 gotit:
3579#if JOBS
3580 err_msg = "job %s not created under job control";
3581 if (getctl && jp->jobctl == 0)
3582 goto err;
3583#endif
3584 return jp;
3585 err:
3586 ash_msg_and_raise_error(err_msg, name);
3587}
3588
3589/*
3590 * Mark a job structure as unused.
3591 */
3592static void
3593freejob(struct job *jp)
3594{
3595 struct procstat *ps;
3596 int i;
3597
3598 INT_OFF;
3599 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3600 if (ps->cmd != nullstr)
3601 free(ps->cmd);
3602 }
3603 if (jp->ps != &jp->ps0)
3604 free(jp->ps);
3605 jp->used = 0;
3606 set_curjob(jp, CUR_DELETE);
3607 INT_ON;
3608}
3609
3610#if JOBS
3611static void
3612xtcsetpgrp(int fd, pid_t pgrp)
3613{
3614 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003615 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003616}
3617
3618/*
3619 * Turn job control on and off.
3620 *
3621 * Note: This code assumes that the third arg to ioctl is a character
3622 * pointer, which is true on Berkeley systems but not System V. Since
3623 * System V doesn't have job control yet, this isn't a problem now.
3624 *
3625 * Called with interrupts off.
3626 */
3627static void
3628setjobctl(int on)
3629{
3630 int fd;
3631 int pgrp;
3632
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003633 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003634 return;
3635 if (on) {
3636 int ofd;
3637 ofd = fd = open(_PATH_TTY, O_RDWR);
3638 if (fd < 0) {
3639 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3640 * That sometimes helps to acquire controlling tty.
3641 * Obviously, a workaround for bugs when someone
3642 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003643 fd = 2;
3644 while (!isatty(fd))
3645 if (--fd < 0)
3646 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003647 }
3648 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003649 if (ofd >= 0)
3650 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003651 if (fd < 0)
3652 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003653 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003654 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003655 do { /* while we are in the background */
3656 pgrp = tcgetpgrp(fd);
3657 if (pgrp < 0) {
3658 out:
3659 ash_msg("can't access tty; job control turned off");
3660 mflag = on = 0;
3661 goto close;
3662 }
3663 if (pgrp == getpgrp())
3664 break;
3665 killpg(0, SIGTTIN);
3666 } while (1);
3667 initialpgrp = pgrp;
3668
3669 setsignal(SIGTSTP);
3670 setsignal(SIGTTOU);
3671 setsignal(SIGTTIN);
3672 pgrp = rootpid;
3673 setpgid(0, pgrp);
3674 xtcsetpgrp(fd, pgrp);
3675 } else {
3676 /* turning job control off */
3677 fd = ttyfd;
3678 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003679 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003680 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003681 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003682 setpgid(0, pgrp);
3683 setsignal(SIGTSTP);
3684 setsignal(SIGTTOU);
3685 setsignal(SIGTTIN);
3686 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003687 if (fd >= 0)
3688 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003689 fd = -1;
3690 }
3691 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003692 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003693}
3694
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003695static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003696killcmd(int argc, char **argv)
3697{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003698 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003699 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003700 do {
3701 if (argv[i][0] == '%') {
3702 struct job *jp = getjob(argv[i], 0);
3703 unsigned pid = jp->ps[0].pid;
3704 /* Enough space for ' -NNN<nul>' */
3705 argv[i] = alloca(sizeof(int)*3 + 3);
3706 /* kill_main has matching code to expect
3707 * leading space. Needed to not confuse
3708 * negative pids with "kill -SIGNAL_NO" syntax */
3709 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003710 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003711 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003712 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003713 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714}
3715
3716static void
3717showpipe(struct job *jp, FILE *out)
3718{
3719 struct procstat *sp;
3720 struct procstat *spend;
3721
3722 spend = jp->ps + jp->nprocs;
3723 for (sp = jp->ps + 1; sp < spend; sp++)
3724 fprintf(out, " | %s", sp->cmd);
3725 outcslow('\n', out);
3726 flush_stdout_stderr();
3727}
3728
3729
3730static int
3731restartjob(struct job *jp, int mode)
3732{
3733 struct procstat *ps;
3734 int i;
3735 int status;
3736 pid_t pgid;
3737
3738 INT_OFF;
3739 if (jp->state == JOBDONE)
3740 goto out;
3741 jp->state = JOBRUNNING;
3742 pgid = jp->ps->pid;
3743 if (mode == FORK_FG)
3744 xtcsetpgrp(ttyfd, pgid);
3745 killpg(pgid, SIGCONT);
3746 ps = jp->ps;
3747 i = jp->nprocs;
3748 do {
3749 if (WIFSTOPPED(ps->status)) {
3750 ps->status = -1;
3751 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003752 ps++;
3753 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003754 out:
3755 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3756 INT_ON;
3757 return status;
3758}
3759
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003760static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003761fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003762{
3763 struct job *jp;
3764 FILE *out;
3765 int mode;
3766 int retval;
3767
3768 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3769 nextopt(nullstr);
3770 argv = argptr;
3771 out = stdout;
3772 do {
3773 jp = getjob(*argv, 1);
3774 if (mode == FORK_BG) {
3775 set_curjob(jp, CUR_RUNNING);
3776 fprintf(out, "[%d] ", jobno(jp));
3777 }
3778 outstr(jp->ps->cmd, out);
3779 showpipe(jp, out);
3780 retval = restartjob(jp, mode);
3781 } while (*argv && *++argv);
3782 return retval;
3783}
3784#endif
3785
3786static int
3787sprint_status(char *s, int status, int sigonly)
3788{
3789 int col;
3790 int st;
3791
3792 col = 0;
3793 if (!WIFEXITED(status)) {
3794#if JOBS
3795 if (WIFSTOPPED(status))
3796 st = WSTOPSIG(status);
3797 else
3798#endif
3799 st = WTERMSIG(status);
3800 if (sigonly) {
3801 if (st == SIGINT || st == SIGPIPE)
3802 goto out;
3803#if JOBS
3804 if (WIFSTOPPED(status))
3805 goto out;
3806#endif
3807 }
3808 st &= 0x7f;
3809 col = fmtstr(s, 32, strsignal(st));
3810 if (WCOREDUMP(status)) {
3811 col += fmtstr(s + col, 16, " (core dumped)");
3812 }
3813 } else if (!sigonly) {
3814 st = WEXITSTATUS(status);
3815 if (st)
3816 col = fmtstr(s, 16, "Done(%d)", st);
3817 else
3818 col = fmtstr(s, 16, "Done");
3819 }
3820 out:
3821 return col;
3822}
3823
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003824static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003825dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003826{
3827 int pid;
3828 int status;
3829 struct job *jp;
3830 struct job *thisjob;
3831 int state;
3832
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003833 TRACE(("dowait(0x%x) called\n", wait_flags));
3834
3835 /* Do a wait system call. If job control is compiled in, we accept
3836 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3837 * NB: _not_ safe_waitpid, we need to detect EINTR */
3838 pid = waitpid(-1, &status,
3839 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003840 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3841 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003842 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003843 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003844
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003845 INT_OFF;
3846 thisjob = NULL;
3847 for (jp = curjob; jp; jp = jp->prev_job) {
3848 struct procstat *sp;
3849 struct procstat *spend;
3850 if (jp->state == JOBDONE)
3851 continue;
3852 state = JOBDONE;
3853 spend = jp->ps + jp->nprocs;
3854 sp = jp->ps;
3855 do {
3856 if (sp->pid == pid) {
3857 TRACE(("Job %d: changing status of proc %d "
3858 "from 0x%x to 0x%x\n",
3859 jobno(jp), pid, sp->status, status));
3860 sp->status = status;
3861 thisjob = jp;
3862 }
3863 if (sp->status == -1)
3864 state = JOBRUNNING;
3865#if JOBS
3866 if (state == JOBRUNNING)
3867 continue;
3868 if (WIFSTOPPED(sp->status)) {
3869 jp->stopstatus = sp->status;
3870 state = JOBSTOPPED;
3871 }
3872#endif
3873 } while (++sp < spend);
3874 if (thisjob)
3875 goto gotjob;
3876 }
3877#if JOBS
3878 if (!WIFSTOPPED(status))
3879#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003880 jobless--;
3881 goto out;
3882
3883 gotjob:
3884 if (state != JOBRUNNING) {
3885 thisjob->changed = 1;
3886
3887 if (thisjob->state != state) {
3888 TRACE(("Job %d: changing state from %d to %d\n",
3889 jobno(thisjob), thisjob->state, state));
3890 thisjob->state = state;
3891#if JOBS
3892 if (state == JOBSTOPPED) {
3893 set_curjob(thisjob, CUR_STOPPED);
3894 }
3895#endif
3896 }
3897 }
3898
3899 out:
3900 INT_ON;
3901
3902 if (thisjob && thisjob == job) {
3903 char s[48 + 1];
3904 int len;
3905
3906 len = sprint_status(s, status, 1);
3907 if (len) {
3908 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003909 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003910 out2str(s);
3911 }
3912 }
3913 return pid;
3914}
3915
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003916static int
3917blocking_wait_with_raise_on_sig(struct job *job)
3918{
3919 pid_t pid = dowait(DOWAIT_BLOCK, job);
3920 if (pid <= 0 && pendingsig)
3921 raise_exception(EXSIG);
3922 return pid;
3923}
3924
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925#if JOBS
3926static void
3927showjob(FILE *out, struct job *jp, int mode)
3928{
3929 struct procstat *ps;
3930 struct procstat *psend;
3931 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003932 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003933 char s[80];
3934
3935 ps = jp->ps;
3936
3937 if (mode & SHOW_PGID) {
3938 /* just output process (group) id of pipeline */
3939 fprintf(out, "%d\n", ps->pid);
3940 return;
3941 }
3942
3943 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003944 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003945
3946 if (jp == curjob)
3947 s[col - 2] = '+';
3948 else if (curjob && jp == curjob->prev_job)
3949 s[col - 2] = '-';
3950
3951 if (mode & SHOW_PID)
3952 col += fmtstr(s + col, 16, "%d ", ps->pid);
3953
3954 psend = ps + jp->nprocs;
3955
3956 if (jp->state == JOBRUNNING) {
3957 strcpy(s + col, "Running");
3958 col += sizeof("Running") - 1;
3959 } else {
3960 int status = psend[-1].status;
3961 if (jp->state == JOBSTOPPED)
3962 status = jp->stopstatus;
3963 col += sprint_status(s + col, status, 0);
3964 }
3965
3966 goto start;
3967
3968 do {
3969 /* for each process */
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003970 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 start:
3972 fprintf(out, "%s%*c%s",
3973 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3974 );
3975 if (!(mode & SHOW_PID)) {
3976 showpipe(jp, out);
3977 break;
3978 }
3979 if (++ps == psend) {
3980 outcslow('\n', out);
3981 break;
3982 }
3983 } while (1);
3984
3985 jp->changed = 0;
3986
3987 if (jp->state == JOBDONE) {
3988 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3989 freejob(jp);
3990 }
3991}
3992
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003993/*
3994 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3995 * statuses have changed since the last call to showjobs.
3996 */
3997static void
3998showjobs(FILE *out, int mode)
3999{
4000 struct job *jp;
4001
Denys Vlasenko883cea42009-07-11 15:31:59 +02004002 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004003
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004004 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004005 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006 continue;
4007
4008 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004009 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004010 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004011 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004012 }
4013}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004014
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004015static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004016jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004017{
4018 int mode, m;
4019
4020 mode = 0;
4021 while ((m = nextopt("lp"))) {
4022 if (m == 'l')
4023 mode = SHOW_PID;
4024 else
4025 mode = SHOW_PGID;
4026 }
4027
4028 argv = argptr;
4029 if (*argv) {
4030 do
4031 showjob(stdout, getjob(*argv,0), mode);
4032 while (*++argv);
4033 } else
4034 showjobs(stdout, mode);
4035
4036 return 0;
4037}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004038#endif /* JOBS */
4039
4040static int
4041getstatus(struct job *job)
4042{
4043 int status;
4044 int retval;
4045
4046 status = job->ps[job->nprocs - 1].status;
4047 retval = WEXITSTATUS(status);
4048 if (!WIFEXITED(status)) {
4049#if JOBS
4050 retval = WSTOPSIG(status);
4051 if (!WIFSTOPPED(status))
4052#endif
4053 {
4054 /* XXX: limits number of signals */
4055 retval = WTERMSIG(status);
4056#if JOBS
4057 if (retval == SIGINT)
4058 job->sigint = 1;
4059#endif
4060 }
4061 retval += 128;
4062 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004063 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004064 jobno(job), job->nprocs, status, retval));
4065 return retval;
4066}
4067
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004068static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004069waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004070{
4071 struct job *job;
4072 int retval;
4073 struct job *jp;
4074
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004075// exsig++;
4076// xbarrier();
4077 if (pendingsig)
4078 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004079
4080 nextopt(nullstr);
4081 retval = 0;
4082
4083 argv = argptr;
4084 if (!*argv) {
4085 /* wait for all jobs */
4086 for (;;) {
4087 jp = curjob;
4088 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004089 if (!jp) /* no running procs */
4090 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004091 if (jp->state == JOBRUNNING)
4092 break;
4093 jp->waited = 1;
4094 jp = jp->prev_job;
4095 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004096 /* man bash:
4097 * "When bash is waiting for an asynchronous command via
4098 * the wait builtin, the reception of a signal for which a trap
4099 * has been set will cause the wait builtin to return immediately
4100 * with an exit status greater than 128, immediately after which
4101 * the trap is executed."
4102 * Do we do it that way? */
4103 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004104 }
4105 }
4106
4107 retval = 127;
4108 do {
4109 if (**argv != '%') {
4110 pid_t pid = number(*argv);
4111 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004112 while (1) {
4113 if (!job)
4114 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004115 if (job->ps[job->nprocs - 1].pid == pid)
4116 break;
4117 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004118 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004119 } else
4120 job = getjob(*argv, 0);
4121 /* loop until process terminated or stopped */
4122 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004123 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124 job->waited = 1;
4125 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004126 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004127 } while (*++argv);
4128
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004129 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004130 return retval;
4131}
4132
4133static struct job *
4134growjobtab(void)
4135{
4136 size_t len;
4137 ptrdiff_t offset;
4138 struct job *jp, *jq;
4139
4140 len = njobs * sizeof(*jp);
4141 jq = jobtab;
4142 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4143
4144 offset = (char *)jp - (char *)jq;
4145 if (offset) {
4146 /* Relocate pointers */
4147 size_t l = len;
4148
4149 jq = (struct job *)((char *)jq + l);
4150 while (l) {
4151 l -= sizeof(*jp);
4152 jq--;
4153#define joff(p) ((struct job *)((char *)(p) + l))
4154#define jmove(p) (p) = (void *)((char *)(p) + offset)
4155 if (joff(jp)->ps == &jq->ps0)
4156 jmove(joff(jp)->ps);
4157 if (joff(jp)->prev_job)
4158 jmove(joff(jp)->prev_job);
4159 }
4160 if (curjob)
4161 jmove(curjob);
4162#undef joff
4163#undef jmove
4164 }
4165
4166 njobs += 4;
4167 jobtab = jp;
4168 jp = (struct job *)((char *)jp + len);
4169 jq = jp + 3;
4170 do {
4171 jq->used = 0;
4172 } while (--jq >= jp);
4173 return jp;
4174}
4175
4176/*
4177 * Return a new job structure.
4178 * Called with interrupts off.
4179 */
4180static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004181makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004182{
4183 int i;
4184 struct job *jp;
4185
4186 for (i = njobs, jp = jobtab; ; jp++) {
4187 if (--i < 0) {
4188 jp = growjobtab();
4189 break;
4190 }
4191 if (jp->used == 0)
4192 break;
4193 if (jp->state != JOBDONE || !jp->waited)
4194 continue;
4195#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004196 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004197 continue;
4198#endif
4199 freejob(jp);
4200 break;
4201 }
4202 memset(jp, 0, sizeof(*jp));
4203#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004204 /* jp->jobctl is a bitfield.
4205 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004206 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004207 jp->jobctl = 1;
4208#endif
4209 jp->prev_job = curjob;
4210 curjob = jp;
4211 jp->used = 1;
4212 jp->ps = &jp->ps0;
4213 if (nprocs > 1) {
4214 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4215 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004216 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 jobno(jp)));
4218 return jp;
4219}
4220
4221#if JOBS
4222/*
4223 * Return a string identifying a command (to be printed by the
4224 * jobs command).
4225 */
4226static char *cmdnextc;
4227
4228static void
4229cmdputs(const char *s)
4230{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004231 static const char vstype[VSTYPE + 1][3] = {
4232 "", "}", "-", "+", "?", "=",
4233 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004234 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004235 };
4236
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004237 const char *p, *str;
4238 char c, cc[2] = " ";
4239 char *nextc;
4240 int subtype = 0;
4241 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004242
4243 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4244 p = s;
4245 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004246 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004247 switch (c) {
4248 case CTLESC:
4249 c = *p++;
4250 break;
4251 case CTLVAR:
4252 subtype = *p++;
4253 if ((subtype & VSTYPE) == VSLENGTH)
4254 str = "${#";
4255 else
4256 str = "${";
4257 if (!(subtype & VSQUOTE) == !(quoted & 1))
4258 goto dostr;
4259 quoted ^= 1;
4260 c = '"';
4261 break;
4262 case CTLENDVAR:
4263 str = "\"}" + !(quoted & 1);
4264 quoted >>= 1;
4265 subtype = 0;
4266 goto dostr;
4267 case CTLBACKQ:
4268 str = "$(...)";
4269 goto dostr;
4270 case CTLBACKQ+CTLQUOTE:
4271 str = "\"$(...)\"";
4272 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004273#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004274 case CTLARI:
4275 str = "$((";
4276 goto dostr;
4277 case CTLENDARI:
4278 str = "))";
4279 goto dostr;
4280#endif
4281 case CTLQUOTEMARK:
4282 quoted ^= 1;
4283 c = '"';
4284 break;
4285 case '=':
4286 if (subtype == 0)
4287 break;
4288 if ((subtype & VSTYPE) != VSNORMAL)
4289 quoted <<= 1;
4290 str = vstype[subtype & VSTYPE];
4291 if (subtype & VSNUL)
4292 c = ':';
4293 else
4294 goto checkstr;
4295 break;
4296 case '\'':
4297 case '\\':
4298 case '"':
4299 case '$':
4300 /* These can only happen inside quotes */
4301 cc[0] = c;
4302 str = cc;
4303 c = '\\';
4304 break;
4305 default:
4306 break;
4307 }
4308 USTPUTC(c, nextc);
4309 checkstr:
4310 if (!str)
4311 continue;
4312 dostr:
4313 while ((c = *str++)) {
4314 USTPUTC(c, nextc);
4315 }
4316 }
4317 if (quoted & 1) {
4318 USTPUTC('"', nextc);
4319 }
4320 *nextc = 0;
4321 cmdnextc = nextc;
4322}
4323
4324/* cmdtxt() and cmdlist() call each other */
4325static void cmdtxt(union node *n);
4326
4327static void
4328cmdlist(union node *np, int sep)
4329{
4330 for (; np; np = np->narg.next) {
4331 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004332 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004333 cmdtxt(np);
4334 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004335 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004336 }
4337}
4338
4339static void
4340cmdtxt(union node *n)
4341{
4342 union node *np;
4343 struct nodelist *lp;
4344 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004345
4346 if (!n)
4347 return;
4348 switch (n->type) {
4349 default:
4350#if DEBUG
4351 abort();
4352#endif
4353 case NPIPE:
4354 lp = n->npipe.cmdlist;
4355 for (;;) {
4356 cmdtxt(lp->n);
4357 lp = lp->next;
4358 if (!lp)
4359 break;
4360 cmdputs(" | ");
4361 }
4362 break;
4363 case NSEMI:
4364 p = "; ";
4365 goto binop;
4366 case NAND:
4367 p = " && ";
4368 goto binop;
4369 case NOR:
4370 p = " || ";
4371 binop:
4372 cmdtxt(n->nbinary.ch1);
4373 cmdputs(p);
4374 n = n->nbinary.ch2;
4375 goto donode;
4376 case NREDIR:
4377 case NBACKGND:
4378 n = n->nredir.n;
4379 goto donode;
4380 case NNOT:
4381 cmdputs("!");
4382 n = n->nnot.com;
4383 donode:
4384 cmdtxt(n);
4385 break;
4386 case NIF:
4387 cmdputs("if ");
4388 cmdtxt(n->nif.test);
4389 cmdputs("; then ");
4390 n = n->nif.ifpart;
4391 if (n->nif.elsepart) {
4392 cmdtxt(n);
4393 cmdputs("; else ");
4394 n = n->nif.elsepart;
4395 }
4396 p = "; fi";
4397 goto dotail;
4398 case NSUBSHELL:
4399 cmdputs("(");
4400 n = n->nredir.n;
4401 p = ")";
4402 goto dotail;
4403 case NWHILE:
4404 p = "while ";
4405 goto until;
4406 case NUNTIL:
4407 p = "until ";
4408 until:
4409 cmdputs(p);
4410 cmdtxt(n->nbinary.ch1);
4411 n = n->nbinary.ch2;
4412 p = "; done";
4413 dodo:
4414 cmdputs("; do ");
4415 dotail:
4416 cmdtxt(n);
4417 goto dotail2;
4418 case NFOR:
4419 cmdputs("for ");
4420 cmdputs(n->nfor.var);
4421 cmdputs(" in ");
4422 cmdlist(n->nfor.args, 1);
4423 n = n->nfor.body;
4424 p = "; done";
4425 goto dodo;
4426 case NDEFUN:
4427 cmdputs(n->narg.text);
4428 p = "() { ... }";
4429 goto dotail2;
4430 case NCMD:
4431 cmdlist(n->ncmd.args, 1);
4432 cmdlist(n->ncmd.redirect, 0);
4433 break;
4434 case NARG:
4435 p = n->narg.text;
4436 dotail2:
4437 cmdputs(p);
4438 break;
4439 case NHERE:
4440 case NXHERE:
4441 p = "<<...";
4442 goto dotail2;
4443 case NCASE:
4444 cmdputs("case ");
4445 cmdputs(n->ncase.expr->narg.text);
4446 cmdputs(" in ");
4447 for (np = n->ncase.cases; np; np = np->nclist.next) {
4448 cmdtxt(np->nclist.pattern);
4449 cmdputs(") ");
4450 cmdtxt(np->nclist.body);
4451 cmdputs(";; ");
4452 }
4453 p = "esac";
4454 goto dotail2;
4455 case NTO:
4456 p = ">";
4457 goto redir;
4458 case NCLOBBER:
4459 p = ">|";
4460 goto redir;
4461 case NAPPEND:
4462 p = ">>";
4463 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004464#if ENABLE_ASH_BASH_COMPAT
4465 case NTO2:
4466#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004467 case NTOFD:
4468 p = ">&";
4469 goto redir;
4470 case NFROM:
4471 p = "<";
4472 goto redir;
4473 case NFROMFD:
4474 p = "<&";
4475 goto redir;
4476 case NFROMTO:
4477 p = "<>";
4478 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004479 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004480 cmdputs(p);
4481 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004482 cmdputs(utoa(n->ndup.dupfd));
4483 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004484 }
4485 n = n->nfile.fname;
4486 goto donode;
4487 }
4488}
4489
4490static char *
4491commandtext(union node *n)
4492{
4493 char *name;
4494
4495 STARTSTACKSTR(cmdnextc);
4496 cmdtxt(n);
4497 name = stackblock();
4498 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4499 name, cmdnextc, cmdnextc));
4500 return ckstrdup(name);
4501}
4502#endif /* JOBS */
4503
4504/*
4505 * Fork off a subshell. If we are doing job control, give the subshell its
4506 * own process group. Jp is a job structure that the job is to be added to.
4507 * N is the command that will be evaluated by the child. Both jp and n may
4508 * be NULL. The mode parameter can be one of the following:
4509 * FORK_FG - Fork off a foreground process.
4510 * FORK_BG - Fork off a background process.
4511 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4512 * process group even if job control is on.
4513 *
4514 * When job control is turned off, background processes have their standard
4515 * input redirected to /dev/null (except for the second and later processes
4516 * in a pipeline).
4517 *
4518 * Called with interrupts off.
4519 */
4520/*
4521 * Clear traps on a fork.
4522 */
4523static void
4524clear_traps(void)
4525{
4526 char **tp;
4527
4528 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004529 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004530 INT_OFF;
4531 free(*tp);
4532 *tp = NULL;
4533 if (tp != &trap[0])
4534 setsignal(tp - trap);
4535 INT_ON;
4536 }
4537 }
4538}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004539
4540/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004542
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004543/* Called after fork(), in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004544#if !JOBS
4545# define forkchild(jp, n, mode) forkchild(jp, mode)
4546#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004547static void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004548forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004549{
4550 int oldlvl;
4551
4552 TRACE(("Child shell %d\n", getpid()));
4553 oldlvl = shlvl;
4554 shlvl++;
4555
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004556 /* man bash: "Non-builtin commands run by bash have signal handlers
4557 * set to the values inherited by the shell from its parent".
4558 * Do we do it correctly? */
4559
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004560 closescript();
4561 clear_traps();
4562#if JOBS
4563 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004564 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004565 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4566 pid_t pgrp;
4567
4568 if (jp->nprocs == 0)
4569 pgrp = getpid();
4570 else
4571 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004572 /* this can fail because we are doing it in the parent also */
4573 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004574 if (mode == FORK_FG)
4575 xtcsetpgrp(ttyfd, pgrp);
4576 setsignal(SIGTSTP);
4577 setsignal(SIGTTOU);
4578 } else
4579#endif
4580 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004581 /* man bash: "When job control is not in effect,
4582 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004583 ignoresig(SIGINT);
4584 ignoresig(SIGQUIT);
4585 if (jp->nprocs == 0) {
4586 close(0);
4587 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004588 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004589 }
4590 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004591 if (!oldlvl) {
4592 if (iflag) { /* why if iflag only? */
4593 setsignal(SIGINT);
4594 setsignal(SIGTERM);
4595 }
4596 /* man bash:
4597 * "In all cases, bash ignores SIGQUIT. Non-builtin
4598 * commands run by bash have signal handlers
4599 * set to the values inherited by the shell
4600 * from its parent".
4601 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004602 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004603 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004604#if JOBS
4605 if (n && n->type == NCMD && strcmp(n->ncmd.args->narg.text, "jobs") == 0) {
4606 TRACE(("Job hack\n"));
4607 freejob(curjob);
4608 return;
4609 }
4610#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 for (jp = curjob; jp; jp = jp->prev_job)
4612 freejob(jp);
4613 jobless = 0;
4614}
4615
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004616/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004617#if !JOBS
4618#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4619#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004620static void
4621forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4622{
4623 TRACE(("In parent shell: child = %d\n", pid));
4624 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004625 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4626 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 jobless++;
4628 return;
4629 }
4630#if JOBS
4631 if (mode != FORK_NOJOB && jp->jobctl) {
4632 int pgrp;
4633
4634 if (jp->nprocs == 0)
4635 pgrp = pid;
4636 else
4637 pgrp = jp->ps[0].pid;
4638 /* This can fail because we are doing it in the child also */
4639 setpgid(pid, pgrp);
4640 }
4641#endif
4642 if (mode == FORK_BG) {
4643 backgndpid = pid; /* set $! */
4644 set_curjob(jp, CUR_RUNNING);
4645 }
4646 if (jp) {
4647 struct procstat *ps = &jp->ps[jp->nprocs++];
4648 ps->pid = pid;
4649 ps->status = -1;
4650 ps->cmd = nullstr;
4651#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004652 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004653 ps->cmd = commandtext(n);
4654#endif
4655 }
4656}
4657
4658static int
4659forkshell(struct job *jp, union node *n, int mode)
4660{
4661 int pid;
4662
4663 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4664 pid = fork();
4665 if (pid < 0) {
4666 TRACE(("Fork failed, errno=%d", errno));
4667 if (jp)
4668 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004669 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004670 }
4671 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004672 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004673 else
4674 forkparent(jp, n, mode, pid);
4675 return pid;
4676}
4677
4678/*
4679 * Wait for job to finish.
4680 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004681 * Under job control we have the problem that while a child process
4682 * is running interrupts generated by the user are sent to the child
4683 * but not to the shell. This means that an infinite loop started by
4684 * an interactive user may be hard to kill. With job control turned off,
4685 * an interactive user may place an interactive program inside a loop.
4686 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004687 * these interrupts to also abort the loop. The approach we take here
4688 * is to have the shell ignore interrupt signals while waiting for a
4689 * foreground process to terminate, and then send itself an interrupt
4690 * signal if the child process was terminated by an interrupt signal.
4691 * Unfortunately, some programs want to do a bit of cleanup and then
4692 * exit on interrupt; unless these processes terminate themselves by
4693 * sending a signal to themselves (instead of calling exit) they will
4694 * confuse this approach.
4695 *
4696 * Called with interrupts off.
4697 */
4698static int
4699waitforjob(struct job *jp)
4700{
4701 int st;
4702
4703 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004704
4705 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004706 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004707 /* In non-interactive shells, we _can_ get
4708 * a keyboard signal here and be EINTRed,
4709 * but we just loop back, waiting for command to complete.
4710 *
4711 * man bash:
4712 * "If bash is waiting for a command to complete and receives
4713 * a signal for which a trap has been set, the trap
4714 * will not be executed until the command completes."
4715 *
4716 * Reality is that even if trap is not set, bash
4717 * will not act on the signal until command completes.
4718 * Try this. sleep5intoff.c:
4719 * #include <signal.h>
4720 * #include <unistd.h>
4721 * int main() {
4722 * sigset_t set;
4723 * sigemptyset(&set);
4724 * sigaddset(&set, SIGINT);
4725 * sigaddset(&set, SIGQUIT);
4726 * sigprocmask(SIG_BLOCK, &set, NULL);
4727 * sleep(5);
4728 * return 0;
4729 * }
4730 * $ bash -c './sleep5intoff; echo hi'
4731 * ^C^C^C^C <--- pressing ^C once a second
4732 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004733 * $ bash -c './sleep5intoff; echo hi'
4734 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4735 * $ _
4736 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004737 dowait(DOWAIT_BLOCK, jp);
4738 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004739 INT_ON;
4740
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004741 st = getstatus(jp);
4742#if JOBS
4743 if (jp->jobctl) {
4744 xtcsetpgrp(ttyfd, rootpid);
4745 /*
4746 * This is truly gross.
4747 * If we're doing job control, then we did a TIOCSPGRP which
4748 * caused us (the shell) to no longer be in the controlling
4749 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4750 * intuit from the subprocess exit status whether a SIGINT
4751 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4752 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004753 if (jp->sigint) /* TODO: do the same with all signals */
4754 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004755 }
4756 if (jp->state == JOBDONE)
4757#endif
4758 freejob(jp);
4759 return st;
4760}
4761
4762/*
4763 * return 1 if there are stopped jobs, otherwise 0
4764 */
4765static int
4766stoppedjobs(void)
4767{
4768 struct job *jp;
4769 int retval;
4770
4771 retval = 0;
4772 if (job_warning)
4773 goto out;
4774 jp = curjob;
4775 if (jp && jp->state == JOBSTOPPED) {
4776 out2str("You have stopped jobs.\n");
4777 job_warning = 2;
4778 retval++;
4779 }
4780 out:
4781 return retval;
4782}
4783
4784
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004785/* ============ redir.c
4786 *
4787 * Code for dealing with input/output redirection.
4788 */
4789
4790#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004791#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004792
4793/*
4794 * Open a file in noclobber mode.
4795 * The code was copied from bash.
4796 */
4797static int
4798noclobberopen(const char *fname)
4799{
4800 int r, fd;
4801 struct stat finfo, finfo2;
4802
4803 /*
4804 * If the file exists and is a regular file, return an error
4805 * immediately.
4806 */
4807 r = stat(fname, &finfo);
4808 if (r == 0 && S_ISREG(finfo.st_mode)) {
4809 errno = EEXIST;
4810 return -1;
4811 }
4812
4813 /*
4814 * If the file was not present (r != 0), make sure we open it
4815 * exclusively so that if it is created before we open it, our open
4816 * will fail. Make sure that we do not truncate an existing file.
4817 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4818 * file was not a regular file, we leave O_EXCL off.
4819 */
4820 if (r != 0)
4821 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4822 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4823
4824 /* If the open failed, return the file descriptor right away. */
4825 if (fd < 0)
4826 return fd;
4827
4828 /*
4829 * OK, the open succeeded, but the file may have been changed from a
4830 * non-regular file to a regular file between the stat and the open.
4831 * We are assuming that the O_EXCL open handles the case where FILENAME
4832 * did not exist and is symlinked to an existing file between the stat
4833 * and open.
4834 */
4835
4836 /*
4837 * If we can open it and fstat the file descriptor, and neither check
4838 * revealed that it was a regular file, and the file has not been
4839 * replaced, return the file descriptor.
4840 */
4841 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4842 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4843 return fd;
4844
4845 /* The file has been replaced. badness. */
4846 close(fd);
4847 errno = EEXIST;
4848 return -1;
4849}
4850
4851/*
4852 * Handle here documents. Normally we fork off a process to write the
4853 * data to a pipe. If the document is short, we can stuff the data in
4854 * the pipe without forking.
4855 */
4856/* openhere needs this forward reference */
4857static void expandhere(union node *arg, int fd);
4858static int
4859openhere(union node *redir)
4860{
4861 int pip[2];
4862 size_t len = 0;
4863
4864 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004865 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004866 if (redir->type == NHERE) {
4867 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004868 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004869 full_write(pip[1], redir->nhere.doc->narg.text, len);
4870 goto out;
4871 }
4872 }
4873 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004874 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004875 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004876 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4877 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4878 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4879 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004880 signal(SIGPIPE, SIG_DFL);
4881 if (redir->type == NHERE)
4882 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004883 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004884 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004885 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004886 }
4887 out:
4888 close(pip[1]);
4889 return pip[0];
4890}
4891
4892static int
4893openredirect(union node *redir)
4894{
4895 char *fname;
4896 int f;
4897
4898 switch (redir->nfile.type) {
4899 case NFROM:
4900 fname = redir->nfile.expfname;
4901 f = open(fname, O_RDONLY);
4902 if (f < 0)
4903 goto eopen;
4904 break;
4905 case NFROMTO:
4906 fname = redir->nfile.expfname;
4907 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4908 if (f < 0)
4909 goto ecreate;
4910 break;
4911 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004912#if ENABLE_ASH_BASH_COMPAT
4913 case NTO2:
4914#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004915 /* Take care of noclobber mode. */
4916 if (Cflag) {
4917 fname = redir->nfile.expfname;
4918 f = noclobberopen(fname);
4919 if (f < 0)
4920 goto ecreate;
4921 break;
4922 }
4923 /* FALLTHROUGH */
4924 case NCLOBBER:
4925 fname = redir->nfile.expfname;
4926 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4927 if (f < 0)
4928 goto ecreate;
4929 break;
4930 case NAPPEND:
4931 fname = redir->nfile.expfname;
4932 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4933 if (f < 0)
4934 goto ecreate;
4935 break;
4936 default:
4937#if DEBUG
4938 abort();
4939#endif
4940 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004941/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004942// case NTOFD:
4943// case NFROMFD:
4944// f = -1;
4945// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004946 case NHERE:
4947 case NXHERE:
4948 f = openhere(redir);
4949 break;
4950 }
4951
4952 return f;
4953 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004954 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004955 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004956 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004957}
4958
4959/*
4960 * Copy a file descriptor to be >= to. Returns -1
4961 * if the source file descriptor is closed, EMPTY if there are no unused
4962 * file descriptors left.
4963 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004964/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4965 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004966enum {
4967 COPYFD_EXACT = (int)~(INT_MAX),
4968 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4969};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004970static int
4971copyfd(int from, int to)
4972{
4973 int newfd;
4974
Denis Vlasenko5a867312008-07-24 19:46:38 +00004975 if (to & COPYFD_EXACT) {
4976 to &= ~COPYFD_EXACT;
4977 /*if (from != to)*/
4978 newfd = dup2(from, to);
4979 } else {
4980 newfd = fcntl(from, F_DUPFD, to);
4981 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004982 if (newfd < 0) {
4983 if (errno == EMFILE)
4984 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004985 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004986 ash_msg_and_raise_error("%d: %m", from);
4987 }
4988 return newfd;
4989}
4990
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004991/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004992struct two_fd_t {
4993 int orig, copy;
4994};
Denis Vlasenko0b769642008-07-24 07:54:57 +00004995struct redirtab {
4996 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00004997 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004998 int pair_count;
4999 struct two_fd_t two_fd[0];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005000};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005001#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005002
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005003static int need_to_remember(struct redirtab *rp, int fd)
5004{
5005 int i;
5006
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005007 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005008 return 0;
5009
5010 for (i = 0; i < rp->pair_count; i++) {
5011 if (rp->two_fd[i].orig == fd) {
5012 /* already remembered */
5013 return 0;
5014 }
5015 }
5016 return 1;
5017}
5018
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005019/* "hidden" fd is a fd used to read scripts, or a copy of such */
5020static int is_hidden_fd(struct redirtab *rp, int fd)
5021{
5022 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005023 struct parsefile *pf;
5024
5025 if (fd == -1)
5026 return 0;
5027 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005028 while (pf) {
5029 if (fd == pf->fd) {
5030 return 1;
5031 }
5032 pf = pf->prev;
5033 }
5034 if (!rp)
5035 return 0;
5036 fd |= COPYFD_RESTORE;
5037 for (i = 0; i < rp->pair_count; i++) {
5038 if (rp->two_fd[i].copy == fd) {
5039 return 1;
5040 }
5041 }
5042 return 0;
5043}
5044
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005045/*
5046 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5047 * old file descriptors are stashed away so that the redirection can be
5048 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5049 * standard output, and the standard error if it becomes a duplicate of
5050 * stdout, is saved in memory.
5051 */
5052/* flags passed to redirect */
5053#define REDIR_PUSH 01 /* save previous values of file descriptors */
5054#define REDIR_SAVEFD2 03 /* set preverrout */
5055static void
5056redirect(union node *redir, int flags)
5057{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005058 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005059 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005060 int i;
5061 int fd;
5062 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005063 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005064
Denis Vlasenko01631112007-12-16 17:20:38 +00005065 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005066 if (!redir) {
5067 return;
5068 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005069
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005070 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005071 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005072 INT_OFF;
5073 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005074 union node *tmp = redir;
5075 do {
5076 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005077#if ENABLE_ASH_BASH_COMPAT
5078 if (redir->nfile.type == NTO2)
5079 sv_pos++;
5080#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005081 tmp = tmp->nfile.next;
5082 } while (tmp);
5083 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005084 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005085 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005086 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005087 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005088 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005089 while (sv_pos > 0) {
5090 sv_pos--;
5091 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5092 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005093 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005094
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005095 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005096 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005097 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005098 int right_fd = redir->ndup.dupfd;
5099 /* redirect from/to same file descriptor? */
5100 if (right_fd == fd)
5101 continue;
5102 /* echo >&10 and 10 is a fd opened to the sh script? */
5103 if (is_hidden_fd(sv, right_fd)) {
5104 errno = EBADF; /* as if it is closed */
5105 ash_msg_and_raise_error("%d: %m", right_fd);
5106 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005107 newfd = -1;
5108 } else {
5109 newfd = openredirect(redir); /* always >= 0 */
5110 if (fd == newfd) {
5111 /* Descriptor wasn't open before redirect.
5112 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005113 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005114 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005116 continue;
5117 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005118 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005119#if ENABLE_ASH_BASH_COMPAT
5120 redirect_more:
5121#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005123 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005124 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005125/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5126 * are closed in popredir() in the child, preventing them from leaking
5127 * into child. (popredir() also cleans up the mess in case of failures)
5128 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129 if (i == -1) {
5130 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005131 if (i != EBADF) {
5132 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005133 if (newfd >= 0)
5134 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005135 errno = i;
5136 ash_msg_and_raise_error("%d: %m", fd);
5137 /* NOTREACHED */
5138 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005139 /* EBADF: it is not open - good, remember to close it */
5140 remember_to_close:
5141 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005142 } else { /* fd is open, save its copy */
5143 /* "exec fd>&-" should not close fds
5144 * which point to script file(s).
5145 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005146 if (is_hidden_fd(sv, fd))
5147 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005148 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005149 if (fd == 2)
5150 copied_fd2 = i;
5151 sv->two_fd[sv_pos].orig = fd;
5152 sv->two_fd[sv_pos].copy = i;
5153 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005154 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005155 if (newfd < 0) {
5156 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005157 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005158 /* Don't want to trigger debugging */
5159 if (fd != -1)
5160 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005161 } else {
5162 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005163 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005164 } else if (fd != newfd) { /* move newfd to fd */
5165 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005166#if ENABLE_ASH_BASH_COMPAT
5167 if (!(redir->nfile.type == NTO2 && fd == 2))
5168#endif
5169 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005170 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005171#if ENABLE_ASH_BASH_COMPAT
5172 if (redir->nfile.type == NTO2 && fd == 1) {
5173 /* We already redirected it to fd 1, now copy it to 2 */
5174 newfd = 1;
5175 fd = 2;
5176 goto redirect_more;
5177 }
5178#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005179 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005180
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005182 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5183 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005184}
5185
5186/*
5187 * Undo the effects of the last redirection.
5188 */
5189static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005190popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005191{
5192 struct redirtab *rp;
5193 int i;
5194
Denis Vlasenko01631112007-12-16 17:20:38 +00005195 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005196 return;
5197 INT_OFF;
5198 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005199 for (i = 0; i < rp->pair_count; i++) {
5200 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005201 int copy = rp->two_fd[i].copy;
5202 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005203 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005204 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005205 continue;
5206 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005207 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005208 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005209 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005210 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005211 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005212 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005213 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005214 }
5215 }
5216 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005217 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005218 free(rp);
5219 INT_ON;
5220}
5221
5222/*
5223 * Undo all redirections. Called on error or interrupt.
5224 */
5225
5226/*
5227 * Discard all saved file descriptors.
5228 */
5229static void
5230clearredir(int drop)
5231{
5232 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005233 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005234 if (!redirlist)
5235 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005236 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005237 }
5238}
5239
5240static int
5241redirectsafe(union node *redir, int flags)
5242{
5243 int err;
5244 volatile int saveint;
5245 struct jmploc *volatile savehandler = exception_handler;
5246 struct jmploc jmploc;
5247
5248 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005249 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5250 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005251 if (!err) {
5252 exception_handler = &jmploc;
5253 redirect(redir, flags);
5254 }
5255 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005256 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005257 longjmp(exception_handler->loc, 1);
5258 RESTORE_INT(saveint);
5259 return err;
5260}
5261
5262
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005263/* ============ Routines to expand arguments to commands
5264 *
5265 * We have to deal with backquotes, shell variables, and file metacharacters.
5266 */
5267
Mike Frysinger98c52642009-04-02 10:02:37 +00005268#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005269static arith_t
5270ash_arith(const char *s)
5271{
5272 arith_eval_hooks_t math_hooks;
5273 arith_t result;
5274 int errcode = 0;
5275
5276 math_hooks.lookupvar = lookupvar;
5277 math_hooks.setvar = setvar;
5278 math_hooks.endofname = endofname;
5279
5280 INT_OFF;
5281 result = arith(s, &errcode, &math_hooks);
5282 if (errcode < 0) {
5283 if (errcode == -3)
5284 ash_msg_and_raise_error("exponent less than 0");
5285 if (errcode == -2)
5286 ash_msg_and_raise_error("divide by zero");
5287 if (errcode == -5)
5288 ash_msg_and_raise_error("expression recursion loop detected");
5289 raise_error_syntax(s);
5290 }
5291 INT_ON;
5292
5293 return result;
5294}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005295#endif
5296
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005297/*
5298 * expandarg flags
5299 */
5300#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5301#define EXP_TILDE 0x2 /* do normal tilde expansion */
5302#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5303#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5304#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5305#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5306#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5307#define EXP_WORD 0x80 /* expand word in parameter expansion */
5308#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5309/*
5310 * _rmescape() flags
5311 */
5312#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5313#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5314#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5315#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5316#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5317
5318/*
5319 * Structure specifying which parts of the string should be searched
5320 * for IFS characters.
5321 */
5322struct ifsregion {
5323 struct ifsregion *next; /* next region in list */
5324 int begoff; /* offset of start of region */
5325 int endoff; /* offset of end of region */
5326 int nulonly; /* search for nul bytes only */
5327};
5328
5329struct arglist {
5330 struct strlist *list;
5331 struct strlist **lastp;
5332};
5333
5334/* output of current string */
5335static char *expdest;
5336/* list of back quote expressions */
5337static struct nodelist *argbackq;
5338/* first struct in list of ifs regions */
5339static struct ifsregion ifsfirst;
5340/* last struct in list */
5341static struct ifsregion *ifslastp;
5342/* holds expanded arg list */
5343static struct arglist exparg;
5344
5345/*
5346 * Our own itoa().
5347 */
5348static int
5349cvtnum(arith_t num)
5350{
5351 int len;
5352
5353 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005354 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005355 STADJUST(len, expdest);
5356 return len;
5357}
5358
5359static size_t
5360esclen(const char *start, const char *p)
5361{
5362 size_t esc = 0;
5363
5364 while (p > start && *--p == CTLESC) {
5365 esc++;
5366 }
5367 return esc;
5368}
5369
5370/*
5371 * Remove any CTLESC characters from a string.
5372 */
5373static char *
5374_rmescapes(char *str, int flag)
5375{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005376 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005377
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005378 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005379 unsigned inquotes;
5380 int notescaped;
5381 int globbing;
5382
5383 p = strpbrk(str, qchars);
5384 if (!p) {
5385 return str;
5386 }
5387 q = p;
5388 r = str;
5389 if (flag & RMESCAPE_ALLOC) {
5390 size_t len = p - str;
5391 size_t fulllen = len + strlen(p) + 1;
5392
5393 if (flag & RMESCAPE_GROW) {
5394 r = makestrspace(fulllen, expdest);
5395 } else if (flag & RMESCAPE_HEAP) {
5396 r = ckmalloc(fulllen);
5397 } else {
5398 r = stalloc(fulllen);
5399 }
5400 q = r;
5401 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005402 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005403 }
5404 }
5405 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5406 globbing = flag & RMESCAPE_GLOB;
5407 notescaped = globbing;
5408 while (*p) {
5409 if (*p == CTLQUOTEMARK) {
5410 inquotes = ~inquotes;
5411 p++;
5412 notescaped = globbing;
5413 continue;
5414 }
5415 if (*p == '\\') {
5416 /* naked back slash */
5417 notescaped = 0;
5418 goto copy;
5419 }
5420 if (*p == CTLESC) {
5421 p++;
5422 if (notescaped && inquotes && *p != '/') {
5423 *q++ = '\\';
5424 }
5425 }
5426 notescaped = globbing;
5427 copy:
5428 *q++ = *p++;
5429 }
5430 *q = '\0';
5431 if (flag & RMESCAPE_GROW) {
5432 expdest = r;
5433 STADJUST(q - r + 1, expdest);
5434 }
5435 return r;
5436}
5437#define rmescapes(p) _rmescapes((p), 0)
5438
5439#define pmatch(a, b) !fnmatch((a), (b), 0)
5440
5441/*
5442 * Prepare a pattern for a expmeta (internal glob(3)) call.
5443 *
5444 * Returns an stalloced string.
5445 */
5446static char *
5447preglob(const char *pattern, int quoted, int flag)
5448{
5449 flag |= RMESCAPE_GLOB;
5450 if (quoted) {
5451 flag |= RMESCAPE_QUOTED;
5452 }
5453 return _rmescapes((char *)pattern, flag);
5454}
5455
5456/*
5457 * Put a string on the stack.
5458 */
5459static void
5460memtodest(const char *p, size_t len, int syntax, int quotes)
5461{
5462 char *q = expdest;
5463
5464 q = makestrspace(len * 2, q);
5465
5466 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005467 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 if (!c)
5469 continue;
5470 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5471 USTPUTC(CTLESC, q);
5472 USTPUTC(c, q);
5473 }
5474
5475 expdest = q;
5476}
5477
5478static void
5479strtodest(const char *p, int syntax, int quotes)
5480{
5481 memtodest(p, strlen(p), syntax, quotes);
5482}
5483
5484/*
5485 * Record the fact that we have to scan this region of the
5486 * string for IFS characters.
5487 */
5488static void
5489recordregion(int start, int end, int nulonly)
5490{
5491 struct ifsregion *ifsp;
5492
5493 if (ifslastp == NULL) {
5494 ifsp = &ifsfirst;
5495 } else {
5496 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005497 ifsp = ckzalloc(sizeof(*ifsp));
5498 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005499 ifslastp->next = ifsp;
5500 INT_ON;
5501 }
5502 ifslastp = ifsp;
5503 ifslastp->begoff = start;
5504 ifslastp->endoff = end;
5505 ifslastp->nulonly = nulonly;
5506}
5507
5508static void
5509removerecordregions(int endoff)
5510{
5511 if (ifslastp == NULL)
5512 return;
5513
5514 if (ifsfirst.endoff > endoff) {
5515 while (ifsfirst.next != NULL) {
5516 struct ifsregion *ifsp;
5517 INT_OFF;
5518 ifsp = ifsfirst.next->next;
5519 free(ifsfirst.next);
5520 ifsfirst.next = ifsp;
5521 INT_ON;
5522 }
5523 if (ifsfirst.begoff > endoff)
5524 ifslastp = NULL;
5525 else {
5526 ifslastp = &ifsfirst;
5527 ifsfirst.endoff = endoff;
5528 }
5529 return;
5530 }
5531
5532 ifslastp = &ifsfirst;
5533 while (ifslastp->next && ifslastp->next->begoff < endoff)
5534 ifslastp=ifslastp->next;
5535 while (ifslastp->next != NULL) {
5536 struct ifsregion *ifsp;
5537 INT_OFF;
5538 ifsp = ifslastp->next->next;
5539 free(ifslastp->next);
5540 ifslastp->next = ifsp;
5541 INT_ON;
5542 }
5543 if (ifslastp->endoff > endoff)
5544 ifslastp->endoff = endoff;
5545}
5546
5547static char *
5548exptilde(char *startp, char *p, int flag)
5549{
5550 char c;
5551 char *name;
5552 struct passwd *pw;
5553 const char *home;
5554 int quotes = flag & (EXP_FULL | EXP_CASE);
5555 int startloc;
5556
5557 name = p + 1;
5558
5559 while ((c = *++p) != '\0') {
5560 switch (c) {
5561 case CTLESC:
5562 return startp;
5563 case CTLQUOTEMARK:
5564 return startp;
5565 case ':':
5566 if (flag & EXP_VARTILDE)
5567 goto done;
5568 break;
5569 case '/':
5570 case CTLENDVAR:
5571 goto done;
5572 }
5573 }
5574 done:
5575 *p = '\0';
5576 if (*name == '\0') {
5577 home = lookupvar(homestr);
5578 } else {
5579 pw = getpwnam(name);
5580 if (pw == NULL)
5581 goto lose;
5582 home = pw->pw_dir;
5583 }
5584 if (!home || !*home)
5585 goto lose;
5586 *p = c;
5587 startloc = expdest - (char *)stackblock();
5588 strtodest(home, SQSYNTAX, quotes);
5589 recordregion(startloc, expdest - (char *)stackblock(), 0);
5590 return p;
5591 lose:
5592 *p = c;
5593 return startp;
5594}
5595
5596/*
5597 * Execute a command inside back quotes. If it's a builtin command, we
5598 * want to save its output in a block obtained from malloc. Otherwise
5599 * we fork off a subprocess and get the output of the command via a pipe.
5600 * Should be called with interrupts off.
5601 */
5602struct backcmd { /* result of evalbackcmd */
5603 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005604 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005605 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005606 struct job *jp; /* job structure for command */
5607};
5608
5609/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005610static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005611#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005612static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005614static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005615evalbackcmd(union node *n, struct backcmd *result)
5616{
5617 int saveherefd;
5618
5619 result->fd = -1;
5620 result->buf = NULL;
5621 result->nleft = 0;
5622 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005623 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005624 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005625
5626 saveherefd = herefd;
5627 herefd = -1;
5628
5629 {
5630 int pip[2];
5631 struct job *jp;
5632
5633 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005634 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005635 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005636 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5637 FORCE_INT_ON;
5638 close(pip[0]);
5639 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005640 /*close(1);*/
5641 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005642 close(pip[1]);
5643 }
5644 eflag = 0;
5645 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5646 /* NOTREACHED */
5647 }
5648 close(pip[1]);
5649 result->fd = pip[0];
5650 result->jp = jp;
5651 }
5652 herefd = saveherefd;
5653 out:
5654 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5655 result->fd, result->buf, result->nleft, result->jp));
5656}
5657
5658/*
5659 * Expand stuff in backwards quotes.
5660 */
5661static void
5662expbackq(union node *cmd, int quoted, int quotes)
5663{
5664 struct backcmd in;
5665 int i;
5666 char buf[128];
5667 char *p;
5668 char *dest;
5669 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005670 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671 struct stackmark smark;
5672
5673 INT_OFF;
5674 setstackmark(&smark);
5675 dest = expdest;
5676 startloc = dest - (char *)stackblock();
5677 grabstackstr(dest);
5678 evalbackcmd(cmd, &in);
5679 popstackmark(&smark);
5680
5681 p = in.buf;
5682 i = in.nleft;
5683 if (i == 0)
5684 goto read;
5685 for (;;) {
5686 memtodest(p, i, syntax, quotes);
5687 read:
5688 if (in.fd < 0)
5689 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005690 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005691 TRACE(("expbackq: read returns %d\n", i));
5692 if (i <= 0)
5693 break;
5694 p = buf;
5695 }
5696
Denis Vlasenko60818682007-09-28 22:07:23 +00005697 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005698 if (in.fd >= 0) {
5699 close(in.fd);
5700 back_exitstatus = waitforjob(in.jp);
5701 }
5702 INT_ON;
5703
5704 /* Eat all trailing newlines */
5705 dest = expdest;
5706 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5707 STUNPUTC(dest);
5708 expdest = dest;
5709
5710 if (quoted == 0)
5711 recordregion(startloc, dest - (char *)stackblock(), 0);
5712 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5713 (dest - (char *)stackblock()) - startloc,
5714 (dest - (char *)stackblock()) - startloc,
5715 stackblock() + startloc));
5716}
5717
Mike Frysinger98c52642009-04-02 10:02:37 +00005718#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005719/*
5720 * Expand arithmetic expression. Backup to start of expression,
5721 * evaluate, place result in (backed up) result, adjust string position.
5722 */
5723static void
5724expari(int quotes)
5725{
5726 char *p, *start;
5727 int begoff;
5728 int flag;
5729 int len;
5730
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005731 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005732
5733 /*
5734 * This routine is slightly over-complicated for
5735 * efficiency. Next we scan backwards looking for the
5736 * start of arithmetic.
5737 */
5738 start = stackblock();
5739 p = expdest - 1;
5740 *p = '\0';
5741 p--;
5742 do {
5743 int esc;
5744
5745 while (*p != CTLARI) {
5746 p--;
5747#if DEBUG
5748 if (p < start) {
5749 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5750 }
5751#endif
5752 }
5753
5754 esc = esclen(start, p);
5755 if (!(esc % 2)) {
5756 break;
5757 }
5758
5759 p -= esc + 1;
5760 } while (1);
5761
5762 begoff = p - start;
5763
5764 removerecordregions(begoff);
5765
5766 flag = p[1];
5767
5768 expdest = p;
5769
5770 if (quotes)
5771 rmescapes(p + 2);
5772
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005773 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005774
5775 if (flag != '"')
5776 recordregion(begoff, begoff + len, 0);
5777}
5778#endif
5779
5780/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005781static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005782
5783/*
5784 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5785 * characters to allow for further processing. Otherwise treat
5786 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005787 *
5788 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5789 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5790 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005791 */
5792static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005793argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005794{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005795 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796 '=',
5797 ':',
5798 CTLQUOTEMARK,
5799 CTLENDVAR,
5800 CTLESC,
5801 CTLVAR,
5802 CTLBACKQ,
5803 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005804#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005805 CTLENDARI,
5806#endif
5807 0
5808 };
5809 const char *reject = spclchars;
5810 int c;
5811 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5812 int breakall = flag & EXP_WORD;
5813 int inquotes;
5814 size_t length;
5815 int startloc;
5816
5817 if (!(flag & EXP_VARTILDE)) {
5818 reject += 2;
5819 } else if (flag & EXP_VARTILDE2) {
5820 reject++;
5821 }
5822 inquotes = 0;
5823 length = 0;
5824 if (flag & EXP_TILDE) {
5825 char *q;
5826
5827 flag &= ~EXP_TILDE;
5828 tilde:
5829 q = p;
5830 if (*q == CTLESC && (flag & EXP_QWORD))
5831 q++;
5832 if (*q == '~')
5833 p = exptilde(p, q, flag);
5834 }
5835 start:
5836 startloc = expdest - (char *)stackblock();
5837 for (;;) {
5838 length += strcspn(p + length, reject);
5839 c = p[length];
5840 if (c && (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005841#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005842 || c == CTLENDARI
5843#endif
5844 )) {
5845 /* c == '=' || c == ':' || c == CTLENDARI */
5846 length++;
5847 }
5848 if (length > 0) {
5849 int newloc;
5850 expdest = stack_nputstr(p, length, expdest);
5851 newloc = expdest - (char *)stackblock();
5852 if (breakall && !inquotes && newloc > startloc) {
5853 recordregion(startloc, newloc, 0);
5854 }
5855 startloc = newloc;
5856 }
5857 p += length + 1;
5858 length = 0;
5859
5860 switch (c) {
5861 case '\0':
5862 goto breakloop;
5863 case '=':
5864 if (flag & EXP_VARTILDE2) {
5865 p--;
5866 continue;
5867 }
5868 flag |= EXP_VARTILDE2;
5869 reject++;
5870 /* fall through */
5871 case ':':
5872 /*
5873 * sort of a hack - expand tildes in variable
5874 * assignments (after the first '=' and after ':'s).
5875 */
5876 if (*--p == '~') {
5877 goto tilde;
5878 }
5879 continue;
5880 }
5881
5882 switch (c) {
5883 case CTLENDVAR: /* ??? */
5884 goto breakloop;
5885 case CTLQUOTEMARK:
5886 /* "$@" syntax adherence hack */
5887 if (
5888 !inquotes &&
5889 !memcmp(p, dolatstr, 4) &&
5890 (p[4] == CTLQUOTEMARK || (
5891 p[4] == CTLENDVAR &&
5892 p[5] == CTLQUOTEMARK
5893 ))
5894 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005895 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005896 goto start;
5897 }
5898 inquotes = !inquotes;
5899 addquote:
5900 if (quotes) {
5901 p--;
5902 length++;
5903 startloc++;
5904 }
5905 break;
5906 case CTLESC:
5907 startloc++;
5908 length++;
5909 goto addquote;
5910 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005911 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005912 goto start;
5913 case CTLBACKQ:
5914 c = 0;
5915 case CTLBACKQ|CTLQUOTE:
5916 expbackq(argbackq->n, c, quotes);
5917 argbackq = argbackq->next;
5918 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005919#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005920 case CTLENDARI:
5921 p--;
5922 expari(quotes);
5923 goto start;
5924#endif
5925 }
5926 }
5927 breakloop:
5928 ;
5929}
5930
5931static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005932scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005933 int zero)
5934{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005935// This commented out code was added by James Simmons <jsimmons@infradead.org>
5936// as part of a larger change when he added support for ${var/a/b}.
5937// However, it broke # and % operators:
5938//
5939//var=ababcdcd
5940// ok bad
5941//echo ${var#ab} abcdcd abcdcd
5942//echo ${var##ab} abcdcd abcdcd
5943//echo ${var#a*b} abcdcd ababcdcd (!)
5944//echo ${var##a*b} cdcd cdcd
5945//echo ${var#?} babcdcd ababcdcd (!)
5946//echo ${var##?} babcdcd babcdcd
5947//echo ${var#*} ababcdcd babcdcd (!)
5948//echo ${var##*}
5949//echo ${var%cd} ababcd ababcd
5950//echo ${var%%cd} ababcd abab (!)
5951//echo ${var%c*d} ababcd ababcd
5952//echo ${var%%c*d} abab ababcdcd (!)
5953//echo ${var%?} ababcdc ababcdc
5954//echo ${var%%?} ababcdc ababcdcd (!)
5955//echo ${var%*} ababcdcd ababcdcd
5956//echo ${var%%*}
5957//
5958// Commenting it back out helped. Remove it completely if it really
5959// is not needed.
5960
5961 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005962 char c;
5963
5964 loc = startp;
5965 loc2 = rmesc;
5966 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005967 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005968 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005969
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005970 c = *loc2;
5971 if (zero) {
5972 *loc2 = '\0';
5973 s = rmesc;
5974 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005975 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005976
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005977// // chop off end if its '*'
5978// full = strrchr(str, '*');
5979// if (full && full != str)
5980// match--;
5981//
5982// // If str starts with '*' replace with s.
5983// if ((*str == '*') && strlen(s) >= match) {
5984// full = xstrdup(s);
5985// strncpy(full+strlen(s)-match+1, str+1, match-1);
5986// } else
5987// full = xstrndup(str, match);
5988// match = strncmp(s, full, strlen(full));
5989// free(full);
5990//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005991 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005992 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005993 return loc;
5994 if (quotes && *loc == CTLESC)
5995 loc++;
5996 loc++;
5997 loc2++;
5998 } while (c);
5999 return 0;
6000}
6001
6002static char *
6003scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6004 int zero)
6005{
6006 int esc = 0;
6007 char *loc;
6008 char *loc2;
6009
6010 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6011 int match;
6012 char c = *loc2;
6013 const char *s = loc2;
6014 if (zero) {
6015 *loc2 = '\0';
6016 s = rmesc;
6017 }
6018 match = pmatch(str, s);
6019 *loc2 = c;
6020 if (match)
6021 return loc;
6022 loc--;
6023 if (quotes) {
6024 if (--esc < 0) {
6025 esc = esclen(startp, loc);
6026 }
6027 if (esc % 2) {
6028 esc--;
6029 loc--;
6030 }
6031 }
6032 }
6033 return 0;
6034}
6035
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006036static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006037static void
6038varunset(const char *end, const char *var, const char *umsg, int varflags)
6039{
6040 const char *msg;
6041 const char *tail;
6042
6043 tail = nullstr;
6044 msg = "parameter not set";
6045 if (umsg) {
6046 if (*end == CTLENDVAR) {
6047 if (varflags & VSNUL)
6048 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006049 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006050 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006051 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006052 }
6053 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6054}
6055
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006056#if ENABLE_ASH_BASH_COMPAT
6057static char *
6058parse_sub_pattern(char *arg, int inquotes)
6059{
6060 char *idx, *repl = NULL;
6061 unsigned char c;
6062
Denis Vlasenko2659c632008-06-14 06:04:59 +00006063 idx = arg;
6064 while (1) {
6065 c = *arg;
6066 if (!c)
6067 break;
6068 if (c == '/') {
6069 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006070 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006071 repl = idx + 1;
6072 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006073 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006074 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006075 *idx++ = c;
6076 if (!inquotes && c == '\\' && arg[1] == '\\')
6077 arg++; /* skip both \\, not just first one */
6078 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006079 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006080 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006081
6082 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006083}
6084#endif /* ENABLE_ASH_BASH_COMPAT */
6085
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006086static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006087subevalvar(char *p, char *str, int strloc, int subtype,
6088 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006089{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006090 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006091 char *startp;
6092 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006093 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006094 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6095 IF_ASH_BASH_COMPAT(char null = '\0';)
6096 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006097 int saveherefd = herefd;
6098 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006099 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006100 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006101
6102 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006103 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6104 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006105 STPUTC('\0', expdest);
6106 herefd = saveherefd;
6107 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006108 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006109
6110 switch (subtype) {
6111 case VSASSIGN:
6112 setvar(str, startp, 0);
6113 amount = startp - expdest;
6114 STADJUST(amount, expdest);
6115 return startp;
6116
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006117#if ENABLE_ASH_BASH_COMPAT
6118 case VSSUBSTR:
6119 loc = str = stackblock() + strloc;
6120// TODO: number() instead? It does error checking...
6121 pos = atoi(loc);
6122 len = str - startp - 1;
6123
6124 /* *loc != '\0', guaranteed by parser */
6125 if (quotes) {
6126 char *ptr;
6127
6128 /* We must adjust the length by the number of escapes we find. */
6129 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006130 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006131 len--;
6132 ptr++;
6133 }
6134 }
6135 }
6136 orig_len = len;
6137
6138 if (*loc++ == ':') {
6139// TODO: number() instead? It does error checking...
6140 len = atoi(loc);
6141 } else {
6142 len = orig_len;
6143 while (*loc && *loc != ':')
6144 loc++;
6145 if (*loc++ == ':')
6146// TODO: number() instead? It does error checking...
6147 len = atoi(loc);
6148 }
6149 if (pos >= orig_len) {
6150 pos = 0;
6151 len = 0;
6152 }
6153 if (len > (orig_len - pos))
6154 len = orig_len - pos;
6155
6156 for (str = startp; pos; str++, pos--) {
6157 if (quotes && *str == CTLESC)
6158 str++;
6159 }
6160 for (loc = startp; len; len--) {
6161 if (quotes && *str == CTLESC)
6162 *loc++ = *str++;
6163 *loc++ = *str++;
6164 }
6165 *loc = '\0';
6166 amount = loc - expdest;
6167 STADJUST(amount, expdest);
6168 return loc;
6169#endif
6170
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006171 case VSQUESTION:
6172 varunset(p, str, startp, varflags);
6173 /* NOTREACHED */
6174 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006176
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006177 /* We'll comeback here if we grow the stack while handling
6178 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6179 * stack will need rebasing, and we'll need to remove our work
6180 * areas each time
6181 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006182 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006183
6184 amount = expdest - ((char *)stackblock() + resetloc);
6185 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006186 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187
6188 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006189 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006190 if (quotes) {
6191 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6192 if (rmesc != startp) {
6193 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006194 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006195 }
6196 }
6197 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006198 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006199 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006200 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006201
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006202#if ENABLE_ASH_BASH_COMPAT
6203 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6204 char *idx, *end, *restart_detect;
6205
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006206 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006207 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6208 if (!repl)
6209 repl = &null;
6210 }
6211
6212 /* If there's no pattern to match, return the expansion unmolested */
6213 if (*str == '\0')
6214 return 0;
6215
6216 len = 0;
6217 idx = startp;
6218 end = str - 1;
6219 while (idx < end) {
6220 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6221 if (!loc) {
6222 /* No match, advance */
6223 restart_detect = stackblock();
6224 STPUTC(*idx, expdest);
6225 if (quotes && *idx == CTLESC) {
6226 idx++;
6227 len++;
6228 STPUTC(*idx, expdest);
6229 }
6230 if (stackblock() != restart_detect)
6231 goto restart;
6232 idx++;
6233 len++;
6234 rmesc++;
6235 continue;
6236 }
6237
6238 if (subtype == VSREPLACEALL) {
6239 while (idx < loc) {
6240 if (quotes && *idx == CTLESC)
6241 idx++;
6242 idx++;
6243 rmesc++;
6244 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006245 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006246 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006247 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006248
6249 for (loc = repl; *loc; loc++) {
6250 restart_detect = stackblock();
6251 STPUTC(*loc, expdest);
6252 if (stackblock() != restart_detect)
6253 goto restart;
6254 len++;
6255 }
6256
6257 if (subtype == VSREPLACE) {
6258 while (*idx) {
6259 restart_detect = stackblock();
6260 STPUTC(*idx, expdest);
6261 if (stackblock() != restart_detect)
6262 goto restart;
6263 len++;
6264 idx++;
6265 }
6266 break;
6267 }
6268 }
6269
6270 /* We've put the replaced text into a buffer at workloc, now
6271 * move it to the right place and adjust the stack.
6272 */
6273 startp = stackblock() + startloc;
6274 STPUTC('\0', expdest);
6275 memmove(startp, stackblock() + workloc, len);
6276 startp[len++] = '\0';
6277 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6278 STADJUST(-amount, expdest);
6279 return startp;
6280 }
6281#endif /* ENABLE_ASH_BASH_COMPAT */
6282
6283 subtype -= VSTRIMRIGHT;
6284#if DEBUG
6285 if (subtype < 0 || subtype > 7)
6286 abort();
6287#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006288 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6289 zero = subtype >> 1;
6290 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6291 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6292
6293 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6294 if (loc) {
6295 if (zero) {
6296 memmove(startp, loc, str - loc);
6297 loc = startp + (str - loc) - 1;
6298 }
6299 *loc = '\0';
6300 amount = loc - expdest;
6301 STADJUST(amount, expdest);
6302 }
6303 return loc;
6304}
6305
6306/*
6307 * Add the value of a specialized variable to the stack string.
6308 */
6309static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006310varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006311{
6312 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006313 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006314 int i;
6315 int sep = 0;
6316 int sepq = 0;
6317 ssize_t len = 0;
6318 char **ap;
6319 int syntax;
6320 int quoted = varflags & VSQUOTE;
6321 int subtype = varflags & VSTYPE;
6322 int quotes = flags & (EXP_FULL | EXP_CASE);
6323
6324 if (quoted && (flags & EXP_FULL))
6325 sep = 1 << CHAR_BIT;
6326
6327 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6328 switch (*name) {
6329 case '$':
6330 num = rootpid;
6331 goto numvar;
6332 case '?':
6333 num = exitstatus;
6334 goto numvar;
6335 case '#':
6336 num = shellparam.nparam;
6337 goto numvar;
6338 case '!':
6339 num = backgndpid;
6340 if (num == 0)
6341 return -1;
6342 numvar:
6343 len = cvtnum(num);
6344 break;
6345 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006346 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006347 for (i = NOPTS - 1; i >= 0; i--) {
6348 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006349 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006350 len++;
6351 }
6352 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006353 break;
6354 case '@':
6355 if (sep)
6356 goto param;
6357 /* fall through */
6358 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006359 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006360 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6361 sepq = 1;
6362 param:
6363 ap = shellparam.p;
6364 if (!ap)
6365 return -1;
6366 while ((p = *ap++)) {
6367 size_t partlen;
6368
6369 partlen = strlen(p);
6370 len += partlen;
6371
6372 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6373 memtodest(p, partlen, syntax, quotes);
6374
6375 if (*ap && sep) {
6376 char *q;
6377
6378 len++;
6379 if (subtype == VSPLUS || subtype == VSLENGTH) {
6380 continue;
6381 }
6382 q = expdest;
6383 if (sepq)
6384 STPUTC(CTLESC, q);
6385 STPUTC(sep, q);
6386 expdest = q;
6387 }
6388 }
6389 return len;
6390 case '0':
6391 case '1':
6392 case '2':
6393 case '3':
6394 case '4':
6395 case '5':
6396 case '6':
6397 case '7':
6398 case '8':
6399 case '9':
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006400// TODO: number() instead? It does error checking...
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006401 num = atoi(name);
6402 if (num < 0 || num > shellparam.nparam)
6403 return -1;
6404 p = num ? shellparam.p[num - 1] : arg0;
6405 goto value;
6406 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006407 /* NB: name has form "VAR=..." */
6408
6409 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6410 * which should be considered before we check variables. */
6411 if (var_str_list) {
6412 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6413 p = NULL;
6414 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006415 char *str, *eq;
6416 str = var_str_list->text;
6417 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006418 if (!eq) /* stop at first non-assignment */
6419 break;
6420 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006421 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006422 && strncmp(str, name, name_len) == 0) {
6423 p = eq;
6424 /* goto value; - WRONG! */
6425 /* think "A=1 A=2 B=$A" */
6426 }
6427 var_str_list = var_str_list->next;
6428 } while (var_str_list);
6429 if (p)
6430 goto value;
6431 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006432 p = lookupvar(name);
6433 value:
6434 if (!p)
6435 return -1;
6436
6437 len = strlen(p);
6438 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6439 memtodest(p, len, syntax, quotes);
6440 return len;
6441 }
6442
6443 if (subtype == VSPLUS || subtype == VSLENGTH)
6444 STADJUST(-len, expdest);
6445 return len;
6446}
6447
6448/*
6449 * Expand a variable, and return a pointer to the next character in the
6450 * input string.
6451 */
6452static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006453evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006454{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006455 char varflags;
6456 char subtype;
6457 char quoted;
6458 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006459 char *var;
6460 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006461 int startloc;
6462 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006463
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006464 varflags = *p++;
6465 subtype = varflags & VSTYPE;
6466 quoted = varflags & VSQUOTE;
6467 var = p;
6468 easy = (!quoted || (*var == '@' && shellparam.nparam));
6469 startloc = expdest - (char *)stackblock();
6470 p = strchr(p, '=') + 1;
6471
6472 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006473 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006474 if (varflags & VSNUL)
6475 varlen--;
6476
6477 if (subtype == VSPLUS) {
6478 varlen = -1 - varlen;
6479 goto vsplus;
6480 }
6481
6482 if (subtype == VSMINUS) {
6483 vsplus:
6484 if (varlen < 0) {
6485 argstr(
6486 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006487 (quoted ? EXP_QWORD : EXP_WORD),
6488 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006489 );
6490 goto end;
6491 }
6492 if (easy)
6493 goto record;
6494 goto end;
6495 }
6496
6497 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6498 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006499 if (subevalvar(p, var, /* strloc: */ 0,
6500 subtype, startloc, varflags,
6501 /* quotes: */ 0,
6502 var_str_list)
6503 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006504 varflags &= ~VSNUL;
6505 /*
6506 * Remove any recorded regions beyond
6507 * start of variable
6508 */
6509 removerecordregions(startloc);
6510 goto again;
6511 }
6512 goto end;
6513 }
6514 if (easy)
6515 goto record;
6516 goto end;
6517 }
6518
6519 if (varlen < 0 && uflag)
6520 varunset(p, var, 0, 0);
6521
6522 if (subtype == VSLENGTH) {
6523 cvtnum(varlen > 0 ? varlen : 0);
6524 goto record;
6525 }
6526
6527 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006528 if (easy)
6529 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006530 goto end;
6531 }
6532
6533#if DEBUG
6534 switch (subtype) {
6535 case VSTRIMLEFT:
6536 case VSTRIMLEFTMAX:
6537 case VSTRIMRIGHT:
6538 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006539#if ENABLE_ASH_BASH_COMPAT
6540 case VSSUBSTR:
6541 case VSREPLACE:
6542 case VSREPLACEALL:
6543#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006544 break;
6545 default:
6546 abort();
6547 }
6548#endif
6549
6550 if (varlen >= 0) {
6551 /*
6552 * Terminate the string and start recording the pattern
6553 * right after it
6554 */
6555 STPUTC('\0', expdest);
6556 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006557 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6558 startloc, varflags,
6559 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6560 var_str_list)
6561 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006562 int amount = expdest - (
6563 (char *)stackblock() + patloc - 1
6564 );
6565 STADJUST(-amount, expdest);
6566 }
6567 /* Remove any recorded regions beyond start of variable */
6568 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006569 record:
6570 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 }
6572
6573 end:
6574 if (subtype != VSNORMAL) { /* skip to end of alternative */
6575 int nesting = 1;
6576 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006577 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006578 if (c == CTLESC)
6579 p++;
6580 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6581 if (varlen >= 0)
6582 argbackq = argbackq->next;
6583 } else if (c == CTLVAR) {
6584 if ((*p++ & VSTYPE) != VSNORMAL)
6585 nesting++;
6586 } else if (c == CTLENDVAR) {
6587 if (--nesting == 0)
6588 break;
6589 }
6590 }
6591 }
6592 return p;
6593}
6594
6595/*
6596 * Break the argument string into pieces based upon IFS and add the
6597 * strings to the argument list. The regions of the string to be
6598 * searched for IFS characters have been stored by recordregion.
6599 */
6600static void
6601ifsbreakup(char *string, struct arglist *arglist)
6602{
6603 struct ifsregion *ifsp;
6604 struct strlist *sp;
6605 char *start;
6606 char *p;
6607 char *q;
6608 const char *ifs, *realifs;
6609 int ifsspc;
6610 int nulonly;
6611
6612 start = string;
6613 if (ifslastp != NULL) {
6614 ifsspc = 0;
6615 nulonly = 0;
6616 realifs = ifsset() ? ifsval() : defifs;
6617 ifsp = &ifsfirst;
6618 do {
6619 p = string + ifsp->begoff;
6620 nulonly = ifsp->nulonly;
6621 ifs = nulonly ? nullstr : realifs;
6622 ifsspc = 0;
6623 while (p < string + ifsp->endoff) {
6624 q = p;
6625 if (*p == CTLESC)
6626 p++;
6627 if (!strchr(ifs, *p)) {
6628 p++;
6629 continue;
6630 }
6631 if (!nulonly)
6632 ifsspc = (strchr(defifs, *p) != NULL);
6633 /* Ignore IFS whitespace at start */
6634 if (q == start && ifsspc) {
6635 p++;
6636 start = p;
6637 continue;
6638 }
6639 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006640 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006641 sp->text = start;
6642 *arglist->lastp = sp;
6643 arglist->lastp = &sp->next;
6644 p++;
6645 if (!nulonly) {
6646 for (;;) {
6647 if (p >= string + ifsp->endoff) {
6648 break;
6649 }
6650 q = p;
6651 if (*p == CTLESC)
6652 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006653 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006654 p = q;
6655 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006656 }
6657 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006658 if (ifsspc) {
6659 p++;
6660 ifsspc = 0;
6661 } else {
6662 p = q;
6663 break;
6664 }
6665 } else
6666 p++;
6667 }
6668 }
6669 start = p;
6670 } /* while */
6671 ifsp = ifsp->next;
6672 } while (ifsp != NULL);
6673 if (nulonly)
6674 goto add;
6675 }
6676
6677 if (!*start)
6678 return;
6679
6680 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006681 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006682 sp->text = start;
6683 *arglist->lastp = sp;
6684 arglist->lastp = &sp->next;
6685}
6686
6687static void
6688ifsfree(void)
6689{
6690 struct ifsregion *p;
6691
6692 INT_OFF;
6693 p = ifsfirst.next;
6694 do {
6695 struct ifsregion *ifsp;
6696 ifsp = p->next;
6697 free(p);
6698 p = ifsp;
6699 } while (p);
6700 ifslastp = NULL;
6701 ifsfirst.next = NULL;
6702 INT_ON;
6703}
6704
6705/*
6706 * Add a file name to the list.
6707 */
6708static void
6709addfname(const char *name)
6710{
6711 struct strlist *sp;
6712
Denis Vlasenko597906c2008-02-20 16:38:54 +00006713 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006714 sp->text = ststrdup(name);
6715 *exparg.lastp = sp;
6716 exparg.lastp = &sp->next;
6717}
6718
6719static char *expdir;
6720
6721/*
6722 * Do metacharacter (i.e. *, ?, [...]) expansion.
6723 */
6724static void
6725expmeta(char *enddir, char *name)
6726{
6727 char *p;
6728 const char *cp;
6729 char *start;
6730 char *endname;
6731 int metaflag;
6732 struct stat statb;
6733 DIR *dirp;
6734 struct dirent *dp;
6735 int atend;
6736 int matchdot;
6737
6738 metaflag = 0;
6739 start = name;
6740 for (p = name; *p; p++) {
6741 if (*p == '*' || *p == '?')
6742 metaflag = 1;
6743 else if (*p == '[') {
6744 char *q = p + 1;
6745 if (*q == '!')
6746 q++;
6747 for (;;) {
6748 if (*q == '\\')
6749 q++;
6750 if (*q == '/' || *q == '\0')
6751 break;
6752 if (*++q == ']') {
6753 metaflag = 1;
6754 break;
6755 }
6756 }
6757 } else if (*p == '\\')
6758 p++;
6759 else if (*p == '/') {
6760 if (metaflag)
6761 goto out;
6762 start = p + 1;
6763 }
6764 }
6765 out:
6766 if (metaflag == 0) { /* we've reached the end of the file name */
6767 if (enddir != expdir)
6768 metaflag++;
6769 p = name;
6770 do {
6771 if (*p == '\\')
6772 p++;
6773 *enddir++ = *p;
6774 } while (*p++);
6775 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6776 addfname(expdir);
6777 return;
6778 }
6779 endname = p;
6780 if (name < start) {
6781 p = name;
6782 do {
6783 if (*p == '\\')
6784 p++;
6785 *enddir++ = *p++;
6786 } while (p < start);
6787 }
6788 if (enddir == expdir) {
6789 cp = ".";
6790 } else if (enddir == expdir + 1 && *expdir == '/') {
6791 cp = "/";
6792 } else {
6793 cp = expdir;
6794 enddir[-1] = '\0';
6795 }
6796 dirp = opendir(cp);
6797 if (dirp == NULL)
6798 return;
6799 if (enddir != expdir)
6800 enddir[-1] = '/';
6801 if (*endname == 0) {
6802 atend = 1;
6803 } else {
6804 atend = 0;
6805 *endname++ = '\0';
6806 }
6807 matchdot = 0;
6808 p = start;
6809 if (*p == '\\')
6810 p++;
6811 if (*p == '.')
6812 matchdot++;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00006813 while (!intpending && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006814 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006815 continue;
6816 if (pmatch(start, dp->d_name)) {
6817 if (atend) {
6818 strcpy(enddir, dp->d_name);
6819 addfname(expdir);
6820 } else {
6821 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6822 continue;
6823 p[-1] = '/';
6824 expmeta(p, endname);
6825 }
6826 }
6827 }
6828 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006829 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006830 endname[-1] = '/';
6831}
6832
6833static struct strlist *
6834msort(struct strlist *list, int len)
6835{
6836 struct strlist *p, *q = NULL;
6837 struct strlist **lpp;
6838 int half;
6839 int n;
6840
6841 if (len <= 1)
6842 return list;
6843 half = len >> 1;
6844 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006845 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006846 q = p;
6847 p = p->next;
6848 }
6849 q->next = NULL; /* terminate first half of list */
6850 q = msort(list, half); /* sort first half of list */
6851 p = msort(p, len - half); /* sort second half */
6852 lpp = &list;
6853 for (;;) {
6854#if ENABLE_LOCALE_SUPPORT
6855 if (strcoll(p->text, q->text) < 0)
6856#else
6857 if (strcmp(p->text, q->text) < 0)
6858#endif
6859 {
6860 *lpp = p;
6861 lpp = &p->next;
6862 p = *lpp;
6863 if (p == NULL) {
6864 *lpp = q;
6865 break;
6866 }
6867 } else {
6868 *lpp = q;
6869 lpp = &q->next;
6870 q = *lpp;
6871 if (q == NULL) {
6872 *lpp = p;
6873 break;
6874 }
6875 }
6876 }
6877 return list;
6878}
6879
6880/*
6881 * Sort the results of file name expansion. It calculates the number of
6882 * strings to sort and then calls msort (short for merge sort) to do the
6883 * work.
6884 */
6885static struct strlist *
6886expsort(struct strlist *str)
6887{
6888 int len;
6889 struct strlist *sp;
6890
6891 len = 0;
6892 for (sp = str; sp; sp = sp->next)
6893 len++;
6894 return msort(str, len);
6895}
6896
6897static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006898expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006899{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006900 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901 '*', '?', '[', 0
6902 };
6903 /* TODO - EXP_REDIR */
6904
6905 while (str) {
6906 struct strlist **savelastp;
6907 struct strlist *sp;
6908 char *p;
6909
6910 if (fflag)
6911 goto nometa;
6912 if (!strpbrk(str->text, metachars))
6913 goto nometa;
6914 savelastp = exparg.lastp;
6915
6916 INT_OFF;
6917 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6918 {
6919 int i = strlen(str->text);
6920 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6921 }
6922
6923 expmeta(expdir, p);
6924 free(expdir);
6925 if (p != str->text)
6926 free(p);
6927 INT_ON;
6928 if (exparg.lastp == savelastp) {
6929 /*
6930 * no matches
6931 */
6932 nometa:
6933 *exparg.lastp = str;
6934 rmescapes(str->text);
6935 exparg.lastp = &str->next;
6936 } else {
6937 *exparg.lastp = NULL;
6938 *savelastp = sp = expsort(*savelastp);
6939 while (sp->next != NULL)
6940 sp = sp->next;
6941 exparg.lastp = &sp->next;
6942 }
6943 str = str->next;
6944 }
6945}
6946
6947/*
6948 * Perform variable substitution and command substitution on an argument,
6949 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6950 * perform splitting and file name expansion. When arglist is NULL, perform
6951 * here document expansion.
6952 */
6953static void
6954expandarg(union node *arg, struct arglist *arglist, int flag)
6955{
6956 struct strlist *sp;
6957 char *p;
6958
6959 argbackq = arg->narg.backquote;
6960 STARTSTACKSTR(expdest);
6961 ifsfirst.next = NULL;
6962 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006963 argstr(arg->narg.text, flag,
6964 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006965 p = _STPUTC('\0', expdest);
6966 expdest = p - 1;
6967 if (arglist == NULL) {
6968 return; /* here document expanded */
6969 }
6970 p = grabstackstr(p);
6971 exparg.lastp = &exparg.list;
6972 /*
6973 * TODO - EXP_REDIR
6974 */
6975 if (flag & EXP_FULL) {
6976 ifsbreakup(p, &exparg);
6977 *exparg.lastp = NULL;
6978 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00006979 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006980 } else {
6981 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6982 rmescapes(p);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006983 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006984 sp->text = p;
6985 *exparg.lastp = sp;
6986 exparg.lastp = &sp->next;
6987 }
6988 if (ifsfirst.next)
6989 ifsfree();
6990 *exparg.lastp = NULL;
6991 if (exparg.list) {
6992 *arglist->lastp = exparg.list;
6993 arglist->lastp = exparg.lastp;
6994 }
6995}
6996
6997/*
6998 * Expand shell variables and backquotes inside a here document.
6999 */
7000static void
7001expandhere(union node *arg, int fd)
7002{
7003 herefd = fd;
7004 expandarg(arg, (struct arglist *)NULL, 0);
7005 full_write(fd, stackblock(), expdest - (char *)stackblock());
7006}
7007
7008/*
7009 * Returns true if the pattern matches the string.
7010 */
7011static int
7012patmatch(char *pattern, const char *string)
7013{
7014 return pmatch(preglob(pattern, 0, 0), string);
7015}
7016
7017/*
7018 * See if a pattern matches in a case statement.
7019 */
7020static int
7021casematch(union node *pattern, char *val)
7022{
7023 struct stackmark smark;
7024 int result;
7025
7026 setstackmark(&smark);
7027 argbackq = pattern->narg.backquote;
7028 STARTSTACKSTR(expdest);
7029 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007030 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7031 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007032 STACKSTRNUL(expdest);
7033 result = patmatch(stackblock(), val);
7034 popstackmark(&smark);
7035 return result;
7036}
7037
7038
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007039/* ============ find_command */
7040
7041struct builtincmd {
7042 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007043 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007044 /* unsigned flags; */
7045};
7046#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007047/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007048 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007049#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007050#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007051
7052struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007053 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007054 union param {
7055 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007056 /* index >= 0 for commands without path (slashes) */
7057 /* (TODO: what exactly does the value mean? PATH position?) */
7058 /* index == -1 for commands with slashes */
7059 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007060 const struct builtincmd *cmd;
7061 struct funcnode *func;
7062 } u;
7063};
7064/* values of cmdtype */
7065#define CMDUNKNOWN -1 /* no entry in table for command */
7066#define CMDNORMAL 0 /* command is an executable program */
7067#define CMDFUNCTION 1 /* command is a shell function */
7068#define CMDBUILTIN 2 /* command is a shell builtin */
7069
7070/* action to find_command() */
7071#define DO_ERR 0x01 /* prints errors */
7072#define DO_ABS 0x02 /* checks absolute paths */
7073#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7074#define DO_ALTPATH 0x08 /* using alternate path */
7075#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7076
7077static void find_command(char *, struct cmdentry *, int, const char *);
7078
7079
7080/* ============ Hashing commands */
7081
7082/*
7083 * When commands are first encountered, they are entered in a hash table.
7084 * This ensures that a full path search will not have to be done for them
7085 * on each invocation.
7086 *
7087 * We should investigate converting to a linear search, even though that
7088 * would make the command name "hash" a misnomer.
7089 */
7090
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007091struct tblentry {
7092 struct tblentry *next; /* next entry in hash chain */
7093 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007094 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007095 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007096 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007097};
7098
Denis Vlasenko01631112007-12-16 17:20:38 +00007099static struct tblentry **cmdtable;
7100#define INIT_G_cmdtable() do { \
7101 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7102} while (0)
7103
7104static int builtinloc = -1; /* index in path of %builtin, or -1 */
7105
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007106
7107static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007108tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007109{
7110 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007111
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007112#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007113 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007114 if (APPLET_IS_NOEXEC(applet_no)) {
7115 while (*envp)
7116 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007117 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007118 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007119 /* re-exec ourselves with the new arguments */
7120 execve(bb_busybox_exec_path, argv, envp);
7121 /* If they called chroot or otherwise made the binary no longer
7122 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007123 }
7124#endif
7125
7126 repeat:
7127#ifdef SYSV
7128 do {
7129 execve(cmd, argv, envp);
7130 } while (errno == EINTR);
7131#else
7132 execve(cmd, argv, envp);
7133#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007134 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007135 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007136 return;
7137 }
7138 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007139 char **ap;
7140 char **new;
7141
7142 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007143 continue;
7144 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007145 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007146 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007147 ap += 2;
7148 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007149 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007150 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007151 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007152 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007153 goto repeat;
7154 }
7155}
7156
7157/*
7158 * Exec a program. Never returns. If you change this routine, you may
7159 * have to change the find_command routine as well.
7160 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007161static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162static void
7163shellexec(char **argv, const char *path, int idx)
7164{
7165 char *cmdname;
7166 int e;
7167 char **envp;
7168 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007169#if ENABLE_FEATURE_SH_STANDALONE
7170 int applet_no = -1;
7171#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007172
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007173 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007174 envp = listvars(VEXPORT, VUNSET, 0);
7175 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007176#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007177 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007178#endif
7179 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007180 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181 e = errno;
7182 } else {
7183 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007184 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007186 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187 if (errno != ENOENT && errno != ENOTDIR)
7188 e = errno;
7189 }
7190 stunalloc(cmdname);
7191 }
7192 }
7193
7194 /* Map to POSIX errors */
7195 switch (e) {
7196 case EACCES:
7197 exerrno = 126;
7198 break;
7199 case ENOENT:
7200 exerrno = 127;
7201 break;
7202 default:
7203 exerrno = 2;
7204 break;
7205 }
7206 exitstatus = exerrno;
7207 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007208 argv[0], e, suppressint));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007209 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7210 /* NOTREACHED */
7211}
7212
7213static void
7214printentry(struct tblentry *cmdp)
7215{
7216 int idx;
7217 const char *path;
7218 char *name;
7219
7220 idx = cmdp->param.index;
7221 path = pathval();
7222 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007223 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007224 stunalloc(name);
7225 } while (--idx >= 0);
7226 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7227}
7228
7229/*
7230 * Clear out command entries. The argument specifies the first entry in
7231 * PATH which has changed.
7232 */
7233static void
7234clearcmdentry(int firstchange)
7235{
7236 struct tblentry **tblp;
7237 struct tblentry **pp;
7238 struct tblentry *cmdp;
7239
7240 INT_OFF;
7241 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7242 pp = tblp;
7243 while ((cmdp = *pp) != NULL) {
7244 if ((cmdp->cmdtype == CMDNORMAL &&
7245 cmdp->param.index >= firstchange)
7246 || (cmdp->cmdtype == CMDBUILTIN &&
7247 builtinloc >= firstchange)
7248 ) {
7249 *pp = cmdp->next;
7250 free(cmdp);
7251 } else {
7252 pp = &cmdp->next;
7253 }
7254 }
7255 }
7256 INT_ON;
7257}
7258
7259/*
7260 * Locate a command in the command hash table. If "add" is nonzero,
7261 * add the command to the table if it is not already present. The
7262 * variable "lastcmdentry" is set to point to the address of the link
7263 * pointing to the entry, so that delete_cmd_entry can delete the
7264 * entry.
7265 *
7266 * Interrupts must be off if called with add != 0.
7267 */
7268static struct tblentry **lastcmdentry;
7269
7270static struct tblentry *
7271cmdlookup(const char *name, int add)
7272{
7273 unsigned int hashval;
7274 const char *p;
7275 struct tblentry *cmdp;
7276 struct tblentry **pp;
7277
7278 p = name;
7279 hashval = (unsigned char)*p << 4;
7280 while (*p)
7281 hashval += (unsigned char)*p++;
7282 hashval &= 0x7FFF;
7283 pp = &cmdtable[hashval % CMDTABLESIZE];
7284 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7285 if (strcmp(cmdp->cmdname, name) == 0)
7286 break;
7287 pp = &cmdp->next;
7288 }
7289 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007290 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7291 + strlen(name)
7292 /* + 1 - already done because
7293 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007294 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007295 cmdp->cmdtype = CMDUNKNOWN;
7296 strcpy(cmdp->cmdname, name);
7297 }
7298 lastcmdentry = pp;
7299 return cmdp;
7300}
7301
7302/*
7303 * Delete the command entry returned on the last lookup.
7304 */
7305static void
7306delete_cmd_entry(void)
7307{
7308 struct tblentry *cmdp;
7309
7310 INT_OFF;
7311 cmdp = *lastcmdentry;
7312 *lastcmdentry = cmdp->next;
7313 if (cmdp->cmdtype == CMDFUNCTION)
7314 freefunc(cmdp->param.func);
7315 free(cmdp);
7316 INT_ON;
7317}
7318
7319/*
7320 * Add a new command entry, replacing any existing command entry for
7321 * the same name - except special builtins.
7322 */
7323static void
7324addcmdentry(char *name, struct cmdentry *entry)
7325{
7326 struct tblentry *cmdp;
7327
7328 cmdp = cmdlookup(name, 1);
7329 if (cmdp->cmdtype == CMDFUNCTION) {
7330 freefunc(cmdp->param.func);
7331 }
7332 cmdp->cmdtype = entry->cmdtype;
7333 cmdp->param = entry->u;
7334 cmdp->rehash = 0;
7335}
7336
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007337static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007338hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007339{
7340 struct tblentry **pp;
7341 struct tblentry *cmdp;
7342 int c;
7343 struct cmdentry entry;
7344 char *name;
7345
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007346 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007347 clearcmdentry(0);
7348 return 0;
7349 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007350
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007351 if (*argptr == NULL) {
7352 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7353 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7354 if (cmdp->cmdtype == CMDNORMAL)
7355 printentry(cmdp);
7356 }
7357 }
7358 return 0;
7359 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007360
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007361 c = 0;
7362 while ((name = *argptr) != NULL) {
7363 cmdp = cmdlookup(name, 0);
7364 if (cmdp != NULL
7365 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007366 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7367 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007368 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007369 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007370 find_command(name, &entry, DO_ERR, pathval());
7371 if (entry.cmdtype == CMDUNKNOWN)
7372 c = 1;
7373 argptr++;
7374 }
7375 return c;
7376}
7377
7378/*
7379 * Called when a cd is done. Marks all commands so the next time they
7380 * are executed they will be rehashed.
7381 */
7382static void
7383hashcd(void)
7384{
7385 struct tblentry **pp;
7386 struct tblentry *cmdp;
7387
7388 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7389 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007390 if (cmdp->cmdtype == CMDNORMAL
7391 || (cmdp->cmdtype == CMDBUILTIN
7392 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7393 && builtinloc > 0)
7394 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007395 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007396 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007397 }
7398 }
7399}
7400
7401/*
7402 * Fix command hash table when PATH changed.
7403 * Called before PATH is changed. The argument is the new value of PATH;
7404 * pathval() still returns the old value at this point.
7405 * Called with interrupts off.
7406 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007407static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007408changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007409{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007410 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007411 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007412 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007413 int idx_bltin;
7414
7415 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007416 firstchange = 9999; /* assume no change */
7417 idx = 0;
7418 idx_bltin = -1;
7419 for (;;) {
7420 if (*old != *new) {
7421 firstchange = idx;
7422 if ((*old == '\0' && *new == ':')
7423 || (*old == ':' && *new == '\0'))
7424 firstchange++;
7425 old = new; /* ignore subsequent differences */
7426 }
7427 if (*new == '\0')
7428 break;
7429 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7430 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007431 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007432 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007433 new++, old++;
7434 }
7435 if (builtinloc < 0 && idx_bltin >= 0)
7436 builtinloc = idx_bltin; /* zap builtins */
7437 if (builtinloc >= 0 && idx_bltin < 0)
7438 firstchange = 0;
7439 clearcmdentry(firstchange);
7440 builtinloc = idx_bltin;
7441}
7442
7443#define TEOF 0
7444#define TNL 1
7445#define TREDIR 2
7446#define TWORD 3
7447#define TSEMI 4
7448#define TBACKGND 5
7449#define TAND 6
7450#define TOR 7
7451#define TPIPE 8
7452#define TLP 9
7453#define TRP 10
7454#define TENDCASE 11
7455#define TENDBQUOTE 12
7456#define TNOT 13
7457#define TCASE 14
7458#define TDO 15
7459#define TDONE 16
7460#define TELIF 17
7461#define TELSE 18
7462#define TESAC 19
7463#define TFI 20
7464#define TFOR 21
7465#define TIF 22
7466#define TIN 23
7467#define TTHEN 24
7468#define TUNTIL 25
7469#define TWHILE 26
7470#define TBEGIN 27
7471#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007472typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007473
7474/* first char is indicating which tokens mark the end of a list */
7475static const char *const tokname_array[] = {
7476 "\1end of file",
7477 "\0newline",
7478 "\0redirection",
7479 "\0word",
7480 "\0;",
7481 "\0&",
7482 "\0&&",
7483 "\0||",
7484 "\0|",
7485 "\0(",
7486 "\1)",
7487 "\1;;",
7488 "\1`",
7489#define KWDOFFSET 13
7490 /* the following are keywords */
7491 "\0!",
7492 "\0case",
7493 "\1do",
7494 "\1done",
7495 "\1elif",
7496 "\1else",
7497 "\1esac",
7498 "\1fi",
7499 "\0for",
7500 "\0if",
7501 "\0in",
7502 "\1then",
7503 "\0until",
7504 "\0while",
7505 "\0{",
7506 "\1}",
7507};
7508
7509static const char *
7510tokname(int tok)
7511{
7512 static char buf[16];
7513
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007514//try this:
7515//if (tok < TSEMI) return tokname_array[tok] + 1;
7516//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7517//return buf;
7518
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007519 if (tok >= TSEMI)
7520 buf[0] = '"';
7521 sprintf(buf + (tok >= TSEMI), "%s%c",
7522 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7523 return buf;
7524}
7525
7526/* Wrapper around strcmp for qsort/bsearch/... */
7527static int
7528pstrcmp(const void *a, const void *b)
7529{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007530 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007531}
7532
7533static const char *const *
7534findkwd(const char *s)
7535{
7536 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007537 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7538 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007539}
7540
7541/*
7542 * Locate and print what a word is...
7543 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007544static int
7545describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007546{
7547 struct cmdentry entry;
7548 struct tblentry *cmdp;
7549#if ENABLE_ASH_ALIAS
7550 const struct alias *ap;
7551#endif
7552 const char *path = pathval();
7553
7554 if (describe_command_verbose) {
7555 out1str(command);
7556 }
7557
7558 /* First look at the keywords */
7559 if (findkwd(command)) {
7560 out1str(describe_command_verbose ? " is a shell keyword" : command);
7561 goto out;
7562 }
7563
7564#if ENABLE_ASH_ALIAS
7565 /* Then look at the aliases */
7566 ap = lookupalias(command, 0);
7567 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007568 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007569 out1str("alias ");
7570 printalias(ap);
7571 return 0;
7572 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007573 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007574 goto out;
7575 }
7576#endif
7577 /* Then check if it is a tracked alias */
7578 cmdp = cmdlookup(command, 0);
7579 if (cmdp != NULL) {
7580 entry.cmdtype = cmdp->cmdtype;
7581 entry.u = cmdp->param;
7582 } else {
7583 /* Finally use brute force */
7584 find_command(command, &entry, DO_ABS, path);
7585 }
7586
7587 switch (entry.cmdtype) {
7588 case CMDNORMAL: {
7589 int j = entry.u.index;
7590 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007591 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007592 p = command;
7593 } else {
7594 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007595 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007596 stunalloc(p);
7597 } while (--j >= 0);
7598 }
7599 if (describe_command_verbose) {
7600 out1fmt(" is%s %s",
7601 (cmdp ? " a tracked alias for" : nullstr), p
7602 );
7603 } else {
7604 out1str(p);
7605 }
7606 break;
7607 }
7608
7609 case CMDFUNCTION:
7610 if (describe_command_verbose) {
7611 out1str(" is a shell function");
7612 } else {
7613 out1str(command);
7614 }
7615 break;
7616
7617 case CMDBUILTIN:
7618 if (describe_command_verbose) {
7619 out1fmt(" is a %sshell builtin",
7620 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7621 "special " : nullstr
7622 );
7623 } else {
7624 out1str(command);
7625 }
7626 break;
7627
7628 default:
7629 if (describe_command_verbose) {
7630 out1str(": not found\n");
7631 }
7632 return 127;
7633 }
7634 out:
7635 outstr("\n", stdout);
7636 return 0;
7637}
7638
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007639static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007640typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007641{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007642 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007643 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007644 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007645
Denis Vlasenko46846e22007-05-20 13:08:31 +00007646 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007647 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007648 i++;
7649 verbose = 0;
7650 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007651 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007652 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007653 }
7654 return err;
7655}
7656
7657#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007658static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007659commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007660{
7661 int c;
7662 enum {
7663 VERIFY_BRIEF = 1,
7664 VERIFY_VERBOSE = 2,
7665 } verify = 0;
7666
7667 while ((c = nextopt("pvV")) != '\0')
7668 if (c == 'V')
7669 verify |= VERIFY_VERBOSE;
7670 else if (c == 'v')
7671 verify |= VERIFY_BRIEF;
7672#if DEBUG
7673 else if (c != 'p')
7674 abort();
7675#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007676 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7677 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007678 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007679 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007680
7681 return 0;
7682}
7683#endif
7684
7685
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007686/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007687
Denis Vlasenko340299a2008-11-21 10:36:36 +00007688static int funcblocksize; /* size of structures in function */
7689static int funcstringsize; /* size of strings in node */
7690static void *funcblock; /* block to allocate function from */
7691static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007692
Eric Andersencb57d552001-06-28 07:25:16 +00007693/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007694#define EV_EXIT 01 /* exit after evaluating tree */
7695#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007696#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007697
Denis Vlasenko340299a2008-11-21 10:36:36 +00007698static const short nodesize[N_NUMBER] = {
7699 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7700 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7701 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7702 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7703 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7704 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7705 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7706 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7707 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7708 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7709 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7710 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7711 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7712 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7713 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7714 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7715 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007716#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007717 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007718#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007719 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7720 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7721 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7722 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7723 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7724 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7725 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7726 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7727 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007728};
7729
7730static void calcsize(union node *n);
7731
7732static void
7733sizenodelist(struct nodelist *lp)
7734{
7735 while (lp) {
7736 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7737 calcsize(lp->n);
7738 lp = lp->next;
7739 }
7740}
7741
7742static void
7743calcsize(union node *n)
7744{
7745 if (n == NULL)
7746 return;
7747 funcblocksize += nodesize[n->type];
7748 switch (n->type) {
7749 case NCMD:
7750 calcsize(n->ncmd.redirect);
7751 calcsize(n->ncmd.args);
7752 calcsize(n->ncmd.assign);
7753 break;
7754 case NPIPE:
7755 sizenodelist(n->npipe.cmdlist);
7756 break;
7757 case NREDIR:
7758 case NBACKGND:
7759 case NSUBSHELL:
7760 calcsize(n->nredir.redirect);
7761 calcsize(n->nredir.n);
7762 break;
7763 case NAND:
7764 case NOR:
7765 case NSEMI:
7766 case NWHILE:
7767 case NUNTIL:
7768 calcsize(n->nbinary.ch2);
7769 calcsize(n->nbinary.ch1);
7770 break;
7771 case NIF:
7772 calcsize(n->nif.elsepart);
7773 calcsize(n->nif.ifpart);
7774 calcsize(n->nif.test);
7775 break;
7776 case NFOR:
7777 funcstringsize += strlen(n->nfor.var) + 1;
7778 calcsize(n->nfor.body);
7779 calcsize(n->nfor.args);
7780 break;
7781 case NCASE:
7782 calcsize(n->ncase.cases);
7783 calcsize(n->ncase.expr);
7784 break;
7785 case NCLIST:
7786 calcsize(n->nclist.body);
7787 calcsize(n->nclist.pattern);
7788 calcsize(n->nclist.next);
7789 break;
7790 case NDEFUN:
7791 case NARG:
7792 sizenodelist(n->narg.backquote);
7793 funcstringsize += strlen(n->narg.text) + 1;
7794 calcsize(n->narg.next);
7795 break;
7796 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007797#if ENABLE_ASH_BASH_COMPAT
7798 case NTO2:
7799#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007800 case NCLOBBER:
7801 case NFROM:
7802 case NFROMTO:
7803 case NAPPEND:
7804 calcsize(n->nfile.fname);
7805 calcsize(n->nfile.next);
7806 break;
7807 case NTOFD:
7808 case NFROMFD:
7809 calcsize(n->ndup.vname);
7810 calcsize(n->ndup.next);
7811 break;
7812 case NHERE:
7813 case NXHERE:
7814 calcsize(n->nhere.doc);
7815 calcsize(n->nhere.next);
7816 break;
7817 case NNOT:
7818 calcsize(n->nnot.com);
7819 break;
7820 };
7821}
7822
7823static char *
7824nodeckstrdup(char *s)
7825{
7826 char *rtn = funcstring;
7827
7828 strcpy(funcstring, s);
7829 funcstring += strlen(s) + 1;
7830 return rtn;
7831}
7832
7833static union node *copynode(union node *);
7834
7835static struct nodelist *
7836copynodelist(struct nodelist *lp)
7837{
7838 struct nodelist *start;
7839 struct nodelist **lpp;
7840
7841 lpp = &start;
7842 while (lp) {
7843 *lpp = funcblock;
7844 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7845 (*lpp)->n = copynode(lp->n);
7846 lp = lp->next;
7847 lpp = &(*lpp)->next;
7848 }
7849 *lpp = NULL;
7850 return start;
7851}
7852
7853static union node *
7854copynode(union node *n)
7855{
7856 union node *new;
7857
7858 if (n == NULL)
7859 return NULL;
7860 new = funcblock;
7861 funcblock = (char *) funcblock + nodesize[n->type];
7862
7863 switch (n->type) {
7864 case NCMD:
7865 new->ncmd.redirect = copynode(n->ncmd.redirect);
7866 new->ncmd.args = copynode(n->ncmd.args);
7867 new->ncmd.assign = copynode(n->ncmd.assign);
7868 break;
7869 case NPIPE:
7870 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007871 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007872 break;
7873 case NREDIR:
7874 case NBACKGND:
7875 case NSUBSHELL:
7876 new->nredir.redirect = copynode(n->nredir.redirect);
7877 new->nredir.n = copynode(n->nredir.n);
7878 break;
7879 case NAND:
7880 case NOR:
7881 case NSEMI:
7882 case NWHILE:
7883 case NUNTIL:
7884 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7885 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7886 break;
7887 case NIF:
7888 new->nif.elsepart = copynode(n->nif.elsepart);
7889 new->nif.ifpart = copynode(n->nif.ifpart);
7890 new->nif.test = copynode(n->nif.test);
7891 break;
7892 case NFOR:
7893 new->nfor.var = nodeckstrdup(n->nfor.var);
7894 new->nfor.body = copynode(n->nfor.body);
7895 new->nfor.args = copynode(n->nfor.args);
7896 break;
7897 case NCASE:
7898 new->ncase.cases = copynode(n->ncase.cases);
7899 new->ncase.expr = copynode(n->ncase.expr);
7900 break;
7901 case NCLIST:
7902 new->nclist.body = copynode(n->nclist.body);
7903 new->nclist.pattern = copynode(n->nclist.pattern);
7904 new->nclist.next = copynode(n->nclist.next);
7905 break;
7906 case NDEFUN:
7907 case NARG:
7908 new->narg.backquote = copynodelist(n->narg.backquote);
7909 new->narg.text = nodeckstrdup(n->narg.text);
7910 new->narg.next = copynode(n->narg.next);
7911 break;
7912 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007913#if ENABLE_ASH_BASH_COMPAT
7914 case NTO2:
7915#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007916 case NCLOBBER:
7917 case NFROM:
7918 case NFROMTO:
7919 case NAPPEND:
7920 new->nfile.fname = copynode(n->nfile.fname);
7921 new->nfile.fd = n->nfile.fd;
7922 new->nfile.next = copynode(n->nfile.next);
7923 break;
7924 case NTOFD:
7925 case NFROMFD:
7926 new->ndup.vname = copynode(n->ndup.vname);
7927 new->ndup.dupfd = n->ndup.dupfd;
7928 new->ndup.fd = n->ndup.fd;
7929 new->ndup.next = copynode(n->ndup.next);
7930 break;
7931 case NHERE:
7932 case NXHERE:
7933 new->nhere.doc = copynode(n->nhere.doc);
7934 new->nhere.fd = n->nhere.fd;
7935 new->nhere.next = copynode(n->nhere.next);
7936 break;
7937 case NNOT:
7938 new->nnot.com = copynode(n->nnot.com);
7939 break;
7940 };
7941 new->type = n->type;
7942 return new;
7943}
7944
7945/*
7946 * Make a copy of a parse tree.
7947 */
7948static struct funcnode *
7949copyfunc(union node *n)
7950{
7951 struct funcnode *f;
7952 size_t blocksize;
7953
7954 funcblocksize = offsetof(struct funcnode, n);
7955 funcstringsize = 0;
7956 calcsize(n);
7957 blocksize = funcblocksize;
7958 f = ckmalloc(blocksize + funcstringsize);
7959 funcblock = (char *) f + offsetof(struct funcnode, n);
7960 funcstring = (char *) f + blocksize;
7961 copynode(n);
7962 f->count = 0;
7963 return f;
7964}
7965
7966/*
7967 * Define a shell function.
7968 */
7969static void
7970defun(char *name, union node *func)
7971{
7972 struct cmdentry entry;
7973
7974 INT_OFF;
7975 entry.cmdtype = CMDFUNCTION;
7976 entry.u.func = copyfunc(func);
7977 addcmdentry(name, &entry);
7978 INT_ON;
7979}
7980
Denis Vlasenko4b875702009-03-19 13:30:04 +00007981/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007982#define SKIPBREAK (1 << 0)
7983#define SKIPCONT (1 << 1)
7984#define SKIPFUNC (1 << 2)
7985#define SKIPFILE (1 << 3)
7986#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00007987static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007988static int skipcount; /* number of levels to skip */
7989static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007990static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007991
Denis Vlasenko4b875702009-03-19 13:30:04 +00007992/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007993static int evalstring(char *s, int mask);
7994
Denis Vlasenko4b875702009-03-19 13:30:04 +00007995/* Called to execute a trap.
7996 * Single callsite - at the end of evaltree().
7997 * If we return non-zero, exaltree raises EXEXIT exception.
7998 *
7999 * Perhaps we should avoid entering new trap handlers
8000 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008001 */
8002static int
8003dotrap(void)
8004{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008005 uint8_t *g;
8006 int sig;
8007 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008008
8009 savestatus = exitstatus;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00008010 pendingsig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008011 xbarrier();
8012
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008013 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008014 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8015 int want_exexit;
8016 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008017
Denis Vlasenko4b875702009-03-19 13:30:04 +00008018 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008019 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008020 t = trap[sig];
8021 /* non-trapped SIGINT is handled separately by raise_interrupt,
8022 * don't upset it by resetting gotsig[SIGINT-1] */
8023 if (sig == SIGINT && !t)
8024 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008025
8026 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008027 *g = 0;
8028 if (!t)
8029 continue;
8030 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008031 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008032 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008033 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008034 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008035 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008036 }
8037
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008038 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008039 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008040}
8041
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008042/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008043static void evalloop(union node *, int);
8044static void evalfor(union node *, int);
8045static void evalcase(union node *, int);
8046static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008047static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008048static void evalpipe(union node *, int);
8049static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008050static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008051static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008052
Eric Andersen62483552001-07-10 06:09:16 +00008053/*
Eric Andersenc470f442003-07-28 09:56:35 +00008054 * Evaluate a parse tree. The value is left in the global variable
8055 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008056 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008057static void
Eric Andersenc470f442003-07-28 09:56:35 +00008058evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008059{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008060 struct jmploc *volatile savehandler = exception_handler;
8061 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008062 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008063 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008064 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008065 int int_level;
8066
8067 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008068
Eric Andersenc470f442003-07-28 09:56:35 +00008069 if (n == NULL) {
8070 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008071 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008072 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008073 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008074
8075 exception_handler = &jmploc;
8076 {
8077 int err = setjmp(jmploc.loc);
8078 if (err) {
8079 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008080 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008081 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8082 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008083 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008084 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008085 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008086 TRACE(("exception %d in evaltree, propagating err=%d\n",
8087 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008088 exception_handler = savehandler;
8089 longjmp(exception_handler->loc, err);
8090 }
8091 }
8092
Eric Andersenc470f442003-07-28 09:56:35 +00008093 switch (n->type) {
8094 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008095#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008096 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008097 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008098 break;
8099#endif
8100 case NNOT:
8101 evaltree(n->nnot.com, EV_TESTED);
8102 status = !exitstatus;
8103 goto setstatus;
8104 case NREDIR:
8105 expredir(n->nredir.redirect);
8106 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8107 if (!status) {
8108 evaltree(n->nredir.n, flags & EV_TESTED);
8109 status = exitstatus;
8110 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008111 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008112 goto setstatus;
8113 case NCMD:
8114 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008115 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008116 if (eflag && !(flags & EV_TESTED))
8117 checkexit = ~0;
8118 goto calleval;
8119 case NFOR:
8120 evalfn = evalfor;
8121 goto calleval;
8122 case NWHILE:
8123 case NUNTIL:
8124 evalfn = evalloop;
8125 goto calleval;
8126 case NSUBSHELL:
8127 case NBACKGND:
8128 evalfn = evalsubshell;
8129 goto calleval;
8130 case NPIPE:
8131 evalfn = evalpipe;
8132 goto checkexit;
8133 case NCASE:
8134 evalfn = evalcase;
8135 goto calleval;
8136 case NAND:
8137 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008138 case NSEMI: {
8139
Eric Andersenc470f442003-07-28 09:56:35 +00008140#if NAND + 1 != NOR
8141#error NAND + 1 != NOR
8142#endif
8143#if NOR + 1 != NSEMI
8144#error NOR + 1 != NSEMI
8145#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008146 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008147 evaltree(
8148 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008149 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008150 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008151 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008152 break;
8153 if (!evalskip) {
8154 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008155 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008156 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008157 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008158 evalfn(n, flags);
8159 break;
8160 }
8161 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008162 }
Eric Andersenc470f442003-07-28 09:56:35 +00008163 case NIF:
8164 evaltree(n->nif.test, EV_TESTED);
8165 if (evalskip)
8166 break;
8167 if (exitstatus == 0) {
8168 n = n->nif.ifpart;
8169 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008170 }
8171 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008172 n = n->nif.elsepart;
8173 goto evaln;
8174 }
8175 goto success;
8176 case NDEFUN:
8177 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008178 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008179 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008180 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008181 exitstatus = status;
8182 break;
8183 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008184
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008185 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008186 exception_handler = savehandler;
8187 out1:
8188 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008189 evalskip |= SKIPEVAL;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00008190 else if (pendingsig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008191 goto exexit;
8192
8193 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008194 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008195 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008196 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008197
8198 RESTORE_INT(int_level);
8199 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008200}
8201
Eric Andersenc470f442003-07-28 09:56:35 +00008202#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8203static
8204#endif
8205void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8206
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008207static void
Eric Andersenc470f442003-07-28 09:56:35 +00008208evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008209{
8210 int status;
8211
8212 loopnest++;
8213 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008214 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008215 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008216 int i;
8217
Eric Andersencb57d552001-06-28 07:25:16 +00008218 evaltree(n->nbinary.ch1, EV_TESTED);
8219 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008220 skipping:
8221 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008222 evalskip = 0;
8223 continue;
8224 }
8225 if (evalskip == SKIPBREAK && --skipcount <= 0)
8226 evalskip = 0;
8227 break;
8228 }
Eric Andersenc470f442003-07-28 09:56:35 +00008229 i = exitstatus;
8230 if (n->type != NWHILE)
8231 i = !i;
8232 if (i != 0)
8233 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008234 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008235 status = exitstatus;
8236 if (evalskip)
8237 goto skipping;
8238 }
8239 loopnest--;
8240 exitstatus = status;
8241}
8242
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008243static void
Eric Andersenc470f442003-07-28 09:56:35 +00008244evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008245{
8246 struct arglist arglist;
8247 union node *argp;
8248 struct strlist *sp;
8249 struct stackmark smark;
8250
8251 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008252 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008253 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008254 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008255 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008256 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008257 if (evalskip)
8258 goto out;
8259 }
8260 *arglist.lastp = NULL;
8261
8262 exitstatus = 0;
8263 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008264 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008265 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008266 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008267 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008268 if (evalskip) {
8269 if (evalskip == SKIPCONT && --skipcount <= 0) {
8270 evalskip = 0;
8271 continue;
8272 }
8273 if (evalskip == SKIPBREAK && --skipcount <= 0)
8274 evalskip = 0;
8275 break;
8276 }
8277 }
8278 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008279 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008280 popstackmark(&smark);
8281}
8282
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008283static void
Eric Andersenc470f442003-07-28 09:56:35 +00008284evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008285{
8286 union node *cp;
8287 union node *patp;
8288 struct arglist arglist;
8289 struct stackmark smark;
8290
8291 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008292 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008293 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008294 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008295 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008296 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8297 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008298 if (casematch(patp, arglist.list->text)) {
8299 if (evalskip == 0) {
8300 evaltree(cp->nclist.body, flags);
8301 }
8302 goto out;
8303 }
8304 }
8305 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008306 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008307 popstackmark(&smark);
8308}
8309
Eric Andersenc470f442003-07-28 09:56:35 +00008310/*
8311 * Kick off a subshell to evaluate a tree.
8312 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008313static void
Eric Andersenc470f442003-07-28 09:56:35 +00008314evalsubshell(union node *n, int flags)
8315{
8316 struct job *jp;
8317 int backgnd = (n->type == NBACKGND);
8318 int status;
8319
8320 expredir(n->nredir.redirect);
8321 if (!backgnd && flags & EV_EXIT && !trap[0])
8322 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008323 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008324 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008325 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008326 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008327 flags |= EV_EXIT;
8328 if (backgnd)
8329 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008330 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008331 redirect(n->nredir.redirect, 0);
8332 evaltreenr(n->nredir.n, flags);
8333 /* never returns */
8334 }
8335 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008336 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008337 status = waitforjob(jp);
8338 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008339 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008340}
8341
Eric Andersenc470f442003-07-28 09:56:35 +00008342/*
8343 * Compute the names of the files in a redirection list.
8344 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008345static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008346static void
8347expredir(union node *n)
8348{
8349 union node *redir;
8350
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008351 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008352 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008353
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008354 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008355 fn.lastp = &fn.list;
8356 switch (redir->type) {
8357 case NFROMTO:
8358 case NFROM:
8359 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008360#if ENABLE_ASH_BASH_COMPAT
8361 case NTO2:
8362#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008363 case NCLOBBER:
8364 case NAPPEND:
8365 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008366#if ENABLE_ASH_BASH_COMPAT
8367 store_expfname:
8368#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008369 redir->nfile.expfname = fn.list->text;
8370 break;
8371 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008372 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008373 if (redir->ndup.vname) {
8374 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008375 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008376 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008377#if ENABLE_ASH_BASH_COMPAT
8378//FIXME: we used expandarg with different args!
8379 if (!isdigit_str9(fn.list->text)) {
8380 /* >&file, not >&fd */
8381 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8382 ash_msg_and_raise_error("redir error");
8383 redir->type = NTO2;
8384 goto store_expfname;
8385 }
8386#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008387 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008388 }
8389 break;
8390 }
8391 }
8392}
8393
Eric Andersencb57d552001-06-28 07:25:16 +00008394/*
Eric Andersencb57d552001-06-28 07:25:16 +00008395 * Evaluate a pipeline. All the processes in the pipeline are children
8396 * of the process creating the pipeline. (This differs from some versions
8397 * of the shell, which make the last process in a pipeline the parent
8398 * of all the rest.)
8399 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008400static void
Eric Andersenc470f442003-07-28 09:56:35 +00008401evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008402{
8403 struct job *jp;
8404 struct nodelist *lp;
8405 int pipelen;
8406 int prevfd;
8407 int pip[2];
8408
Eric Andersenc470f442003-07-28 09:56:35 +00008409 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008410 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008411 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008412 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008413 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008414 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008415 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008416 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008417 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008418 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008419 pip[1] = -1;
8420 if (lp->next) {
8421 if (pipe(pip) < 0) {
8422 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008423 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008424 }
8425 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008426 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008427 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008428 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008429 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008430 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008431 if (prevfd > 0) {
8432 dup2(prevfd, 0);
8433 close(prevfd);
8434 }
8435 if (pip[1] > 1) {
8436 dup2(pip[1], 1);
8437 close(pip[1]);
8438 }
Eric Andersenc470f442003-07-28 09:56:35 +00008439 evaltreenr(lp->n, flags);
8440 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008441 }
8442 if (prevfd >= 0)
8443 close(prevfd);
8444 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008445 /* Don't want to trigger debugging */
8446 if (pip[1] != -1)
8447 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008448 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008449 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008450 exitstatus = waitforjob(jp);
8451 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008452 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008453 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008454}
8455
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008456/*
8457 * Controls whether the shell is interactive or not.
8458 */
8459static void
8460setinteractive(int on)
8461{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008462 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008463
8464 if (++on == is_interactive)
8465 return;
8466 is_interactive = on;
8467 setsignal(SIGINT);
8468 setsignal(SIGQUIT);
8469 setsignal(SIGTERM);
8470#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8471 if (is_interactive > 1) {
8472 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008473 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008474
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008475 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008476 out1fmt(
8477 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008478 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008479 "Enter 'help' for a list of built-in commands."
8480 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008481 bb_banner);
8482 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008483 }
8484 }
8485#endif
8486}
8487
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008488static void
8489optschanged(void)
8490{
8491#if DEBUG
8492 opentrace();
8493#endif
8494 setinteractive(iflag);
8495 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008496#if ENABLE_FEATURE_EDITING_VI
8497 if (viflag)
8498 line_input_state->flags |= VI_MODE;
8499 else
8500 line_input_state->flags &= ~VI_MODE;
8501#else
8502 viflag = 0; /* forcibly keep the option off */
8503#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008504}
8505
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008506static struct localvar *localvars;
8507
8508/*
8509 * Called after a function returns.
8510 * Interrupts must be off.
8511 */
8512static void
8513poplocalvars(void)
8514{
8515 struct localvar *lvp;
8516 struct var *vp;
8517
8518 while ((lvp = localvars) != NULL) {
8519 localvars = lvp->next;
8520 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008521 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008522 if (vp == NULL) { /* $- saved */
8523 memcpy(optlist, lvp->text, sizeof(optlist));
8524 free((char*)lvp->text);
8525 optschanged();
8526 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8527 unsetvar(vp->text);
8528 } else {
8529 if (vp->func)
8530 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8531 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8532 free((char*)vp->text);
8533 vp->flags = lvp->flags;
8534 vp->text = lvp->text;
8535 }
8536 free(lvp);
8537 }
8538}
8539
8540static int
8541evalfun(struct funcnode *func, int argc, char **argv, int flags)
8542{
8543 volatile struct shparam saveparam;
8544 struct localvar *volatile savelocalvars;
8545 struct jmploc *volatile savehandler;
8546 struct jmploc jmploc;
8547 int e;
8548
8549 saveparam = shellparam;
8550 savelocalvars = localvars;
8551 e = setjmp(jmploc.loc);
8552 if (e) {
8553 goto funcdone;
8554 }
8555 INT_OFF;
8556 savehandler = exception_handler;
8557 exception_handler = &jmploc;
8558 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008559 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008560 func->count++;
8561 funcnest++;
8562 INT_ON;
8563 shellparam.nparam = argc - 1;
8564 shellparam.p = argv + 1;
8565#if ENABLE_ASH_GETOPTS
8566 shellparam.optind = 1;
8567 shellparam.optoff = -1;
8568#endif
8569 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008570 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008571 INT_OFF;
8572 funcnest--;
8573 freefunc(func);
8574 poplocalvars();
8575 localvars = savelocalvars;
8576 freeparam(&shellparam);
8577 shellparam = saveparam;
8578 exception_handler = savehandler;
8579 INT_ON;
8580 evalskip &= ~SKIPFUNC;
8581 return e;
8582}
8583
Denis Vlasenko131ae172007-02-18 13:00:19 +00008584#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008585static char **
8586parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008587{
8588 char *cp, c;
8589
8590 for (;;) {
8591 cp = *++argv;
8592 if (!cp)
8593 return 0;
8594 if (*cp++ != '-')
8595 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008596 c = *cp++;
8597 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008598 break;
8599 if (c == '-' && !*cp) {
8600 argv++;
8601 break;
8602 }
8603 do {
8604 switch (c) {
8605 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008606 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008607 break;
8608 default:
8609 /* run 'typecmd' for other options */
8610 return 0;
8611 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008612 c = *cp++;
8613 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008614 }
8615 return argv;
8616}
8617#endif
8618
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008619/*
8620 * Make a variable a local variable. When a variable is made local, it's
8621 * value and flags are saved in a localvar structure. The saved values
8622 * will be restored when the shell function returns. We handle the name
8623 * "-" as a special case.
8624 */
8625static void
8626mklocal(char *name)
8627{
8628 struct localvar *lvp;
8629 struct var **vpp;
8630 struct var *vp;
8631
8632 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008633 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008634 if (LONE_DASH(name)) {
8635 char *p;
8636 p = ckmalloc(sizeof(optlist));
8637 lvp->text = memcpy(p, optlist, sizeof(optlist));
8638 vp = NULL;
8639 } else {
8640 char *eq;
8641
8642 vpp = hashvar(name);
8643 vp = *findvar(vpp, name);
8644 eq = strchr(name, '=');
8645 if (vp == NULL) {
8646 if (eq)
8647 setvareq(name, VSTRFIXED);
8648 else
8649 setvar(name, NULL, VSTRFIXED);
8650 vp = *vpp; /* the new variable */
8651 lvp->flags = VUNSET;
8652 } else {
8653 lvp->text = vp->text;
8654 lvp->flags = vp->flags;
8655 vp->flags |= VSTRFIXED|VTEXTFIXED;
8656 if (eq)
8657 setvareq(name, 0);
8658 }
8659 }
8660 lvp->vp = vp;
8661 lvp->next = localvars;
8662 localvars = lvp;
8663 INT_ON;
8664}
8665
8666/*
8667 * The "local" command.
8668 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008669static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008670localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008671{
8672 char *name;
8673
8674 argv = argptr;
8675 while ((name = *argv++) != NULL) {
8676 mklocal(name);
8677 }
8678 return 0;
8679}
8680
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008681static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008682falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008683{
8684 return 1;
8685}
8686
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008687static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008688truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008689{
8690 return 0;
8691}
8692
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008693static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008694execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008695{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008696 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008697 iflag = 0; /* exit on error */
8698 mflag = 0;
8699 optschanged();
8700 shellexec(argv + 1, pathval(), 0);
8701 }
8702 return 0;
8703}
8704
8705/*
8706 * The return command.
8707 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008708static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008709returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008710{
8711 /*
8712 * If called outside a function, do what ksh does;
8713 * skip the rest of the file.
8714 */
8715 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8716 return argv[1] ? number(argv[1]) : exitstatus;
8717}
8718
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008719/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008720static int breakcmd(int, char **) FAST_FUNC;
8721static int dotcmd(int, char **) FAST_FUNC;
8722static int evalcmd(int, char **) FAST_FUNC;
8723static int exitcmd(int, char **) FAST_FUNC;
8724static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008725#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008726static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008727#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008728#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008729static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008730#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008731#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008732static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008733#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008734static int readcmd(int, char **) FAST_FUNC;
8735static int setcmd(int, char **) FAST_FUNC;
8736static int shiftcmd(int, char **) FAST_FUNC;
8737static int timescmd(int, char **) FAST_FUNC;
8738static int trapcmd(int, char **) FAST_FUNC;
8739static int umaskcmd(int, char **) FAST_FUNC;
8740static int unsetcmd(int, char **) FAST_FUNC;
8741static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008742
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008743#define BUILTIN_NOSPEC "0"
8744#define BUILTIN_SPECIAL "1"
8745#define BUILTIN_REGULAR "2"
8746#define BUILTIN_SPEC_REG "3"
8747#define BUILTIN_ASSIGN "4"
8748#define BUILTIN_SPEC_ASSG "5"
8749#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008750#define BUILTIN_SPEC_REG_ASSG "7"
8751
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008752/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008753#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008754static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008755#endif
8756#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008757static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008758#endif
8759#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008760static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008761#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008762
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008763/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008764static const struct builtincmd builtintab[] = {
8765 { BUILTIN_SPEC_REG ".", dotcmd },
8766 { BUILTIN_SPEC_REG ":", truecmd },
8767#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008768 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008769#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008770 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008771#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008772#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008773#if ENABLE_ASH_ALIAS
8774 { BUILTIN_REG_ASSG "alias", aliascmd },
8775#endif
8776#if JOBS
8777 { BUILTIN_REGULAR "bg", fg_bgcmd },
8778#endif
8779 { BUILTIN_SPEC_REG "break", breakcmd },
8780 { BUILTIN_REGULAR "cd", cdcmd },
8781 { BUILTIN_NOSPEC "chdir", cdcmd },
8782#if ENABLE_ASH_CMDCMD
8783 { BUILTIN_REGULAR "command", commandcmd },
8784#endif
8785 { BUILTIN_SPEC_REG "continue", breakcmd },
8786#if ENABLE_ASH_BUILTIN_ECHO
8787 { BUILTIN_REGULAR "echo", echocmd },
8788#endif
8789 { BUILTIN_SPEC_REG "eval", evalcmd },
8790 { BUILTIN_SPEC_REG "exec", execcmd },
8791 { BUILTIN_SPEC_REG "exit", exitcmd },
8792 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8793 { BUILTIN_REGULAR "false", falsecmd },
8794#if JOBS
8795 { BUILTIN_REGULAR "fg", fg_bgcmd },
8796#endif
8797#if ENABLE_ASH_GETOPTS
8798 { BUILTIN_REGULAR "getopts", getoptscmd },
8799#endif
8800 { BUILTIN_NOSPEC "hash", hashcmd },
8801#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8802 { BUILTIN_NOSPEC "help", helpcmd },
8803#endif
8804#if JOBS
8805 { BUILTIN_REGULAR "jobs", jobscmd },
8806 { BUILTIN_REGULAR "kill", killcmd },
8807#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008808#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008809 { BUILTIN_NOSPEC "let", letcmd },
8810#endif
8811 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008812#if ENABLE_ASH_BUILTIN_PRINTF
8813 { BUILTIN_REGULAR "printf", printfcmd },
8814#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008815 { BUILTIN_NOSPEC "pwd", pwdcmd },
8816 { BUILTIN_REGULAR "read", readcmd },
8817 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8818 { BUILTIN_SPEC_REG "return", returncmd },
8819 { BUILTIN_SPEC_REG "set", setcmd },
8820 { BUILTIN_SPEC_REG "shift", shiftcmd },
8821 { BUILTIN_SPEC_REG "source", dotcmd },
8822#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008823 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008824#endif
8825 { BUILTIN_SPEC_REG "times", timescmd },
8826 { BUILTIN_SPEC_REG "trap", trapcmd },
8827 { BUILTIN_REGULAR "true", truecmd },
8828 { BUILTIN_NOSPEC "type", typecmd },
8829 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8830 { BUILTIN_REGULAR "umask", umaskcmd },
8831#if ENABLE_ASH_ALIAS
8832 { BUILTIN_REGULAR "unalias", unaliascmd },
8833#endif
8834 { BUILTIN_SPEC_REG "unset", unsetcmd },
8835 { BUILTIN_REGULAR "wait", waitcmd },
8836};
8837
Denis Vlasenko80591b02008-03-25 07:49:43 +00008838/* Should match the above table! */
8839#define COMMANDCMD (builtintab + \
8840 2 + \
8841 1 * ENABLE_ASH_BUILTIN_TEST + \
8842 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8843 1 * ENABLE_ASH_ALIAS + \
8844 1 * ENABLE_ASH_JOB_CONTROL + \
8845 3)
8846#define EXECCMD (builtintab + \
8847 2 + \
8848 1 * ENABLE_ASH_BUILTIN_TEST + \
8849 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8850 1 * ENABLE_ASH_ALIAS + \
8851 1 * ENABLE_ASH_JOB_CONTROL + \
8852 3 + \
8853 1 * ENABLE_ASH_CMDCMD + \
8854 1 + \
8855 ENABLE_ASH_BUILTIN_ECHO + \
8856 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008857
8858/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008859 * Search the table of builtin commands.
8860 */
8861static struct builtincmd *
8862find_builtin(const char *name)
8863{
8864 struct builtincmd *bp;
8865
8866 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008867 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008868 pstrcmp
8869 );
8870 return bp;
8871}
8872
8873/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008874 * Execute a simple command.
8875 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008876static int
8877isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008878{
8879 const char *q = endofname(p);
8880 if (p == q)
8881 return 0;
8882 return *q == '=';
8883}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008884static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008885bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008886{
8887 /* Preserve exitstatus of a previous possible redirection
8888 * as POSIX mandates */
8889 return back_exitstatus;
8890}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008891static void
Eric Andersenc470f442003-07-28 09:56:35 +00008892evalcommand(union node *cmd, int flags)
8893{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008894 static const struct builtincmd null_bltin = {
8895 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896 };
Eric Andersenc470f442003-07-28 09:56:35 +00008897 struct stackmark smark;
8898 union node *argp;
8899 struct arglist arglist;
8900 struct arglist varlist;
8901 char **argv;
8902 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008903 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008904 struct cmdentry cmdentry;
8905 struct job *jp;
8906 char *lastarg;
8907 const char *path;
8908 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008909 int status;
8910 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008911 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008912 smallint cmd_is_exec;
8913 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008914
8915 /* First expand the arguments. */
8916 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8917 setstackmark(&smark);
8918 back_exitstatus = 0;
8919
8920 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008921 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008922 varlist.lastp = &varlist.list;
8923 *varlist.lastp = NULL;
8924 arglist.lastp = &arglist.list;
8925 *arglist.lastp = NULL;
8926
8927 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008928 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008929 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8930 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8931 }
8932
Eric Andersenc470f442003-07-28 09:56:35 +00008933 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8934 struct strlist **spp;
8935
8936 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008937 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008938 expandarg(argp, &arglist, EXP_VARTILDE);
8939 else
8940 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8941
Eric Andersenc470f442003-07-28 09:56:35 +00008942 for (sp = *spp; sp; sp = sp->next)
8943 argc++;
8944 }
8945
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008946 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008947 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008948 TRACE(("evalcommand arg: %s\n", sp->text));
8949 *nargv++ = sp->text;
8950 }
8951 *nargv = NULL;
8952
8953 lastarg = NULL;
8954 if (iflag && funcnest == 0 && argc > 0)
8955 lastarg = nargv[-1];
8956
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008957 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008958 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008959 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008960
8961 path = vpath.text;
8962 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8963 struct strlist **spp;
8964 char *p;
8965
8966 spp = varlist.lastp;
8967 expandarg(argp, &varlist, EXP_VARTILDE);
8968
8969 /*
8970 * Modify the command lookup path, if a PATH= assignment
8971 * is present
8972 */
8973 p = (*spp)->text;
8974 if (varequal(p, path))
8975 path = p;
8976 }
8977
8978 /* Print the command if xflag is set. */
8979 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008980 int n;
8981 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008982
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008983 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008984 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008985
8986 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008987 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008988 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008989 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008990 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008991 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008992 p--;
8993 }
8994 }
8995 sp = arglist.list;
8996 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008997 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008998 }
8999
9000 cmd_is_exec = 0;
9001 spclbltin = -1;
9002
9003 /* Now locate the command. */
9004 if (argc) {
9005 const char *oldpath;
9006 int cmd_flag = DO_ERR;
9007
9008 path += 5;
9009 oldpath = path;
9010 for (;;) {
9011 find_command(argv[0], &cmdentry, cmd_flag, path);
9012 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009013 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009014 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009015 goto bail;
9016 }
9017
9018 /* implement bltin and command here */
9019 if (cmdentry.cmdtype != CMDBUILTIN)
9020 break;
9021 if (spclbltin < 0)
9022 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9023 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009024 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009025#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009026 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009027 path = oldpath;
9028 nargv = parse_command_args(argv, &path);
9029 if (!nargv)
9030 break;
9031 argc -= nargv - argv;
9032 argv = nargv;
9033 cmd_flag |= DO_NOFUNC;
9034 } else
9035#endif
9036 break;
9037 }
9038 }
9039
9040 if (status) {
9041 /* We have a redirection error. */
9042 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009043 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009044 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009045 exitstatus = status;
9046 goto out;
9047 }
9048
9049 /* Execute the command. */
9050 switch (cmdentry.cmdtype) {
9051 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009052
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009053#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009054/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9055 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009056 {
9057 /* find_command() encodes applet_no as (-2 - applet_no) */
9058 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009059 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009060 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009061 /* run <applet>_main() */
9062 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009063 break;
9064 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009065 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009066#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009067 /* Fork off a child process if necessary. */
9068 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009069 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009070 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009071 if (forkshell(jp, cmd, FORK_FG) != 0) {
9072 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009073 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009074 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009075 break;
9076 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009077 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009078 }
9079 listsetvar(varlist.list, VEXPORT|VSTACK);
9080 shellexec(argv, path, cmdentry.u.index);
9081 /* NOTREACHED */
9082
9083 case CMDBUILTIN:
9084 cmdenviron = varlist.list;
9085 if (cmdenviron) {
9086 struct strlist *list = cmdenviron;
9087 int i = VNOSET;
9088 if (spclbltin > 0 || argc == 0) {
9089 i = 0;
9090 if (cmd_is_exec && argc > 1)
9091 i = VEXPORT;
9092 }
9093 listsetvar(list, i);
9094 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009095 /* Tight loop with builtins only:
9096 * "while kill -0 $child; do true; done"
9097 * will never exit even if $child died, unless we do this
9098 * to reap the zombie and make kill detect that it's gone: */
9099 dowait(DOWAIT_NONBLOCK, NULL);
9100
Eric Andersenc470f442003-07-28 09:56:35 +00009101 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9102 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009103 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009104 if (i == EXEXIT)
9105 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009106 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009107 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009108 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009109 if (i == EXSIG)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009110 exit_status = 128 + pendingsig;
Eric Andersenc470f442003-07-28 09:56:35 +00009111 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009112 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009113 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009114 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009115 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009116 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009117 }
9118 break;
9119
9120 case CMDFUNCTION:
9121 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009122 /* See above for the rationale */
9123 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009124 if (evalfun(cmdentry.u.func, argc, argv, flags))
9125 goto raise;
9126 break;
9127 }
9128
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009129 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009130 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009131 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009132 /* dsl: I think this is intended to be used to support
9133 * '_' in 'vi' command mode during line editing...
9134 * However I implemented that within libedit itself.
9135 */
9136 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009137 }
Eric Andersenc470f442003-07-28 09:56:35 +00009138 popstackmark(&smark);
9139}
9140
9141static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009142evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9143{
Eric Andersenc470f442003-07-28 09:56:35 +00009144 char *volatile savecmdname;
9145 struct jmploc *volatile savehandler;
9146 struct jmploc jmploc;
9147 int i;
9148
9149 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009150 i = setjmp(jmploc.loc);
9151 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009152 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009153 savehandler = exception_handler;
9154 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009155 commandname = argv[0];
9156 argptr = argv + 1;
9157 optptr = NULL; /* initialize nextopt */
9158 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009159 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009160 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009161 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009162 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009163 commandname = savecmdname;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009164// exsig = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009165 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009166
9167 return i;
9168}
9169
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009170static int
9171goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009172{
9173 return !*endofname(p);
9174}
9175
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009176
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009177/*
9178 * Search for a command. This is called before we fork so that the
9179 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009180 * the child. The check for "goodname" is an overly conservative
9181 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009182 */
Eric Andersenc470f442003-07-28 09:56:35 +00009183static void
9184prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009185{
9186 struct cmdentry entry;
9187
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009188 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9189 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009190}
9191
Eric Andersencb57d552001-06-28 07:25:16 +00009192
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009193/* ============ Builtin commands
9194 *
9195 * Builtin commands whose functions are closely tied to evaluation
9196 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009197 */
9198
9199/*
Eric Andersencb57d552001-06-28 07:25:16 +00009200 * Handle break and continue commands. Break, continue, and return are
9201 * all handled by setting the evalskip flag. The evaluation routines
9202 * above all check this flag, and if it is set they start skipping
9203 * commands rather than executing them. The variable skipcount is
9204 * the number of loops to break/continue, or the number of function
9205 * levels to return. (The latter is always 1.) It should probably
9206 * be an error to break out of more loops than exist, but it isn't
9207 * in the standard shell so we don't make it one here.
9208 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009209static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009210breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009211{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009212 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009213
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009214 if (n <= 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009215 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009216 if (n > loopnest)
9217 n = loopnest;
9218 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009219 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009220 skipcount = n;
9221 }
9222 return 0;
9223}
9224
Eric Andersenc470f442003-07-28 09:56:35 +00009225
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009226/* ============ input.c
9227 *
Eric Andersen90898442003-08-06 11:20:52 +00009228 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009229 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009230
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009231enum {
9232 INPUT_PUSH_FILE = 1,
9233 INPUT_NOFILE_OK = 2,
9234};
Eric Andersencb57d552001-06-28 07:25:16 +00009235
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009236static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009237/* values of checkkwd variable */
9238#define CHKALIAS 0x1
9239#define CHKKWD 0x2
9240#define CHKNL 0x4
9241
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009242/*
9243 * Push a string back onto the input at this current parsefile level.
9244 * We handle aliases this way.
9245 */
9246#if !ENABLE_ASH_ALIAS
9247#define pushstring(s, ap) pushstring(s)
9248#endif
9249static void
9250pushstring(char *s, struct alias *ap)
9251{
9252 struct strpush *sp;
9253 int len;
9254
9255 len = strlen(s);
9256 INT_OFF;
9257 if (g_parsefile->strpush) {
9258 sp = ckzalloc(sizeof(*sp));
9259 sp->prev = g_parsefile->strpush;
9260 } else {
9261 sp = &(g_parsefile->basestrpush);
9262 }
9263 g_parsefile->strpush = sp;
9264 sp->prev_string = g_parsefile->next_to_pgetc;
9265 sp->prev_left_in_line = g_parsefile->left_in_line;
9266#if ENABLE_ASH_ALIAS
9267 sp->ap = ap;
9268 if (ap) {
9269 ap->flag |= ALIASINUSE;
9270 sp->string = s;
9271 }
9272#endif
9273 g_parsefile->next_to_pgetc = s;
9274 g_parsefile->left_in_line = len;
9275 INT_ON;
9276}
9277
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009278static void
9279popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009280{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009281 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009282
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009283 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009284#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009285 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009286 if (g_parsefile->next_to_pgetc[-1] == ' '
9287 || g_parsefile->next_to_pgetc[-1] == '\t'
9288 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009289 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009290 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009291 if (sp->string != sp->ap->val) {
9292 free(sp->string);
9293 }
9294 sp->ap->flag &= ~ALIASINUSE;
9295 if (sp->ap->flag & ALIASDEAD) {
9296 unalias(sp->ap->name);
9297 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009298 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009299#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009300 g_parsefile->next_to_pgetc = sp->prev_string;
9301 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009302 g_parsefile->strpush = sp->prev;
9303 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009304 free(sp);
9305 INT_ON;
9306}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009307
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009308//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9309//it peeks whether it is &>, and then pushes back both chars.
9310//This function needs to save last *next_to_pgetc to buf[0]
9311//to make two pungetc() reliable. Currently,
9312// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009313static int
9314preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009315{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009316 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009317 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009318
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009319 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009320#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009321 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009322 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009323 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009324 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009325#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009326 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009327#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009328 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9329 if (nr == 0) {
9330 /* Ctrl+C pressed */
9331 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009332 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009333 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009334 raise(SIGINT);
9335 return 1;
9336 }
Eric Andersenc470f442003-07-28 09:56:35 +00009337 goto retry;
9338 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009339 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009340 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009341 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009342 }
Eric Andersencb57d552001-06-28 07:25:16 +00009343 }
9344#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009345 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009346#endif
9347
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009348#if 0
9349/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009350 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009351 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009352 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009353 if (flags >= 0 && (flags & O_NONBLOCK)) {
9354 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009355 if (fcntl(0, F_SETFL, flags) >= 0) {
9356 out2str("sh: turning off NDELAY mode\n");
9357 goto retry;
9358 }
9359 }
9360 }
9361 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009362#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009363 return nr;
9364}
9365
9366/*
9367 * Refill the input buffer and return the next input character:
9368 *
9369 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009370 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9371 * or we are reading from a string so we can't refill the buffer,
9372 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009373 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009374 * 4) Process input up to the next newline, deleting nul characters.
9375 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009376//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9377#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009378/*
9379 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9380 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9381 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9382 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9383 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009384static int
Eric Andersenc470f442003-07-28 09:56:35 +00009385preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009386{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009387 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009388 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009389
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009390 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009391#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009392 if (g_parsefile->left_in_line == -1
9393 && g_parsefile->strpush->ap
9394 && g_parsefile->next_to_pgetc[-1] != ' '
9395 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009396 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009397 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009398 return PEOA;
9399 }
Eric Andersen2870d962001-07-02 17:27:21 +00009400#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009401 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009402 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009403 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9404 g_parsefile->left_in_line,
9405 g_parsefile->next_to_pgetc,
9406 g_parsefile->next_to_pgetc);
9407 if (--g_parsefile->left_in_line >= 0)
9408 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009409 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009410 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009411 * "pgetc" needs refilling.
9412 */
9413
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009414 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009415 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009416 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009417 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009418 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009419 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009420 /* even in failure keep left_in_line and next_to_pgetc
9421 * in lock step, for correct multi-layer pungetc.
9422 * left_in_line was decremented before preadbuffer(),
9423 * must inc next_to_pgetc: */
9424 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009425 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009426 }
Eric Andersencb57d552001-06-28 07:25:16 +00009427
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009428 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009429 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009430 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009431 again:
9432 more = preadfd();
9433 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009434 /* don't try reading again */
9435 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009436 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009437 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009438 return PEOF;
9439 }
9440 }
9441
Denis Vlasenko727752d2008-11-28 03:41:47 +00009442 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009443 * Set g_parsefile->left_in_line
9444 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009445 * NUL chars are deleted.
9446 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009447 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009448 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009449 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009450
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009451 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009452
Denis Vlasenko727752d2008-11-28 03:41:47 +00009453 c = *q;
9454 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009455 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009456 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009457 q++;
9458 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009459 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009460 break;
9461 }
Eric Andersencb57d552001-06-28 07:25:16 +00009462 }
9463
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009464 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009465 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9466 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009467 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009468 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009469 }
9470 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009471 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009472
Eric Andersencb57d552001-06-28 07:25:16 +00009473 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009474 char save = *q;
9475 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009476 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009477 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009478 }
9479
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009480 pgetc_debug("preadbuffer at %d:%p'%s'",
9481 g_parsefile->left_in_line,
9482 g_parsefile->next_to_pgetc,
9483 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009484 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009485}
9486
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009487#define pgetc_as_macro() \
9488 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009489 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009490 : preadbuffer() \
9491 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009492
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009493static int
9494pgetc(void)
9495{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 pgetc_debug("pgetc_fast at %d:%p'%s'",
9497 g_parsefile->left_in_line,
9498 g_parsefile->next_to_pgetc,
9499 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009500 return pgetc_as_macro();
9501}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009502
9503#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009504#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009505#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009506#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009507#endif
9508
9509/*
9510 * Same as pgetc(), but ignores PEOA.
9511 */
9512#if ENABLE_ASH_ALIAS
9513static int
9514pgetc2(void)
9515{
9516 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009517 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009518 pgetc_debug("pgetc_fast at %d:%p'%s'",
9519 g_parsefile->left_in_line,
9520 g_parsefile->next_to_pgetc,
9521 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009522 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009523 } while (c == PEOA);
9524 return c;
9525}
9526#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009527#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009528#endif
9529
9530/*
9531 * Read a line from the script.
9532 */
9533static char *
9534pfgets(char *line, int len)
9535{
9536 char *p = line;
9537 int nleft = len;
9538 int c;
9539
9540 while (--nleft > 0) {
9541 c = pgetc2();
9542 if (c == PEOF) {
9543 if (p == line)
9544 return NULL;
9545 break;
9546 }
9547 *p++ = c;
9548 if (c == '\n')
9549 break;
9550 }
9551 *p = '\0';
9552 return line;
9553}
9554
Eric Andersenc470f442003-07-28 09:56:35 +00009555/*
9556 * Undo the last call to pgetc. Only one character may be pushed back.
9557 * PEOF may be pushed back.
9558 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009559static void
Eric Andersenc470f442003-07-28 09:56:35 +00009560pungetc(void)
9561{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009562 g_parsefile->left_in_line++;
9563 g_parsefile->next_to_pgetc--;
9564 pgetc_debug("pushed back to %d:%p'%s'",
9565 g_parsefile->left_in_line,
9566 g_parsefile->next_to_pgetc,
9567 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009568}
9569
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009570/*
9571 * To handle the "." command, a stack of input files is used. Pushfile
9572 * adds a new entry to the stack and popfile restores the previous level.
9573 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009574static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009575pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009576{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009577 struct parsefile *pf;
9578
Denis Vlasenko597906c2008-02-20 16:38:54 +00009579 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009580 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009582 /*pf->strpush = NULL; - ckzalloc did it */
9583 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009584 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009585}
9586
9587static void
9588popfile(void)
9589{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009590 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009591
Denis Vlasenkob012b102007-02-19 22:43:01 +00009592 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009593 if (pf->fd >= 0)
9594 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009595 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009596 while (pf->strpush)
9597 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009598 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009599 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009600 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009601}
9602
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009603/*
9604 * Return to top level.
9605 */
9606static void
9607popallfiles(void)
9608{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009609 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009610 popfile();
9611}
9612
9613/*
9614 * Close the file(s) that the shell is reading commands from. Called
9615 * after a fork is done.
9616 */
9617static void
9618closescript(void)
9619{
9620 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009621 if (g_parsefile->fd > 0) {
9622 close(g_parsefile->fd);
9623 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009624 }
9625}
9626
9627/*
9628 * Like setinputfile, but takes an open file descriptor. Call this with
9629 * interrupts off.
9630 */
9631static void
9632setinputfd(int fd, int push)
9633{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009634 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009635 if (push) {
9636 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009637 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009638 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009639 g_parsefile->fd = fd;
9640 if (g_parsefile->buf == NULL)
9641 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009642 g_parsefile->left_in_buffer = 0;
9643 g_parsefile->left_in_line = 0;
9644 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009645}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009646
Eric Andersenc470f442003-07-28 09:56:35 +00009647/*
9648 * Set the input to take input from a file. If push is set, push the
9649 * old input onto the stack first.
9650 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009651static int
9652setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009653{
9654 int fd;
9655 int fd2;
9656
Denis Vlasenkob012b102007-02-19 22:43:01 +00009657 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009658 fd = open(fname, O_RDONLY);
9659 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009660 if (flags & INPUT_NOFILE_OK)
9661 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009662 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009663 }
Eric Andersenc470f442003-07-28 09:56:35 +00009664 if (fd < 10) {
9665 fd2 = copyfd(fd, 10);
9666 close(fd);
9667 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009668 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009669 fd = fd2;
9670 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009671 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009672 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009673 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009674 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009675}
9676
Eric Andersencb57d552001-06-28 07:25:16 +00009677/*
9678 * Like setinputfile, but takes input from a string.
9679 */
Eric Andersenc470f442003-07-28 09:56:35 +00009680static void
9681setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009682{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009683 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009684 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009685 g_parsefile->next_to_pgetc = string;
9686 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009687 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009688 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009689 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009690}
9691
9692
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009693/* ============ mail.c
9694 *
9695 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009696 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009697
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009698#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009699
Eric Andersencb57d552001-06-28 07:25:16 +00009700#define MAXMBOXES 10
9701
Eric Andersenc470f442003-07-28 09:56:35 +00009702/* times of mailboxes */
9703static time_t mailtime[MAXMBOXES];
9704/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009705static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009706
Eric Andersencb57d552001-06-28 07:25:16 +00009707/*
Eric Andersenc470f442003-07-28 09:56:35 +00009708 * Print appropriate message(s) if mail has arrived.
9709 * If mail_var_path_changed is set,
9710 * then the value of MAIL has mail_var_path_changed,
9711 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009712 */
Eric Andersenc470f442003-07-28 09:56:35 +00009713static void
9714chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009715{
Eric Andersencb57d552001-06-28 07:25:16 +00009716 const char *mpath;
9717 char *p;
9718 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009719 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009720 struct stackmark smark;
9721 struct stat statb;
9722
Eric Andersencb57d552001-06-28 07:25:16 +00009723 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009724 mpath = mpathset() ? mpathval() : mailval();
9725 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009726 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009727 if (p == NULL)
9728 break;
9729 if (*p == '\0')
9730 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009731 for (q = p; *q; q++)
9732 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009733#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009734 if (q[-1] != '/')
9735 abort();
9736#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009737 q[-1] = '\0'; /* delete trailing '/' */
9738 if (stat(p, &statb) < 0) {
9739 *mtp = 0;
9740 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009741 }
Eric Andersenc470f442003-07-28 09:56:35 +00009742 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9743 fprintf(
9744 stderr, snlfmt,
9745 pathopt ? pathopt : "you have mail"
9746 );
9747 }
9748 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009749 }
Eric Andersenc470f442003-07-28 09:56:35 +00009750 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009751 popstackmark(&smark);
9752}
Eric Andersencb57d552001-06-28 07:25:16 +00009753
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009754static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009755changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009756{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009757 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009758}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009759
Denis Vlasenko131ae172007-02-18 13:00:19 +00009760#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009761
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009762
9763/* ============ ??? */
9764
Eric Andersencb57d552001-06-28 07:25:16 +00009765/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009766 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009767 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009768static void
9769setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009770{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009771 char **newparam;
9772 char **ap;
9773 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009774
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009775 for (nparam = 0; argv[nparam]; nparam++)
9776 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009777 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9778 while (*argv) {
9779 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009780 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009781 *ap = NULL;
9782 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009783 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009784 shellparam.nparam = nparam;
9785 shellparam.p = newparam;
9786#if ENABLE_ASH_GETOPTS
9787 shellparam.optind = 1;
9788 shellparam.optoff = -1;
9789#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009790}
9791
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009792/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009793 * Process shell options. The global variable argptr contains a pointer
9794 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009795 *
9796 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9797 * For a non-interactive shell, an error condition encountered
9798 * by a special built-in ... shall cause the shell to write a diagnostic message
9799 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009800 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009801 * ...
9802 * Utility syntax error (option or operand error) Shall exit
9803 * ...
9804 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9805 * we see that bash does not do that (set "finishes" with error code 1 instead,
9806 * and shell continues), and people rely on this behavior!
9807 * Testcase:
9808 * set -o barfoo 2>/dev/null
9809 * echo $?
9810 *
9811 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009812 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009813static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009814plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009815{
9816 int i;
9817
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009818 if (name) {
9819 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009820 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009821 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009822 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009823 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009824 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009825 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009826 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009827 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009828 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009829 if (val) {
9830 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9831 } else {
9832 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9833 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009834 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009835 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009836}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009837static void
9838setoption(int flag, int val)
9839{
9840 int i;
9841
9842 for (i = 0; i < NOPTS; i++) {
9843 if (optletters(i) == flag) {
9844 optlist[i] = val;
9845 return;
9846 }
9847 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009848 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009849 /* NOTREACHED */
9850}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009851static int
Eric Andersenc470f442003-07-28 09:56:35 +00009852options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009853{
9854 char *p;
9855 int val;
9856 int c;
9857
9858 if (cmdline)
9859 minusc = NULL;
9860 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009861 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009862 if (c != '-' && c != '+')
9863 break;
9864 argptr++;
9865 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009866 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009867 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009868 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009869 if (!cmdline) {
9870 /* "-" means turn off -x and -v */
9871 if (p[0] == '\0')
9872 xflag = vflag = 0;
9873 /* "--" means reset params */
9874 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009875 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009876 }
Eric Andersenc470f442003-07-28 09:56:35 +00009877 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009878 }
Eric Andersencb57d552001-06-28 07:25:16 +00009879 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009880 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009881 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009882 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009883 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009884 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009885 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009886 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009887 /* it already printed err message */
9888 return 1; /* error */
9889 }
Eric Andersencb57d552001-06-28 07:25:16 +00009890 if (*argptr)
9891 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009892 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9893 isloginsh = 1;
9894 /* bash does not accept +-login, we also won't */
9895 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009896 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009897 isloginsh = 1;
9898 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009899 } else {
9900 setoption(c, val);
9901 }
9902 }
9903 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009904 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009905}
9906
Eric Andersencb57d552001-06-28 07:25:16 +00009907/*
Eric Andersencb57d552001-06-28 07:25:16 +00009908 * The shift builtin command.
9909 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009910static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009911shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009912{
9913 int n;
9914 char **ap1, **ap2;
9915
9916 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009917 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009918 n = number(argv[1]);
9919 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009920 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009921 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009922 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009923 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009924 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009925 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009926 }
9927 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009928 while ((*ap2++ = *ap1++) != NULL)
9929 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009930#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009931 shellparam.optind = 1;
9932 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009933#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009934 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009935 return 0;
9936}
9937
Eric Andersencb57d552001-06-28 07:25:16 +00009938/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009939 * POSIX requires that 'set' (but not export or readonly) output the
9940 * variables in lexicographic order - by the locale's collating order (sigh).
9941 * Maybe we could keep them in an ordered balanced binary tree
9942 * instead of hashed lists.
9943 * For now just roll 'em through qsort for printing...
9944 */
9945static int
9946showvars(const char *sep_prefix, int on, int off)
9947{
9948 const char *sep;
9949 char **ep, **epend;
9950
9951 ep = listvars(on, off, &epend);
9952 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9953
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009954 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009955
9956 for (; ep < epend; ep++) {
9957 const char *p;
9958 const char *q;
9959
9960 p = strchrnul(*ep, '=');
9961 q = nullstr;
9962 if (*p)
9963 q = single_quote(++p);
9964 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9965 }
9966 return 0;
9967}
9968
9969/*
Eric Andersencb57d552001-06-28 07:25:16 +00009970 * The set command builtin.
9971 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009972static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009973setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00009974{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009975 int retval;
9976
Denis Vlasenko68404f12008-03-17 09:00:54 +00009977 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +00009978 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009979 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009980 retval = 1;
9981 if (!options(0)) { /* if no parse error... */
9982 retval = 0;
9983 optschanged();
9984 if (*argptr != NULL) {
9985 setparam(argptr);
9986 }
Eric Andersencb57d552001-06-28 07:25:16 +00009987 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009988 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009989 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009990}
9991
Denis Vlasenko131ae172007-02-18 13:00:19 +00009992#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009993static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009994change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +00009995{
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009996 /* Galois LFSR parameter */
9997 /* Taps at 32 31 29 1: */
9998 enum { MASK = 0x8000000b };
9999 /* Another example - taps at 32 31 30 10: */
10000 /* MASK = 0x00400007 */
10001
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010002 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010003 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010004 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010005
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010006 /* LCG has period of 2^32 and alternating lowest bit */
10007 random_LCG = 1664525 * random_LCG + 1013904223;
10008 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10009 t = (random_galois_LFSR << 1);
10010 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10011 t ^= MASK;
10012 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010013 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010014 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010015 * for $RANDOM range. Combining with subtraction is
10016 * just for fun. + and ^ would work equally well. */
10017 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010018 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010019 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010020 vrandom.flags &= ~VNOFUNC;
10021 } else {
10022 /* set/reset */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010023 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010024 }
Eric Andersenef02f822004-03-11 13:34:24 +000010025}
Eric Andersen16767e22004-03-16 05:14:10 +000010026#endif
10027
Denis Vlasenko131ae172007-02-18 13:00:19 +000010028#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010029static int
Eric Andersenc470f442003-07-28 09:56:35 +000010030getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010031{
10032 char *p, *q;
10033 char c = '?';
10034 int done = 0;
10035 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010036 char s[12];
10037 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010038
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010039 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010040 return 1;
10041 optnext = optfirst + *param_optind - 1;
10042
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010043 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010044 p = NULL;
10045 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010046 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010047 if (p == NULL || *p == '\0') {
10048 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010049 p = *optnext;
10050 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010051 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010052 p = NULL;
10053 done = 1;
10054 goto out;
10055 }
10056 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010057 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010058 goto atend;
10059 }
10060
10061 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010062 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010063 if (*q == '\0') {
10064 if (optstr[0] == ':') {
10065 s[0] = c;
10066 s[1] = '\0';
10067 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010068 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010069 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010070 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010071 }
10072 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010073 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010074 }
10075 if (*++q == ':')
10076 q++;
10077 }
10078
10079 if (*++q == ':') {
10080 if (*p == '\0' && (p = *optnext) == NULL) {
10081 if (optstr[0] == ':') {
10082 s[0] = c;
10083 s[1] = '\0';
10084 err |= setvarsafe("OPTARG", s, 0);
10085 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010086 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010087 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010088 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010089 c = '?';
10090 }
Eric Andersenc470f442003-07-28 09:56:35 +000010091 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010092 }
10093
10094 if (p == *optnext)
10095 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010096 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010097 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010098 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010099 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010100 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010101 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010102 *param_optind = optnext - optfirst + 1;
10103 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010104 err |= setvarsafe("OPTIND", s, VNOFUNC);
10105 s[0] = c;
10106 s[1] = '\0';
10107 err |= setvarsafe(optvar, s, 0);
10108 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010109 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010110 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010111 flush_stdout_stderr();
10112 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010113 }
10114 return done;
10115}
Eric Andersenc470f442003-07-28 09:56:35 +000010116
10117/*
10118 * The getopts builtin. Shellparam.optnext points to the next argument
10119 * to be processed. Shellparam.optptr points to the next character to
10120 * be processed in the current argument. If shellparam.optnext is NULL,
10121 * then it's the first time getopts has been called.
10122 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010123static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010124getoptscmd(int argc, char **argv)
10125{
10126 char **optbase;
10127
10128 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010129 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010130 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010131 optbase = shellparam.p;
10132 if (shellparam.optind > shellparam.nparam + 1) {
10133 shellparam.optind = 1;
10134 shellparam.optoff = -1;
10135 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010136 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010137 optbase = &argv[3];
10138 if (shellparam.optind > argc - 2) {
10139 shellparam.optind = 1;
10140 shellparam.optoff = -1;
10141 }
10142 }
10143
10144 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010145 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010146}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010147#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010148
Eric Andersencb57d552001-06-28 07:25:16 +000010149
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010150/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010151
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010152struct heredoc {
10153 struct heredoc *next; /* next here document in list */
10154 union node *here; /* redirection node */
10155 char *eofmark; /* string indicating end of input */
10156 smallint striptabs; /* if set, strip leading tabs */
10157};
10158
10159static smallint tokpushback; /* last token pushed back */
10160static smallint parsebackquote; /* nonzero if we are inside backquotes */
10161static smallint quoteflag; /* set if (part of) last token was quoted */
10162static token_id_t lasttoken; /* last token read (integer id Txxx) */
10163static struct heredoc *heredoclist; /* list of here documents to read */
10164static char *wordtext; /* text of last word returned by readtoken */
10165static struct nodelist *backquotelist;
10166static union node *redirnode;
10167static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010168
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010169/*
10170 * Called when an unexpected token is read during the parse. The argument
10171 * is the token that is expected, or -1 if more than one type of token can
10172 * occur at this point.
10173 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010174static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010175static void
10176raise_error_unexpected_syntax(int token)
10177{
10178 char msg[64];
10179 int l;
10180
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010181 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010182 if (token >= 0)
10183 sprintf(msg + l, " (expecting %s)", tokname(token));
10184 raise_error_syntax(msg);
10185 /* NOTREACHED */
10186}
Eric Andersencb57d552001-06-28 07:25:16 +000010187
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010188#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010189
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010190/* parsing is heavily cross-recursive, need these forward decls */
10191static union node *andor(void);
10192static union node *pipeline(void);
10193static union node *parse_command(void);
10194static void parseheredoc(void);
10195static char peektoken(void);
10196static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010197
Eric Andersenc470f442003-07-28 09:56:35 +000010198static union node *
10199list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010200{
10201 union node *n1, *n2, *n3;
10202 int tok;
10203
Eric Andersenc470f442003-07-28 09:56:35 +000010204 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10205 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010206 return NULL;
10207 n1 = NULL;
10208 for (;;) {
10209 n2 = andor();
10210 tok = readtoken();
10211 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010212 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010213 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010214 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010215 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010216 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010217 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010218 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010219 n2 = n3;
10220 }
10221 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010222 }
10223 }
10224 if (n1 == NULL) {
10225 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010226 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010227 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010228 n3->type = NSEMI;
10229 n3->nbinary.ch1 = n1;
10230 n3->nbinary.ch2 = n2;
10231 n1 = n3;
10232 }
10233 switch (tok) {
10234 case TBACKGND:
10235 case TSEMI:
10236 tok = readtoken();
10237 /* fall through */
10238 case TNL:
10239 if (tok == TNL) {
10240 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010241 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010242 return n1;
10243 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010244 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010245 }
Eric Andersenc470f442003-07-28 09:56:35 +000010246 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010247 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010248 return n1;
10249 break;
10250 case TEOF:
10251 if (heredoclist)
10252 parseheredoc();
10253 else
Eric Andersenc470f442003-07-28 09:56:35 +000010254 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010255 return n1;
10256 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010257 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010258 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010259 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010260 return n1;
10261 }
10262 }
10263}
10264
Eric Andersenc470f442003-07-28 09:56:35 +000010265static union node *
10266andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010267{
Eric Andersencb57d552001-06-28 07:25:16 +000010268 union node *n1, *n2, *n3;
10269 int t;
10270
Eric Andersencb57d552001-06-28 07:25:16 +000010271 n1 = pipeline();
10272 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010273 t = readtoken();
10274 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010275 t = NAND;
10276 } else if (t == TOR) {
10277 t = NOR;
10278 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010279 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010280 return n1;
10281 }
Eric Andersenc470f442003-07-28 09:56:35 +000010282 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010283 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010284 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010285 n3->type = t;
10286 n3->nbinary.ch1 = n1;
10287 n3->nbinary.ch2 = n2;
10288 n1 = n3;
10289 }
10290}
10291
Eric Andersenc470f442003-07-28 09:56:35 +000010292static union node *
10293pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010294{
Eric Andersencb57d552001-06-28 07:25:16 +000010295 union node *n1, *n2, *pipenode;
10296 struct nodelist *lp, *prev;
10297 int negate;
10298
10299 negate = 0;
10300 TRACE(("pipeline: entered\n"));
10301 if (readtoken() == TNOT) {
10302 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010303 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010304 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010305 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010306 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010307 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010308 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010309 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010310 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010311 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010312 pipenode->npipe.cmdlist = lp;
10313 lp->n = n1;
10314 do {
10315 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010316 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010317 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010318 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010319 prev->next = lp;
10320 } while (readtoken() == TPIPE);
10321 lp->next = NULL;
10322 n1 = pipenode;
10323 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010324 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010325 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010326 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010327 n2->type = NNOT;
10328 n2->nnot.com = n1;
10329 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010330 }
10331 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010332}
10333
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010334static union node *
10335makename(void)
10336{
10337 union node *n;
10338
Denis Vlasenko597906c2008-02-20 16:38:54 +000010339 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010340 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010341 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010342 n->narg.text = wordtext;
10343 n->narg.backquote = backquotelist;
10344 return n;
10345}
10346
10347static void
10348fixredir(union node *n, const char *text, int err)
10349{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010350 int fd;
10351
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010352 TRACE(("Fix redir %s %d\n", text, err));
10353 if (!err)
10354 n->ndup.vname = NULL;
10355
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010356 fd = bb_strtou(text, NULL, 10);
10357 if (!errno && fd >= 0)
10358 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010359 else if (LONE_DASH(text))
10360 n->ndup.dupfd = -1;
10361 else {
10362 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010363 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010364 n->ndup.vname = makename();
10365 }
10366}
10367
10368/*
10369 * Returns true if the text contains nothing to expand (no dollar signs
10370 * or backquotes).
10371 */
10372static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010373noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010374{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010375 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010376 char c;
10377
10378 p = text;
10379 while ((c = *p++) != '\0') {
10380 if (c == CTLQUOTEMARK)
10381 continue;
10382 if (c == CTLESC)
10383 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010384 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010385 return 0;
10386 }
10387 return 1;
10388}
10389
10390static void
10391parsefname(void)
10392{
10393 union node *n = redirnode;
10394
10395 if (readtoken() != TWORD)
10396 raise_error_unexpected_syntax(-1);
10397 if (n->type == NHERE) {
10398 struct heredoc *here = heredoc;
10399 struct heredoc *p;
10400 int i;
10401
10402 if (quoteflag == 0)
10403 n->type = NXHERE;
10404 TRACE(("Here document %d\n", n->type));
10405 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010406 raise_error_syntax("illegal eof marker for << redirection");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010407 rmescapes(wordtext);
10408 here->eofmark = wordtext;
10409 here->next = NULL;
10410 if (heredoclist == NULL)
10411 heredoclist = here;
10412 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010413 for (p = heredoclist; p->next; p = p->next)
10414 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010415 p->next = here;
10416 }
10417 } else if (n->type == NTOFD || n->type == NFROMFD) {
10418 fixredir(n, wordtext, 0);
10419 } else {
10420 n->nfile.fname = makename();
10421 }
10422}
Eric Andersencb57d552001-06-28 07:25:16 +000010423
Eric Andersenc470f442003-07-28 09:56:35 +000010424static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010425simplecmd(void)
10426{
10427 union node *args, **app;
10428 union node *n = NULL;
10429 union node *vars, **vpp;
10430 union node **rpp, *redir;
10431 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010432#if ENABLE_ASH_BASH_COMPAT
10433 smallint double_brackets_flag = 0;
10434#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010435
10436 args = NULL;
10437 app = &args;
10438 vars = NULL;
10439 vpp = &vars;
10440 redir = NULL;
10441 rpp = &redir;
10442
10443 savecheckkwd = CHKALIAS;
10444 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010445 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010446 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010447 t = readtoken();
10448 switch (t) {
10449#if ENABLE_ASH_BASH_COMPAT
10450 case TAND: /* "&&" */
10451 case TOR: /* "||" */
10452 if (!double_brackets_flag) {
10453 tokpushback = 1;
10454 goto out;
10455 }
10456 wordtext = (char *) (t == TAND ? "-a" : "-o");
10457#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010458 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010459 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010460 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010461 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010462 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010463#if ENABLE_ASH_BASH_COMPAT
10464 if (strcmp("[[", wordtext) == 0)
10465 double_brackets_flag = 1;
10466 else if (strcmp("]]", wordtext) == 0)
10467 double_brackets_flag = 0;
10468#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010469 n->narg.backquote = backquotelist;
10470 if (savecheckkwd && isassignment(wordtext)) {
10471 *vpp = n;
10472 vpp = &n->narg.next;
10473 } else {
10474 *app = n;
10475 app = &n->narg.next;
10476 savecheckkwd = 0;
10477 }
10478 break;
10479 case TREDIR:
10480 *rpp = n = redirnode;
10481 rpp = &n->nfile.next;
10482 parsefname(); /* read name of redirection file */
10483 break;
10484 case TLP:
10485 if (args && app == &args->narg.next
10486 && !vars && !redir
10487 ) {
10488 struct builtincmd *bcmd;
10489 const char *name;
10490
10491 /* We have a function */
10492 if (readtoken() != TRP)
10493 raise_error_unexpected_syntax(TRP);
10494 name = n->narg.text;
10495 if (!goodname(name)
10496 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10497 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010498 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499 }
10500 n->type = NDEFUN;
10501 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10502 n->narg.next = parse_command();
10503 return n;
10504 }
10505 /* fall through */
10506 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010507 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010508 goto out;
10509 }
10510 }
10511 out:
10512 *app = NULL;
10513 *vpp = NULL;
10514 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010515 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010516 n->type = NCMD;
10517 n->ncmd.args = args;
10518 n->ncmd.assign = vars;
10519 n->ncmd.redirect = redir;
10520 return n;
10521}
10522
10523static union node *
10524parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010525{
Eric Andersencb57d552001-06-28 07:25:16 +000010526 union node *n1, *n2;
10527 union node *ap, **app;
10528 union node *cp, **cpp;
10529 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010530 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010531 int t;
10532
10533 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010534 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010535
Eric Andersencb57d552001-06-28 07:25:16 +000010536 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010537 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010538 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010539 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010540 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010541 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010542 n1->type = NIF;
10543 n1->nif.test = list(0);
10544 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010545 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010546 n1->nif.ifpart = list(0);
10547 n2 = n1;
10548 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010549 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010550 n2 = n2->nif.elsepart;
10551 n2->type = NIF;
10552 n2->nif.test = list(0);
10553 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010554 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010555 n2->nif.ifpart = list(0);
10556 }
10557 if (lasttoken == TELSE)
10558 n2->nif.elsepart = list(0);
10559 else {
10560 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010561 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010562 }
Eric Andersenc470f442003-07-28 09:56:35 +000010563 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010564 break;
10565 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010566 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010567 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010568 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010569 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010570 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010571 got = readtoken();
10572 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010573 TRACE(("expecting DO got %s %s\n", tokname(got),
10574 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010575 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010576 }
10577 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010578 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010579 break;
10580 }
10581 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010582 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010583 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010584 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010585 n1->type = NFOR;
10586 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010587 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010588 if (readtoken() == TIN) {
10589 app = &ap;
10590 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010591 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010592 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010593 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010594 n2->narg.text = wordtext;
10595 n2->narg.backquote = backquotelist;
10596 *app = n2;
10597 app = &n2->narg.next;
10598 }
10599 *app = NULL;
10600 n1->nfor.args = ap;
10601 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010602 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010603 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010604 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010605 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010606 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010607 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010608 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010609 n1->nfor.args = n2;
10610 /*
10611 * Newline or semicolon here is optional (but note
10612 * that the original Bourne shell only allowed NL).
10613 */
10614 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010615 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010616 }
Eric Andersenc470f442003-07-28 09:56:35 +000010617 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010618 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010619 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010620 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010621 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010622 break;
10623 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010624 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010625 n1->type = NCASE;
10626 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010627 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010628 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010629 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010630 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010631 n2->narg.text = wordtext;
10632 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010633 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010634 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010635 } while (readtoken() == TNL);
10636 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010637 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010638 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010639 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010640 checkkwd = CHKNL | CHKKWD;
10641 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010642 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010643 if (lasttoken == TLP)
10644 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010645 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010646 cp->type = NCLIST;
10647 app = &cp->nclist.pattern;
10648 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010649 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010650 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010651 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010652 ap->narg.text = wordtext;
10653 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010654 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010655 break;
10656 app = &ap->narg.next;
10657 readtoken();
10658 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010659 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010660 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010661 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010662 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010663
Eric Andersenc470f442003-07-28 09:56:35 +000010664 cpp = &cp->nclist.next;
10665
10666 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010667 t = readtoken();
10668 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010669 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010670 raise_error_unexpected_syntax(TENDCASE);
10671 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010672 }
Eric Andersenc470f442003-07-28 09:56:35 +000010673 }
Eric Andersencb57d552001-06-28 07:25:16 +000010674 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010675 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010677 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010678 n1->type = NSUBSHELL;
10679 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010681 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010682 break;
10683 case TBEGIN:
10684 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010685 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010686 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010687 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010688 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010689 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010690 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010691 }
10692
Eric Andersenc470f442003-07-28 09:56:35 +000010693 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010694 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010695
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010696 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010697 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010698 checkkwd = CHKKWD | CHKALIAS;
10699 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010700 while (readtoken() == TREDIR) {
10701 *rpp = n2 = redirnode;
10702 rpp = &n2->nfile.next;
10703 parsefname();
10704 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010705 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010706 *rpp = NULL;
10707 if (redir) {
10708 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010709 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010710 n2->type = NREDIR;
10711 n2->nredir.n = n1;
10712 n1 = n2;
10713 }
10714 n1->nredir.redirect = redir;
10715 }
Eric Andersencb57d552001-06-28 07:25:16 +000010716 return n1;
10717}
10718
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010719#if ENABLE_ASH_BASH_COMPAT
10720static int decode_dollar_squote(void)
10721{
10722 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10723 int c, cnt;
10724 char *p;
10725 char buf[4];
10726
10727 c = pgetc();
10728 p = strchr(C_escapes, c);
10729 if (p) {
10730 buf[0] = c;
10731 p = buf;
10732 cnt = 3;
10733 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10734 do {
10735 c = pgetc();
10736 *++p = c;
10737 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10738 pungetc();
10739 } else if (c == 'x') { /* \xHH */
10740 do {
10741 c = pgetc();
10742 *++p = c;
10743 } while (isxdigit(c) && --cnt);
10744 pungetc();
10745 if (cnt == 3) { /* \x but next char is "bad" */
10746 c = 'x';
10747 goto unrecognized;
10748 }
10749 } else { /* simple seq like \\ or \t */
10750 p++;
10751 }
10752 *p = '\0';
10753 p = buf;
10754 c = bb_process_escape_sequence((void*)&p);
10755 } else { /* unrecognized "\z": print both chars unless ' or " */
10756 if (c != '\'' && c != '"') {
10757 unrecognized:
10758 c |= 0x100; /* "please encode \, then me" */
10759 }
10760 }
10761 return c;
10762}
10763#endif
10764
Eric Andersencb57d552001-06-28 07:25:16 +000010765/*
10766 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10767 * is not NULL, read a here document. In the latter case, eofmark is the
10768 * word which marks the end of the document and striptabs is true if
10769 * leading tabs should be stripped from the document. The argument firstc
10770 * is the first character of the input token or document.
10771 *
10772 * Because C does not have internal subroutines, I have simulated them
10773 * using goto's to implement the subroutine linkage. The following macros
10774 * will run code that appears at the end of readtoken1.
10775 */
Eric Andersen2870d962001-07-02 17:27:21 +000010776#define CHECKEND() {goto checkend; checkend_return:;}
10777#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10778#define PARSESUB() {goto parsesub; parsesub_return:;}
10779#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10780#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10781#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010782static int
Eric Andersenc470f442003-07-28 09:56:35 +000010783readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010784{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010785 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010786 int c = firstc;
10787 char *out;
10788 int len;
10789 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010790 struct nodelist *bqlist;
10791 smallint quotef;
10792 smallint dblquote;
10793 smallint oldstyle;
10794 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010795#if ENABLE_ASH_EXPAND_PRMT
10796 smallint pssyntax; /* we are expanding a prompt string */
10797#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010798 int varnest; /* levels of variables expansion */
10799 int arinest; /* levels of arithmetic expansion */
10800 int parenlevel; /* levels of parens in arithmetic */
10801 int dqvarnest; /* levels of variables expansion within double quotes */
10802
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010803 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010804
Eric Andersencb57d552001-06-28 07:25:16 +000010805#if __GNUC__
10806 /* Avoid longjmp clobbering */
10807 (void) &out;
10808 (void) &quotef;
10809 (void) &dblquote;
10810 (void) &varnest;
10811 (void) &arinest;
10812 (void) &parenlevel;
10813 (void) &dqvarnest;
10814 (void) &oldstyle;
10815 (void) &prevsyntax;
10816 (void) &syntax;
10817#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010818 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010819 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010820 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010821 oldstyle = 0;
10822 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010823#if ENABLE_ASH_EXPAND_PRMT
10824 pssyntax = (syntax == PSSYNTAX);
10825 if (pssyntax)
10826 syntax = DQSYNTAX;
10827#endif
10828 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010829 varnest = 0;
10830 arinest = 0;
10831 parenlevel = 0;
10832 dqvarnest = 0;
10833
10834 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010835 loop:
10836 /* For each line, until end of word */
10837 {
Eric Andersenc470f442003-07-28 09:56:35 +000010838 CHECKEND(); /* set c to PEOF if at end of here document */
10839 for (;;) { /* until end of line or end of word */
10840 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010841 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010842 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010843 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010844 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010845 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010846 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010847 if (doprompt)
10848 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010849 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010850 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010851 case CWORD:
10852 USTPUTC(c, out);
10853 break;
10854 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010855 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010856 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010857#if ENABLE_ASH_BASH_COMPAT
10858 if (c == '\\' && bash_dollar_squote) {
10859 c = decode_dollar_squote();
10860 if (c & 0x100) {
10861 USTPUTC('\\', out);
10862 c = (unsigned char)c;
10863 }
10864 }
10865#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010866 USTPUTC(c, out);
10867 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010868 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010869 c = pgetc2();
10870 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010871 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010872 USTPUTC('\\', out);
10873 pungetc();
10874 } else if (c == '\n') {
10875 if (doprompt)
10876 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010877 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010878#if ENABLE_ASH_EXPAND_PRMT
10879 if (c == '$' && pssyntax) {
10880 USTPUTC(CTLESC, out);
10881 USTPUTC('\\', out);
10882 }
10883#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010884 if (dblquote && c != '\\'
10885 && c != '`' && c != '$'
10886 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010887 ) {
10888 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010889 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010890 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010891 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010892 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010893 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010894 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010895 }
10896 break;
10897 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010898 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010899 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010900 if (eofmark == NULL) {
10901 USTPUTC(CTLQUOTEMARK, out);
10902 }
Eric Andersencb57d552001-06-28 07:25:16 +000010903 break;
10904 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010905 syntax = DQSYNTAX;
10906 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010907 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010908 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010909 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010910 if (eofmark != NULL && arinest == 0
10911 && varnest == 0
10912 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010913 USTPUTC(c, out);
10914 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010915 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010916 syntax = BASESYNTAX;
10917 dblquote = 0;
10918 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010919 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010920 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010921 }
10922 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010923 case CVAR: /* '$' */
10924 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010925 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010926 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010927 if (varnest > 0) {
10928 varnest--;
10929 if (dqvarnest > 0) {
10930 dqvarnest--;
10931 }
10932 USTPUTC(CTLENDVAR, out);
10933 } else {
10934 USTPUTC(c, out);
10935 }
10936 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010937#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010938 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010939 parenlevel++;
10940 USTPUTC(c, out);
10941 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010942 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010943 if (parenlevel > 0) {
10944 USTPUTC(c, out);
10945 --parenlevel;
10946 } else {
10947 if (pgetc() == ')') {
10948 if (--arinest == 0) {
10949 USTPUTC(CTLENDARI, out);
10950 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010951 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010952 } else
10953 USTPUTC(')', out);
10954 } else {
10955 /*
10956 * unbalanced parens
10957 * (don't 2nd guess - no error)
10958 */
10959 pungetc();
10960 USTPUTC(')', out);
10961 }
10962 }
10963 break;
10964#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010965 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010966 PARSEBACKQOLD();
10967 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010968 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010969 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010970 case CIGN:
10971 break;
10972 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000010973 if (varnest == 0) {
10974#if ENABLE_ASH_BASH_COMPAT
10975 if (c == '&') {
10976 if (pgetc() == '>')
10977 c = 0x100 + '>'; /* flag &> */
10978 pungetc();
10979 }
10980#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010981 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000010982 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000010983#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010984 if (c != PEOA)
10985#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010986 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010987
Eric Andersencb57d552001-06-28 07:25:16 +000010988 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000010989 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010990 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000010991 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010992 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000010993#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010994 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010995 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000010996#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010997 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010998 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000010999 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011000 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011001 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011002 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011003 }
11004 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011005 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011006 out = stackblock();
11007 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011008 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011009 && quotef == 0
11010 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011011 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011012 PARSEREDIR(); /* passed as params: out, c */
11013 lasttoken = TREDIR;
11014 return lasttoken;
11015 }
11016 /* else: non-number X seen, interpret it
11017 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011018 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011019 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011020 }
11021 quoteflag = quotef;
11022 backquotelist = bqlist;
11023 grabstackblock(len);
11024 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011025 lasttoken = TWORD;
11026 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011027/* end of readtoken routine */
11028
Eric Andersencb57d552001-06-28 07:25:16 +000011029/*
11030 * Check to see whether we are at the end of the here document. When this
11031 * is called, c is set to the first character of the next input line. If
11032 * we are at the end of the here document, this routine sets the c to PEOF.
11033 */
Eric Andersenc470f442003-07-28 09:56:35 +000011034checkend: {
11035 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011036#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011037 if (c == PEOA) {
11038 c = pgetc2();
11039 }
11040#endif
11041 if (striptabs) {
11042 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011043 c = pgetc2();
11044 }
Eric Andersenc470f442003-07-28 09:56:35 +000011045 }
11046 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011047 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011048 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011049
Eric Andersenc470f442003-07-28 09:56:35 +000011050 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011051 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11052 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011053 if (*p == '\n' && *q == '\0') {
11054 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011055 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011056 needprompt = doprompt;
11057 } else {
11058 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011059 }
11060 }
11061 }
11062 }
Eric Andersenc470f442003-07-28 09:56:35 +000011063 goto checkend_return;
11064}
Eric Andersencb57d552001-06-28 07:25:16 +000011065
Eric Andersencb57d552001-06-28 07:25:16 +000011066/*
11067 * Parse a redirection operator. The variable "out" points to a string
11068 * specifying the fd to be redirected. The variable "c" contains the
11069 * first character of the redirection operator.
11070 */
Eric Andersenc470f442003-07-28 09:56:35 +000011071parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011072 /* out is already checked to be a valid number or "" */
11073 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011074 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011075
Denis Vlasenko597906c2008-02-20 16:38:54 +000011076 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011077 if (c == '>') {
11078 np->nfile.fd = 1;
11079 c = pgetc();
11080 if (c == '>')
11081 np->type = NAPPEND;
11082 else if (c == '|')
11083 np->type = NCLOBBER;
11084 else if (c == '&')
11085 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011086 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011087 else {
11088 np->type = NTO;
11089 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011090 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011091 }
11092#if ENABLE_ASH_BASH_COMPAT
11093 else if (c == 0x100 + '>') { /* this flags &> redirection */
11094 np->nfile.fd = 1;
11095 pgetc(); /* this is '>', no need to check */
11096 np->type = NTO2;
11097 }
11098#endif
11099 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011100 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011101 c = pgetc();
11102 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011103 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011104 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011105 np = stzalloc(sizeof(struct nhere));
11106 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011107 }
11108 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011109 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011110 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011111 c = pgetc();
11112 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011113 heredoc->striptabs = 1;
11114 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011115 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011116 pungetc();
11117 }
11118 break;
11119
11120 case '&':
11121 np->type = NFROMFD;
11122 break;
11123
11124 case '>':
11125 np->type = NFROMTO;
11126 break;
11127
11128 default:
11129 np->type = NFROM;
11130 pungetc();
11131 break;
11132 }
Eric Andersencb57d552001-06-28 07:25:16 +000011133 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011134 if (fd >= 0)
11135 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011136 redirnode = np;
11137 goto parseredir_return;
11138}
Eric Andersencb57d552001-06-28 07:25:16 +000011139
Eric Andersencb57d552001-06-28 07:25:16 +000011140/*
11141 * Parse a substitution. At this point, we have read the dollar sign
11142 * and nothing else.
11143 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011144
11145/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11146 * (assuming ascii char codes, as the original implementation did) */
11147#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011148 (((unsigned)(c) - 33 < 32) \
11149 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011150parsesub: {
11151 int subtype;
11152 int typeloc;
11153 int flags;
11154 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011155 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011156
Eric Andersenc470f442003-07-28 09:56:35 +000011157 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011158 if (c <= PEOA_OR_PEOF
11159 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011160 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011161#if ENABLE_ASH_BASH_COMPAT
11162 if (c == '\'')
11163 bash_dollar_squote = 1;
11164 else
11165#endif
11166 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011167 pungetc();
11168 } else if (c == '(') { /* $(command) or $((arith)) */
11169 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011170#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011171 PARSEARITH();
11172#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011173 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011174#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011175 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011176 pungetc();
11177 PARSEBACKQNEW();
11178 }
11179 } else {
11180 USTPUTC(CTLVAR, out);
11181 typeloc = out - (char *)stackblock();
11182 USTPUTC(VSNORMAL, out);
11183 subtype = VSNORMAL;
11184 if (c == '{') {
11185 c = pgetc();
11186 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011187 c = pgetc();
11188 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011189 c = '#';
11190 else
11191 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011192 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011193 subtype = 0;
11194 }
11195 if (c > PEOA_OR_PEOF && is_name(c)) {
11196 do {
11197 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011198 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011199 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011200 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011201 do {
11202 STPUTC(c, out);
11203 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011204 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011205 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011206 USTPUTC(c, out);
11207 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011208 } else {
11209 badsub:
11210 raise_error_syntax("bad substitution");
11211 }
Eric Andersencb57d552001-06-28 07:25:16 +000011212
Eric Andersenc470f442003-07-28 09:56:35 +000011213 STPUTC('=', out);
11214 flags = 0;
11215 if (subtype == 0) {
11216 switch (c) {
11217 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011218 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011219#if ENABLE_ASH_BASH_COMPAT
11220 if (c == ':' || c == '$' || isdigit(c)) {
11221 pungetc();
11222 subtype = VSSUBSTR;
11223 break;
11224 }
11225#endif
11226 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011227 /*FALLTHROUGH*/
11228 default:
11229 p = strchr(types, c);
11230 if (p == NULL)
11231 goto badsub;
11232 subtype = p - types + VSNORMAL;
11233 break;
11234 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011235 case '#': {
11236 int cc = c;
11237 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11238 c = pgetc();
11239 if (c == cc)
11240 subtype++;
11241 else
11242 pungetc();
11243 break;
11244 }
11245#if ENABLE_ASH_BASH_COMPAT
11246 case '/':
11247 subtype = VSREPLACE;
11248 c = pgetc();
11249 if (c == '/')
11250 subtype++; /* VSREPLACEALL */
11251 else
11252 pungetc();
11253 break;
11254#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011255 }
Eric Andersenc470f442003-07-28 09:56:35 +000011256 } else {
11257 pungetc();
11258 }
11259 if (dblquote || arinest)
11260 flags |= VSQUOTE;
11261 *((char *)stackblock() + typeloc) = subtype | flags;
11262 if (subtype != VSNORMAL) {
11263 varnest++;
11264 if (dblquote || arinest) {
11265 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011266 }
11267 }
11268 }
Eric Andersenc470f442003-07-28 09:56:35 +000011269 goto parsesub_return;
11270}
Eric Andersencb57d552001-06-28 07:25:16 +000011271
Eric Andersencb57d552001-06-28 07:25:16 +000011272/*
11273 * Called to parse command substitutions. Newstyle is set if the command
11274 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11275 * list of commands (passed by reference), and savelen is the number of
11276 * characters on the top of the stack which must be preserved.
11277 */
Eric Andersenc470f442003-07-28 09:56:35 +000011278parsebackq: {
11279 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011280 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011281 union node *n;
11282 char *volatile str;
11283 struct jmploc jmploc;
11284 struct jmploc *volatile savehandler;
11285 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011286 smallint saveprompt = 0;
11287
Eric Andersencb57d552001-06-28 07:25:16 +000011288#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011289 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011290#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011291 savepbq = parsebackquote;
11292 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011293 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011294 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011295 exception_handler = savehandler;
11296 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011297 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011298 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011299 str = NULL;
11300 savelen = out - (char *)stackblock();
11301 if (savelen > 0) {
11302 str = ckmalloc(savelen);
11303 memcpy(str, stackblock(), savelen);
11304 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011305 savehandler = exception_handler;
11306 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011307 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011308 if (oldstyle) {
11309 /* We must read until the closing backquote, giving special
11310 treatment to some slashes, and then push the string and
11311 reread it as input, interpreting it normally. */
11312 char *pout;
11313 int pc;
11314 size_t psavelen;
11315 char *pstr;
11316
11317
11318 STARTSTACKSTR(pout);
11319 for (;;) {
11320 if (needprompt) {
11321 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011322 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011323 pc = pgetc();
11324 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011325 case '`':
11326 goto done;
11327
11328 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011329 pc = pgetc();
11330 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011331 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011332 if (doprompt)
11333 setprompt(2);
11334 /*
11335 * If eating a newline, avoid putting
11336 * the newline into the new character
11337 * stream (via the STPUTC after the
11338 * switch).
11339 */
11340 continue;
11341 }
11342 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011343 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011344 STPUTC('\\', pout);
11345 if (pc > PEOA_OR_PEOF) {
11346 break;
11347 }
11348 /* fall through */
11349
11350 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011351#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011352 case PEOA:
11353#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011354 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011355 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011356
11357 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011358 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011359 needprompt = doprompt;
11360 break;
11361
11362 default:
11363 break;
11364 }
11365 STPUTC(pc, pout);
11366 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011367 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011368 STPUTC('\0', pout);
11369 psavelen = pout - (char *)stackblock();
11370 if (psavelen > 0) {
11371 pstr = grabstackstr(pout);
11372 setinputstring(pstr);
11373 }
11374 }
11375 nlpp = &bqlist;
11376 while (*nlpp)
11377 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011378 *nlpp = stzalloc(sizeof(**nlpp));
11379 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011380 parsebackquote = oldstyle;
11381
11382 if (oldstyle) {
11383 saveprompt = doprompt;
11384 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011385 }
11386
Eric Andersenc470f442003-07-28 09:56:35 +000011387 n = list(2);
11388
11389 if (oldstyle)
11390 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011391 else if (readtoken() != TRP)
11392 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011393
11394 (*nlpp)->n = n;
11395 if (oldstyle) {
11396 /*
11397 * Start reading from old file again, ignoring any pushed back
11398 * tokens left from the backquote parsing
11399 */
11400 popfile();
11401 tokpushback = 0;
11402 }
11403 while (stackblocksize() <= savelen)
11404 growstackblock();
11405 STARTSTACKSTR(out);
11406 if (str) {
11407 memcpy(out, str, savelen);
11408 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011409 INT_OFF;
11410 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011411 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011412 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011413 }
11414 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011415 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011416 if (arinest || dblquote)
11417 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11418 else
11419 USTPUTC(CTLBACKQ, out);
11420 if (oldstyle)
11421 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011422 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011423}
11424
Mike Frysinger98c52642009-04-02 10:02:37 +000011425#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011426/*
11427 * Parse an arithmetic expansion (indicate start of one and set state)
11428 */
Eric Andersenc470f442003-07-28 09:56:35 +000011429parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011430 if (++arinest == 1) {
11431 prevsyntax = syntax;
11432 syntax = ARISYNTAX;
11433 USTPUTC(CTLARI, out);
11434 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011435 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011436 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011437 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011438 } else {
11439 /*
11440 * we collapse embedded arithmetic expansion to
11441 * parenthesis, which should be equivalent
11442 */
11443 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011444 }
Eric Andersenc470f442003-07-28 09:56:35 +000011445 goto parsearith_return;
11446}
11447#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011448
Eric Andersenc470f442003-07-28 09:56:35 +000011449} /* end of readtoken */
11450
Eric Andersencb57d552001-06-28 07:25:16 +000011451/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011452 * Read the next input token.
11453 * If the token is a word, we set backquotelist to the list of cmds in
11454 * backquotes. We set quoteflag to true if any part of the word was
11455 * quoted.
11456 * If the token is TREDIR, then we set redirnode to a structure containing
11457 * the redirection.
11458 * In all cases, the variable startlinno is set to the number of the line
11459 * on which the token starts.
11460 *
11461 * [Change comment: here documents and internal procedures]
11462 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11463 * word parsing code into a separate routine. In this case, readtoken
11464 * doesn't need to have any internal procedures, but parseword does.
11465 * We could also make parseoperator in essence the main routine, and
11466 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011467 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011468#define NEW_xxreadtoken
11469#ifdef NEW_xxreadtoken
11470/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011471static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011472 '\n', '(', ')', /* singles */
11473 '&', '|', ';', /* doubles */
11474 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011475};
Eric Andersencb57d552001-06-28 07:25:16 +000011476
Denis Vlasenko834dee72008-10-07 09:18:30 +000011477#define xxreadtoken_singles 3
11478#define xxreadtoken_doubles 3
11479
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011480static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011481 TNL, TLP, TRP, /* only single occurrence allowed */
11482 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11483 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011484 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011485};
11486
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011487static int
11488xxreadtoken(void)
11489{
11490 int c;
11491
11492 if (tokpushback) {
11493 tokpushback = 0;
11494 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011495 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011496 if (needprompt) {
11497 setprompt(2);
11498 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011499 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011500 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011501 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011502 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011503 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011504
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011505 if (c == '#') {
11506 while ((c = pgetc()) != '\n' && c != PEOF)
11507 continue;
11508 pungetc();
11509 } else if (c == '\\') {
11510 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011511 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011512 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011513 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011514 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011515 if (doprompt)
11516 setprompt(2);
11517 } else {
11518 const char *p;
11519
11520 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11521 if (c != PEOF) {
11522 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011523 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011524 needprompt = doprompt;
11525 }
11526
11527 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011528 if (p == NULL)
11529 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011530
Denis Vlasenko834dee72008-10-07 09:18:30 +000011531 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11532 int cc = pgetc();
11533 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011534 p += xxreadtoken_doubles + 1;
11535 } else {
11536 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011537#if ENABLE_ASH_BASH_COMPAT
11538 if (c == '&' && cc == '>') /* &> */
11539 break; /* return readtoken1(...) */
11540#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011541 }
11542 }
11543 }
11544 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11545 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011546 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011547 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011548
11549 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011550}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011551#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011552#define RETURN(token) return lasttoken = token
11553static int
11554xxreadtoken(void)
11555{
11556 int c;
11557
11558 if (tokpushback) {
11559 tokpushback = 0;
11560 return lasttoken;
11561 }
11562 if (needprompt) {
11563 setprompt(2);
11564 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011565 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011566 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011567 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011568 switch (c) {
11569 case ' ': case '\t':
11570#if ENABLE_ASH_ALIAS
11571 case PEOA:
11572#endif
11573 continue;
11574 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011575 while ((c = pgetc()) != '\n' && c != PEOF)
11576 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011577 pungetc();
11578 continue;
11579 case '\\':
11580 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011581 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011582 if (doprompt)
11583 setprompt(2);
11584 continue;
11585 }
11586 pungetc();
11587 goto breakloop;
11588 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011589 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011590 needprompt = doprompt;
11591 RETURN(TNL);
11592 case PEOF:
11593 RETURN(TEOF);
11594 case '&':
11595 if (pgetc() == '&')
11596 RETURN(TAND);
11597 pungetc();
11598 RETURN(TBACKGND);
11599 case '|':
11600 if (pgetc() == '|')
11601 RETURN(TOR);
11602 pungetc();
11603 RETURN(TPIPE);
11604 case ';':
11605 if (pgetc() == ';')
11606 RETURN(TENDCASE);
11607 pungetc();
11608 RETURN(TSEMI);
11609 case '(':
11610 RETURN(TLP);
11611 case ')':
11612 RETURN(TRP);
11613 default:
11614 goto breakloop;
11615 }
11616 }
11617 breakloop:
11618 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11619#undef RETURN
11620}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011621#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011622
11623static int
11624readtoken(void)
11625{
11626 int t;
11627#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011628 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011629#endif
11630
11631#if ENABLE_ASH_ALIAS
11632 top:
11633#endif
11634
11635 t = xxreadtoken();
11636
11637 /*
11638 * eat newlines
11639 */
11640 if (checkkwd & CHKNL) {
11641 while (t == TNL) {
11642 parseheredoc();
11643 t = xxreadtoken();
11644 }
11645 }
11646
11647 if (t != TWORD || quoteflag) {
11648 goto out;
11649 }
11650
11651 /*
11652 * check for keywords
11653 */
11654 if (checkkwd & CHKKWD) {
11655 const char *const *pp;
11656
11657 pp = findkwd(wordtext);
11658 if (pp) {
11659 lasttoken = t = pp - tokname_array;
11660 TRACE(("keyword %s recognized\n", tokname(t)));
11661 goto out;
11662 }
11663 }
11664
11665 if (checkkwd & CHKALIAS) {
11666#if ENABLE_ASH_ALIAS
11667 struct alias *ap;
11668 ap = lookupalias(wordtext, 1);
11669 if (ap != NULL) {
11670 if (*ap->val) {
11671 pushstring(ap->val, ap);
11672 }
11673 goto top;
11674 }
11675#endif
11676 }
11677 out:
11678 checkkwd = 0;
11679#if DEBUG
11680 if (!alreadyseen)
11681 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11682 else
11683 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11684#endif
11685 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011686}
11687
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011688static char
11689peektoken(void)
11690{
11691 int t;
11692
11693 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011694 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011695 return tokname_array[t][0];
11696}
Eric Andersencb57d552001-06-28 07:25:16 +000011697
11698/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011699 * Read and parse a command. Returns NODE_EOF on end of file.
11700 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011701 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011702static union node *
11703parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011704{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011705 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011706
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011707 tokpushback = 0;
11708 doprompt = interact;
11709 if (doprompt)
11710 setprompt(doprompt);
11711 needprompt = 0;
11712 t = readtoken();
11713 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011714 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011715 if (t == TNL)
11716 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011717 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011718 return list(1);
11719}
11720
11721/*
11722 * Input any here documents.
11723 */
11724static void
11725parseheredoc(void)
11726{
11727 struct heredoc *here;
11728 union node *n;
11729
11730 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011731 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011732
11733 while (here) {
11734 if (needprompt) {
11735 setprompt(2);
11736 }
11737 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11738 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011739 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011740 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011741 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011742 n->narg.text = wordtext;
11743 n->narg.backquote = backquotelist;
11744 here->here->nhere.doc = n;
11745 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011746 }
Eric Andersencb57d552001-06-28 07:25:16 +000011747}
11748
11749
11750/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011751 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011752 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011753#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011754static const char *
11755expandstr(const char *ps)
11756{
11757 union node n;
11758
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011759 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11760 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011761 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011762 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011763 popfile();
11764
11765 n.narg.type = NARG;
11766 n.narg.next = NULL;
11767 n.narg.text = wordtext;
11768 n.narg.backquote = backquotelist;
11769
11770 expandarg(&n, NULL, 0);
11771 return stackblock();
11772}
11773#endif
11774
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011775/*
11776 * Execute a command or commands contained in a string.
11777 */
11778static int
11779evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011780{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011781 union node *n;
11782 struct stackmark smark;
11783 int skip;
11784
11785 setinputstring(s);
11786 setstackmark(&smark);
11787
11788 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011789 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011790 evaltree(n, 0);
11791 popstackmark(&smark);
11792 skip = evalskip;
11793 if (skip)
11794 break;
11795 }
11796 popfile();
11797
11798 skip &= mask;
11799 evalskip = skip;
11800 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011801}
11802
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011803/*
11804 * The eval command.
11805 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011806static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011807evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011808{
11809 char *p;
11810 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011811
Denis Vlasenko68404f12008-03-17 09:00:54 +000011812 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011813 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011814 argv += 2;
11815 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011816 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011817 for (;;) {
11818 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011819 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011820 if (p == NULL)
11821 break;
11822 STPUTC(' ', concat);
11823 }
11824 STPUTC('\0', concat);
11825 p = grabstackstr(concat);
11826 }
11827 evalstring(p, ~SKIPEVAL);
11828
11829 }
11830 return exitstatus;
11831}
11832
11833/*
11834 * Read and execute commands. "Top" is nonzero for the top level command
11835 * loop; it turns on prompting if the shell is interactive.
11836 */
11837static int
11838cmdloop(int top)
11839{
11840 union node *n;
11841 struct stackmark smark;
11842 int inter;
11843 int numeof = 0;
11844
11845 TRACE(("cmdloop(%d) called\n", top));
11846 for (;;) {
11847 int skip;
11848
11849 setstackmark(&smark);
11850#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011851 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011852 showjobs(stderr, SHOW_CHANGED);
11853#endif
11854 inter = 0;
11855 if (iflag && top) {
11856 inter++;
11857#if ENABLE_ASH_MAIL
11858 chkmail();
11859#endif
11860 }
11861 n = parsecmd(inter);
Denys Vlasenko883cea42009-07-11 15:31:59 +020011862#if DEBUG > 2
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011863 if (debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011864 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011865#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011866 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011867 if (!top || numeof >= 50)
11868 break;
11869 if (!stoppedjobs()) {
11870 if (!Iflag)
11871 break;
11872 out2str("\nUse \"exit\" to leave shell.\n");
11873 }
11874 numeof++;
11875 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011876 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11877 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878 numeof = 0;
11879 evaltree(n, 0);
11880 }
11881 popstackmark(&smark);
11882 skip = evalskip;
11883
11884 if (skip) {
11885 evalskip = 0;
11886 return skip & SKIPEVAL;
11887 }
11888 }
11889 return 0;
11890}
11891
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011892/*
11893 * Take commands from a file. To be compatible we should do a path
11894 * search for the file, which is necessary to find sub-commands.
11895 */
11896static char *
11897find_dot_file(char *name)
11898{
11899 char *fullname;
11900 const char *path = pathval();
11901 struct stat statb;
11902
11903 /* don't try this for absolute or relative paths */
11904 if (strchr(name, '/'))
11905 return name;
11906
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011907 /* IIRC standards do not say whether . is to be searched.
11908 * And it is even smaller this way, making it unconditional for now:
11909 */
11910 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11911 fullname = name;
11912 goto try_cur_dir;
11913 }
11914
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011915 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011916 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011917 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11918 /*
11919 * Don't bother freeing here, since it will
11920 * be freed by the caller.
11921 */
11922 return fullname;
11923 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011924 if (fullname != name)
11925 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011926 }
11927
11928 /* not found in the PATH */
11929 ash_msg_and_raise_error("%s: not found", name);
11930 /* NOTREACHED */
11931}
11932
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011933static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011934dotcmd(int argc, char **argv)
11935{
11936 struct strlist *sp;
11937 volatile struct shparam saveparam;
11938 int status = 0;
11939
11940 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011941 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011942
Denis Vlasenko68404f12008-03-17 09:00:54 +000011943 if (argv[1]) { /* That's what SVR2 does */
11944 char *fullname = find_dot_file(argv[1]);
11945 argv += 2;
11946 argc -= 2;
11947 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011948 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011949 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011950 shellparam.nparam = argc;
11951 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011952 };
11953
11954 setinputfile(fullname, INPUT_PUSH_FILE);
11955 commandname = fullname;
11956 cmdloop(0);
11957 popfile();
11958
Denis Vlasenko68404f12008-03-17 09:00:54 +000011959 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011960 freeparam(&shellparam);
11961 shellparam = saveparam;
11962 };
11963 status = exitstatus;
11964 }
11965 return status;
11966}
11967
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011968static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011969exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011970{
11971 if (stoppedjobs())
11972 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011973 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011974 exitstatus = number(argv[1]);
11975 raise_exception(EXEXIT);
11976 /* NOTREACHED */
11977}
11978
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011979/*
11980 * Read a file containing shell functions.
11981 */
11982static void
11983readcmdfile(char *name)
11984{
11985 setinputfile(name, INPUT_PUSH_FILE);
11986 cmdloop(0);
11987 popfile();
11988}
11989
11990
Denis Vlasenkocc571512007-02-23 21:10:35 +000011991/* ============ find_command inplementation */
11992
11993/*
11994 * Resolve a command name. If you change this routine, you may have to
11995 * change the shellexec routine as well.
11996 */
11997static void
11998find_command(char *name, struct cmdentry *entry, int act, const char *path)
11999{
12000 struct tblentry *cmdp;
12001 int idx;
12002 int prev;
12003 char *fullname;
12004 struct stat statb;
12005 int e;
12006 int updatetbl;
12007 struct builtincmd *bcmd;
12008
12009 /* If name contains a slash, don't use PATH or hash table */
12010 if (strchr(name, '/') != NULL) {
12011 entry->u.index = -1;
12012 if (act & DO_ABS) {
12013 while (stat(name, &statb) < 0) {
12014#ifdef SYSV
12015 if (errno == EINTR)
12016 continue;
12017#endif
12018 entry->cmdtype = CMDUNKNOWN;
12019 return;
12020 }
12021 }
12022 entry->cmdtype = CMDNORMAL;
12023 return;
12024 }
12025
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012026/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012027
12028 updatetbl = (path == pathval());
12029 if (!updatetbl) {
12030 act |= DO_ALTPATH;
12031 if (strstr(path, "%builtin") != NULL)
12032 act |= DO_ALTBLTIN;
12033 }
12034
12035 /* If name is in the table, check answer will be ok */
12036 cmdp = cmdlookup(name, 0);
12037 if (cmdp != NULL) {
12038 int bit;
12039
12040 switch (cmdp->cmdtype) {
12041 default:
12042#if DEBUG
12043 abort();
12044#endif
12045 case CMDNORMAL:
12046 bit = DO_ALTPATH;
12047 break;
12048 case CMDFUNCTION:
12049 bit = DO_NOFUNC;
12050 break;
12051 case CMDBUILTIN:
12052 bit = DO_ALTBLTIN;
12053 break;
12054 }
12055 if (act & bit) {
12056 updatetbl = 0;
12057 cmdp = NULL;
12058 } else if (cmdp->rehash == 0)
12059 /* if not invalidated by cd, we're done */
12060 goto success;
12061 }
12062
12063 /* If %builtin not in path, check for builtin next */
12064 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012065 if (bcmd) {
12066 if (IS_BUILTIN_REGULAR(bcmd))
12067 goto builtin_success;
12068 if (act & DO_ALTPATH) {
12069 if (!(act & DO_ALTBLTIN))
12070 goto builtin_success;
12071 } else if (builtinloc <= 0) {
12072 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012073 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012074 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012075
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012076#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012077 {
12078 int applet_no = find_applet_by_name(name);
12079 if (applet_no >= 0) {
12080 entry->cmdtype = CMDNORMAL;
12081 entry->u.index = -2 - applet_no;
12082 return;
12083 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012084 }
12085#endif
12086
Denis Vlasenkocc571512007-02-23 21:10:35 +000012087 /* We have to search path. */
12088 prev = -1; /* where to start */
12089 if (cmdp && cmdp->rehash) { /* doing a rehash */
12090 if (cmdp->cmdtype == CMDBUILTIN)
12091 prev = builtinloc;
12092 else
12093 prev = cmdp->param.index;
12094 }
12095
12096 e = ENOENT;
12097 idx = -1;
12098 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012099 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012100 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012101 /* NB: code below will still use fullname
12102 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012103 idx++;
12104 if (pathopt) {
12105 if (prefix(pathopt, "builtin")) {
12106 if (bcmd)
12107 goto builtin_success;
12108 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012109 }
12110 if ((act & DO_NOFUNC)
12111 || !prefix(pathopt, "func")
12112 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012113 continue;
12114 }
12115 }
12116 /* if rehash, don't redo absolute path names */
12117 if (fullname[0] == '/' && idx <= prev) {
12118 if (idx < prev)
12119 continue;
12120 TRACE(("searchexec \"%s\": no change\n", name));
12121 goto success;
12122 }
12123 while (stat(fullname, &statb) < 0) {
12124#ifdef SYSV
12125 if (errno == EINTR)
12126 continue;
12127#endif
12128 if (errno != ENOENT && errno != ENOTDIR)
12129 e = errno;
12130 goto loop;
12131 }
12132 e = EACCES; /* if we fail, this will be the error */
12133 if (!S_ISREG(statb.st_mode))
12134 continue;
12135 if (pathopt) { /* this is a %func directory */
12136 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012137 /* NB: stalloc will return space pointed by fullname
12138 * (because we don't have any intervening allocations
12139 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012140 readcmdfile(fullname);
12141 cmdp = cmdlookup(name, 0);
12142 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12143 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12144 stunalloc(fullname);
12145 goto success;
12146 }
12147 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12148 if (!updatetbl) {
12149 entry->cmdtype = CMDNORMAL;
12150 entry->u.index = idx;
12151 return;
12152 }
12153 INT_OFF;
12154 cmdp = cmdlookup(name, 1);
12155 cmdp->cmdtype = CMDNORMAL;
12156 cmdp->param.index = idx;
12157 INT_ON;
12158 goto success;
12159 }
12160
12161 /* We failed. If there was an entry for this command, delete it */
12162 if (cmdp && updatetbl)
12163 delete_cmd_entry();
12164 if (act & DO_ERR)
12165 ash_msg("%s: %s", name, errmsg(e, "not found"));
12166 entry->cmdtype = CMDUNKNOWN;
12167 return;
12168
12169 builtin_success:
12170 if (!updatetbl) {
12171 entry->cmdtype = CMDBUILTIN;
12172 entry->u.cmd = bcmd;
12173 return;
12174 }
12175 INT_OFF;
12176 cmdp = cmdlookup(name, 1);
12177 cmdp->cmdtype = CMDBUILTIN;
12178 cmdp->param.cmd = bcmd;
12179 INT_ON;
12180 success:
12181 cmdp->rehash = 0;
12182 entry->cmdtype = cmdp->cmdtype;
12183 entry->u = cmdp->param;
12184}
12185
12186
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012187/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012188
Eric Andersencb57d552001-06-28 07:25:16 +000012189/*
Eric Andersencb57d552001-06-28 07:25:16 +000012190 * The trap builtin.
12191 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012192static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012193trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012194{
12195 char *action;
12196 char **ap;
12197 int signo;
12198
Eric Andersenc470f442003-07-28 09:56:35 +000012199 nextopt(nullstr);
12200 ap = argptr;
12201 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012202 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000012203 if (trap[signo] != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012204 out1fmt("trap -- %s %s\n",
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012205 single_quote(trap[signo]),
12206 get_signame(signo));
Eric Andersencb57d552001-06-28 07:25:16 +000012207 }
12208 }
12209 return 0;
12210 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012211 action = NULL;
12212 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012213 action = *ap++;
12214 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012215 signo = get_signum(*ap);
12216 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012217 ash_msg_and_raise_error("%s: bad trap", *ap);
12218 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012219 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012220 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012221 action = NULL;
12222 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012223 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012224 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012225 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012226 trap[signo] = action;
12227 if (signo != 0)
12228 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012229 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012230 ap++;
12231 }
12232 return 0;
12233}
12234
Eric Andersenc470f442003-07-28 09:56:35 +000012235
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012236/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012237
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012238#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012239/*
12240 * Lists available builtins
12241 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012242static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012243helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012244{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012245 unsigned col;
12246 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012247
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012248 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012249 "Built-in commands:\n"
12250 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012251 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012252 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012253 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012254 if (col > 60) {
12255 out1fmt("\n");
12256 col = 0;
12257 }
12258 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012259#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012260 {
12261 const char *a = applet_names;
12262 while (*a) {
12263 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12264 if (col > 60) {
12265 out1fmt("\n");
12266 col = 0;
12267 }
12268 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012269 }
12270 }
12271#endif
12272 out1fmt("\n\n");
12273 return EXIT_SUCCESS;
12274}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012275#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012276
Eric Andersencb57d552001-06-28 07:25:16 +000012277/*
Eric Andersencb57d552001-06-28 07:25:16 +000012278 * The export and readonly commands.
12279 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012280static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012281exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012282{
12283 struct var *vp;
12284 char *name;
12285 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012286 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012287 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012288
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012289 if (nextopt("p") != 'p') {
12290 aptr = argptr;
12291 name = *aptr;
12292 if (name) {
12293 do {
12294 p = strchr(name, '=');
12295 if (p != NULL) {
12296 p++;
12297 } else {
12298 vp = *findvar(hashvar(name), name);
12299 if (vp) {
12300 vp->flags |= flag;
12301 continue;
12302 }
Eric Andersencb57d552001-06-28 07:25:16 +000012303 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012304 setvar(name, p, flag);
12305 } while ((name = *++aptr) != NULL);
12306 return 0;
12307 }
Eric Andersencb57d552001-06-28 07:25:16 +000012308 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012309 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012310 return 0;
12311}
12312
Eric Andersencb57d552001-06-28 07:25:16 +000012313/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012314 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012315 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012316static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012317unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012318{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012319 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012320
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012321 cmdp = cmdlookup(name, 0);
12322 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12323 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012324}
12325
Eric Andersencb57d552001-06-28 07:25:16 +000012326/*
Eric Andersencb57d552001-06-28 07:25:16 +000012327 * The unset builtin command. We unset the function before we unset the
12328 * variable to allow a function to be unset when there is a readonly variable
12329 * with the same name.
12330 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012331static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012332unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012333{
12334 char **ap;
12335 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012336 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012337 int ret = 0;
12338
12339 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012340 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012341 }
Eric Andersencb57d552001-06-28 07:25:16 +000012342
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012343 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012344 if (flag != 'f') {
12345 i = unsetvar(*ap);
12346 ret |= i;
12347 if (!(i & 2))
12348 continue;
12349 }
12350 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012351 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012352 }
Eric Andersenc470f442003-07-28 09:56:35 +000012353 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012354}
12355
12356
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012357/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012358
Eric Andersenc470f442003-07-28 09:56:35 +000012359#include <sys/times.h>
12360
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012361static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012362 ' ', offsetof(struct tms, tms_utime),
12363 '\n', offsetof(struct tms, tms_stime),
12364 ' ', offsetof(struct tms, tms_cutime),
12365 '\n', offsetof(struct tms, tms_cstime),
12366 0
12367};
Eric Andersencb57d552001-06-28 07:25:16 +000012368
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012369static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012370timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012371{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012372 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012373 const unsigned char *p;
12374 struct tms buf;
12375
12376 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012377 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012378
12379 p = timescmd_str;
12380 do {
12381 t = *(clock_t *)(((char *) &buf) + p[1]);
12382 s = t / clk_tck;
12383 out1fmt("%ldm%ld.%.3lds%c",
12384 s/60, s%60,
12385 ((t - s * clk_tck) * 1000) / clk_tck,
12386 p[0]);
12387 } while (*(p += 2));
12388
Eric Andersencb57d552001-06-28 07:25:16 +000012389 return 0;
12390}
12391
Mike Frysinger98c52642009-04-02 10:02:37 +000012392#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012393/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012394 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12395 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012396 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012397 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012398 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012399static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012400letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012401{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012402 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012403
Denis Vlasenko68404f12008-03-17 09:00:54 +000012404 argv++;
12405 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012406 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012407 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012408 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012409 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012410
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012411 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012412}
Mike Frysinger98c52642009-04-02 10:02:37 +000012413#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012414
Eric Andersenc470f442003-07-28 09:56:35 +000012415
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012416/* ============ miscbltin.c
12417 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012418 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012419 */
12420
12421#undef rflag
12422
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012423#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012424typedef enum __rlimit_resource rlim_t;
12425#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012426
Eric Andersenc470f442003-07-28 09:56:35 +000012427/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012428 * The read builtin. Options:
12429 * -r Do not interpret '\' specially
12430 * -s Turn off echo (tty only)
12431 * -n NCHARS Read NCHARS max
12432 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12433 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12434 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012435 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012436 * TODO: bash also has:
12437 * -a ARRAY Read into array[0],[1],etc
12438 * -d DELIM End on DELIM char, not newline
12439 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012440 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012441static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012442readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012443{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012444 static const char *const arg_REPLY[] = { "REPLY", NULL };
12445
Eric Andersenc470f442003-07-28 09:56:35 +000012446 char **ap;
12447 int backslash;
12448 char c;
12449 int rflag;
12450 char *prompt;
12451 const char *ifs;
12452 char *p;
12453 int startword;
12454 int status;
12455 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012456 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012457#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012458 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012459 int silent = 0;
12460 struct termios tty, old_tty;
12461#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012462#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012463 unsigned end_ms = 0;
12464 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012465#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012466
12467 rflag = 0;
12468 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012469 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012470 IF_ASH_READ_TIMEOUT("t:")
12471 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012472 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012473 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012474 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012475 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012476 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012477#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012478 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012479 nchars = bb_strtou(optionarg, NULL, 10);
12480 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012481 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012482 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012483 break;
12484 case 's':
12485 silent = 1;
12486 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012487#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012488#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012489 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012490 timeout = bb_strtou(optionarg, NULL, 10);
12491 if (errno || timeout > UINT_MAX / 2048)
12492 ash_msg_and_raise_error("invalid timeout");
12493 timeout *= 1000;
12494#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012495 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012496 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012497 /* EINVAL means number is ok, but not terminated by NUL */
12498 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012499 char *p2;
12500 if (*++p) {
12501 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012502 ts.tv_usec = bb_strtou(p, &p2, 10);
12503 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012504 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012505 scale = p2 - p;
12506 /* normalize to usec */
12507 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012508 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012509 while (scale++ < 6)
12510 ts.tv_usec *= 10;
12511 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012512 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012513 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012514 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012515 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012516 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012517 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012518#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012519 break;
12520#endif
12521 case 'r':
12522 rflag = 1;
12523 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012524 case 'u':
12525 fd = bb_strtou(optionarg, NULL, 10);
12526 if (fd < 0 || errno)
12527 ash_msg_and_raise_error("invalid file descriptor");
12528 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012529 default:
12530 break;
12531 }
Eric Andersenc470f442003-07-28 09:56:35 +000012532 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012533 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012534 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012535 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012536 ap = argptr;
12537 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012538 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012539 ifs = bltinlookup("IFS");
12540 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012541 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012542#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012543 tcgetattr(fd, &tty);
12544 old_tty = tty;
12545 if (nchars || silent) {
12546 if (nchars) {
12547 tty.c_lflag &= ~ICANON;
12548 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012549 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012550 if (silent) {
12551 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12552 }
12553 /* if tcgetattr failed, tcsetattr will fail too.
12554 * Ignoring, it's harmless. */
12555 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012556 }
12557#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012558
Eric Andersenc470f442003-07-28 09:56:35 +000012559 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012560 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012561 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012562#if ENABLE_ASH_READ_TIMEOUT
12563 if (timeout) /* NB: ensuring end_ms is nonzero */
12564 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12565#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012566 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012567 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012568 const char *is_ifs;
12569
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012570#if ENABLE_ASH_READ_TIMEOUT
12571 if (end_ms) {
12572 struct pollfd pfd[1];
12573 pfd[0].fd = fd;
12574 pfd[0].events = POLLIN;
12575 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12576 if ((int)timeout <= 0 /* already late? */
12577 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12578 ) { /* timed out! */
12579#if ENABLE_ASH_READ_NCHARS
12580 tcsetattr(fd, TCSANOW, &old_tty);
12581#endif
12582 return 1;
12583 }
12584 }
12585#endif
12586 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012587 status = 1;
12588 break;
12589 }
12590 if (c == '\0')
12591 continue;
12592 if (backslash) {
12593 backslash = 0;
12594 if (c != '\n')
12595 goto put;
12596 continue;
12597 }
12598 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012599 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012600 continue;
12601 }
12602 if (c == '\n')
12603 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012604 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012605/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012606 is_ifs = strchr(ifs, c);
12607 if (startword && is_ifs) {
12608 if (isspace(c))
12609 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012610 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012611 startword--;
12612 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012613 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012614 }
12615 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012616 if (ap[1] != NULL && is_ifs) {
12617 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012618 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012619 beg = stackblock();
12620 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012621 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012622 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012623 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012624 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012625 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012626 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012627 put:
12628 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012629 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012630/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012631#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012632 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012633#else
12634 while (1);
12635#endif
12636
12637#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012638 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012639#endif
12640
Eric Andersenc470f442003-07-28 09:56:35 +000012641 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012642 /* Remove trailing space ifs chars */
12643 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012644 *p = '\0';
12645 setvar(*ap, stackblock(), 0);
12646 while (*++ap != NULL)
12647 setvar(*ap, nullstr, 0);
12648 return status;
12649}
12650
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012651static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012652umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012653{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012654 static const char permuser[3] ALIGN1 = "ugo";
12655 static const char permmode[3] ALIGN1 = "rwx";
12656 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012657 S_IRUSR, S_IWUSR, S_IXUSR,
12658 S_IRGRP, S_IWGRP, S_IXGRP,
12659 S_IROTH, S_IWOTH, S_IXOTH
12660 };
12661
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012662 /* TODO: use bb_parse_mode() instead */
12663
Eric Andersenc470f442003-07-28 09:56:35 +000012664 char *ap;
12665 mode_t mask;
12666 int i;
12667 int symbolic_mode = 0;
12668
12669 while (nextopt("S") != '\0') {
12670 symbolic_mode = 1;
12671 }
12672
Denis Vlasenkob012b102007-02-19 22:43:01 +000012673 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012674 mask = umask(0);
12675 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012676 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012677
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012678 ap = *argptr;
12679 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012680 if (symbolic_mode) {
12681 char buf[18];
12682 char *p = buf;
12683
12684 for (i = 0; i < 3; i++) {
12685 int j;
12686
12687 *p++ = permuser[i];
12688 *p++ = '=';
12689 for (j = 0; j < 3; j++) {
12690 if ((mask & permmask[3 * i + j]) == 0) {
12691 *p++ = permmode[j];
12692 }
12693 }
12694 *p++ = ',';
12695 }
12696 *--p = 0;
12697 puts(buf);
12698 } else {
12699 out1fmt("%.4o\n", mask);
12700 }
12701 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012702 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012703 mask = 0;
12704 do {
12705 if (*ap >= '8' || *ap < '0')
Denis Vlasenkob012b102007-02-19 22:43:01 +000012706 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012707 mask = (mask << 3) + (*ap - '0');
12708 } while (*++ap != '\0');
12709 umask(mask);
12710 } else {
12711 mask = ~mask & 0777;
12712 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012713 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012714 }
12715 umask(~mask & 0777);
12716 }
12717 }
12718 return 0;
12719}
12720
12721/*
12722 * ulimit builtin
12723 *
12724 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12725 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12726 * ash by J.T. Conklin.
12727 *
12728 * Public domain.
12729 */
Eric Andersenc470f442003-07-28 09:56:35 +000012730struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012731 uint8_t cmd; /* RLIMIT_xxx fit into it */
12732 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012733 char option;
12734};
12735
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012736static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012737#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012738 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012739#endif
12740#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012741 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012742#endif
12743#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012744 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012745#endif
12746#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012747 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012748#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012749#ifdef RLIMIT_CORE
12750 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012751#endif
12752#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012753 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012754#endif
12755#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012756 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012757#endif
12758#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012759 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012760#endif
12761#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012762 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012763#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012764#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012765 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012766#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012767#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012768 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012769#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012770};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012771static const char limits_name[] =
12772#ifdef RLIMIT_CPU
12773 "time(seconds)" "\0"
12774#endif
12775#ifdef RLIMIT_FSIZE
12776 "file(blocks)" "\0"
12777#endif
12778#ifdef RLIMIT_DATA
12779 "data(kb)" "\0"
12780#endif
12781#ifdef RLIMIT_STACK
12782 "stack(kb)" "\0"
12783#endif
12784#ifdef RLIMIT_CORE
12785 "coredump(blocks)" "\0"
12786#endif
12787#ifdef RLIMIT_RSS
12788 "memory(kb)" "\0"
12789#endif
12790#ifdef RLIMIT_MEMLOCK
12791 "locked memory(kb)" "\0"
12792#endif
12793#ifdef RLIMIT_NPROC
12794 "process" "\0"
12795#endif
12796#ifdef RLIMIT_NOFILE
12797 "nofiles" "\0"
12798#endif
12799#ifdef RLIMIT_AS
12800 "vmemory(kb)" "\0"
12801#endif
12802#ifdef RLIMIT_LOCKS
12803 "locks" "\0"
12804#endif
12805;
Eric Andersenc470f442003-07-28 09:56:35 +000012806
Glenn L McGrath76620622004-01-13 10:19:37 +000012807enum limtype { SOFT = 0x1, HARD = 0x2 };
12808
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012809static void
12810printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012811 const struct limits *l)
12812{
12813 rlim_t val;
12814
12815 val = limit->rlim_max;
12816 if (how & SOFT)
12817 val = limit->rlim_cur;
12818
12819 if (val == RLIM_INFINITY)
12820 out1fmt("unlimited\n");
12821 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012822 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012823 out1fmt("%lld\n", (long long) val);
12824 }
12825}
12826
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012827static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012828ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012829{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012830 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012831 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012832 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012833 const struct limits *l;
12834 int set, all = 0;
12835 int optc, what;
12836 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012837
12838 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012839 while ((optc = nextopt("HSa"
12840#ifdef RLIMIT_CPU
12841 "t"
12842#endif
12843#ifdef RLIMIT_FSIZE
12844 "f"
12845#endif
12846#ifdef RLIMIT_DATA
12847 "d"
12848#endif
12849#ifdef RLIMIT_STACK
12850 "s"
12851#endif
12852#ifdef RLIMIT_CORE
12853 "c"
12854#endif
12855#ifdef RLIMIT_RSS
12856 "m"
12857#endif
12858#ifdef RLIMIT_MEMLOCK
12859 "l"
12860#endif
12861#ifdef RLIMIT_NPROC
12862 "p"
12863#endif
12864#ifdef RLIMIT_NOFILE
12865 "n"
12866#endif
12867#ifdef RLIMIT_AS
12868 "v"
12869#endif
12870#ifdef RLIMIT_LOCKS
12871 "w"
12872#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012873 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012874 switch (optc) {
12875 case 'H':
12876 how = HARD;
12877 break;
12878 case 'S':
12879 how = SOFT;
12880 break;
12881 case 'a':
12882 all = 1;
12883 break;
12884 default:
12885 what = optc;
12886 }
12887
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012888 for (l = limits_tbl; l->option != what; l++)
12889 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012890
12891 set = *argptr ? 1 : 0;
12892 if (set) {
12893 char *p = *argptr;
12894
12895 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012896 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012897 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012898 val = RLIM_INFINITY;
12899 else {
12900 val = (rlim_t) 0;
12901
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012902 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012903 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012904 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012905 if (val < (rlim_t) 0)
12906 break;
12907 }
12908 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012909 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012910 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012911 }
12912 }
12913 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012914 const char *lname = limits_name;
12915 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012916 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012917 out1fmt("%-20s ", lname);
12918 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012919 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012920 }
12921 return 0;
12922 }
12923
12924 getrlimit(l->cmd, &limit);
12925 if (set) {
12926 if (how & HARD)
12927 limit.rlim_max = val;
12928 if (how & SOFT)
12929 limit.rlim_cur = val;
12930 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012931 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012932 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012933 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012934 }
12935 return 0;
12936}
12937
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012938/* ============ main() and helpers */
12939
12940/*
12941 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012942 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012943static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012944static void
12945exitshell(void)
12946{
12947 struct jmploc loc;
12948 char *p;
12949 int status;
12950
12951 status = exitstatus;
12952 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12953 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012954 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012955/* dash bug: it just does _exit(exitstatus) here
12956 * but we have to do setjobctl(0) first!
12957 * (bug is still not fixed in dash-0.5.3 - if you run dash
12958 * under Midnight Commander, on exit from dash MC is backgrounded) */
12959 status = exitstatus;
12960 goto out;
12961 }
12962 exception_handler = &loc;
12963 p = trap[0];
12964 if (p) {
12965 trap[0] = NULL;
12966 evalstring(p, 0);
12967 }
12968 flush_stdout_stderr();
12969 out:
12970 setjobctl(0);
12971 _exit(status);
12972 /* NOTREACHED */
12973}
12974
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012975static void
12976init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012977{
12978 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012979 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012980
12981 /* from trap.c: */
12982 signal(SIGCHLD, SIG_DFL);
12983
12984 /* from var.c: */
12985 {
12986 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012987 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012988 const char *p;
12989 struct stat st1, st2;
12990
12991 initvar();
12992 for (envp = environ; envp && *envp; envp++) {
12993 if (strchr(*envp, '=')) {
12994 setvareq(*envp, VEXPORT|VTEXTFIXED);
12995 }
12996 }
12997
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012998 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012999 setvar("PPID", ppid, 0);
13000
13001 p = lookupvar("PWD");
13002 if (p)
13003 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13004 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13005 p = '\0';
13006 setpwd(p, 0);
13007 }
13008}
13009
13010/*
13011 * Process the shell command line arguments.
13012 */
13013static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013014procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013015{
13016 int i;
13017 const char *xminusc;
13018 char **xargv;
13019
13020 xargv = argv;
13021 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013022 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013023 xargv++;
13024 for (i = 0; i < NOPTS; i++)
13025 optlist[i] = 2;
13026 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013027 if (options(1)) {
13028 /* it already printed err message */
13029 raise_exception(EXERROR);
13030 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013031 xargv = argptr;
13032 xminusc = minusc;
13033 if (*xargv == NULL) {
13034 if (xminusc)
13035 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13036 sflag = 1;
13037 }
13038 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13039 iflag = 1;
13040 if (mflag == 2)
13041 mflag = iflag;
13042 for (i = 0; i < NOPTS; i++)
13043 if (optlist[i] == 2)
13044 optlist[i] = 0;
13045#if DEBUG == 2
13046 debug = 1;
13047#endif
13048 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13049 if (xminusc) {
13050 minusc = *xargv++;
13051 if (*xargv)
13052 goto setarg0;
13053 } else if (!sflag) {
13054 setinputfile(*xargv, 0);
13055 setarg0:
13056 arg0 = *xargv++;
13057 commandname = arg0;
13058 }
13059
13060 shellparam.p = xargv;
13061#if ENABLE_ASH_GETOPTS
13062 shellparam.optind = 1;
13063 shellparam.optoff = -1;
13064#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013065 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013066 while (*xargv) {
13067 shellparam.nparam++;
13068 xargv++;
13069 }
13070 optschanged();
13071}
13072
13073/*
13074 * Read /etc/profile or .profile.
13075 */
13076static void
13077read_profile(const char *name)
13078{
13079 int skip;
13080
13081 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13082 return;
13083 skip = cmdloop(0);
13084 popfile();
13085 if (skip)
13086 exitshell();
13087}
13088
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013089/*
13090 * This routine is called when an error or an interrupt occurs in an
13091 * interactive shell and control is returned to the main command loop.
13092 */
13093static void
13094reset(void)
13095{
13096 /* from eval.c: */
13097 evalskip = 0;
13098 loopnest = 0;
13099 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013100 g_parsefile->left_in_buffer = 0;
13101 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013102 popallfiles();
13103 /* from parser.c: */
13104 tokpushback = 0;
13105 checkkwd = 0;
13106 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013107 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013108}
13109
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013110#if PROFILE
13111static short profile_buf[16384];
13112extern int etext();
13113#endif
13114
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013115/*
13116 * Main routine. We initialize things, parse the arguments, execute
13117 * profiles if we're a login shell, and then call cmdloop to execute
13118 * commands. The setjmp call sets up the location to jump to when an
13119 * exception occurs. When an exception occurs the variable "state"
13120 * is used to figure out how far we had gotten.
13121 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013122int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013123int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013124{
Mike Frysinger98c52642009-04-02 10:02:37 +000013125 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013126 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013127 struct jmploc jmploc;
13128 struct stackmark smark;
13129
Denis Vlasenko01631112007-12-16 17:20:38 +000013130 /* Initialize global data */
13131 INIT_G_misc();
13132 INIT_G_memstack();
13133 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013134#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013135 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013136#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013137 INIT_G_cmdtable();
13138
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013139#if PROFILE
13140 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13141#endif
13142
13143#if ENABLE_FEATURE_EDITING
13144 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13145#endif
13146 state = 0;
13147 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013148 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013149 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013150
13151 reset();
13152
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013153 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013154 if (e == EXERROR)
13155 exitstatus = 2;
13156 s = state;
13157 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13158 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013159 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013160 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013161
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013162 popstackmark(&smark);
13163 FORCE_INT_ON; /* enable interrupts */
13164 if (s == 1)
13165 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013166 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013167 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013168 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013169 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013170 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013171 }
13172 exception_handler = &jmploc;
13173#if DEBUG
13174 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013175 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013176 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013177#endif
13178 rootpid = getpid();
13179
13180#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013181 /* Can use monotonic_ns() for better randomness but for now it is
13182 * not used anywhere else in busybox... so avoid bloat */
13183 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013184#endif
13185 init();
13186 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013187 procargs(argv);
13188
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013189#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13190 if (iflag) {
13191 const char *hp = lookupvar("HISTFILE");
13192
13193 if (hp == NULL) {
13194 hp = lookupvar("HOME");
13195 if (hp != NULL) {
13196 char *defhp = concat_path_file(hp, ".ash_history");
13197 setvar("HISTFILE", defhp, 0);
13198 free(defhp);
13199 }
13200 }
13201 }
13202#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013203 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013204 isloginsh = 1;
13205 if (isloginsh) {
13206 state = 1;
13207 read_profile("/etc/profile");
13208 state1:
13209 state = 2;
13210 read_profile(".profile");
13211 }
13212 state2:
13213 state = 3;
13214 if (
13215#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013216 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013217#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013218 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013219 ) {
13220 shinit = lookupvar("ENV");
13221 if (shinit != NULL && *shinit != '\0') {
13222 read_profile(shinit);
13223 }
13224 }
13225 state3:
13226 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013227 if (minusc) {
13228 /* evalstring pushes parsefile stack.
13229 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013230 * is one of stacked source fds.
13231 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013232 if (!sflag)
13233 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013234 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013235 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013236
13237 if (sflag || minusc == NULL) {
13238#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013239 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013240 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013241 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013242 line_input_state->hist_file = hp;
13243 }
13244#endif
13245 state4: /* XXX ??? - why isn't this before the "if" statement */
13246 cmdloop(1);
13247 }
13248#if PROFILE
13249 monitor(0);
13250#endif
13251#ifdef GPROF
13252 {
13253 extern void _mcleanup(void);
13254 _mcleanup();
13255 }
13256#endif
13257 exitshell();
13258 /* NOTREACHED */
13259}
13260
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013261
Eric Andersendf82f612001-06-28 07:46:40 +000013262/*-
13263 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013264 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013265 *
13266 * This code is derived from software contributed to Berkeley by
13267 * Kenneth Almquist.
13268 *
13269 * Redistribution and use in source and binary forms, with or without
13270 * modification, are permitted provided that the following conditions
13271 * are met:
13272 * 1. Redistributions of source code must retain the above copyright
13273 * notice, this list of conditions and the following disclaimer.
13274 * 2. Redistributions in binary form must reproduce the above copyright
13275 * notice, this list of conditions and the following disclaimer in the
13276 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013277 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013278 * may be used to endorse or promote products derived from this software
13279 * without specific prior written permission.
13280 *
13281 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13282 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13283 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13284 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13285 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13286 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13287 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13288 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13289 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13290 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13291 * SUCH DAMAGE.
13292 */