blob: f9c89f13fc577345a58ce0f128716eb146a574aa [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
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200266/* C99 says: "char" declaration may be signed or unsigned by default */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000267#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 */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200464#define CTLESC ((unsigned char)'\201') /* escape next character */
465#define CTLVAR ((unsigned char)'\202') /* variable defn */
466#define CTLENDVAR ((unsigned char)'\203')
467#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000468#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
469/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200470#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
471#define CTLENDARI ((unsigned char)'\207')
472#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000473
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) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200991 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000992 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) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003243#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3244#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3245#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246
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 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003253struct procstat {
3254 pid_t pid; /* process id */
3255 int status; /* last process status from wait() */
3256 char *cmd; /* text of command being run */
3257};
3258
3259struct job {
3260 struct procstat ps0; /* status of process */
3261 struct procstat *ps; /* status or processes when more than one */
3262#if JOBS
3263 int stopstatus; /* status of a stopped job */
3264#endif
3265 uint32_t
3266 nprocs: 16, /* number of processes */
3267 state: 8,
3268#define JOBRUNNING 0 /* at least one proc running */
3269#define JOBSTOPPED 1 /* all procs are stopped */
3270#define JOBDONE 2 /* all procs are completed */
3271#if JOBS
3272 sigint: 1, /* job was killed by SIGINT */
3273 jobctl: 1, /* job running under job control */
3274#endif
3275 waited: 1, /* true if this entry has been waited for */
3276 used: 1, /* true if this entry is in used */
3277 changed: 1; /* true if status has changed */
3278 struct job *prev_job; /* previous job */
3279};
3280
Denis Vlasenko68404f12008-03-17 09:00:54 +00003281static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003282#if !JOBS
3283#define forkshell(job, node, mode) forkshell(job, mode)
3284#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003285static int forkshell(struct job *, union node *, int);
3286static int waitforjob(struct job *);
3287
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003288#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003289enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003290#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003292static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003293static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003294#endif
3295
3296/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003297 * Ignore a signal.
3298 */
3299static void
3300ignoresig(int signo)
3301{
3302 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3303 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3304 /* No, need to do it */
3305 signal(signo, SIG_IGN);
3306 }
3307 sigmode[signo - 1] = S_HARD_IGN;
3308}
3309
3310/*
3311 * Signal handler. Only one usage site - in setsignal()
3312 */
3313static void
3314onsig(int signo)
3315{
3316 gotsig[signo - 1] = 1;
3317
3318 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3319 if (!suppressint) {
3320 pendingsig = 0;
3321 raise_interrupt(); /* does not return */
3322 }
3323 intpending = 1;
3324 } else {
3325 pendingsig = signo;
3326 }
3327}
3328
3329/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 * Set the signal handler for the specified signal. The routine figures
3331 * out what it should be set to.
3332 */
3333static void
3334setsignal(int signo)
3335{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003336 char *t;
3337 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003338 struct sigaction act;
3339
3340 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003341 new_act = S_DFL;
3342 if (t != NULL) { /* trap for this sig is set */
3343 new_act = S_CATCH;
3344 if (t[0] == '\0') /* trap is "": ignore this sig */
3345 new_act = S_IGN;
3346 }
3347
3348 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003349 switch (signo) {
3350 case SIGINT:
3351 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003352 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 break;
3354 case SIGQUIT:
3355#if DEBUG
3356 if (debug)
3357 break;
3358#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003359 /* man bash:
3360 * "In all cases, bash ignores SIGQUIT. Non-builtin
3361 * commands run by bash have signal handlers
3362 * set to the values inherited by the shell
3363 * from its parent". */
3364 new_act = S_IGN;
3365 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003366 case SIGTERM:
3367 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 break;
3370#if JOBS
3371 case SIGTSTP:
3372 case SIGTTOU:
3373 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375 break;
3376#endif
3377 }
3378 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379//TODO: if !rootshell, we reset SIGQUIT to DFL,
3380//whereas we have to restore it to what shell got on entry
3381//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382
3383 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003384 cur_act = *t;
3385 if (cur_act == 0) {
3386 /* current setting is not yet known */
3387 if (sigaction(signo, NULL, &act)) {
3388 /* pretend it worked; maybe we should give a warning,
3389 * but other shells don't. We don't alter sigmode,
3390 * so we retry every time.
3391 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003392 return;
3393 }
3394 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003395 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396 if (mflag
3397 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3398 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003399 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003400 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401 }
3402 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003403 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003404 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003405
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003406 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003407 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003408 case S_CATCH:
3409 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003410 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3411 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003412 break;
3413 case S_IGN:
3414 act.sa_handler = SIG_IGN;
3415 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003416 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003417 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003418
3419 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003420}
3421
3422/* mode flags for set_curjob */
3423#define CUR_DELETE 2
3424#define CUR_RUNNING 1
3425#define CUR_STOPPED 0
3426
3427/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003428#define DOWAIT_NONBLOCK WNOHANG
3429#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430
3431#if JOBS
3432/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003433static int initialpgrp; //references:2
3434static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003435#endif
3436/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003437static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003438/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003439static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003440/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003441static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003442/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003443static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003444
3445static void
3446set_curjob(struct job *jp, unsigned mode)
3447{
3448 struct job *jp1;
3449 struct job **jpp, **curp;
3450
3451 /* first remove from list */
3452 jpp = curp = &curjob;
3453 do {
3454 jp1 = *jpp;
3455 if (jp1 == jp)
3456 break;
3457 jpp = &jp1->prev_job;
3458 } while (1);
3459 *jpp = jp1->prev_job;
3460
3461 /* Then re-insert in correct position */
3462 jpp = curp;
3463 switch (mode) {
3464 default:
3465#if DEBUG
3466 abort();
3467#endif
3468 case CUR_DELETE:
3469 /* job being deleted */
3470 break;
3471 case CUR_RUNNING:
3472 /* newly created job or backgrounded job,
3473 put after all stopped jobs. */
3474 do {
3475 jp1 = *jpp;
3476#if JOBS
3477 if (!jp1 || jp1->state != JOBSTOPPED)
3478#endif
3479 break;
3480 jpp = &jp1->prev_job;
3481 } while (1);
3482 /* FALLTHROUGH */
3483#if JOBS
3484 case CUR_STOPPED:
3485#endif
3486 /* newly stopped job - becomes curjob */
3487 jp->prev_job = *jpp;
3488 *jpp = jp;
3489 break;
3490 }
3491}
3492
3493#if JOBS || DEBUG
3494static int
3495jobno(const struct job *jp)
3496{
3497 return jp - jobtab + 1;
3498}
3499#endif
3500
3501/*
3502 * Convert a job name to a job structure.
3503 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003504#if !JOBS
3505#define getjob(name, getctl) getjob(name)
3506#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003507static struct job *
3508getjob(const char *name, int getctl)
3509{
3510 struct job *jp;
3511 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003512 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003513 unsigned num;
3514 int c;
3515 const char *p;
3516 char *(*match)(const char *, const char *);
3517
3518 jp = curjob;
3519 p = name;
3520 if (!p)
3521 goto currentjob;
3522
3523 if (*p != '%')
3524 goto err;
3525
3526 c = *++p;
3527 if (!c)
3528 goto currentjob;
3529
3530 if (!p[1]) {
3531 if (c == '+' || c == '%') {
3532 currentjob:
3533 err_msg = "No current job";
3534 goto check;
3535 }
3536 if (c == '-') {
3537 if (jp)
3538 jp = jp->prev_job;
3539 err_msg = "No previous job";
3540 check:
3541 if (!jp)
3542 goto err;
3543 goto gotit;
3544 }
3545 }
3546
3547 if (is_number(p)) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00003548// TODO: number() instead? It does error checking...
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003549 num = atoi(p);
3550 if (num < njobs) {
3551 jp = jobtab + num - 1;
3552 if (jp->used)
3553 goto gotit;
3554 goto err;
3555 }
3556 }
3557
3558 match = prefix;
3559 if (*p == '?') {
3560 match = strstr;
3561 p++;
3562 }
3563
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003564 found = NULL;
3565 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003566 if (match(jp->ps[0].cmd, p)) {
3567 if (found)
3568 goto err;
3569 found = jp;
3570 err_msg = "%s: ambiguous";
3571 }
3572 jp = jp->prev_job;
3573 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003574 if (!found)
3575 goto err;
3576 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003577
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
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003937 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003938 /* 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)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003947 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003948 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003949 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003950
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003951 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003952 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 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003965 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003966
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003967 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3968 * or prints several "PID | <cmdN>" lines,
3969 * depending on SHOW_PIDS bit.
3970 * We do not print status of individual processes
3971 * between PID and <cmdN>. bash does it, but not very well:
3972 * first line shows overall job status, not process status,
3973 * making it impossible to know 1st process status.
3974 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003975 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003976 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003977 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003978 s[0] = '\0';
3979 col = 33;
3980 if (mode & SHOW_PIDS)
3981 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003982 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003983 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3984 if (ps != jp->ps)
3985 fprintf(out, "| ");
3986 fprintf(out, "%s", ps->cmd);
3987 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003988 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 }
3990 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003991
3992 jp->changed = 0;
3993
3994 if (jp->state == JOBDONE) {
3995 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3996 freejob(jp);
3997 }
3998}
3999
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004000/*
4001 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4002 * statuses have changed since the last call to showjobs.
4003 */
4004static void
4005showjobs(FILE *out, int mode)
4006{
4007 struct job *jp;
4008
Denys Vlasenko883cea42009-07-11 15:31:59 +02004009 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004010
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004011 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004012 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004013 continue;
4014
4015 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004016 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004017 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004018 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004019 }
4020}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004021
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004022static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004023jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004024{
4025 int mode, m;
4026
4027 mode = 0;
4028 while ((m = nextopt("lp"))) {
4029 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004030 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004031 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004032 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004033 }
4034
4035 argv = argptr;
4036 if (*argv) {
4037 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004038 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004039 while (*++argv);
4040 } else
4041 showjobs(stdout, mode);
4042
4043 return 0;
4044}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004045#endif /* JOBS */
4046
4047static int
4048getstatus(struct job *job)
4049{
4050 int status;
4051 int retval;
4052
4053 status = job->ps[job->nprocs - 1].status;
4054 retval = WEXITSTATUS(status);
4055 if (!WIFEXITED(status)) {
4056#if JOBS
4057 retval = WSTOPSIG(status);
4058 if (!WIFSTOPPED(status))
4059#endif
4060 {
4061 /* XXX: limits number of signals */
4062 retval = WTERMSIG(status);
4063#if JOBS
4064 if (retval == SIGINT)
4065 job->sigint = 1;
4066#endif
4067 }
4068 retval += 128;
4069 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004070 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004071 jobno(job), job->nprocs, status, retval));
4072 return retval;
4073}
4074
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004075static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004076waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004077{
4078 struct job *job;
4079 int retval;
4080 struct job *jp;
4081
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004082// exsig++;
4083// xbarrier();
4084 if (pendingsig)
4085 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004086
4087 nextopt(nullstr);
4088 retval = 0;
4089
4090 argv = argptr;
4091 if (!*argv) {
4092 /* wait for all jobs */
4093 for (;;) {
4094 jp = curjob;
4095 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004096 if (!jp) /* no running procs */
4097 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 if (jp->state == JOBRUNNING)
4099 break;
4100 jp->waited = 1;
4101 jp = jp->prev_job;
4102 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004103 /* man bash:
4104 * "When bash is waiting for an asynchronous command via
4105 * the wait builtin, the reception of a signal for which a trap
4106 * has been set will cause the wait builtin to return immediately
4107 * with an exit status greater than 128, immediately after which
4108 * the trap is executed."
4109 * Do we do it that way? */
4110 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004111 }
4112 }
4113
4114 retval = 127;
4115 do {
4116 if (**argv != '%') {
4117 pid_t pid = number(*argv);
4118 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004119 while (1) {
4120 if (!job)
4121 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004122 if (job->ps[job->nprocs - 1].pid == pid)
4123 break;
4124 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004125 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004126 } else
4127 job = getjob(*argv, 0);
4128 /* loop until process terminated or stopped */
4129 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004130 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004131 job->waited = 1;
4132 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004133 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004134 } while (*++argv);
4135
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004136 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004137 return retval;
4138}
4139
4140static struct job *
4141growjobtab(void)
4142{
4143 size_t len;
4144 ptrdiff_t offset;
4145 struct job *jp, *jq;
4146
4147 len = njobs * sizeof(*jp);
4148 jq = jobtab;
4149 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4150
4151 offset = (char *)jp - (char *)jq;
4152 if (offset) {
4153 /* Relocate pointers */
4154 size_t l = len;
4155
4156 jq = (struct job *)((char *)jq + l);
4157 while (l) {
4158 l -= sizeof(*jp);
4159 jq--;
4160#define joff(p) ((struct job *)((char *)(p) + l))
4161#define jmove(p) (p) = (void *)((char *)(p) + offset)
4162 if (joff(jp)->ps == &jq->ps0)
4163 jmove(joff(jp)->ps);
4164 if (joff(jp)->prev_job)
4165 jmove(joff(jp)->prev_job);
4166 }
4167 if (curjob)
4168 jmove(curjob);
4169#undef joff
4170#undef jmove
4171 }
4172
4173 njobs += 4;
4174 jobtab = jp;
4175 jp = (struct job *)((char *)jp + len);
4176 jq = jp + 3;
4177 do {
4178 jq->used = 0;
4179 } while (--jq >= jp);
4180 return jp;
4181}
4182
4183/*
4184 * Return a new job structure.
4185 * Called with interrupts off.
4186 */
4187static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004188makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004189{
4190 int i;
4191 struct job *jp;
4192
4193 for (i = njobs, jp = jobtab; ; jp++) {
4194 if (--i < 0) {
4195 jp = growjobtab();
4196 break;
4197 }
4198 if (jp->used == 0)
4199 break;
4200 if (jp->state != JOBDONE || !jp->waited)
4201 continue;
4202#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004203 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004204 continue;
4205#endif
4206 freejob(jp);
4207 break;
4208 }
4209 memset(jp, 0, sizeof(*jp));
4210#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004211 /* jp->jobctl is a bitfield.
4212 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004213 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 jp->jobctl = 1;
4215#endif
4216 jp->prev_job = curjob;
4217 curjob = jp;
4218 jp->used = 1;
4219 jp->ps = &jp->ps0;
4220 if (nprocs > 1) {
4221 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4222 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004223 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224 jobno(jp)));
4225 return jp;
4226}
4227
4228#if JOBS
4229/*
4230 * Return a string identifying a command (to be printed by the
4231 * jobs command).
4232 */
4233static char *cmdnextc;
4234
4235static void
4236cmdputs(const char *s)
4237{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004238 static const char vstype[VSTYPE + 1][3] = {
4239 "", "}", "-", "+", "?", "=",
4240 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004241 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004242 };
4243
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004244 const char *p, *str;
4245 char c, cc[2] = " ";
4246 char *nextc;
4247 int subtype = 0;
4248 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004249
4250 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4251 p = s;
4252 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004253 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004254 switch (c) {
4255 case CTLESC:
4256 c = *p++;
4257 break;
4258 case CTLVAR:
4259 subtype = *p++;
4260 if ((subtype & VSTYPE) == VSLENGTH)
4261 str = "${#";
4262 else
4263 str = "${";
4264 if (!(subtype & VSQUOTE) == !(quoted & 1))
4265 goto dostr;
4266 quoted ^= 1;
4267 c = '"';
4268 break;
4269 case CTLENDVAR:
4270 str = "\"}" + !(quoted & 1);
4271 quoted >>= 1;
4272 subtype = 0;
4273 goto dostr;
4274 case CTLBACKQ:
4275 str = "$(...)";
4276 goto dostr;
4277 case CTLBACKQ+CTLQUOTE:
4278 str = "\"$(...)\"";
4279 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004280#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004281 case CTLARI:
4282 str = "$((";
4283 goto dostr;
4284 case CTLENDARI:
4285 str = "))";
4286 goto dostr;
4287#endif
4288 case CTLQUOTEMARK:
4289 quoted ^= 1;
4290 c = '"';
4291 break;
4292 case '=':
4293 if (subtype == 0)
4294 break;
4295 if ((subtype & VSTYPE) != VSNORMAL)
4296 quoted <<= 1;
4297 str = vstype[subtype & VSTYPE];
4298 if (subtype & VSNUL)
4299 c = ':';
4300 else
4301 goto checkstr;
4302 break;
4303 case '\'':
4304 case '\\':
4305 case '"':
4306 case '$':
4307 /* These can only happen inside quotes */
4308 cc[0] = c;
4309 str = cc;
4310 c = '\\';
4311 break;
4312 default:
4313 break;
4314 }
4315 USTPUTC(c, nextc);
4316 checkstr:
4317 if (!str)
4318 continue;
4319 dostr:
4320 while ((c = *str++)) {
4321 USTPUTC(c, nextc);
4322 }
4323 }
4324 if (quoted & 1) {
4325 USTPUTC('"', nextc);
4326 }
4327 *nextc = 0;
4328 cmdnextc = nextc;
4329}
4330
4331/* cmdtxt() and cmdlist() call each other */
4332static void cmdtxt(union node *n);
4333
4334static void
4335cmdlist(union node *np, int sep)
4336{
4337 for (; np; np = np->narg.next) {
4338 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004339 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004340 cmdtxt(np);
4341 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004342 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004343 }
4344}
4345
4346static void
4347cmdtxt(union node *n)
4348{
4349 union node *np;
4350 struct nodelist *lp;
4351 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004352
4353 if (!n)
4354 return;
4355 switch (n->type) {
4356 default:
4357#if DEBUG
4358 abort();
4359#endif
4360 case NPIPE:
4361 lp = n->npipe.cmdlist;
4362 for (;;) {
4363 cmdtxt(lp->n);
4364 lp = lp->next;
4365 if (!lp)
4366 break;
4367 cmdputs(" | ");
4368 }
4369 break;
4370 case NSEMI:
4371 p = "; ";
4372 goto binop;
4373 case NAND:
4374 p = " && ";
4375 goto binop;
4376 case NOR:
4377 p = " || ";
4378 binop:
4379 cmdtxt(n->nbinary.ch1);
4380 cmdputs(p);
4381 n = n->nbinary.ch2;
4382 goto donode;
4383 case NREDIR:
4384 case NBACKGND:
4385 n = n->nredir.n;
4386 goto donode;
4387 case NNOT:
4388 cmdputs("!");
4389 n = n->nnot.com;
4390 donode:
4391 cmdtxt(n);
4392 break;
4393 case NIF:
4394 cmdputs("if ");
4395 cmdtxt(n->nif.test);
4396 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004397 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004398 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004399 cmdputs("; else ");
4400 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004401 } else {
4402 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004403 }
4404 p = "; fi";
4405 goto dotail;
4406 case NSUBSHELL:
4407 cmdputs("(");
4408 n = n->nredir.n;
4409 p = ")";
4410 goto dotail;
4411 case NWHILE:
4412 p = "while ";
4413 goto until;
4414 case NUNTIL:
4415 p = "until ";
4416 until:
4417 cmdputs(p);
4418 cmdtxt(n->nbinary.ch1);
4419 n = n->nbinary.ch2;
4420 p = "; done";
4421 dodo:
4422 cmdputs("; do ");
4423 dotail:
4424 cmdtxt(n);
4425 goto dotail2;
4426 case NFOR:
4427 cmdputs("for ");
4428 cmdputs(n->nfor.var);
4429 cmdputs(" in ");
4430 cmdlist(n->nfor.args, 1);
4431 n = n->nfor.body;
4432 p = "; done";
4433 goto dodo;
4434 case NDEFUN:
4435 cmdputs(n->narg.text);
4436 p = "() { ... }";
4437 goto dotail2;
4438 case NCMD:
4439 cmdlist(n->ncmd.args, 1);
4440 cmdlist(n->ncmd.redirect, 0);
4441 break;
4442 case NARG:
4443 p = n->narg.text;
4444 dotail2:
4445 cmdputs(p);
4446 break;
4447 case NHERE:
4448 case NXHERE:
4449 p = "<<...";
4450 goto dotail2;
4451 case NCASE:
4452 cmdputs("case ");
4453 cmdputs(n->ncase.expr->narg.text);
4454 cmdputs(" in ");
4455 for (np = n->ncase.cases; np; np = np->nclist.next) {
4456 cmdtxt(np->nclist.pattern);
4457 cmdputs(") ");
4458 cmdtxt(np->nclist.body);
4459 cmdputs(";; ");
4460 }
4461 p = "esac";
4462 goto dotail2;
4463 case NTO:
4464 p = ">";
4465 goto redir;
4466 case NCLOBBER:
4467 p = ">|";
4468 goto redir;
4469 case NAPPEND:
4470 p = ">>";
4471 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004472#if ENABLE_ASH_BASH_COMPAT
4473 case NTO2:
4474#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004475 case NTOFD:
4476 p = ">&";
4477 goto redir;
4478 case NFROM:
4479 p = "<";
4480 goto redir;
4481 case NFROMFD:
4482 p = "<&";
4483 goto redir;
4484 case NFROMTO:
4485 p = "<>";
4486 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004487 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004488 cmdputs(p);
4489 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004490 cmdputs(utoa(n->ndup.dupfd));
4491 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004492 }
4493 n = n->nfile.fname;
4494 goto donode;
4495 }
4496}
4497
4498static char *
4499commandtext(union node *n)
4500{
4501 char *name;
4502
4503 STARTSTACKSTR(cmdnextc);
4504 cmdtxt(n);
4505 name = stackblock();
4506 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4507 name, cmdnextc, cmdnextc));
4508 return ckstrdup(name);
4509}
4510#endif /* JOBS */
4511
4512/*
4513 * Fork off a subshell. If we are doing job control, give the subshell its
4514 * own process group. Jp is a job structure that the job is to be added to.
4515 * N is the command that will be evaluated by the child. Both jp and n may
4516 * be NULL. The mode parameter can be one of the following:
4517 * FORK_FG - Fork off a foreground process.
4518 * FORK_BG - Fork off a background process.
4519 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4520 * process group even if job control is on.
4521 *
4522 * When job control is turned off, background processes have their standard
4523 * input redirected to /dev/null (except for the second and later processes
4524 * in a pipeline).
4525 *
4526 * Called with interrupts off.
4527 */
4528/*
4529 * Clear traps on a fork.
4530 */
4531static void
4532clear_traps(void)
4533{
4534 char **tp;
4535
4536 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004537 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004538 INT_OFF;
4539 free(*tp);
4540 *tp = NULL;
4541 if (tp != &trap[0])
4542 setsignal(tp - trap);
4543 INT_ON;
4544 }
4545 }
4546}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004547
4548/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004549static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004550
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004551/* Called after fork(), in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004552#if !JOBS
4553# define forkchild(jp, n, mode) forkchild(jp, mode)
4554#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004555static void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004556forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004557{
4558 int oldlvl;
4559
4560 TRACE(("Child shell %d\n", getpid()));
4561 oldlvl = shlvl;
4562 shlvl++;
4563
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004564 /* man bash: "Non-builtin commands run by bash have signal handlers
4565 * set to the values inherited by the shell from its parent".
4566 * Do we do it correctly? */
4567
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004568 closescript();
4569 clear_traps();
4570#if JOBS
4571 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004572 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004573 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4574 pid_t pgrp;
4575
4576 if (jp->nprocs == 0)
4577 pgrp = getpid();
4578 else
4579 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004580 /* this can fail because we are doing it in the parent also */
4581 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004582 if (mode == FORK_FG)
4583 xtcsetpgrp(ttyfd, pgrp);
4584 setsignal(SIGTSTP);
4585 setsignal(SIGTTOU);
4586 } else
4587#endif
4588 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004589 /* man bash: "When job control is not in effect,
4590 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004591 ignoresig(SIGINT);
4592 ignoresig(SIGQUIT);
4593 if (jp->nprocs == 0) {
4594 close(0);
4595 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004596 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004597 }
4598 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004599 if (!oldlvl) {
4600 if (iflag) { /* why if iflag only? */
4601 setsignal(SIGINT);
4602 setsignal(SIGTERM);
4603 }
4604 /* man bash:
4605 * "In all cases, bash ignores SIGQUIT. Non-builtin
4606 * commands run by bash have signal handlers
4607 * set to the values inherited by the shell
4608 * from its parent".
4609 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004610 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004612#if JOBS
4613 if (n && n->type == NCMD && strcmp(n->ncmd.args->narg.text, "jobs") == 0) {
4614 TRACE(("Job hack\n"));
4615 freejob(curjob);
4616 return;
4617 }
4618#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004619 for (jp = curjob; jp; jp = jp->prev_job)
4620 freejob(jp);
4621 jobless = 0;
4622}
4623
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004624/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004625#if !JOBS
4626#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4627#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004628static void
4629forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4630{
4631 TRACE(("In parent shell: child = %d\n", pid));
4632 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004633 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4634 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004635 jobless++;
4636 return;
4637 }
4638#if JOBS
4639 if (mode != FORK_NOJOB && jp->jobctl) {
4640 int pgrp;
4641
4642 if (jp->nprocs == 0)
4643 pgrp = pid;
4644 else
4645 pgrp = jp->ps[0].pid;
4646 /* This can fail because we are doing it in the child also */
4647 setpgid(pid, pgrp);
4648 }
4649#endif
4650 if (mode == FORK_BG) {
4651 backgndpid = pid; /* set $! */
4652 set_curjob(jp, CUR_RUNNING);
4653 }
4654 if (jp) {
4655 struct procstat *ps = &jp->ps[jp->nprocs++];
4656 ps->pid = pid;
4657 ps->status = -1;
4658 ps->cmd = nullstr;
4659#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004660 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004661 ps->cmd = commandtext(n);
4662#endif
4663 }
4664}
4665
4666static int
4667forkshell(struct job *jp, union node *n, int mode)
4668{
4669 int pid;
4670
4671 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4672 pid = fork();
4673 if (pid < 0) {
4674 TRACE(("Fork failed, errno=%d", errno));
4675 if (jp)
4676 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004677 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004678 }
4679 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004680 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004681 else
4682 forkparent(jp, n, mode, pid);
4683 return pid;
4684}
4685
4686/*
4687 * Wait for job to finish.
4688 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004689 * Under job control we have the problem that while a child process
4690 * is running interrupts generated by the user are sent to the child
4691 * but not to the shell. This means that an infinite loop started by
4692 * an interactive user may be hard to kill. With job control turned off,
4693 * an interactive user may place an interactive program inside a loop.
4694 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004695 * these interrupts to also abort the loop. The approach we take here
4696 * is to have the shell ignore interrupt signals while waiting for a
4697 * foreground process to terminate, and then send itself an interrupt
4698 * signal if the child process was terminated by an interrupt signal.
4699 * Unfortunately, some programs want to do a bit of cleanup and then
4700 * exit on interrupt; unless these processes terminate themselves by
4701 * sending a signal to themselves (instead of calling exit) they will
4702 * confuse this approach.
4703 *
4704 * Called with interrupts off.
4705 */
4706static int
4707waitforjob(struct job *jp)
4708{
4709 int st;
4710
4711 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004712
4713 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004714 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004715 /* In non-interactive shells, we _can_ get
4716 * a keyboard signal here and be EINTRed,
4717 * but we just loop back, waiting for command to complete.
4718 *
4719 * man bash:
4720 * "If bash is waiting for a command to complete and receives
4721 * a signal for which a trap has been set, the trap
4722 * will not be executed until the command completes."
4723 *
4724 * Reality is that even if trap is not set, bash
4725 * will not act on the signal until command completes.
4726 * Try this. sleep5intoff.c:
4727 * #include <signal.h>
4728 * #include <unistd.h>
4729 * int main() {
4730 * sigset_t set;
4731 * sigemptyset(&set);
4732 * sigaddset(&set, SIGINT);
4733 * sigaddset(&set, SIGQUIT);
4734 * sigprocmask(SIG_BLOCK, &set, NULL);
4735 * sleep(5);
4736 * return 0;
4737 * }
4738 * $ bash -c './sleep5intoff; echo hi'
4739 * ^C^C^C^C <--- pressing ^C once a second
4740 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004741 * $ bash -c './sleep5intoff; echo hi'
4742 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4743 * $ _
4744 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004745 dowait(DOWAIT_BLOCK, jp);
4746 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004747 INT_ON;
4748
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004749 st = getstatus(jp);
4750#if JOBS
4751 if (jp->jobctl) {
4752 xtcsetpgrp(ttyfd, rootpid);
4753 /*
4754 * This is truly gross.
4755 * If we're doing job control, then we did a TIOCSPGRP which
4756 * caused us (the shell) to no longer be in the controlling
4757 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4758 * intuit from the subprocess exit status whether a SIGINT
4759 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4760 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004761 if (jp->sigint) /* TODO: do the same with all signals */
4762 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004763 }
4764 if (jp->state == JOBDONE)
4765#endif
4766 freejob(jp);
4767 return st;
4768}
4769
4770/*
4771 * return 1 if there are stopped jobs, otherwise 0
4772 */
4773static int
4774stoppedjobs(void)
4775{
4776 struct job *jp;
4777 int retval;
4778
4779 retval = 0;
4780 if (job_warning)
4781 goto out;
4782 jp = curjob;
4783 if (jp && jp->state == JOBSTOPPED) {
4784 out2str("You have stopped jobs.\n");
4785 job_warning = 2;
4786 retval++;
4787 }
4788 out:
4789 return retval;
4790}
4791
4792
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004793/* ============ redir.c
4794 *
4795 * Code for dealing with input/output redirection.
4796 */
4797
4798#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004799#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004800
4801/*
4802 * Open a file in noclobber mode.
4803 * The code was copied from bash.
4804 */
4805static int
4806noclobberopen(const char *fname)
4807{
4808 int r, fd;
4809 struct stat finfo, finfo2;
4810
4811 /*
4812 * If the file exists and is a regular file, return an error
4813 * immediately.
4814 */
4815 r = stat(fname, &finfo);
4816 if (r == 0 && S_ISREG(finfo.st_mode)) {
4817 errno = EEXIST;
4818 return -1;
4819 }
4820
4821 /*
4822 * If the file was not present (r != 0), make sure we open it
4823 * exclusively so that if it is created before we open it, our open
4824 * will fail. Make sure that we do not truncate an existing file.
4825 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4826 * file was not a regular file, we leave O_EXCL off.
4827 */
4828 if (r != 0)
4829 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4830 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4831
4832 /* If the open failed, return the file descriptor right away. */
4833 if (fd < 0)
4834 return fd;
4835
4836 /*
4837 * OK, the open succeeded, but the file may have been changed from a
4838 * non-regular file to a regular file between the stat and the open.
4839 * We are assuming that the O_EXCL open handles the case where FILENAME
4840 * did not exist and is symlinked to an existing file between the stat
4841 * and open.
4842 */
4843
4844 /*
4845 * If we can open it and fstat the file descriptor, and neither check
4846 * revealed that it was a regular file, and the file has not been
4847 * replaced, return the file descriptor.
4848 */
4849 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4850 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4851 return fd;
4852
4853 /* The file has been replaced. badness. */
4854 close(fd);
4855 errno = EEXIST;
4856 return -1;
4857}
4858
4859/*
4860 * Handle here documents. Normally we fork off a process to write the
4861 * data to a pipe. If the document is short, we can stuff the data in
4862 * the pipe without forking.
4863 */
4864/* openhere needs this forward reference */
4865static void expandhere(union node *arg, int fd);
4866static int
4867openhere(union node *redir)
4868{
4869 int pip[2];
4870 size_t len = 0;
4871
4872 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004873 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004874 if (redir->type == NHERE) {
4875 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004876 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004877 full_write(pip[1], redir->nhere.doc->narg.text, len);
4878 goto out;
4879 }
4880 }
4881 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004882 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004883 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004884 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4885 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4886 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4887 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004888 signal(SIGPIPE, SIG_DFL);
4889 if (redir->type == NHERE)
4890 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004891 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004892 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004893 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004894 }
4895 out:
4896 close(pip[1]);
4897 return pip[0];
4898}
4899
4900static int
4901openredirect(union node *redir)
4902{
4903 char *fname;
4904 int f;
4905
4906 switch (redir->nfile.type) {
4907 case NFROM:
4908 fname = redir->nfile.expfname;
4909 f = open(fname, O_RDONLY);
4910 if (f < 0)
4911 goto eopen;
4912 break;
4913 case NFROMTO:
4914 fname = redir->nfile.expfname;
4915 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4916 if (f < 0)
4917 goto ecreate;
4918 break;
4919 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004920#if ENABLE_ASH_BASH_COMPAT
4921 case NTO2:
4922#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004923 /* Take care of noclobber mode. */
4924 if (Cflag) {
4925 fname = redir->nfile.expfname;
4926 f = noclobberopen(fname);
4927 if (f < 0)
4928 goto ecreate;
4929 break;
4930 }
4931 /* FALLTHROUGH */
4932 case NCLOBBER:
4933 fname = redir->nfile.expfname;
4934 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4935 if (f < 0)
4936 goto ecreate;
4937 break;
4938 case NAPPEND:
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4941 if (f < 0)
4942 goto ecreate;
4943 break;
4944 default:
4945#if DEBUG
4946 abort();
4947#endif
4948 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004949/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004950// case NTOFD:
4951// case NFROMFD:
4952// f = -1;
4953// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004954 case NHERE:
4955 case NXHERE:
4956 f = openhere(redir);
4957 break;
4958 }
4959
4960 return f;
4961 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004962 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004963 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004964 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004965}
4966
4967/*
4968 * Copy a file descriptor to be >= to. Returns -1
4969 * if the source file descriptor is closed, EMPTY if there are no unused
4970 * file descriptors left.
4971 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004972/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4973 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004974enum {
4975 COPYFD_EXACT = (int)~(INT_MAX),
4976 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4977};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004978static int
4979copyfd(int from, int to)
4980{
4981 int newfd;
4982
Denis Vlasenko5a867312008-07-24 19:46:38 +00004983 if (to & COPYFD_EXACT) {
4984 to &= ~COPYFD_EXACT;
4985 /*if (from != to)*/
4986 newfd = dup2(from, to);
4987 } else {
4988 newfd = fcntl(from, F_DUPFD, to);
4989 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004990 if (newfd < 0) {
4991 if (errno == EMFILE)
4992 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004993 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004994 ash_msg_and_raise_error("%d: %m", from);
4995 }
4996 return newfd;
4997}
4998
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004999/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005000struct two_fd_t {
5001 int orig, copy;
5002};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005003struct redirtab {
5004 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005005 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005006 int pair_count;
5007 struct two_fd_t two_fd[0];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005008};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005009#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005010
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005011static int need_to_remember(struct redirtab *rp, int fd)
5012{
5013 int i;
5014
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005015 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005016 return 0;
5017
5018 for (i = 0; i < rp->pair_count; i++) {
5019 if (rp->two_fd[i].orig == fd) {
5020 /* already remembered */
5021 return 0;
5022 }
5023 }
5024 return 1;
5025}
5026
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005027/* "hidden" fd is a fd used to read scripts, or a copy of such */
5028static int is_hidden_fd(struct redirtab *rp, int fd)
5029{
5030 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005031 struct parsefile *pf;
5032
5033 if (fd == -1)
5034 return 0;
5035 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005036 while (pf) {
5037 if (fd == pf->fd) {
5038 return 1;
5039 }
5040 pf = pf->prev;
5041 }
5042 if (!rp)
5043 return 0;
5044 fd |= COPYFD_RESTORE;
5045 for (i = 0; i < rp->pair_count; i++) {
5046 if (rp->two_fd[i].copy == fd) {
5047 return 1;
5048 }
5049 }
5050 return 0;
5051}
5052
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005053/*
5054 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5055 * old file descriptors are stashed away so that the redirection can be
5056 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5057 * standard output, and the standard error if it becomes a duplicate of
5058 * stdout, is saved in memory.
5059 */
5060/* flags passed to redirect */
5061#define REDIR_PUSH 01 /* save previous values of file descriptors */
5062#define REDIR_SAVEFD2 03 /* set preverrout */
5063static void
5064redirect(union node *redir, int flags)
5065{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005066 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005067 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005068 int i;
5069 int fd;
5070 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005071 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005072
Denis Vlasenko01631112007-12-16 17:20:38 +00005073 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005074 if (!redir) {
5075 return;
5076 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005077
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005078 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005079 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005080 INT_OFF;
5081 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005082 union node *tmp = redir;
5083 do {
5084 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005085#if ENABLE_ASH_BASH_COMPAT
5086 if (redir->nfile.type == NTO2)
5087 sv_pos++;
5088#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005089 tmp = tmp->nfile.next;
5090 } while (tmp);
5091 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005092 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005093 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005094 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005095 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005096 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005097 while (sv_pos > 0) {
5098 sv_pos--;
5099 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5100 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005101 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005102
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005103 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005104 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005105 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005106 int right_fd = redir->ndup.dupfd;
5107 /* redirect from/to same file descriptor? */
5108 if (right_fd == fd)
5109 continue;
5110 /* echo >&10 and 10 is a fd opened to the sh script? */
5111 if (is_hidden_fd(sv, right_fd)) {
5112 errno = EBADF; /* as if it is closed */
5113 ash_msg_and_raise_error("%d: %m", right_fd);
5114 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005115 newfd = -1;
5116 } else {
5117 newfd = openredirect(redir); /* always >= 0 */
5118 if (fd == newfd) {
5119 /* Descriptor wasn't open before redirect.
5120 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005121 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005122 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005123 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005124 continue;
5125 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005126 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005127#if ENABLE_ASH_BASH_COMPAT
5128 redirect_more:
5129#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005131 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005132 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005133/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5134 * are closed in popredir() in the child, preventing them from leaking
5135 * into child. (popredir() also cleans up the mess in case of failures)
5136 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005137 if (i == -1) {
5138 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005139 if (i != EBADF) {
5140 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005141 if (newfd >= 0)
5142 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005143 errno = i;
5144 ash_msg_and_raise_error("%d: %m", fd);
5145 /* NOTREACHED */
5146 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005147 /* EBADF: it is not open - good, remember to close it */
5148 remember_to_close:
5149 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005150 } else { /* fd is open, save its copy */
5151 /* "exec fd>&-" should not close fds
5152 * which point to script file(s).
5153 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005154 if (is_hidden_fd(sv, fd))
5155 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005156 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005157 if (fd == 2)
5158 copied_fd2 = i;
5159 sv->two_fd[sv_pos].orig = fd;
5160 sv->two_fd[sv_pos].copy = i;
5161 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005162 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005163 if (newfd < 0) {
5164 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005165 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005166 /* Don't want to trigger debugging */
5167 if (fd != -1)
5168 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005169 } else {
5170 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005171 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005172 } else if (fd != newfd) { /* move newfd to fd */
5173 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005174#if ENABLE_ASH_BASH_COMPAT
5175 if (!(redir->nfile.type == NTO2 && fd == 2))
5176#endif
5177 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005178 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005179#if ENABLE_ASH_BASH_COMPAT
5180 if (redir->nfile.type == NTO2 && fd == 1) {
5181 /* We already redirected it to fd 1, now copy it to 2 */
5182 newfd = 1;
5183 fd = 2;
5184 goto redirect_more;
5185 }
5186#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005187 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005188
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005189 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005190 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5191 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005192}
5193
5194/*
5195 * Undo the effects of the last redirection.
5196 */
5197static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005198popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005199{
5200 struct redirtab *rp;
5201 int i;
5202
Denis Vlasenko01631112007-12-16 17:20:38 +00005203 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005204 return;
5205 INT_OFF;
5206 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005207 for (i = 0; i < rp->pair_count; i++) {
5208 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005209 int copy = rp->two_fd[i].copy;
5210 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005211 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005212 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005213 continue;
5214 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005215 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005216 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005217 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005218 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005219 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005220 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005221 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005222 }
5223 }
5224 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005225 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005226 free(rp);
5227 INT_ON;
5228}
5229
5230/*
5231 * Undo all redirections. Called on error or interrupt.
5232 */
5233
5234/*
5235 * Discard all saved file descriptors.
5236 */
5237static void
5238clearredir(int drop)
5239{
5240 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005241 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 if (!redirlist)
5243 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005244 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245 }
5246}
5247
5248static int
5249redirectsafe(union node *redir, int flags)
5250{
5251 int err;
5252 volatile int saveint;
5253 struct jmploc *volatile savehandler = exception_handler;
5254 struct jmploc jmploc;
5255
5256 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005257 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5258 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005259 if (!err) {
5260 exception_handler = &jmploc;
5261 redirect(redir, flags);
5262 }
5263 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005264 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005265 longjmp(exception_handler->loc, 1);
5266 RESTORE_INT(saveint);
5267 return err;
5268}
5269
5270
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005271/* ============ Routines to expand arguments to commands
5272 *
5273 * We have to deal with backquotes, shell variables, and file metacharacters.
5274 */
5275
Mike Frysinger98c52642009-04-02 10:02:37 +00005276#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005277static arith_t
5278ash_arith(const char *s)
5279{
5280 arith_eval_hooks_t math_hooks;
5281 arith_t result;
5282 int errcode = 0;
5283
5284 math_hooks.lookupvar = lookupvar;
5285 math_hooks.setvar = setvar;
5286 math_hooks.endofname = endofname;
5287
5288 INT_OFF;
5289 result = arith(s, &errcode, &math_hooks);
5290 if (errcode < 0) {
5291 if (errcode == -3)
5292 ash_msg_and_raise_error("exponent less than 0");
5293 if (errcode == -2)
5294 ash_msg_and_raise_error("divide by zero");
5295 if (errcode == -5)
5296 ash_msg_and_raise_error("expression recursion loop detected");
5297 raise_error_syntax(s);
5298 }
5299 INT_ON;
5300
5301 return result;
5302}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005303#endif
5304
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005305/*
5306 * expandarg flags
5307 */
5308#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5309#define EXP_TILDE 0x2 /* do normal tilde expansion */
5310#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5311#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5312#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5313#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5314#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5315#define EXP_WORD 0x80 /* expand word in parameter expansion */
5316#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5317/*
5318 * _rmescape() flags
5319 */
5320#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5321#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5322#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5323#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5324#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5325
5326/*
5327 * Structure specifying which parts of the string should be searched
5328 * for IFS characters.
5329 */
5330struct ifsregion {
5331 struct ifsregion *next; /* next region in list */
5332 int begoff; /* offset of start of region */
5333 int endoff; /* offset of end of region */
5334 int nulonly; /* search for nul bytes only */
5335};
5336
5337struct arglist {
5338 struct strlist *list;
5339 struct strlist **lastp;
5340};
5341
5342/* output of current string */
5343static char *expdest;
5344/* list of back quote expressions */
5345static struct nodelist *argbackq;
5346/* first struct in list of ifs regions */
5347static struct ifsregion ifsfirst;
5348/* last struct in list */
5349static struct ifsregion *ifslastp;
5350/* holds expanded arg list */
5351static struct arglist exparg;
5352
5353/*
5354 * Our own itoa().
5355 */
5356static int
5357cvtnum(arith_t num)
5358{
5359 int len;
5360
5361 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005362 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005363 STADJUST(len, expdest);
5364 return len;
5365}
5366
5367static size_t
5368esclen(const char *start, const char *p)
5369{
5370 size_t esc = 0;
5371
5372 while (p > start && *--p == CTLESC) {
5373 esc++;
5374 }
5375 return esc;
5376}
5377
5378/*
5379 * Remove any CTLESC characters from a string.
5380 */
5381static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005382rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005383{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005384 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005385
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005386 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005387 unsigned inquotes;
5388 int notescaped;
5389 int globbing;
5390
5391 p = strpbrk(str, qchars);
5392 if (!p) {
5393 return str;
5394 }
5395 q = p;
5396 r = str;
5397 if (flag & RMESCAPE_ALLOC) {
5398 size_t len = p - str;
5399 size_t fulllen = len + strlen(p) + 1;
5400
5401 if (flag & RMESCAPE_GROW) {
5402 r = makestrspace(fulllen, expdest);
5403 } else if (flag & RMESCAPE_HEAP) {
5404 r = ckmalloc(fulllen);
5405 } else {
5406 r = stalloc(fulllen);
5407 }
5408 q = r;
5409 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005410 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411 }
5412 }
5413 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5414 globbing = flag & RMESCAPE_GLOB;
5415 notescaped = globbing;
5416 while (*p) {
5417 if (*p == CTLQUOTEMARK) {
5418 inquotes = ~inquotes;
5419 p++;
5420 notescaped = globbing;
5421 continue;
5422 }
5423 if (*p == '\\') {
5424 /* naked back slash */
5425 notescaped = 0;
5426 goto copy;
5427 }
5428 if (*p == CTLESC) {
5429 p++;
5430 if (notescaped && inquotes && *p != '/') {
5431 *q++ = '\\';
5432 }
5433 }
5434 notescaped = globbing;
5435 copy:
5436 *q++ = *p++;
5437 }
5438 *q = '\0';
5439 if (flag & RMESCAPE_GROW) {
5440 expdest = r;
5441 STADJUST(q - r + 1, expdest);
5442 }
5443 return r;
5444}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005445#define pmatch(a, b) !fnmatch((a), (b), 0)
5446
5447/*
5448 * Prepare a pattern for a expmeta (internal glob(3)) call.
5449 *
5450 * Returns an stalloced string.
5451 */
5452static char *
5453preglob(const char *pattern, int quoted, int flag)
5454{
5455 flag |= RMESCAPE_GLOB;
5456 if (quoted) {
5457 flag |= RMESCAPE_QUOTED;
5458 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005459 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005460}
5461
5462/*
5463 * Put a string on the stack.
5464 */
5465static void
5466memtodest(const char *p, size_t len, int syntax, int quotes)
5467{
5468 char *q = expdest;
5469
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005470 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005471
5472 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005473 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005474 if (!c)
5475 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005476 if (quotes) {
5477 int n = SIT(c, syntax);
5478 if (n == CCTL || n == CBACK)
5479 USTPUTC(CTLESC, q);
5480 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005481 USTPUTC(c, q);
5482 }
5483
5484 expdest = q;
5485}
5486
5487static void
5488strtodest(const char *p, int syntax, int quotes)
5489{
5490 memtodest(p, strlen(p), syntax, quotes);
5491}
5492
5493/*
5494 * Record the fact that we have to scan this region of the
5495 * string for IFS characters.
5496 */
5497static void
5498recordregion(int start, int end, int nulonly)
5499{
5500 struct ifsregion *ifsp;
5501
5502 if (ifslastp == NULL) {
5503 ifsp = &ifsfirst;
5504 } else {
5505 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005506 ifsp = ckzalloc(sizeof(*ifsp));
5507 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005508 ifslastp->next = ifsp;
5509 INT_ON;
5510 }
5511 ifslastp = ifsp;
5512 ifslastp->begoff = start;
5513 ifslastp->endoff = end;
5514 ifslastp->nulonly = nulonly;
5515}
5516
5517static void
5518removerecordregions(int endoff)
5519{
5520 if (ifslastp == NULL)
5521 return;
5522
5523 if (ifsfirst.endoff > endoff) {
5524 while (ifsfirst.next != NULL) {
5525 struct ifsregion *ifsp;
5526 INT_OFF;
5527 ifsp = ifsfirst.next->next;
5528 free(ifsfirst.next);
5529 ifsfirst.next = ifsp;
5530 INT_ON;
5531 }
5532 if (ifsfirst.begoff > endoff)
5533 ifslastp = NULL;
5534 else {
5535 ifslastp = &ifsfirst;
5536 ifsfirst.endoff = endoff;
5537 }
5538 return;
5539 }
5540
5541 ifslastp = &ifsfirst;
5542 while (ifslastp->next && ifslastp->next->begoff < endoff)
5543 ifslastp=ifslastp->next;
5544 while (ifslastp->next != NULL) {
5545 struct ifsregion *ifsp;
5546 INT_OFF;
5547 ifsp = ifslastp->next->next;
5548 free(ifslastp->next);
5549 ifslastp->next = ifsp;
5550 INT_ON;
5551 }
5552 if (ifslastp->endoff > endoff)
5553 ifslastp->endoff = endoff;
5554}
5555
5556static char *
5557exptilde(char *startp, char *p, int flag)
5558{
5559 char c;
5560 char *name;
5561 struct passwd *pw;
5562 const char *home;
5563 int quotes = flag & (EXP_FULL | EXP_CASE);
5564 int startloc;
5565
5566 name = p + 1;
5567
5568 while ((c = *++p) != '\0') {
5569 switch (c) {
5570 case CTLESC:
5571 return startp;
5572 case CTLQUOTEMARK:
5573 return startp;
5574 case ':':
5575 if (flag & EXP_VARTILDE)
5576 goto done;
5577 break;
5578 case '/':
5579 case CTLENDVAR:
5580 goto done;
5581 }
5582 }
5583 done:
5584 *p = '\0';
5585 if (*name == '\0') {
5586 home = lookupvar(homestr);
5587 } else {
5588 pw = getpwnam(name);
5589 if (pw == NULL)
5590 goto lose;
5591 home = pw->pw_dir;
5592 }
5593 if (!home || !*home)
5594 goto lose;
5595 *p = c;
5596 startloc = expdest - (char *)stackblock();
5597 strtodest(home, SQSYNTAX, quotes);
5598 recordregion(startloc, expdest - (char *)stackblock(), 0);
5599 return p;
5600 lose:
5601 *p = c;
5602 return startp;
5603}
5604
5605/*
5606 * Execute a command inside back quotes. If it's a builtin command, we
5607 * want to save its output in a block obtained from malloc. Otherwise
5608 * we fork off a subprocess and get the output of the command via a pipe.
5609 * Should be called with interrupts off.
5610 */
5611struct backcmd { /* result of evalbackcmd */
5612 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005614 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005615 struct job *jp; /* job structure for command */
5616};
5617
5618/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005619static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005620#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005621static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005622
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005623static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005624evalbackcmd(union node *n, struct backcmd *result)
5625{
5626 int saveherefd;
5627
5628 result->fd = -1;
5629 result->buf = NULL;
5630 result->nleft = 0;
5631 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005632 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005633 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005634
5635 saveherefd = herefd;
5636 herefd = -1;
5637
5638 {
5639 int pip[2];
5640 struct job *jp;
5641
5642 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005643 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005644 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005645 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5646 FORCE_INT_ON;
5647 close(pip[0]);
5648 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005649 /*close(1);*/
5650 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005651 close(pip[1]);
5652 }
5653 eflag = 0;
5654 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5655 /* NOTREACHED */
5656 }
5657 close(pip[1]);
5658 result->fd = pip[0];
5659 result->jp = jp;
5660 }
5661 herefd = saveherefd;
5662 out:
5663 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5664 result->fd, result->buf, result->nleft, result->jp));
5665}
5666
5667/*
5668 * Expand stuff in backwards quotes.
5669 */
5670static void
5671expbackq(union node *cmd, int quoted, int quotes)
5672{
5673 struct backcmd in;
5674 int i;
5675 char buf[128];
5676 char *p;
5677 char *dest;
5678 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005679 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005680 struct stackmark smark;
5681
5682 INT_OFF;
5683 setstackmark(&smark);
5684 dest = expdest;
5685 startloc = dest - (char *)stackblock();
5686 grabstackstr(dest);
5687 evalbackcmd(cmd, &in);
5688 popstackmark(&smark);
5689
5690 p = in.buf;
5691 i = in.nleft;
5692 if (i == 0)
5693 goto read;
5694 for (;;) {
5695 memtodest(p, i, syntax, quotes);
5696 read:
5697 if (in.fd < 0)
5698 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005699 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 TRACE(("expbackq: read returns %d\n", i));
5701 if (i <= 0)
5702 break;
5703 p = buf;
5704 }
5705
Denis Vlasenko60818682007-09-28 22:07:23 +00005706 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005707 if (in.fd >= 0) {
5708 close(in.fd);
5709 back_exitstatus = waitforjob(in.jp);
5710 }
5711 INT_ON;
5712
5713 /* Eat all trailing newlines */
5714 dest = expdest;
5715 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5716 STUNPUTC(dest);
5717 expdest = dest;
5718
5719 if (quoted == 0)
5720 recordregion(startloc, dest - (char *)stackblock(), 0);
5721 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5722 (dest - (char *)stackblock()) - startloc,
5723 (dest - (char *)stackblock()) - startloc,
5724 stackblock() + startloc));
5725}
5726
Mike Frysinger98c52642009-04-02 10:02:37 +00005727#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005728/*
5729 * Expand arithmetic expression. Backup to start of expression,
5730 * evaluate, place result in (backed up) result, adjust string position.
5731 */
5732static void
5733expari(int quotes)
5734{
5735 char *p, *start;
5736 int begoff;
5737 int flag;
5738 int len;
5739
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005740 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005741
5742 /*
5743 * This routine is slightly over-complicated for
5744 * efficiency. Next we scan backwards looking for the
5745 * start of arithmetic.
5746 */
5747 start = stackblock();
5748 p = expdest - 1;
5749 *p = '\0';
5750 p--;
5751 do {
5752 int esc;
5753
5754 while (*p != CTLARI) {
5755 p--;
5756#if DEBUG
5757 if (p < start) {
5758 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5759 }
5760#endif
5761 }
5762
5763 esc = esclen(start, p);
5764 if (!(esc % 2)) {
5765 break;
5766 }
5767
5768 p -= esc + 1;
5769 } while (1);
5770
5771 begoff = p - start;
5772
5773 removerecordregions(begoff);
5774
5775 flag = p[1];
5776
5777 expdest = p;
5778
5779 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005780 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005781
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005782 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005783
5784 if (flag != '"')
5785 recordregion(begoff, begoff + len, 0);
5786}
5787#endif
5788
5789/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005790static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005791
5792/*
5793 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5794 * characters to allow for further processing. Otherwise treat
5795 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005796 *
5797 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5798 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5799 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005800 */
5801static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005802argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005803{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005804 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005805 '=',
5806 ':',
5807 CTLQUOTEMARK,
5808 CTLENDVAR,
5809 CTLESC,
5810 CTLVAR,
5811 CTLBACKQ,
5812 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005813#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005814 CTLENDARI,
5815#endif
5816 0
5817 };
5818 const char *reject = spclchars;
5819 int c;
5820 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5821 int breakall = flag & EXP_WORD;
5822 int inquotes;
5823 size_t length;
5824 int startloc;
5825
5826 if (!(flag & EXP_VARTILDE)) {
5827 reject += 2;
5828 } else if (flag & EXP_VARTILDE2) {
5829 reject++;
5830 }
5831 inquotes = 0;
5832 length = 0;
5833 if (flag & EXP_TILDE) {
5834 char *q;
5835
5836 flag &= ~EXP_TILDE;
5837 tilde:
5838 q = p;
5839 if (*q == CTLESC && (flag & EXP_QWORD))
5840 q++;
5841 if (*q == '~')
5842 p = exptilde(p, q, flag);
5843 }
5844 start:
5845 startloc = expdest - (char *)stackblock();
5846 for (;;) {
5847 length += strcspn(p + length, reject);
5848 c = p[length];
5849 if (c && (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005850#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005851 || c == CTLENDARI
5852#endif
5853 )) {
5854 /* c == '=' || c == ':' || c == CTLENDARI */
5855 length++;
5856 }
5857 if (length > 0) {
5858 int newloc;
5859 expdest = stack_nputstr(p, length, expdest);
5860 newloc = expdest - (char *)stackblock();
5861 if (breakall && !inquotes && newloc > startloc) {
5862 recordregion(startloc, newloc, 0);
5863 }
5864 startloc = newloc;
5865 }
5866 p += length + 1;
5867 length = 0;
5868
5869 switch (c) {
5870 case '\0':
5871 goto breakloop;
5872 case '=':
5873 if (flag & EXP_VARTILDE2) {
5874 p--;
5875 continue;
5876 }
5877 flag |= EXP_VARTILDE2;
5878 reject++;
5879 /* fall through */
5880 case ':':
5881 /*
5882 * sort of a hack - expand tildes in variable
5883 * assignments (after the first '=' and after ':'s).
5884 */
5885 if (*--p == '~') {
5886 goto tilde;
5887 }
5888 continue;
5889 }
5890
5891 switch (c) {
5892 case CTLENDVAR: /* ??? */
5893 goto breakloop;
5894 case CTLQUOTEMARK:
5895 /* "$@" syntax adherence hack */
5896 if (
5897 !inquotes &&
5898 !memcmp(p, dolatstr, 4) &&
5899 (p[4] == CTLQUOTEMARK || (
5900 p[4] == CTLENDVAR &&
5901 p[5] == CTLQUOTEMARK
5902 ))
5903 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005904 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005905 goto start;
5906 }
5907 inquotes = !inquotes;
5908 addquote:
5909 if (quotes) {
5910 p--;
5911 length++;
5912 startloc++;
5913 }
5914 break;
5915 case CTLESC:
5916 startloc++;
5917 length++;
5918 goto addquote;
5919 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005920 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005921 goto start;
5922 case CTLBACKQ:
5923 c = 0;
5924 case CTLBACKQ|CTLQUOTE:
5925 expbackq(argbackq->n, c, quotes);
5926 argbackq = argbackq->next;
5927 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005928#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 case CTLENDARI:
5930 p--;
5931 expari(quotes);
5932 goto start;
5933#endif
5934 }
5935 }
5936 breakloop:
5937 ;
5938}
5939
5940static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005941scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005942 int zero)
5943{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005944// This commented out code was added by James Simmons <jsimmons@infradead.org>
5945// as part of a larger change when he added support for ${var/a/b}.
5946// However, it broke # and % operators:
5947//
5948//var=ababcdcd
5949// ok bad
5950//echo ${var#ab} abcdcd abcdcd
5951//echo ${var##ab} abcdcd abcdcd
5952//echo ${var#a*b} abcdcd ababcdcd (!)
5953//echo ${var##a*b} cdcd cdcd
5954//echo ${var#?} babcdcd ababcdcd (!)
5955//echo ${var##?} babcdcd babcdcd
5956//echo ${var#*} ababcdcd babcdcd (!)
5957//echo ${var##*}
5958//echo ${var%cd} ababcd ababcd
5959//echo ${var%%cd} ababcd abab (!)
5960//echo ${var%c*d} ababcd ababcd
5961//echo ${var%%c*d} abab ababcdcd (!)
5962//echo ${var%?} ababcdc ababcdc
5963//echo ${var%%?} ababcdc ababcdcd (!)
5964//echo ${var%*} ababcdcd ababcdcd
5965//echo ${var%%*}
5966//
5967// Commenting it back out helped. Remove it completely if it really
5968// is not needed.
5969
5970 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005971 char c;
5972
5973 loc = startp;
5974 loc2 = rmesc;
5975 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005976 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005977 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005978
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005979 c = *loc2;
5980 if (zero) {
5981 *loc2 = '\0';
5982 s = rmesc;
5983 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005984 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005985
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005986// // chop off end if its '*'
5987// full = strrchr(str, '*');
5988// if (full && full != str)
5989// match--;
5990//
5991// // If str starts with '*' replace with s.
5992// if ((*str == '*') && strlen(s) >= match) {
5993// full = xstrdup(s);
5994// strncpy(full+strlen(s)-match+1, str+1, match-1);
5995// } else
5996// full = xstrndup(str, match);
5997// match = strncmp(s, full, strlen(full));
5998// free(full);
5999//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006000 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006001 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006002 return loc;
6003 if (quotes && *loc == CTLESC)
6004 loc++;
6005 loc++;
6006 loc2++;
6007 } while (c);
6008 return 0;
6009}
6010
6011static char *
6012scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6013 int zero)
6014{
6015 int esc = 0;
6016 char *loc;
6017 char *loc2;
6018
6019 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6020 int match;
6021 char c = *loc2;
6022 const char *s = loc2;
6023 if (zero) {
6024 *loc2 = '\0';
6025 s = rmesc;
6026 }
6027 match = pmatch(str, s);
6028 *loc2 = c;
6029 if (match)
6030 return loc;
6031 loc--;
6032 if (quotes) {
6033 if (--esc < 0) {
6034 esc = esclen(startp, loc);
6035 }
6036 if (esc % 2) {
6037 esc--;
6038 loc--;
6039 }
6040 }
6041 }
6042 return 0;
6043}
6044
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006045static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006046static void
6047varunset(const char *end, const char *var, const char *umsg, int varflags)
6048{
6049 const char *msg;
6050 const char *tail;
6051
6052 tail = nullstr;
6053 msg = "parameter not set";
6054 if (umsg) {
6055 if (*end == CTLENDVAR) {
6056 if (varflags & VSNUL)
6057 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006058 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006059 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006060 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006061 }
6062 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6063}
6064
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006065#if ENABLE_ASH_BASH_COMPAT
6066static char *
6067parse_sub_pattern(char *arg, int inquotes)
6068{
6069 char *idx, *repl = NULL;
6070 unsigned char c;
6071
Denis Vlasenko2659c632008-06-14 06:04:59 +00006072 idx = arg;
6073 while (1) {
6074 c = *arg;
6075 if (!c)
6076 break;
6077 if (c == '/') {
6078 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006079 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006080 repl = idx + 1;
6081 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006082 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006083 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006084 *idx++ = c;
6085 if (!inquotes && c == '\\' && arg[1] == '\\')
6086 arg++; /* skip both \\, not just first one */
6087 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006088 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006089 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006090
6091 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006092}
6093#endif /* ENABLE_ASH_BASH_COMPAT */
6094
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006095static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006096subevalvar(char *p, char *str, int strloc, int subtype,
6097 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006098{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006099 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006100 char *startp;
6101 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006102 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006103 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6104 IF_ASH_BASH_COMPAT(char null = '\0';)
6105 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006106 int saveherefd = herefd;
6107 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006108 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006109 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006110
6111 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006112 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6113 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006114 STPUTC('\0', expdest);
6115 herefd = saveherefd;
6116 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006117 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006118
6119 switch (subtype) {
6120 case VSASSIGN:
6121 setvar(str, startp, 0);
6122 amount = startp - expdest;
6123 STADJUST(amount, expdest);
6124 return startp;
6125
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006126#if ENABLE_ASH_BASH_COMPAT
6127 case VSSUBSTR:
6128 loc = str = stackblock() + strloc;
6129// TODO: number() instead? It does error checking...
6130 pos = atoi(loc);
6131 len = str - startp - 1;
6132
6133 /* *loc != '\0', guaranteed by parser */
6134 if (quotes) {
6135 char *ptr;
6136
6137 /* We must adjust the length by the number of escapes we find. */
6138 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006139 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006140 len--;
6141 ptr++;
6142 }
6143 }
6144 }
6145 orig_len = len;
6146
6147 if (*loc++ == ':') {
6148// TODO: number() instead? It does error checking...
6149 len = atoi(loc);
6150 } else {
6151 len = orig_len;
6152 while (*loc && *loc != ':')
6153 loc++;
6154 if (*loc++ == ':')
6155// TODO: number() instead? It does error checking...
6156 len = atoi(loc);
6157 }
6158 if (pos >= orig_len) {
6159 pos = 0;
6160 len = 0;
6161 }
6162 if (len > (orig_len - pos))
6163 len = orig_len - pos;
6164
6165 for (str = startp; pos; str++, pos--) {
6166 if (quotes && *str == CTLESC)
6167 str++;
6168 }
6169 for (loc = startp; len; len--) {
6170 if (quotes && *str == CTLESC)
6171 *loc++ = *str++;
6172 *loc++ = *str++;
6173 }
6174 *loc = '\0';
6175 amount = loc - expdest;
6176 STADJUST(amount, expdest);
6177 return loc;
6178#endif
6179
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006180 case VSQUESTION:
6181 varunset(p, str, startp, varflags);
6182 /* NOTREACHED */
6183 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006185
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006186 /* We'll comeback here if we grow the stack while handling
6187 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6188 * stack will need rebasing, and we'll need to remove our work
6189 * areas each time
6190 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006191 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006192
6193 amount = expdest - ((char *)stackblock() + resetloc);
6194 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006195 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006196
6197 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006198 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006199 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006200 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006201 if (rmesc != startp) {
6202 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006203 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006204 }
6205 }
6206 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006207 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006208 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006209 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006210
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006211#if ENABLE_ASH_BASH_COMPAT
6212 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6213 char *idx, *end, *restart_detect;
6214
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006215 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006216 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6217 if (!repl)
6218 repl = &null;
6219 }
6220
6221 /* If there's no pattern to match, return the expansion unmolested */
6222 if (*str == '\0')
6223 return 0;
6224
6225 len = 0;
6226 idx = startp;
6227 end = str - 1;
6228 while (idx < end) {
6229 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6230 if (!loc) {
6231 /* No match, advance */
6232 restart_detect = stackblock();
6233 STPUTC(*idx, expdest);
6234 if (quotes && *idx == CTLESC) {
6235 idx++;
6236 len++;
6237 STPUTC(*idx, expdest);
6238 }
6239 if (stackblock() != restart_detect)
6240 goto restart;
6241 idx++;
6242 len++;
6243 rmesc++;
6244 continue;
6245 }
6246
6247 if (subtype == VSREPLACEALL) {
6248 while (idx < loc) {
6249 if (quotes && *idx == CTLESC)
6250 idx++;
6251 idx++;
6252 rmesc++;
6253 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006254 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006255 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006256 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006257
6258 for (loc = repl; *loc; loc++) {
6259 restart_detect = stackblock();
6260 STPUTC(*loc, expdest);
6261 if (stackblock() != restart_detect)
6262 goto restart;
6263 len++;
6264 }
6265
6266 if (subtype == VSREPLACE) {
6267 while (*idx) {
6268 restart_detect = stackblock();
6269 STPUTC(*idx, expdest);
6270 if (stackblock() != restart_detect)
6271 goto restart;
6272 len++;
6273 idx++;
6274 }
6275 break;
6276 }
6277 }
6278
6279 /* We've put the replaced text into a buffer at workloc, now
6280 * move it to the right place and adjust the stack.
6281 */
6282 startp = stackblock() + startloc;
6283 STPUTC('\0', expdest);
6284 memmove(startp, stackblock() + workloc, len);
6285 startp[len++] = '\0';
6286 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6287 STADJUST(-amount, expdest);
6288 return startp;
6289 }
6290#endif /* ENABLE_ASH_BASH_COMPAT */
6291
6292 subtype -= VSTRIMRIGHT;
6293#if DEBUG
6294 if (subtype < 0 || subtype > 7)
6295 abort();
6296#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006297 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6298 zero = subtype >> 1;
6299 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6300 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6301
6302 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6303 if (loc) {
6304 if (zero) {
6305 memmove(startp, loc, str - loc);
6306 loc = startp + (str - loc) - 1;
6307 }
6308 *loc = '\0';
6309 amount = loc - expdest;
6310 STADJUST(amount, expdest);
6311 }
6312 return loc;
6313}
6314
6315/*
6316 * Add the value of a specialized variable to the stack string.
6317 */
6318static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006319varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006320{
6321 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006322 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006323 int i;
6324 int sep = 0;
6325 int sepq = 0;
6326 ssize_t len = 0;
6327 char **ap;
6328 int syntax;
6329 int quoted = varflags & VSQUOTE;
6330 int subtype = varflags & VSTYPE;
6331 int quotes = flags & (EXP_FULL | EXP_CASE);
6332
6333 if (quoted && (flags & EXP_FULL))
6334 sep = 1 << CHAR_BIT;
6335
6336 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6337 switch (*name) {
6338 case '$':
6339 num = rootpid;
6340 goto numvar;
6341 case '?':
6342 num = exitstatus;
6343 goto numvar;
6344 case '#':
6345 num = shellparam.nparam;
6346 goto numvar;
6347 case '!':
6348 num = backgndpid;
6349 if (num == 0)
6350 return -1;
6351 numvar:
6352 len = cvtnum(num);
6353 break;
6354 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006355 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006356 for (i = NOPTS - 1; i >= 0; i--) {
6357 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006358 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006359 len++;
6360 }
6361 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006362 break;
6363 case '@':
6364 if (sep)
6365 goto param;
6366 /* fall through */
6367 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006368 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006369 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6370 sepq = 1;
6371 param:
6372 ap = shellparam.p;
6373 if (!ap)
6374 return -1;
6375 while ((p = *ap++)) {
6376 size_t partlen;
6377
6378 partlen = strlen(p);
6379 len += partlen;
6380
6381 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6382 memtodest(p, partlen, syntax, quotes);
6383
6384 if (*ap && sep) {
6385 char *q;
6386
6387 len++;
6388 if (subtype == VSPLUS || subtype == VSLENGTH) {
6389 continue;
6390 }
6391 q = expdest;
6392 if (sepq)
6393 STPUTC(CTLESC, q);
6394 STPUTC(sep, q);
6395 expdest = q;
6396 }
6397 }
6398 return len;
6399 case '0':
6400 case '1':
6401 case '2':
6402 case '3':
6403 case '4':
6404 case '5':
6405 case '6':
6406 case '7':
6407 case '8':
6408 case '9':
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006409// TODO: number() instead? It does error checking...
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006410 num = atoi(name);
6411 if (num < 0 || num > shellparam.nparam)
6412 return -1;
6413 p = num ? shellparam.p[num - 1] : arg0;
6414 goto value;
6415 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006416 /* NB: name has form "VAR=..." */
6417
6418 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6419 * which should be considered before we check variables. */
6420 if (var_str_list) {
6421 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6422 p = NULL;
6423 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006424 char *str, *eq;
6425 str = var_str_list->text;
6426 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006427 if (!eq) /* stop at first non-assignment */
6428 break;
6429 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006430 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006431 && strncmp(str, name, name_len) == 0) {
6432 p = eq;
6433 /* goto value; - WRONG! */
6434 /* think "A=1 A=2 B=$A" */
6435 }
6436 var_str_list = var_str_list->next;
6437 } while (var_str_list);
6438 if (p)
6439 goto value;
6440 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006441 p = lookupvar(name);
6442 value:
6443 if (!p)
6444 return -1;
6445
6446 len = strlen(p);
6447 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6448 memtodest(p, len, syntax, quotes);
6449 return len;
6450 }
6451
6452 if (subtype == VSPLUS || subtype == VSLENGTH)
6453 STADJUST(-len, expdest);
6454 return len;
6455}
6456
6457/*
6458 * Expand a variable, and return a pointer to the next character in the
6459 * input string.
6460 */
6461static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006462evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006463{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006464 char varflags;
6465 char subtype;
6466 char quoted;
6467 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006468 char *var;
6469 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006470 int startloc;
6471 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006472
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006473 varflags = *p++;
6474 subtype = varflags & VSTYPE;
6475 quoted = varflags & VSQUOTE;
6476 var = p;
6477 easy = (!quoted || (*var == '@' && shellparam.nparam));
6478 startloc = expdest - (char *)stackblock();
6479 p = strchr(p, '=') + 1;
6480
6481 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006482 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006483 if (varflags & VSNUL)
6484 varlen--;
6485
6486 if (subtype == VSPLUS) {
6487 varlen = -1 - varlen;
6488 goto vsplus;
6489 }
6490
6491 if (subtype == VSMINUS) {
6492 vsplus:
6493 if (varlen < 0) {
6494 argstr(
6495 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006496 (quoted ? EXP_QWORD : EXP_WORD),
6497 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006498 );
6499 goto end;
6500 }
6501 if (easy)
6502 goto record;
6503 goto end;
6504 }
6505
6506 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6507 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006508 if (subevalvar(p, var, /* strloc: */ 0,
6509 subtype, startloc, varflags,
6510 /* quotes: */ 0,
6511 var_str_list)
6512 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006513 varflags &= ~VSNUL;
6514 /*
6515 * Remove any recorded regions beyond
6516 * start of variable
6517 */
6518 removerecordregions(startloc);
6519 goto again;
6520 }
6521 goto end;
6522 }
6523 if (easy)
6524 goto record;
6525 goto end;
6526 }
6527
6528 if (varlen < 0 && uflag)
6529 varunset(p, var, 0, 0);
6530
6531 if (subtype == VSLENGTH) {
6532 cvtnum(varlen > 0 ? varlen : 0);
6533 goto record;
6534 }
6535
6536 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006537 if (easy)
6538 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006539 goto end;
6540 }
6541
6542#if DEBUG
6543 switch (subtype) {
6544 case VSTRIMLEFT:
6545 case VSTRIMLEFTMAX:
6546 case VSTRIMRIGHT:
6547 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006548#if ENABLE_ASH_BASH_COMPAT
6549 case VSSUBSTR:
6550 case VSREPLACE:
6551 case VSREPLACEALL:
6552#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006553 break;
6554 default:
6555 abort();
6556 }
6557#endif
6558
6559 if (varlen >= 0) {
6560 /*
6561 * Terminate the string and start recording the pattern
6562 * right after it
6563 */
6564 STPUTC('\0', expdest);
6565 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006566 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6567 startloc, varflags,
6568 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6569 var_str_list)
6570 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 int amount = expdest - (
6572 (char *)stackblock() + patloc - 1
6573 );
6574 STADJUST(-amount, expdest);
6575 }
6576 /* Remove any recorded regions beyond start of variable */
6577 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006578 record:
6579 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006580 }
6581
6582 end:
6583 if (subtype != VSNORMAL) { /* skip to end of alternative */
6584 int nesting = 1;
6585 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006586 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006587 if (c == CTLESC)
6588 p++;
6589 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6590 if (varlen >= 0)
6591 argbackq = argbackq->next;
6592 } else if (c == CTLVAR) {
6593 if ((*p++ & VSTYPE) != VSNORMAL)
6594 nesting++;
6595 } else if (c == CTLENDVAR) {
6596 if (--nesting == 0)
6597 break;
6598 }
6599 }
6600 }
6601 return p;
6602}
6603
6604/*
6605 * Break the argument string into pieces based upon IFS and add the
6606 * strings to the argument list. The regions of the string to be
6607 * searched for IFS characters have been stored by recordregion.
6608 */
6609static void
6610ifsbreakup(char *string, struct arglist *arglist)
6611{
6612 struct ifsregion *ifsp;
6613 struct strlist *sp;
6614 char *start;
6615 char *p;
6616 char *q;
6617 const char *ifs, *realifs;
6618 int ifsspc;
6619 int nulonly;
6620
6621 start = string;
6622 if (ifslastp != NULL) {
6623 ifsspc = 0;
6624 nulonly = 0;
6625 realifs = ifsset() ? ifsval() : defifs;
6626 ifsp = &ifsfirst;
6627 do {
6628 p = string + ifsp->begoff;
6629 nulonly = ifsp->nulonly;
6630 ifs = nulonly ? nullstr : realifs;
6631 ifsspc = 0;
6632 while (p < string + ifsp->endoff) {
6633 q = p;
6634 if (*p == CTLESC)
6635 p++;
6636 if (!strchr(ifs, *p)) {
6637 p++;
6638 continue;
6639 }
6640 if (!nulonly)
6641 ifsspc = (strchr(defifs, *p) != NULL);
6642 /* Ignore IFS whitespace at start */
6643 if (q == start && ifsspc) {
6644 p++;
6645 start = p;
6646 continue;
6647 }
6648 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006649 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006650 sp->text = start;
6651 *arglist->lastp = sp;
6652 arglist->lastp = &sp->next;
6653 p++;
6654 if (!nulonly) {
6655 for (;;) {
6656 if (p >= string + ifsp->endoff) {
6657 break;
6658 }
6659 q = p;
6660 if (*p == CTLESC)
6661 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006662 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006663 p = q;
6664 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006665 }
6666 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006667 if (ifsspc) {
6668 p++;
6669 ifsspc = 0;
6670 } else {
6671 p = q;
6672 break;
6673 }
6674 } else
6675 p++;
6676 }
6677 }
6678 start = p;
6679 } /* while */
6680 ifsp = ifsp->next;
6681 } while (ifsp != NULL);
6682 if (nulonly)
6683 goto add;
6684 }
6685
6686 if (!*start)
6687 return;
6688
6689 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006690 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006691 sp->text = start;
6692 *arglist->lastp = sp;
6693 arglist->lastp = &sp->next;
6694}
6695
6696static void
6697ifsfree(void)
6698{
6699 struct ifsregion *p;
6700
6701 INT_OFF;
6702 p = ifsfirst.next;
6703 do {
6704 struct ifsregion *ifsp;
6705 ifsp = p->next;
6706 free(p);
6707 p = ifsp;
6708 } while (p);
6709 ifslastp = NULL;
6710 ifsfirst.next = NULL;
6711 INT_ON;
6712}
6713
6714/*
6715 * Add a file name to the list.
6716 */
6717static void
6718addfname(const char *name)
6719{
6720 struct strlist *sp;
6721
Denis Vlasenko597906c2008-02-20 16:38:54 +00006722 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006723 sp->text = ststrdup(name);
6724 *exparg.lastp = sp;
6725 exparg.lastp = &sp->next;
6726}
6727
6728static char *expdir;
6729
6730/*
6731 * Do metacharacter (i.e. *, ?, [...]) expansion.
6732 */
6733static void
6734expmeta(char *enddir, char *name)
6735{
6736 char *p;
6737 const char *cp;
6738 char *start;
6739 char *endname;
6740 int metaflag;
6741 struct stat statb;
6742 DIR *dirp;
6743 struct dirent *dp;
6744 int atend;
6745 int matchdot;
6746
6747 metaflag = 0;
6748 start = name;
6749 for (p = name; *p; p++) {
6750 if (*p == '*' || *p == '?')
6751 metaflag = 1;
6752 else if (*p == '[') {
6753 char *q = p + 1;
6754 if (*q == '!')
6755 q++;
6756 for (;;) {
6757 if (*q == '\\')
6758 q++;
6759 if (*q == '/' || *q == '\0')
6760 break;
6761 if (*++q == ']') {
6762 metaflag = 1;
6763 break;
6764 }
6765 }
6766 } else if (*p == '\\')
6767 p++;
6768 else if (*p == '/') {
6769 if (metaflag)
6770 goto out;
6771 start = p + 1;
6772 }
6773 }
6774 out:
6775 if (metaflag == 0) { /* we've reached the end of the file name */
6776 if (enddir != expdir)
6777 metaflag++;
6778 p = name;
6779 do {
6780 if (*p == '\\')
6781 p++;
6782 *enddir++ = *p;
6783 } while (*p++);
6784 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6785 addfname(expdir);
6786 return;
6787 }
6788 endname = p;
6789 if (name < start) {
6790 p = name;
6791 do {
6792 if (*p == '\\')
6793 p++;
6794 *enddir++ = *p++;
6795 } while (p < start);
6796 }
6797 if (enddir == expdir) {
6798 cp = ".";
6799 } else if (enddir == expdir + 1 && *expdir == '/') {
6800 cp = "/";
6801 } else {
6802 cp = expdir;
6803 enddir[-1] = '\0';
6804 }
6805 dirp = opendir(cp);
6806 if (dirp == NULL)
6807 return;
6808 if (enddir != expdir)
6809 enddir[-1] = '/';
6810 if (*endname == 0) {
6811 atend = 1;
6812 } else {
6813 atend = 0;
6814 *endname++ = '\0';
6815 }
6816 matchdot = 0;
6817 p = start;
6818 if (*p == '\\')
6819 p++;
6820 if (*p == '.')
6821 matchdot++;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00006822 while (!intpending && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006823 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006824 continue;
6825 if (pmatch(start, dp->d_name)) {
6826 if (atend) {
6827 strcpy(enddir, dp->d_name);
6828 addfname(expdir);
6829 } else {
6830 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6831 continue;
6832 p[-1] = '/';
6833 expmeta(p, endname);
6834 }
6835 }
6836 }
6837 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006838 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006839 endname[-1] = '/';
6840}
6841
6842static struct strlist *
6843msort(struct strlist *list, int len)
6844{
6845 struct strlist *p, *q = NULL;
6846 struct strlist **lpp;
6847 int half;
6848 int n;
6849
6850 if (len <= 1)
6851 return list;
6852 half = len >> 1;
6853 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006854 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006855 q = p;
6856 p = p->next;
6857 }
6858 q->next = NULL; /* terminate first half of list */
6859 q = msort(list, half); /* sort first half of list */
6860 p = msort(p, len - half); /* sort second half */
6861 lpp = &list;
6862 for (;;) {
6863#if ENABLE_LOCALE_SUPPORT
6864 if (strcoll(p->text, q->text) < 0)
6865#else
6866 if (strcmp(p->text, q->text) < 0)
6867#endif
6868 {
6869 *lpp = p;
6870 lpp = &p->next;
6871 p = *lpp;
6872 if (p == NULL) {
6873 *lpp = q;
6874 break;
6875 }
6876 } else {
6877 *lpp = q;
6878 lpp = &q->next;
6879 q = *lpp;
6880 if (q == NULL) {
6881 *lpp = p;
6882 break;
6883 }
6884 }
6885 }
6886 return list;
6887}
6888
6889/*
6890 * Sort the results of file name expansion. It calculates the number of
6891 * strings to sort and then calls msort (short for merge sort) to do the
6892 * work.
6893 */
6894static struct strlist *
6895expsort(struct strlist *str)
6896{
6897 int len;
6898 struct strlist *sp;
6899
6900 len = 0;
6901 for (sp = str; sp; sp = sp->next)
6902 len++;
6903 return msort(str, len);
6904}
6905
6906static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006907expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006908{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006909 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006910 '*', '?', '[', 0
6911 };
6912 /* TODO - EXP_REDIR */
6913
6914 while (str) {
6915 struct strlist **savelastp;
6916 struct strlist *sp;
6917 char *p;
6918
6919 if (fflag)
6920 goto nometa;
6921 if (!strpbrk(str->text, metachars))
6922 goto nometa;
6923 savelastp = exparg.lastp;
6924
6925 INT_OFF;
6926 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6927 {
6928 int i = strlen(str->text);
6929 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6930 }
6931
6932 expmeta(expdir, p);
6933 free(expdir);
6934 if (p != str->text)
6935 free(p);
6936 INT_ON;
6937 if (exparg.lastp == savelastp) {
6938 /*
6939 * no matches
6940 */
6941 nometa:
6942 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006943 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006944 exparg.lastp = &str->next;
6945 } else {
6946 *exparg.lastp = NULL;
6947 *savelastp = sp = expsort(*savelastp);
6948 while (sp->next != NULL)
6949 sp = sp->next;
6950 exparg.lastp = &sp->next;
6951 }
6952 str = str->next;
6953 }
6954}
6955
6956/*
6957 * Perform variable substitution and command substitution on an argument,
6958 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6959 * perform splitting and file name expansion. When arglist is NULL, perform
6960 * here document expansion.
6961 */
6962static void
6963expandarg(union node *arg, struct arglist *arglist, int flag)
6964{
6965 struct strlist *sp;
6966 char *p;
6967
6968 argbackq = arg->narg.backquote;
6969 STARTSTACKSTR(expdest);
6970 ifsfirst.next = NULL;
6971 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006972 argstr(arg->narg.text, flag,
6973 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006974 p = _STPUTC('\0', expdest);
6975 expdest = p - 1;
6976 if (arglist == NULL) {
6977 return; /* here document expanded */
6978 }
6979 p = grabstackstr(p);
6980 exparg.lastp = &exparg.list;
6981 /*
6982 * TODO - EXP_REDIR
6983 */
6984 if (flag & EXP_FULL) {
6985 ifsbreakup(p, &exparg);
6986 *exparg.lastp = NULL;
6987 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00006988 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006989 } else {
6990 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006991 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006992 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006993 sp->text = p;
6994 *exparg.lastp = sp;
6995 exparg.lastp = &sp->next;
6996 }
6997 if (ifsfirst.next)
6998 ifsfree();
6999 *exparg.lastp = NULL;
7000 if (exparg.list) {
7001 *arglist->lastp = exparg.list;
7002 arglist->lastp = exparg.lastp;
7003 }
7004}
7005
7006/*
7007 * Expand shell variables and backquotes inside a here document.
7008 */
7009static void
7010expandhere(union node *arg, int fd)
7011{
7012 herefd = fd;
7013 expandarg(arg, (struct arglist *)NULL, 0);
7014 full_write(fd, stackblock(), expdest - (char *)stackblock());
7015}
7016
7017/*
7018 * Returns true if the pattern matches the string.
7019 */
7020static int
7021patmatch(char *pattern, const char *string)
7022{
7023 return pmatch(preglob(pattern, 0, 0), string);
7024}
7025
7026/*
7027 * See if a pattern matches in a case statement.
7028 */
7029static int
7030casematch(union node *pattern, char *val)
7031{
7032 struct stackmark smark;
7033 int result;
7034
7035 setstackmark(&smark);
7036 argbackq = pattern->narg.backquote;
7037 STARTSTACKSTR(expdest);
7038 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007039 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7040 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007041 STACKSTRNUL(expdest);
7042 result = patmatch(stackblock(), val);
7043 popstackmark(&smark);
7044 return result;
7045}
7046
7047
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007048/* ============ find_command */
7049
7050struct builtincmd {
7051 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007052 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007053 /* unsigned flags; */
7054};
7055#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007056/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007057 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007058#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007059#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007060
7061struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007062 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007063 union param {
7064 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007065 /* index >= 0 for commands without path (slashes) */
7066 /* (TODO: what exactly does the value mean? PATH position?) */
7067 /* index == -1 for commands with slashes */
7068 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007069 const struct builtincmd *cmd;
7070 struct funcnode *func;
7071 } u;
7072};
7073/* values of cmdtype */
7074#define CMDUNKNOWN -1 /* no entry in table for command */
7075#define CMDNORMAL 0 /* command is an executable program */
7076#define CMDFUNCTION 1 /* command is a shell function */
7077#define CMDBUILTIN 2 /* command is a shell builtin */
7078
7079/* action to find_command() */
7080#define DO_ERR 0x01 /* prints errors */
7081#define DO_ABS 0x02 /* checks absolute paths */
7082#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7083#define DO_ALTPATH 0x08 /* using alternate path */
7084#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7085
7086static void find_command(char *, struct cmdentry *, int, const char *);
7087
7088
7089/* ============ Hashing commands */
7090
7091/*
7092 * When commands are first encountered, they are entered in a hash table.
7093 * This ensures that a full path search will not have to be done for them
7094 * on each invocation.
7095 *
7096 * We should investigate converting to a linear search, even though that
7097 * would make the command name "hash" a misnomer.
7098 */
7099
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007100struct tblentry {
7101 struct tblentry *next; /* next entry in hash chain */
7102 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007103 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007104 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007105 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007106};
7107
Denis Vlasenko01631112007-12-16 17:20:38 +00007108static struct tblentry **cmdtable;
7109#define INIT_G_cmdtable() do { \
7110 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7111} while (0)
7112
7113static int builtinloc = -1; /* index in path of %builtin, or -1 */
7114
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007115
7116static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007117tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007118{
7119 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007120
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007121#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007122 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007123 if (APPLET_IS_NOEXEC(applet_no)) {
7124 while (*envp)
7125 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007126 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007127 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007128 /* re-exec ourselves with the new arguments */
7129 execve(bb_busybox_exec_path, argv, envp);
7130 /* If they called chroot or otherwise made the binary no longer
7131 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007132 }
7133#endif
7134
7135 repeat:
7136#ifdef SYSV
7137 do {
7138 execve(cmd, argv, envp);
7139 } while (errno == EINTR);
7140#else
7141 execve(cmd, argv, envp);
7142#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007143 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007144 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007145 return;
7146 }
7147 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007148 char **ap;
7149 char **new;
7150
7151 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007152 continue;
7153 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007154 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007155 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007156 ap += 2;
7157 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007158 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007159 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007160 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007161 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162 goto repeat;
7163 }
7164}
7165
7166/*
7167 * Exec a program. Never returns. If you change this routine, you may
7168 * have to change the find_command routine as well.
7169 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007170static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171static void
7172shellexec(char **argv, const char *path, int idx)
7173{
7174 char *cmdname;
7175 int e;
7176 char **envp;
7177 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007178#if ENABLE_FEATURE_SH_STANDALONE
7179 int applet_no = -1;
7180#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007182 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007183 envp = listvars(VEXPORT, VUNSET, 0);
7184 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007185#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007186 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187#endif
7188 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007189 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007190 e = errno;
7191 } else {
7192 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007193 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007195 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007196 if (errno != ENOENT && errno != ENOTDIR)
7197 e = errno;
7198 }
7199 stunalloc(cmdname);
7200 }
7201 }
7202
7203 /* Map to POSIX errors */
7204 switch (e) {
7205 case EACCES:
7206 exerrno = 126;
7207 break;
7208 case ENOENT:
7209 exerrno = 127;
7210 break;
7211 default:
7212 exerrno = 2;
7213 break;
7214 }
7215 exitstatus = exerrno;
7216 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007217 argv[0], e, suppressint));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007218 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7219 /* NOTREACHED */
7220}
7221
7222static void
7223printentry(struct tblentry *cmdp)
7224{
7225 int idx;
7226 const char *path;
7227 char *name;
7228
7229 idx = cmdp->param.index;
7230 path = pathval();
7231 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007232 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007233 stunalloc(name);
7234 } while (--idx >= 0);
7235 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7236}
7237
7238/*
7239 * Clear out command entries. The argument specifies the first entry in
7240 * PATH which has changed.
7241 */
7242static void
7243clearcmdentry(int firstchange)
7244{
7245 struct tblentry **tblp;
7246 struct tblentry **pp;
7247 struct tblentry *cmdp;
7248
7249 INT_OFF;
7250 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7251 pp = tblp;
7252 while ((cmdp = *pp) != NULL) {
7253 if ((cmdp->cmdtype == CMDNORMAL &&
7254 cmdp->param.index >= firstchange)
7255 || (cmdp->cmdtype == CMDBUILTIN &&
7256 builtinloc >= firstchange)
7257 ) {
7258 *pp = cmdp->next;
7259 free(cmdp);
7260 } else {
7261 pp = &cmdp->next;
7262 }
7263 }
7264 }
7265 INT_ON;
7266}
7267
7268/*
7269 * Locate a command in the command hash table. If "add" is nonzero,
7270 * add the command to the table if it is not already present. The
7271 * variable "lastcmdentry" is set to point to the address of the link
7272 * pointing to the entry, so that delete_cmd_entry can delete the
7273 * entry.
7274 *
7275 * Interrupts must be off if called with add != 0.
7276 */
7277static struct tblentry **lastcmdentry;
7278
7279static struct tblentry *
7280cmdlookup(const char *name, int add)
7281{
7282 unsigned int hashval;
7283 const char *p;
7284 struct tblentry *cmdp;
7285 struct tblentry **pp;
7286
7287 p = name;
7288 hashval = (unsigned char)*p << 4;
7289 while (*p)
7290 hashval += (unsigned char)*p++;
7291 hashval &= 0x7FFF;
7292 pp = &cmdtable[hashval % CMDTABLESIZE];
7293 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7294 if (strcmp(cmdp->cmdname, name) == 0)
7295 break;
7296 pp = &cmdp->next;
7297 }
7298 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007299 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7300 + strlen(name)
7301 /* + 1 - already done because
7302 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007303 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007304 cmdp->cmdtype = CMDUNKNOWN;
7305 strcpy(cmdp->cmdname, name);
7306 }
7307 lastcmdentry = pp;
7308 return cmdp;
7309}
7310
7311/*
7312 * Delete the command entry returned on the last lookup.
7313 */
7314static void
7315delete_cmd_entry(void)
7316{
7317 struct tblentry *cmdp;
7318
7319 INT_OFF;
7320 cmdp = *lastcmdentry;
7321 *lastcmdentry = cmdp->next;
7322 if (cmdp->cmdtype == CMDFUNCTION)
7323 freefunc(cmdp->param.func);
7324 free(cmdp);
7325 INT_ON;
7326}
7327
7328/*
7329 * Add a new command entry, replacing any existing command entry for
7330 * the same name - except special builtins.
7331 */
7332static void
7333addcmdentry(char *name, struct cmdentry *entry)
7334{
7335 struct tblentry *cmdp;
7336
7337 cmdp = cmdlookup(name, 1);
7338 if (cmdp->cmdtype == CMDFUNCTION) {
7339 freefunc(cmdp->param.func);
7340 }
7341 cmdp->cmdtype = entry->cmdtype;
7342 cmdp->param = entry->u;
7343 cmdp->rehash = 0;
7344}
7345
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007346static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007347hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007348{
7349 struct tblentry **pp;
7350 struct tblentry *cmdp;
7351 int c;
7352 struct cmdentry entry;
7353 char *name;
7354
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007355 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007356 clearcmdentry(0);
7357 return 0;
7358 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007359
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007360 if (*argptr == NULL) {
7361 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7362 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7363 if (cmdp->cmdtype == CMDNORMAL)
7364 printentry(cmdp);
7365 }
7366 }
7367 return 0;
7368 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007369
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007370 c = 0;
7371 while ((name = *argptr) != NULL) {
7372 cmdp = cmdlookup(name, 0);
7373 if (cmdp != NULL
7374 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007375 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7376 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007377 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007378 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007379 find_command(name, &entry, DO_ERR, pathval());
7380 if (entry.cmdtype == CMDUNKNOWN)
7381 c = 1;
7382 argptr++;
7383 }
7384 return c;
7385}
7386
7387/*
7388 * Called when a cd is done. Marks all commands so the next time they
7389 * are executed they will be rehashed.
7390 */
7391static void
7392hashcd(void)
7393{
7394 struct tblentry **pp;
7395 struct tblentry *cmdp;
7396
7397 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7398 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007399 if (cmdp->cmdtype == CMDNORMAL
7400 || (cmdp->cmdtype == CMDBUILTIN
7401 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7402 && builtinloc > 0)
7403 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007404 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007405 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007406 }
7407 }
7408}
7409
7410/*
7411 * Fix command hash table when PATH changed.
7412 * Called before PATH is changed. The argument is the new value of PATH;
7413 * pathval() still returns the old value at this point.
7414 * Called with interrupts off.
7415 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007416static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007417changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007418{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007419 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007420 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007421 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007422 int idx_bltin;
7423
7424 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007425 firstchange = 9999; /* assume no change */
7426 idx = 0;
7427 idx_bltin = -1;
7428 for (;;) {
7429 if (*old != *new) {
7430 firstchange = idx;
7431 if ((*old == '\0' && *new == ':')
7432 || (*old == ':' && *new == '\0'))
7433 firstchange++;
7434 old = new; /* ignore subsequent differences */
7435 }
7436 if (*new == '\0')
7437 break;
7438 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7439 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007440 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007441 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007442 new++, old++;
7443 }
7444 if (builtinloc < 0 && idx_bltin >= 0)
7445 builtinloc = idx_bltin; /* zap builtins */
7446 if (builtinloc >= 0 && idx_bltin < 0)
7447 firstchange = 0;
7448 clearcmdentry(firstchange);
7449 builtinloc = idx_bltin;
7450}
7451
7452#define TEOF 0
7453#define TNL 1
7454#define TREDIR 2
7455#define TWORD 3
7456#define TSEMI 4
7457#define TBACKGND 5
7458#define TAND 6
7459#define TOR 7
7460#define TPIPE 8
7461#define TLP 9
7462#define TRP 10
7463#define TENDCASE 11
7464#define TENDBQUOTE 12
7465#define TNOT 13
7466#define TCASE 14
7467#define TDO 15
7468#define TDONE 16
7469#define TELIF 17
7470#define TELSE 18
7471#define TESAC 19
7472#define TFI 20
7473#define TFOR 21
7474#define TIF 22
7475#define TIN 23
7476#define TTHEN 24
7477#define TUNTIL 25
7478#define TWHILE 26
7479#define TBEGIN 27
7480#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007481typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007482
7483/* first char is indicating which tokens mark the end of a list */
7484static const char *const tokname_array[] = {
7485 "\1end of file",
7486 "\0newline",
7487 "\0redirection",
7488 "\0word",
7489 "\0;",
7490 "\0&",
7491 "\0&&",
7492 "\0||",
7493 "\0|",
7494 "\0(",
7495 "\1)",
7496 "\1;;",
7497 "\1`",
7498#define KWDOFFSET 13
7499 /* the following are keywords */
7500 "\0!",
7501 "\0case",
7502 "\1do",
7503 "\1done",
7504 "\1elif",
7505 "\1else",
7506 "\1esac",
7507 "\1fi",
7508 "\0for",
7509 "\0if",
7510 "\0in",
7511 "\1then",
7512 "\0until",
7513 "\0while",
7514 "\0{",
7515 "\1}",
7516};
7517
7518static const char *
7519tokname(int tok)
7520{
7521 static char buf[16];
7522
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007523//try this:
7524//if (tok < TSEMI) return tokname_array[tok] + 1;
7525//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7526//return buf;
7527
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007528 if (tok >= TSEMI)
7529 buf[0] = '"';
7530 sprintf(buf + (tok >= TSEMI), "%s%c",
7531 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7532 return buf;
7533}
7534
7535/* Wrapper around strcmp for qsort/bsearch/... */
7536static int
7537pstrcmp(const void *a, const void *b)
7538{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007539 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007540}
7541
7542static const char *const *
7543findkwd(const char *s)
7544{
7545 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007546 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7547 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007548}
7549
7550/*
7551 * Locate and print what a word is...
7552 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007553static int
7554describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007555{
7556 struct cmdentry entry;
7557 struct tblentry *cmdp;
7558#if ENABLE_ASH_ALIAS
7559 const struct alias *ap;
7560#endif
7561 const char *path = pathval();
7562
7563 if (describe_command_verbose) {
7564 out1str(command);
7565 }
7566
7567 /* First look at the keywords */
7568 if (findkwd(command)) {
7569 out1str(describe_command_verbose ? " is a shell keyword" : command);
7570 goto out;
7571 }
7572
7573#if ENABLE_ASH_ALIAS
7574 /* Then look at the aliases */
7575 ap = lookupalias(command, 0);
7576 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007577 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007578 out1str("alias ");
7579 printalias(ap);
7580 return 0;
7581 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007582 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007583 goto out;
7584 }
7585#endif
7586 /* Then check if it is a tracked alias */
7587 cmdp = cmdlookup(command, 0);
7588 if (cmdp != NULL) {
7589 entry.cmdtype = cmdp->cmdtype;
7590 entry.u = cmdp->param;
7591 } else {
7592 /* Finally use brute force */
7593 find_command(command, &entry, DO_ABS, path);
7594 }
7595
7596 switch (entry.cmdtype) {
7597 case CMDNORMAL: {
7598 int j = entry.u.index;
7599 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007600 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007601 p = command;
7602 } else {
7603 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007604 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007605 stunalloc(p);
7606 } while (--j >= 0);
7607 }
7608 if (describe_command_verbose) {
7609 out1fmt(" is%s %s",
7610 (cmdp ? " a tracked alias for" : nullstr), p
7611 );
7612 } else {
7613 out1str(p);
7614 }
7615 break;
7616 }
7617
7618 case CMDFUNCTION:
7619 if (describe_command_verbose) {
7620 out1str(" is a shell function");
7621 } else {
7622 out1str(command);
7623 }
7624 break;
7625
7626 case CMDBUILTIN:
7627 if (describe_command_verbose) {
7628 out1fmt(" is a %sshell builtin",
7629 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7630 "special " : nullstr
7631 );
7632 } else {
7633 out1str(command);
7634 }
7635 break;
7636
7637 default:
7638 if (describe_command_verbose) {
7639 out1str(": not found\n");
7640 }
7641 return 127;
7642 }
7643 out:
7644 outstr("\n", stdout);
7645 return 0;
7646}
7647
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007648static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007649typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007651 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007652 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007653 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007654
Denis Vlasenko46846e22007-05-20 13:08:31 +00007655 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007656 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007657 i++;
7658 verbose = 0;
7659 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007660 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007661 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007662 }
7663 return err;
7664}
7665
7666#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007667static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007668commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007669{
7670 int c;
7671 enum {
7672 VERIFY_BRIEF = 1,
7673 VERIFY_VERBOSE = 2,
7674 } verify = 0;
7675
7676 while ((c = nextopt("pvV")) != '\0')
7677 if (c == 'V')
7678 verify |= VERIFY_VERBOSE;
7679 else if (c == 'v')
7680 verify |= VERIFY_BRIEF;
7681#if DEBUG
7682 else if (c != 'p')
7683 abort();
7684#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007685 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7686 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007687 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007688 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007689
7690 return 0;
7691}
7692#endif
7693
7694
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007695/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007696
Denis Vlasenko340299a2008-11-21 10:36:36 +00007697static int funcblocksize; /* size of structures in function */
7698static int funcstringsize; /* size of strings in node */
7699static void *funcblock; /* block to allocate function from */
7700static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007701
Eric Andersencb57d552001-06-28 07:25:16 +00007702/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007703#define EV_EXIT 01 /* exit after evaluating tree */
7704#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007705#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007706
Denis Vlasenko340299a2008-11-21 10:36:36 +00007707static const short nodesize[N_NUMBER] = {
7708 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7709 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7710 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7711 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7712 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7713 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7714 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7715 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7716 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7717 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7718 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7719 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7720 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7721 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7722 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7723 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7724 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007725#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007726 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007727#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007728 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7729 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7730 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7731 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7732 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7733 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7734 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7735 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7736 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007737};
7738
7739static void calcsize(union node *n);
7740
7741static void
7742sizenodelist(struct nodelist *lp)
7743{
7744 while (lp) {
7745 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7746 calcsize(lp->n);
7747 lp = lp->next;
7748 }
7749}
7750
7751static void
7752calcsize(union node *n)
7753{
7754 if (n == NULL)
7755 return;
7756 funcblocksize += nodesize[n->type];
7757 switch (n->type) {
7758 case NCMD:
7759 calcsize(n->ncmd.redirect);
7760 calcsize(n->ncmd.args);
7761 calcsize(n->ncmd.assign);
7762 break;
7763 case NPIPE:
7764 sizenodelist(n->npipe.cmdlist);
7765 break;
7766 case NREDIR:
7767 case NBACKGND:
7768 case NSUBSHELL:
7769 calcsize(n->nredir.redirect);
7770 calcsize(n->nredir.n);
7771 break;
7772 case NAND:
7773 case NOR:
7774 case NSEMI:
7775 case NWHILE:
7776 case NUNTIL:
7777 calcsize(n->nbinary.ch2);
7778 calcsize(n->nbinary.ch1);
7779 break;
7780 case NIF:
7781 calcsize(n->nif.elsepart);
7782 calcsize(n->nif.ifpart);
7783 calcsize(n->nif.test);
7784 break;
7785 case NFOR:
7786 funcstringsize += strlen(n->nfor.var) + 1;
7787 calcsize(n->nfor.body);
7788 calcsize(n->nfor.args);
7789 break;
7790 case NCASE:
7791 calcsize(n->ncase.cases);
7792 calcsize(n->ncase.expr);
7793 break;
7794 case NCLIST:
7795 calcsize(n->nclist.body);
7796 calcsize(n->nclist.pattern);
7797 calcsize(n->nclist.next);
7798 break;
7799 case NDEFUN:
7800 case NARG:
7801 sizenodelist(n->narg.backquote);
7802 funcstringsize += strlen(n->narg.text) + 1;
7803 calcsize(n->narg.next);
7804 break;
7805 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007806#if ENABLE_ASH_BASH_COMPAT
7807 case NTO2:
7808#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007809 case NCLOBBER:
7810 case NFROM:
7811 case NFROMTO:
7812 case NAPPEND:
7813 calcsize(n->nfile.fname);
7814 calcsize(n->nfile.next);
7815 break;
7816 case NTOFD:
7817 case NFROMFD:
7818 calcsize(n->ndup.vname);
7819 calcsize(n->ndup.next);
7820 break;
7821 case NHERE:
7822 case NXHERE:
7823 calcsize(n->nhere.doc);
7824 calcsize(n->nhere.next);
7825 break;
7826 case NNOT:
7827 calcsize(n->nnot.com);
7828 break;
7829 };
7830}
7831
7832static char *
7833nodeckstrdup(char *s)
7834{
7835 char *rtn = funcstring;
7836
7837 strcpy(funcstring, s);
7838 funcstring += strlen(s) + 1;
7839 return rtn;
7840}
7841
7842static union node *copynode(union node *);
7843
7844static struct nodelist *
7845copynodelist(struct nodelist *lp)
7846{
7847 struct nodelist *start;
7848 struct nodelist **lpp;
7849
7850 lpp = &start;
7851 while (lp) {
7852 *lpp = funcblock;
7853 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7854 (*lpp)->n = copynode(lp->n);
7855 lp = lp->next;
7856 lpp = &(*lpp)->next;
7857 }
7858 *lpp = NULL;
7859 return start;
7860}
7861
7862static union node *
7863copynode(union node *n)
7864{
7865 union node *new;
7866
7867 if (n == NULL)
7868 return NULL;
7869 new = funcblock;
7870 funcblock = (char *) funcblock + nodesize[n->type];
7871
7872 switch (n->type) {
7873 case NCMD:
7874 new->ncmd.redirect = copynode(n->ncmd.redirect);
7875 new->ncmd.args = copynode(n->ncmd.args);
7876 new->ncmd.assign = copynode(n->ncmd.assign);
7877 break;
7878 case NPIPE:
7879 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007880 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007881 break;
7882 case NREDIR:
7883 case NBACKGND:
7884 case NSUBSHELL:
7885 new->nredir.redirect = copynode(n->nredir.redirect);
7886 new->nredir.n = copynode(n->nredir.n);
7887 break;
7888 case NAND:
7889 case NOR:
7890 case NSEMI:
7891 case NWHILE:
7892 case NUNTIL:
7893 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7894 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7895 break;
7896 case NIF:
7897 new->nif.elsepart = copynode(n->nif.elsepart);
7898 new->nif.ifpart = copynode(n->nif.ifpart);
7899 new->nif.test = copynode(n->nif.test);
7900 break;
7901 case NFOR:
7902 new->nfor.var = nodeckstrdup(n->nfor.var);
7903 new->nfor.body = copynode(n->nfor.body);
7904 new->nfor.args = copynode(n->nfor.args);
7905 break;
7906 case NCASE:
7907 new->ncase.cases = copynode(n->ncase.cases);
7908 new->ncase.expr = copynode(n->ncase.expr);
7909 break;
7910 case NCLIST:
7911 new->nclist.body = copynode(n->nclist.body);
7912 new->nclist.pattern = copynode(n->nclist.pattern);
7913 new->nclist.next = copynode(n->nclist.next);
7914 break;
7915 case NDEFUN:
7916 case NARG:
7917 new->narg.backquote = copynodelist(n->narg.backquote);
7918 new->narg.text = nodeckstrdup(n->narg.text);
7919 new->narg.next = copynode(n->narg.next);
7920 break;
7921 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007922#if ENABLE_ASH_BASH_COMPAT
7923 case NTO2:
7924#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007925 case NCLOBBER:
7926 case NFROM:
7927 case NFROMTO:
7928 case NAPPEND:
7929 new->nfile.fname = copynode(n->nfile.fname);
7930 new->nfile.fd = n->nfile.fd;
7931 new->nfile.next = copynode(n->nfile.next);
7932 break;
7933 case NTOFD:
7934 case NFROMFD:
7935 new->ndup.vname = copynode(n->ndup.vname);
7936 new->ndup.dupfd = n->ndup.dupfd;
7937 new->ndup.fd = n->ndup.fd;
7938 new->ndup.next = copynode(n->ndup.next);
7939 break;
7940 case NHERE:
7941 case NXHERE:
7942 new->nhere.doc = copynode(n->nhere.doc);
7943 new->nhere.fd = n->nhere.fd;
7944 new->nhere.next = copynode(n->nhere.next);
7945 break;
7946 case NNOT:
7947 new->nnot.com = copynode(n->nnot.com);
7948 break;
7949 };
7950 new->type = n->type;
7951 return new;
7952}
7953
7954/*
7955 * Make a copy of a parse tree.
7956 */
7957static struct funcnode *
7958copyfunc(union node *n)
7959{
7960 struct funcnode *f;
7961 size_t blocksize;
7962
7963 funcblocksize = offsetof(struct funcnode, n);
7964 funcstringsize = 0;
7965 calcsize(n);
7966 blocksize = funcblocksize;
7967 f = ckmalloc(blocksize + funcstringsize);
7968 funcblock = (char *) f + offsetof(struct funcnode, n);
7969 funcstring = (char *) f + blocksize;
7970 copynode(n);
7971 f->count = 0;
7972 return f;
7973}
7974
7975/*
7976 * Define a shell function.
7977 */
7978static void
7979defun(char *name, union node *func)
7980{
7981 struct cmdentry entry;
7982
7983 INT_OFF;
7984 entry.cmdtype = CMDFUNCTION;
7985 entry.u.func = copyfunc(func);
7986 addcmdentry(name, &entry);
7987 INT_ON;
7988}
7989
Denis Vlasenko4b875702009-03-19 13:30:04 +00007990/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007991#define SKIPBREAK (1 << 0)
7992#define SKIPCONT (1 << 1)
7993#define SKIPFUNC (1 << 2)
7994#define SKIPFILE (1 << 3)
7995#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00007996static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007997static int skipcount; /* number of levels to skip */
7998static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007999static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008000
Denis Vlasenko4b875702009-03-19 13:30:04 +00008001/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008002static int evalstring(char *s, int mask);
8003
Denis Vlasenko4b875702009-03-19 13:30:04 +00008004/* Called to execute a trap.
8005 * Single callsite - at the end of evaltree().
8006 * If we return non-zero, exaltree raises EXEXIT exception.
8007 *
8008 * Perhaps we should avoid entering new trap handlers
8009 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008010 */
8011static int
8012dotrap(void)
8013{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008014 uint8_t *g;
8015 int sig;
8016 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008017
8018 savestatus = exitstatus;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00008019 pendingsig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008020 xbarrier();
8021
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008022 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008023 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8024 int want_exexit;
8025 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008026
Denis Vlasenko4b875702009-03-19 13:30:04 +00008027 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008028 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008029 t = trap[sig];
8030 /* non-trapped SIGINT is handled separately by raise_interrupt,
8031 * don't upset it by resetting gotsig[SIGINT-1] */
8032 if (sig == SIGINT && !t)
8033 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008034
8035 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008036 *g = 0;
8037 if (!t)
8038 continue;
8039 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008040 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008041 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008042 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008043 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008044 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008045 }
8046
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008047 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008048 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008049}
8050
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008051/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008052static void evalloop(union node *, int);
8053static void evalfor(union node *, int);
8054static void evalcase(union node *, int);
8055static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008056static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008057static void evalpipe(union node *, int);
8058static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008059static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008060static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008061
Eric Andersen62483552001-07-10 06:09:16 +00008062/*
Eric Andersenc470f442003-07-28 09:56:35 +00008063 * Evaluate a parse tree. The value is left in the global variable
8064 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008065 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008066static void
Eric Andersenc470f442003-07-28 09:56:35 +00008067evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008068{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008069 struct jmploc *volatile savehandler = exception_handler;
8070 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008071 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008072 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008073 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008074 int int_level;
8075
8076 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008077
Eric Andersenc470f442003-07-28 09:56:35 +00008078 if (n == NULL) {
8079 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008080 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008081 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008082 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008083
8084 exception_handler = &jmploc;
8085 {
8086 int err = setjmp(jmploc.loc);
8087 if (err) {
8088 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008089 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008090 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8091 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008092 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008093 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008094 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008095 TRACE(("exception %d in evaltree, propagating err=%d\n",
8096 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008097 exception_handler = savehandler;
8098 longjmp(exception_handler->loc, err);
8099 }
8100 }
8101
Eric Andersenc470f442003-07-28 09:56:35 +00008102 switch (n->type) {
8103 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008104#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008105 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008106 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008107 break;
8108#endif
8109 case NNOT:
8110 evaltree(n->nnot.com, EV_TESTED);
8111 status = !exitstatus;
8112 goto setstatus;
8113 case NREDIR:
8114 expredir(n->nredir.redirect);
8115 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8116 if (!status) {
8117 evaltree(n->nredir.n, flags & EV_TESTED);
8118 status = exitstatus;
8119 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008120 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008121 goto setstatus;
8122 case NCMD:
8123 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008124 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008125 if (eflag && !(flags & EV_TESTED))
8126 checkexit = ~0;
8127 goto calleval;
8128 case NFOR:
8129 evalfn = evalfor;
8130 goto calleval;
8131 case NWHILE:
8132 case NUNTIL:
8133 evalfn = evalloop;
8134 goto calleval;
8135 case NSUBSHELL:
8136 case NBACKGND:
8137 evalfn = evalsubshell;
8138 goto calleval;
8139 case NPIPE:
8140 evalfn = evalpipe;
8141 goto checkexit;
8142 case NCASE:
8143 evalfn = evalcase;
8144 goto calleval;
8145 case NAND:
8146 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008147 case NSEMI: {
8148
Eric Andersenc470f442003-07-28 09:56:35 +00008149#if NAND + 1 != NOR
8150#error NAND + 1 != NOR
8151#endif
8152#if NOR + 1 != NSEMI
8153#error NOR + 1 != NSEMI
8154#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008155 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008156 evaltree(
8157 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008158 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008159 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008160 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008161 break;
8162 if (!evalskip) {
8163 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008164 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008165 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008166 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008167 evalfn(n, flags);
8168 break;
8169 }
8170 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008171 }
Eric Andersenc470f442003-07-28 09:56:35 +00008172 case NIF:
8173 evaltree(n->nif.test, EV_TESTED);
8174 if (evalskip)
8175 break;
8176 if (exitstatus == 0) {
8177 n = n->nif.ifpart;
8178 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008179 }
8180 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008181 n = n->nif.elsepart;
8182 goto evaln;
8183 }
8184 goto success;
8185 case NDEFUN:
8186 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008187 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008188 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008189 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008190 exitstatus = status;
8191 break;
8192 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008193
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008194 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008195 exception_handler = savehandler;
8196 out1:
8197 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008198 evalskip |= SKIPEVAL;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00008199 else if (pendingsig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008200 goto exexit;
8201
8202 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008203 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008204 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008205 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008206
8207 RESTORE_INT(int_level);
8208 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008209}
8210
Eric Andersenc470f442003-07-28 09:56:35 +00008211#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8212static
8213#endif
8214void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8215
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008216static void
Eric Andersenc470f442003-07-28 09:56:35 +00008217evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008218{
8219 int status;
8220
8221 loopnest++;
8222 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008223 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008224 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008225 int i;
8226
Eric Andersencb57d552001-06-28 07:25:16 +00008227 evaltree(n->nbinary.ch1, EV_TESTED);
8228 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008229 skipping:
8230 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008231 evalskip = 0;
8232 continue;
8233 }
8234 if (evalskip == SKIPBREAK && --skipcount <= 0)
8235 evalskip = 0;
8236 break;
8237 }
Eric Andersenc470f442003-07-28 09:56:35 +00008238 i = exitstatus;
8239 if (n->type != NWHILE)
8240 i = !i;
8241 if (i != 0)
8242 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008243 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008244 status = exitstatus;
8245 if (evalskip)
8246 goto skipping;
8247 }
8248 loopnest--;
8249 exitstatus = status;
8250}
8251
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008252static void
Eric Andersenc470f442003-07-28 09:56:35 +00008253evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008254{
8255 struct arglist arglist;
8256 union node *argp;
8257 struct strlist *sp;
8258 struct stackmark smark;
8259
8260 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008261 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008262 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008263 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008264 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008265 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008266 if (evalskip)
8267 goto out;
8268 }
8269 *arglist.lastp = NULL;
8270
8271 exitstatus = 0;
8272 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008273 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008274 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008275 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008276 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008277 if (evalskip) {
8278 if (evalskip == SKIPCONT && --skipcount <= 0) {
8279 evalskip = 0;
8280 continue;
8281 }
8282 if (evalskip == SKIPBREAK && --skipcount <= 0)
8283 evalskip = 0;
8284 break;
8285 }
8286 }
8287 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008288 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008289 popstackmark(&smark);
8290}
8291
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008292static void
Eric Andersenc470f442003-07-28 09:56:35 +00008293evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008294{
8295 union node *cp;
8296 union node *patp;
8297 struct arglist arglist;
8298 struct stackmark smark;
8299
8300 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008301 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008302 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008303 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008304 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008305 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8306 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008307 if (casematch(patp, arglist.list->text)) {
8308 if (evalskip == 0) {
8309 evaltree(cp->nclist.body, flags);
8310 }
8311 goto out;
8312 }
8313 }
8314 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008315 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008316 popstackmark(&smark);
8317}
8318
Eric Andersenc470f442003-07-28 09:56:35 +00008319/*
8320 * Kick off a subshell to evaluate a tree.
8321 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008322static void
Eric Andersenc470f442003-07-28 09:56:35 +00008323evalsubshell(union node *n, int flags)
8324{
8325 struct job *jp;
8326 int backgnd = (n->type == NBACKGND);
8327 int status;
8328
8329 expredir(n->nredir.redirect);
8330 if (!backgnd && flags & EV_EXIT && !trap[0])
8331 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008332 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008333 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008334 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008335 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008336 flags |= EV_EXIT;
8337 if (backgnd)
8338 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008339 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008340 redirect(n->nredir.redirect, 0);
8341 evaltreenr(n->nredir.n, flags);
8342 /* never returns */
8343 }
8344 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008345 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008346 status = waitforjob(jp);
8347 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008348 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008349}
8350
Eric Andersenc470f442003-07-28 09:56:35 +00008351/*
8352 * Compute the names of the files in a redirection list.
8353 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008354static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008355static void
8356expredir(union node *n)
8357{
8358 union node *redir;
8359
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008360 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008361 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008362
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008363 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008364 fn.lastp = &fn.list;
8365 switch (redir->type) {
8366 case NFROMTO:
8367 case NFROM:
8368 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008369#if ENABLE_ASH_BASH_COMPAT
8370 case NTO2:
8371#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008372 case NCLOBBER:
8373 case NAPPEND:
8374 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008375#if ENABLE_ASH_BASH_COMPAT
8376 store_expfname:
8377#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008378 redir->nfile.expfname = fn.list->text;
8379 break;
8380 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008381 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008382 if (redir->ndup.vname) {
8383 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008384 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008385 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008386#if ENABLE_ASH_BASH_COMPAT
8387//FIXME: we used expandarg with different args!
8388 if (!isdigit_str9(fn.list->text)) {
8389 /* >&file, not >&fd */
8390 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8391 ash_msg_and_raise_error("redir error");
8392 redir->type = NTO2;
8393 goto store_expfname;
8394 }
8395#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008396 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008397 }
8398 break;
8399 }
8400 }
8401}
8402
Eric Andersencb57d552001-06-28 07:25:16 +00008403/*
Eric Andersencb57d552001-06-28 07:25:16 +00008404 * Evaluate a pipeline. All the processes in the pipeline are children
8405 * of the process creating the pipeline. (This differs from some versions
8406 * of the shell, which make the last process in a pipeline the parent
8407 * of all the rest.)
8408 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008409static void
Eric Andersenc470f442003-07-28 09:56:35 +00008410evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008411{
8412 struct job *jp;
8413 struct nodelist *lp;
8414 int pipelen;
8415 int prevfd;
8416 int pip[2];
8417
Eric Andersenc470f442003-07-28 09:56:35 +00008418 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008419 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008420 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008421 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008422 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008423 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008424 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008425 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008426 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008427 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008428 pip[1] = -1;
8429 if (lp->next) {
8430 if (pipe(pip) < 0) {
8431 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008432 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008433 }
8434 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008435 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008436 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008437 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008438 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008439 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008440 if (prevfd > 0) {
8441 dup2(prevfd, 0);
8442 close(prevfd);
8443 }
8444 if (pip[1] > 1) {
8445 dup2(pip[1], 1);
8446 close(pip[1]);
8447 }
Eric Andersenc470f442003-07-28 09:56:35 +00008448 evaltreenr(lp->n, flags);
8449 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008450 }
8451 if (prevfd >= 0)
8452 close(prevfd);
8453 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008454 /* Don't want to trigger debugging */
8455 if (pip[1] != -1)
8456 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008457 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008458 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008459 exitstatus = waitforjob(jp);
8460 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008461 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008462 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008463}
8464
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008465/*
8466 * Controls whether the shell is interactive or not.
8467 */
8468static void
8469setinteractive(int on)
8470{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008471 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008472
8473 if (++on == is_interactive)
8474 return;
8475 is_interactive = on;
8476 setsignal(SIGINT);
8477 setsignal(SIGQUIT);
8478 setsignal(SIGTERM);
8479#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8480 if (is_interactive > 1) {
8481 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008482 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008483
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008484 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008485 out1fmt(
8486 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008487 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008488 "Enter 'help' for a list of built-in commands."
8489 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008490 bb_banner);
8491 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008492 }
8493 }
8494#endif
8495}
8496
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008497static void
8498optschanged(void)
8499{
8500#if DEBUG
8501 opentrace();
8502#endif
8503 setinteractive(iflag);
8504 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008505#if ENABLE_FEATURE_EDITING_VI
8506 if (viflag)
8507 line_input_state->flags |= VI_MODE;
8508 else
8509 line_input_state->flags &= ~VI_MODE;
8510#else
8511 viflag = 0; /* forcibly keep the option off */
8512#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008513}
8514
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008515static struct localvar *localvars;
8516
8517/*
8518 * Called after a function returns.
8519 * Interrupts must be off.
8520 */
8521static void
8522poplocalvars(void)
8523{
8524 struct localvar *lvp;
8525 struct var *vp;
8526
8527 while ((lvp = localvars) != NULL) {
8528 localvars = lvp->next;
8529 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008530 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008531 if (vp == NULL) { /* $- saved */
8532 memcpy(optlist, lvp->text, sizeof(optlist));
8533 free((char*)lvp->text);
8534 optschanged();
8535 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8536 unsetvar(vp->text);
8537 } else {
8538 if (vp->func)
8539 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8540 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8541 free((char*)vp->text);
8542 vp->flags = lvp->flags;
8543 vp->text = lvp->text;
8544 }
8545 free(lvp);
8546 }
8547}
8548
8549static int
8550evalfun(struct funcnode *func, int argc, char **argv, int flags)
8551{
8552 volatile struct shparam saveparam;
8553 struct localvar *volatile savelocalvars;
8554 struct jmploc *volatile savehandler;
8555 struct jmploc jmploc;
8556 int e;
8557
8558 saveparam = shellparam;
8559 savelocalvars = localvars;
8560 e = setjmp(jmploc.loc);
8561 if (e) {
8562 goto funcdone;
8563 }
8564 INT_OFF;
8565 savehandler = exception_handler;
8566 exception_handler = &jmploc;
8567 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008568 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008569 func->count++;
8570 funcnest++;
8571 INT_ON;
8572 shellparam.nparam = argc - 1;
8573 shellparam.p = argv + 1;
8574#if ENABLE_ASH_GETOPTS
8575 shellparam.optind = 1;
8576 shellparam.optoff = -1;
8577#endif
8578 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008579 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008580 INT_OFF;
8581 funcnest--;
8582 freefunc(func);
8583 poplocalvars();
8584 localvars = savelocalvars;
8585 freeparam(&shellparam);
8586 shellparam = saveparam;
8587 exception_handler = savehandler;
8588 INT_ON;
8589 evalskip &= ~SKIPFUNC;
8590 return e;
8591}
8592
Denis Vlasenko131ae172007-02-18 13:00:19 +00008593#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008594static char **
8595parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008596{
8597 char *cp, c;
8598
8599 for (;;) {
8600 cp = *++argv;
8601 if (!cp)
8602 return 0;
8603 if (*cp++ != '-')
8604 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008605 c = *cp++;
8606 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008607 break;
8608 if (c == '-' && !*cp) {
8609 argv++;
8610 break;
8611 }
8612 do {
8613 switch (c) {
8614 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008615 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008616 break;
8617 default:
8618 /* run 'typecmd' for other options */
8619 return 0;
8620 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008621 c = *cp++;
8622 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008623 }
8624 return argv;
8625}
8626#endif
8627
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008628/*
8629 * Make a variable a local variable. When a variable is made local, it's
8630 * value and flags are saved in a localvar structure. The saved values
8631 * will be restored when the shell function returns. We handle the name
8632 * "-" as a special case.
8633 */
8634static void
8635mklocal(char *name)
8636{
8637 struct localvar *lvp;
8638 struct var **vpp;
8639 struct var *vp;
8640
8641 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008642 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008643 if (LONE_DASH(name)) {
8644 char *p;
8645 p = ckmalloc(sizeof(optlist));
8646 lvp->text = memcpy(p, optlist, sizeof(optlist));
8647 vp = NULL;
8648 } else {
8649 char *eq;
8650
8651 vpp = hashvar(name);
8652 vp = *findvar(vpp, name);
8653 eq = strchr(name, '=');
8654 if (vp == NULL) {
8655 if (eq)
8656 setvareq(name, VSTRFIXED);
8657 else
8658 setvar(name, NULL, VSTRFIXED);
8659 vp = *vpp; /* the new variable */
8660 lvp->flags = VUNSET;
8661 } else {
8662 lvp->text = vp->text;
8663 lvp->flags = vp->flags;
8664 vp->flags |= VSTRFIXED|VTEXTFIXED;
8665 if (eq)
8666 setvareq(name, 0);
8667 }
8668 }
8669 lvp->vp = vp;
8670 lvp->next = localvars;
8671 localvars = lvp;
8672 INT_ON;
8673}
8674
8675/*
8676 * The "local" command.
8677 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008678static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008679localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008680{
8681 char *name;
8682
8683 argv = argptr;
8684 while ((name = *argv++) != NULL) {
8685 mklocal(name);
8686 }
8687 return 0;
8688}
8689
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008690static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008691falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008692{
8693 return 1;
8694}
8695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008696static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008697truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008698{
8699 return 0;
8700}
8701
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008702static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008703execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008704{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008705 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008706 iflag = 0; /* exit on error */
8707 mflag = 0;
8708 optschanged();
8709 shellexec(argv + 1, pathval(), 0);
8710 }
8711 return 0;
8712}
8713
8714/*
8715 * The return command.
8716 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008717static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008718returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008719{
8720 /*
8721 * If called outside a function, do what ksh does;
8722 * skip the rest of the file.
8723 */
8724 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8725 return argv[1] ? number(argv[1]) : exitstatus;
8726}
8727
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008728/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008729static int breakcmd(int, char **) FAST_FUNC;
8730static int dotcmd(int, char **) FAST_FUNC;
8731static int evalcmd(int, char **) FAST_FUNC;
8732static int exitcmd(int, char **) FAST_FUNC;
8733static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008734#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008735static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008736#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008737#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008738static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008739#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008740#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008741static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008742#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008743static int readcmd(int, char **) FAST_FUNC;
8744static int setcmd(int, char **) FAST_FUNC;
8745static int shiftcmd(int, char **) FAST_FUNC;
8746static int timescmd(int, char **) FAST_FUNC;
8747static int trapcmd(int, char **) FAST_FUNC;
8748static int umaskcmd(int, char **) FAST_FUNC;
8749static int unsetcmd(int, char **) FAST_FUNC;
8750static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008751
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008752#define BUILTIN_NOSPEC "0"
8753#define BUILTIN_SPECIAL "1"
8754#define BUILTIN_REGULAR "2"
8755#define BUILTIN_SPEC_REG "3"
8756#define BUILTIN_ASSIGN "4"
8757#define BUILTIN_SPEC_ASSG "5"
8758#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008759#define BUILTIN_SPEC_REG_ASSG "7"
8760
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008761/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008762#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008763static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008764#endif
8765#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008766static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008767#endif
8768#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008769static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008770#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008771
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008772/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008773static const struct builtincmd builtintab[] = {
8774 { BUILTIN_SPEC_REG ".", dotcmd },
8775 { BUILTIN_SPEC_REG ":", truecmd },
8776#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008777 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008778#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008779 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008780#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008781#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008782#if ENABLE_ASH_ALIAS
8783 { BUILTIN_REG_ASSG "alias", aliascmd },
8784#endif
8785#if JOBS
8786 { BUILTIN_REGULAR "bg", fg_bgcmd },
8787#endif
8788 { BUILTIN_SPEC_REG "break", breakcmd },
8789 { BUILTIN_REGULAR "cd", cdcmd },
8790 { BUILTIN_NOSPEC "chdir", cdcmd },
8791#if ENABLE_ASH_CMDCMD
8792 { BUILTIN_REGULAR "command", commandcmd },
8793#endif
8794 { BUILTIN_SPEC_REG "continue", breakcmd },
8795#if ENABLE_ASH_BUILTIN_ECHO
8796 { BUILTIN_REGULAR "echo", echocmd },
8797#endif
8798 { BUILTIN_SPEC_REG "eval", evalcmd },
8799 { BUILTIN_SPEC_REG "exec", execcmd },
8800 { BUILTIN_SPEC_REG "exit", exitcmd },
8801 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8802 { BUILTIN_REGULAR "false", falsecmd },
8803#if JOBS
8804 { BUILTIN_REGULAR "fg", fg_bgcmd },
8805#endif
8806#if ENABLE_ASH_GETOPTS
8807 { BUILTIN_REGULAR "getopts", getoptscmd },
8808#endif
8809 { BUILTIN_NOSPEC "hash", hashcmd },
8810#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8811 { BUILTIN_NOSPEC "help", helpcmd },
8812#endif
8813#if JOBS
8814 { BUILTIN_REGULAR "jobs", jobscmd },
8815 { BUILTIN_REGULAR "kill", killcmd },
8816#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008817#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008818 { BUILTIN_NOSPEC "let", letcmd },
8819#endif
8820 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008821#if ENABLE_ASH_BUILTIN_PRINTF
8822 { BUILTIN_REGULAR "printf", printfcmd },
8823#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008824 { BUILTIN_NOSPEC "pwd", pwdcmd },
8825 { BUILTIN_REGULAR "read", readcmd },
8826 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8827 { BUILTIN_SPEC_REG "return", returncmd },
8828 { BUILTIN_SPEC_REG "set", setcmd },
8829 { BUILTIN_SPEC_REG "shift", shiftcmd },
8830 { BUILTIN_SPEC_REG "source", dotcmd },
8831#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008832 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008833#endif
8834 { BUILTIN_SPEC_REG "times", timescmd },
8835 { BUILTIN_SPEC_REG "trap", trapcmd },
8836 { BUILTIN_REGULAR "true", truecmd },
8837 { BUILTIN_NOSPEC "type", typecmd },
8838 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8839 { BUILTIN_REGULAR "umask", umaskcmd },
8840#if ENABLE_ASH_ALIAS
8841 { BUILTIN_REGULAR "unalias", unaliascmd },
8842#endif
8843 { BUILTIN_SPEC_REG "unset", unsetcmd },
8844 { BUILTIN_REGULAR "wait", waitcmd },
8845};
8846
Denis Vlasenko80591b02008-03-25 07:49:43 +00008847/* Should match the above table! */
8848#define COMMANDCMD (builtintab + \
8849 2 + \
8850 1 * ENABLE_ASH_BUILTIN_TEST + \
8851 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8852 1 * ENABLE_ASH_ALIAS + \
8853 1 * ENABLE_ASH_JOB_CONTROL + \
8854 3)
8855#define EXECCMD (builtintab + \
8856 2 + \
8857 1 * ENABLE_ASH_BUILTIN_TEST + \
8858 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8859 1 * ENABLE_ASH_ALIAS + \
8860 1 * ENABLE_ASH_JOB_CONTROL + \
8861 3 + \
8862 1 * ENABLE_ASH_CMDCMD + \
8863 1 + \
8864 ENABLE_ASH_BUILTIN_ECHO + \
8865 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008866
8867/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008868 * Search the table of builtin commands.
8869 */
8870static struct builtincmd *
8871find_builtin(const char *name)
8872{
8873 struct builtincmd *bp;
8874
8875 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008876 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008877 pstrcmp
8878 );
8879 return bp;
8880}
8881
8882/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008883 * Execute a simple command.
8884 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008885static int
8886isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008887{
8888 const char *q = endofname(p);
8889 if (p == q)
8890 return 0;
8891 return *q == '=';
8892}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008893static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008894bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008895{
8896 /* Preserve exitstatus of a previous possible redirection
8897 * as POSIX mandates */
8898 return back_exitstatus;
8899}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008900static void
Eric Andersenc470f442003-07-28 09:56:35 +00008901evalcommand(union node *cmd, int flags)
8902{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008903 static const struct builtincmd null_bltin = {
8904 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008905 };
Eric Andersenc470f442003-07-28 09:56:35 +00008906 struct stackmark smark;
8907 union node *argp;
8908 struct arglist arglist;
8909 struct arglist varlist;
8910 char **argv;
8911 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008912 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008913 struct cmdentry cmdentry;
8914 struct job *jp;
8915 char *lastarg;
8916 const char *path;
8917 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008918 int status;
8919 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008920 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008921 smallint cmd_is_exec;
8922 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008923
8924 /* First expand the arguments. */
8925 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8926 setstackmark(&smark);
8927 back_exitstatus = 0;
8928
8929 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008930 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008931 varlist.lastp = &varlist.list;
8932 *varlist.lastp = NULL;
8933 arglist.lastp = &arglist.list;
8934 *arglist.lastp = NULL;
8935
8936 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008937 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008938 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8939 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8940 }
8941
Eric Andersenc470f442003-07-28 09:56:35 +00008942 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8943 struct strlist **spp;
8944
8945 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008946 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008947 expandarg(argp, &arglist, EXP_VARTILDE);
8948 else
8949 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8950
Eric Andersenc470f442003-07-28 09:56:35 +00008951 for (sp = *spp; sp; sp = sp->next)
8952 argc++;
8953 }
8954
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008955 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008956 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008957 TRACE(("evalcommand arg: %s\n", sp->text));
8958 *nargv++ = sp->text;
8959 }
8960 *nargv = NULL;
8961
8962 lastarg = NULL;
8963 if (iflag && funcnest == 0 && argc > 0)
8964 lastarg = nargv[-1];
8965
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008966 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008967 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008968 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008969
8970 path = vpath.text;
8971 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8972 struct strlist **spp;
8973 char *p;
8974
8975 spp = varlist.lastp;
8976 expandarg(argp, &varlist, EXP_VARTILDE);
8977
8978 /*
8979 * Modify the command lookup path, if a PATH= assignment
8980 * is present
8981 */
8982 p = (*spp)->text;
8983 if (varequal(p, path))
8984 path = p;
8985 }
8986
8987 /* Print the command if xflag is set. */
8988 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008989 int n;
8990 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008991
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008992 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008993 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008994
8995 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008996 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008997 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008998 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008999 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009000 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009001 p--;
9002 }
9003 }
9004 sp = arglist.list;
9005 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009006 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009007 }
9008
9009 cmd_is_exec = 0;
9010 spclbltin = -1;
9011
9012 /* Now locate the command. */
9013 if (argc) {
9014 const char *oldpath;
9015 int cmd_flag = DO_ERR;
9016
9017 path += 5;
9018 oldpath = path;
9019 for (;;) {
9020 find_command(argv[0], &cmdentry, cmd_flag, path);
9021 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009022 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009023 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009024 goto bail;
9025 }
9026
9027 /* implement bltin and command here */
9028 if (cmdentry.cmdtype != CMDBUILTIN)
9029 break;
9030 if (spclbltin < 0)
9031 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9032 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009033 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009034#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009035 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009036 path = oldpath;
9037 nargv = parse_command_args(argv, &path);
9038 if (!nargv)
9039 break;
9040 argc -= nargv - argv;
9041 argv = nargv;
9042 cmd_flag |= DO_NOFUNC;
9043 } else
9044#endif
9045 break;
9046 }
9047 }
9048
9049 if (status) {
9050 /* We have a redirection error. */
9051 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009052 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009053 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009054 exitstatus = status;
9055 goto out;
9056 }
9057
9058 /* Execute the command. */
9059 switch (cmdentry.cmdtype) {
9060 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009061
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009062#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009063/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9064 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009065 {
9066 /* find_command() encodes applet_no as (-2 - applet_no) */
9067 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009068 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009069 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009070 /* run <applet>_main() */
9071 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009072 break;
9073 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009074 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009075#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009076 /* Fork off a child process if necessary. */
9077 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009078 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009079 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009080 if (forkshell(jp, cmd, FORK_FG) != 0) {
9081 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009082 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009083 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009084 break;
9085 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009086 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009087 }
9088 listsetvar(varlist.list, VEXPORT|VSTACK);
9089 shellexec(argv, path, cmdentry.u.index);
9090 /* NOTREACHED */
9091
9092 case CMDBUILTIN:
9093 cmdenviron = varlist.list;
9094 if (cmdenviron) {
9095 struct strlist *list = cmdenviron;
9096 int i = VNOSET;
9097 if (spclbltin > 0 || argc == 0) {
9098 i = 0;
9099 if (cmd_is_exec && argc > 1)
9100 i = VEXPORT;
9101 }
9102 listsetvar(list, i);
9103 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009104 /* Tight loop with builtins only:
9105 * "while kill -0 $child; do true; done"
9106 * will never exit even if $child died, unless we do this
9107 * to reap the zombie and make kill detect that it's gone: */
9108 dowait(DOWAIT_NONBLOCK, NULL);
9109
Eric Andersenc470f442003-07-28 09:56:35 +00009110 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9111 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009112 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009113 if (i == EXEXIT)
9114 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009115 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009116 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009117 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009118 if (i == EXSIG)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009119 exit_status = 128 + pendingsig;
Eric Andersenc470f442003-07-28 09:56:35 +00009120 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009121 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009122 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009123 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009124 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009125 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009126 }
9127 break;
9128
9129 case CMDFUNCTION:
9130 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009131 /* See above for the rationale */
9132 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009133 if (evalfun(cmdentry.u.func, argc, argv, flags))
9134 goto raise;
9135 break;
9136 }
9137
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009138 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009139 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009140 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009141 /* dsl: I think this is intended to be used to support
9142 * '_' in 'vi' command mode during line editing...
9143 * However I implemented that within libedit itself.
9144 */
9145 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009146 }
Eric Andersenc470f442003-07-28 09:56:35 +00009147 popstackmark(&smark);
9148}
9149
9150static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009151evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9152{
Eric Andersenc470f442003-07-28 09:56:35 +00009153 char *volatile savecmdname;
9154 struct jmploc *volatile savehandler;
9155 struct jmploc jmploc;
9156 int i;
9157
9158 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009159 i = setjmp(jmploc.loc);
9160 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009161 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009162 savehandler = exception_handler;
9163 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009164 commandname = argv[0];
9165 argptr = argv + 1;
9166 optptr = NULL; /* initialize nextopt */
9167 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009168 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009169 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009170 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009171 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009172 commandname = savecmdname;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009173// exsig = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009174 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009175
9176 return i;
9177}
9178
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009179static int
9180goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009181{
9182 return !*endofname(p);
9183}
9184
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009185
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009186/*
9187 * Search for a command. This is called before we fork so that the
9188 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009189 * the child. The check for "goodname" is an overly conservative
9190 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009191 */
Eric Andersenc470f442003-07-28 09:56:35 +00009192static void
9193prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009194{
9195 struct cmdentry entry;
9196
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009197 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9198 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009199}
9200
Eric Andersencb57d552001-06-28 07:25:16 +00009201
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009202/* ============ Builtin commands
9203 *
9204 * Builtin commands whose functions are closely tied to evaluation
9205 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009206 */
9207
9208/*
Eric Andersencb57d552001-06-28 07:25:16 +00009209 * Handle break and continue commands. Break, continue, and return are
9210 * all handled by setting the evalskip flag. The evaluation routines
9211 * above all check this flag, and if it is set they start skipping
9212 * commands rather than executing them. The variable skipcount is
9213 * the number of loops to break/continue, or the number of function
9214 * levels to return. (The latter is always 1.) It should probably
9215 * be an error to break out of more loops than exist, but it isn't
9216 * in the standard shell so we don't make it one here.
9217 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009218static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009219breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009220{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009221 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009222
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009223 if (n <= 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009224 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009225 if (n > loopnest)
9226 n = loopnest;
9227 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009228 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009229 skipcount = n;
9230 }
9231 return 0;
9232}
9233
Eric Andersenc470f442003-07-28 09:56:35 +00009234
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009235/* ============ input.c
9236 *
Eric Andersen90898442003-08-06 11:20:52 +00009237 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009238 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009239
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009240enum {
9241 INPUT_PUSH_FILE = 1,
9242 INPUT_NOFILE_OK = 2,
9243};
Eric Andersencb57d552001-06-28 07:25:16 +00009244
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009245static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009246/* values of checkkwd variable */
9247#define CHKALIAS 0x1
9248#define CHKKWD 0x2
9249#define CHKNL 0x4
9250
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009251/*
9252 * Push a string back onto the input at this current parsefile level.
9253 * We handle aliases this way.
9254 */
9255#if !ENABLE_ASH_ALIAS
9256#define pushstring(s, ap) pushstring(s)
9257#endif
9258static void
9259pushstring(char *s, struct alias *ap)
9260{
9261 struct strpush *sp;
9262 int len;
9263
9264 len = strlen(s);
9265 INT_OFF;
9266 if (g_parsefile->strpush) {
9267 sp = ckzalloc(sizeof(*sp));
9268 sp->prev = g_parsefile->strpush;
9269 } else {
9270 sp = &(g_parsefile->basestrpush);
9271 }
9272 g_parsefile->strpush = sp;
9273 sp->prev_string = g_parsefile->next_to_pgetc;
9274 sp->prev_left_in_line = g_parsefile->left_in_line;
9275#if ENABLE_ASH_ALIAS
9276 sp->ap = ap;
9277 if (ap) {
9278 ap->flag |= ALIASINUSE;
9279 sp->string = s;
9280 }
9281#endif
9282 g_parsefile->next_to_pgetc = s;
9283 g_parsefile->left_in_line = len;
9284 INT_ON;
9285}
9286
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009287static void
9288popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009289{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009290 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009291
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009292 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009293#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009294 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009295 if (g_parsefile->next_to_pgetc[-1] == ' '
9296 || g_parsefile->next_to_pgetc[-1] == '\t'
9297 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009298 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009299 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009300 if (sp->string != sp->ap->val) {
9301 free(sp->string);
9302 }
9303 sp->ap->flag &= ~ALIASINUSE;
9304 if (sp->ap->flag & ALIASDEAD) {
9305 unalias(sp->ap->name);
9306 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009307 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009308#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009309 g_parsefile->next_to_pgetc = sp->prev_string;
9310 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009311 g_parsefile->strpush = sp->prev;
9312 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009313 free(sp);
9314 INT_ON;
9315}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009316
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009317//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9318//it peeks whether it is &>, and then pushes back both chars.
9319//This function needs to save last *next_to_pgetc to buf[0]
9320//to make two pungetc() reliable. Currently,
9321// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009322static int
9323preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009324{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009325 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009326 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009327
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009328 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009329#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009330 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009331 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009332 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009333 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009334#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009335 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009336#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009337 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9338 if (nr == 0) {
9339 /* Ctrl+C pressed */
9340 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009341 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009342 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009343 raise(SIGINT);
9344 return 1;
9345 }
Eric Andersenc470f442003-07-28 09:56:35 +00009346 goto retry;
9347 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009348 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009349 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009350 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009351 }
Eric Andersencb57d552001-06-28 07:25:16 +00009352 }
9353#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009354 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009355#endif
9356
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009357#if 0
9358/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009359 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009360 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009361 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009362 if (flags >= 0 && (flags & O_NONBLOCK)) {
9363 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009364 if (fcntl(0, F_SETFL, flags) >= 0) {
9365 out2str("sh: turning off NDELAY mode\n");
9366 goto retry;
9367 }
9368 }
9369 }
9370 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009371#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009372 return nr;
9373}
9374
9375/*
9376 * Refill the input buffer and return the next input character:
9377 *
9378 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009379 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9380 * or we are reading from a string so we can't refill the buffer,
9381 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009382 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009383 * 4) Process input up to the next newline, deleting nul characters.
9384 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009385//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9386#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009387/*
9388 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9389 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9390 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9391 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9392 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009393static int
Eric Andersenc470f442003-07-28 09:56:35 +00009394preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009395{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009396 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009397 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009398
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009399 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009400#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009401 if (g_parsefile->left_in_line == -1
9402 && g_parsefile->strpush->ap
9403 && g_parsefile->next_to_pgetc[-1] != ' '
9404 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009405 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009406 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009407 return PEOA;
9408 }
Eric Andersen2870d962001-07-02 17:27:21 +00009409#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009410 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009411 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009412 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9413 g_parsefile->left_in_line,
9414 g_parsefile->next_to_pgetc,
9415 g_parsefile->next_to_pgetc);
9416 if (--g_parsefile->left_in_line >= 0)
9417 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009418 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009419 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009420 * "pgetc" needs refilling.
9421 */
9422
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009423 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009424 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009425 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009426 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009427 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009428 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009429 /* even in failure keep left_in_line and next_to_pgetc
9430 * in lock step, for correct multi-layer pungetc.
9431 * left_in_line was decremented before preadbuffer(),
9432 * must inc next_to_pgetc: */
9433 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009434 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009435 }
Eric Andersencb57d552001-06-28 07:25:16 +00009436
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009437 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009438 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009439 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009440 again:
9441 more = preadfd();
9442 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009443 /* don't try reading again */
9444 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009445 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009446 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009447 return PEOF;
9448 }
9449 }
9450
Denis Vlasenko727752d2008-11-28 03:41:47 +00009451 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009452 * Set g_parsefile->left_in_line
9453 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009454 * NUL chars are deleted.
9455 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009456 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009457 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009458 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009459
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009460 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009461
Denis Vlasenko727752d2008-11-28 03:41:47 +00009462 c = *q;
9463 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009464 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009465 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009466 q++;
9467 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009468 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009469 break;
9470 }
Eric Andersencb57d552001-06-28 07:25:16 +00009471 }
9472
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009473 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009474 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9475 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009476 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009477 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009478 }
9479 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009480 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009481
Eric Andersencb57d552001-06-28 07:25:16 +00009482 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009483 char save = *q;
9484 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009485 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009486 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009487 }
9488
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009489 pgetc_debug("preadbuffer at %d:%p'%s'",
9490 g_parsefile->left_in_line,
9491 g_parsefile->next_to_pgetc,
9492 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009493 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009494}
9495
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496#define pgetc_as_macro() \
9497 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009498 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009499 : preadbuffer() \
9500 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009501
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009502static int
9503pgetc(void)
9504{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009505 pgetc_debug("pgetc_fast at %d:%p'%s'",
9506 g_parsefile->left_in_line,
9507 g_parsefile->next_to_pgetc,
9508 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009509 return pgetc_as_macro();
9510}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009511
9512#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009513#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009514#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009515#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009516#endif
9517
9518/*
9519 * Same as pgetc(), but ignores PEOA.
9520 */
9521#if ENABLE_ASH_ALIAS
9522static int
9523pgetc2(void)
9524{
9525 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009526 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009527 pgetc_debug("pgetc_fast at %d:%p'%s'",
9528 g_parsefile->left_in_line,
9529 g_parsefile->next_to_pgetc,
9530 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009531 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009532 } while (c == PEOA);
9533 return c;
9534}
9535#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009536#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009537#endif
9538
9539/*
9540 * Read a line from the script.
9541 */
9542static char *
9543pfgets(char *line, int len)
9544{
9545 char *p = line;
9546 int nleft = len;
9547 int c;
9548
9549 while (--nleft > 0) {
9550 c = pgetc2();
9551 if (c == PEOF) {
9552 if (p == line)
9553 return NULL;
9554 break;
9555 }
9556 *p++ = c;
9557 if (c == '\n')
9558 break;
9559 }
9560 *p = '\0';
9561 return line;
9562}
9563
Eric Andersenc470f442003-07-28 09:56:35 +00009564/*
9565 * Undo the last call to pgetc. Only one character may be pushed back.
9566 * PEOF may be pushed back.
9567 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009568static void
Eric Andersenc470f442003-07-28 09:56:35 +00009569pungetc(void)
9570{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009571 g_parsefile->left_in_line++;
9572 g_parsefile->next_to_pgetc--;
9573 pgetc_debug("pushed back to %d:%p'%s'",
9574 g_parsefile->left_in_line,
9575 g_parsefile->next_to_pgetc,
9576 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009577}
9578
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009579/*
9580 * To handle the "." command, a stack of input files is used. Pushfile
9581 * adds a new entry to the stack and popfile restores the previous level.
9582 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009583static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009584pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009585{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009586 struct parsefile *pf;
9587
Denis Vlasenko597906c2008-02-20 16:38:54 +00009588 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009589 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009590 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009591 /*pf->strpush = NULL; - ckzalloc did it */
9592 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009593 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009594}
9595
9596static void
9597popfile(void)
9598{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009599 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009600
Denis Vlasenkob012b102007-02-19 22:43:01 +00009601 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009602 if (pf->fd >= 0)
9603 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009604 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009605 while (pf->strpush)
9606 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009607 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009608 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009609 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009610}
9611
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009612/*
9613 * Return to top level.
9614 */
9615static void
9616popallfiles(void)
9617{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009618 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009619 popfile();
9620}
9621
9622/*
9623 * Close the file(s) that the shell is reading commands from. Called
9624 * after a fork is done.
9625 */
9626static void
9627closescript(void)
9628{
9629 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009630 if (g_parsefile->fd > 0) {
9631 close(g_parsefile->fd);
9632 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009633 }
9634}
9635
9636/*
9637 * Like setinputfile, but takes an open file descriptor. Call this with
9638 * interrupts off.
9639 */
9640static void
9641setinputfd(int fd, int push)
9642{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009643 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009644 if (push) {
9645 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009646 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009647 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009648 g_parsefile->fd = fd;
9649 if (g_parsefile->buf == NULL)
9650 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009651 g_parsefile->left_in_buffer = 0;
9652 g_parsefile->left_in_line = 0;
9653 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009654}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009655
Eric Andersenc470f442003-07-28 09:56:35 +00009656/*
9657 * Set the input to take input from a file. If push is set, push the
9658 * old input onto the stack first.
9659 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009660static int
9661setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009662{
9663 int fd;
9664 int fd2;
9665
Denis Vlasenkob012b102007-02-19 22:43:01 +00009666 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009667 fd = open(fname, O_RDONLY);
9668 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009669 if (flags & INPUT_NOFILE_OK)
9670 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009671 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009672 }
Eric Andersenc470f442003-07-28 09:56:35 +00009673 if (fd < 10) {
9674 fd2 = copyfd(fd, 10);
9675 close(fd);
9676 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009677 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009678 fd = fd2;
9679 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009680 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009681 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009682 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009683 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009684}
9685
Eric Andersencb57d552001-06-28 07:25:16 +00009686/*
9687 * Like setinputfile, but takes input from a string.
9688 */
Eric Andersenc470f442003-07-28 09:56:35 +00009689static void
9690setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009691{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009692 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009693 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009694 g_parsefile->next_to_pgetc = string;
9695 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009696 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009697 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009698 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009699}
9700
9701
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009702/* ============ mail.c
9703 *
9704 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009705 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009706
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009707#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009708
Eric Andersencb57d552001-06-28 07:25:16 +00009709#define MAXMBOXES 10
9710
Eric Andersenc470f442003-07-28 09:56:35 +00009711/* times of mailboxes */
9712static time_t mailtime[MAXMBOXES];
9713/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009714static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009715
Eric Andersencb57d552001-06-28 07:25:16 +00009716/*
Eric Andersenc470f442003-07-28 09:56:35 +00009717 * Print appropriate message(s) if mail has arrived.
9718 * If mail_var_path_changed is set,
9719 * then the value of MAIL has mail_var_path_changed,
9720 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009721 */
Eric Andersenc470f442003-07-28 09:56:35 +00009722static void
9723chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009724{
Eric Andersencb57d552001-06-28 07:25:16 +00009725 const char *mpath;
9726 char *p;
9727 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009728 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009729 struct stackmark smark;
9730 struct stat statb;
9731
Eric Andersencb57d552001-06-28 07:25:16 +00009732 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009733 mpath = mpathset() ? mpathval() : mailval();
9734 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009735 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009736 if (p == NULL)
9737 break;
9738 if (*p == '\0')
9739 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009740 for (q = p; *q; q++)
9741 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009742#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009743 if (q[-1] != '/')
9744 abort();
9745#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009746 q[-1] = '\0'; /* delete trailing '/' */
9747 if (stat(p, &statb) < 0) {
9748 *mtp = 0;
9749 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009750 }
Eric Andersenc470f442003-07-28 09:56:35 +00009751 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9752 fprintf(
9753 stderr, snlfmt,
9754 pathopt ? pathopt : "you have mail"
9755 );
9756 }
9757 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009758 }
Eric Andersenc470f442003-07-28 09:56:35 +00009759 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009760 popstackmark(&smark);
9761}
Eric Andersencb57d552001-06-28 07:25:16 +00009762
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009763static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009764changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009765{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009766 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009767}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009768
Denis Vlasenko131ae172007-02-18 13:00:19 +00009769#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009770
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009771
9772/* ============ ??? */
9773
Eric Andersencb57d552001-06-28 07:25:16 +00009774/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009775 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009776 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009777static void
9778setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009779{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009780 char **newparam;
9781 char **ap;
9782 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009783
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009784 for (nparam = 0; argv[nparam]; nparam++)
9785 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009786 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9787 while (*argv) {
9788 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009789 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009790 *ap = NULL;
9791 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009792 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009793 shellparam.nparam = nparam;
9794 shellparam.p = newparam;
9795#if ENABLE_ASH_GETOPTS
9796 shellparam.optind = 1;
9797 shellparam.optoff = -1;
9798#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009799}
9800
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009801/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009802 * Process shell options. The global variable argptr contains a pointer
9803 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009804 *
9805 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9806 * For a non-interactive shell, an error condition encountered
9807 * by a special built-in ... shall cause the shell to write a diagnostic message
9808 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009809 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009810 * ...
9811 * Utility syntax error (option or operand error) Shall exit
9812 * ...
9813 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9814 * we see that bash does not do that (set "finishes" with error code 1 instead,
9815 * and shell continues), and people rely on this behavior!
9816 * Testcase:
9817 * set -o barfoo 2>/dev/null
9818 * echo $?
9819 *
9820 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009821 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009822static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009823plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009824{
9825 int i;
9826
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009827 if (name) {
9828 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009829 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009830 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009831 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009832 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009833 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009834 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009835 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009836 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009837 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009838 if (val) {
9839 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9840 } else {
9841 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9842 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009843 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009844 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009845}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009846static void
9847setoption(int flag, int val)
9848{
9849 int i;
9850
9851 for (i = 0; i < NOPTS; i++) {
9852 if (optletters(i) == flag) {
9853 optlist[i] = val;
9854 return;
9855 }
9856 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009857 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009858 /* NOTREACHED */
9859}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009860static int
Eric Andersenc470f442003-07-28 09:56:35 +00009861options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009862{
9863 char *p;
9864 int val;
9865 int c;
9866
9867 if (cmdline)
9868 minusc = NULL;
9869 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009870 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009871 if (c != '-' && c != '+')
9872 break;
9873 argptr++;
9874 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009875 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009876 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009877 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009878 if (!cmdline) {
9879 /* "-" means turn off -x and -v */
9880 if (p[0] == '\0')
9881 xflag = vflag = 0;
9882 /* "--" means reset params */
9883 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009884 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009885 }
Eric Andersenc470f442003-07-28 09:56:35 +00009886 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009887 }
Eric Andersencb57d552001-06-28 07:25:16 +00009888 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009889 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009890 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009891 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009892 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009893 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009894 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009895 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009896 /* it already printed err message */
9897 return 1; /* error */
9898 }
Eric Andersencb57d552001-06-28 07:25:16 +00009899 if (*argptr)
9900 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009901 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9902 isloginsh = 1;
9903 /* bash does not accept +-login, we also won't */
9904 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009905 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009906 isloginsh = 1;
9907 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009908 } else {
9909 setoption(c, val);
9910 }
9911 }
9912 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009913 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009914}
9915
Eric Andersencb57d552001-06-28 07:25:16 +00009916/*
Eric Andersencb57d552001-06-28 07:25:16 +00009917 * The shift builtin command.
9918 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009919static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009920shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009921{
9922 int n;
9923 char **ap1, **ap2;
9924
9925 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009926 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009927 n = number(argv[1]);
9928 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009929 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009930 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009931 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009932 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009933 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009934 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009935 }
9936 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009937 while ((*ap2++ = *ap1++) != NULL)
9938 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009939#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009940 shellparam.optind = 1;
9941 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009942#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009943 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009944 return 0;
9945}
9946
Eric Andersencb57d552001-06-28 07:25:16 +00009947/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009948 * POSIX requires that 'set' (but not export or readonly) output the
9949 * variables in lexicographic order - by the locale's collating order (sigh).
9950 * Maybe we could keep them in an ordered balanced binary tree
9951 * instead of hashed lists.
9952 * For now just roll 'em through qsort for printing...
9953 */
9954static int
9955showvars(const char *sep_prefix, int on, int off)
9956{
9957 const char *sep;
9958 char **ep, **epend;
9959
9960 ep = listvars(on, off, &epend);
9961 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9962
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009963 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009964
9965 for (; ep < epend; ep++) {
9966 const char *p;
9967 const char *q;
9968
9969 p = strchrnul(*ep, '=');
9970 q = nullstr;
9971 if (*p)
9972 q = single_quote(++p);
9973 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9974 }
9975 return 0;
9976}
9977
9978/*
Eric Andersencb57d552001-06-28 07:25:16 +00009979 * The set command builtin.
9980 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009981static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009982setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00009983{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009984 int retval;
9985
Denis Vlasenko68404f12008-03-17 09:00:54 +00009986 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +00009987 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009988 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009989 retval = 1;
9990 if (!options(0)) { /* if no parse error... */
9991 retval = 0;
9992 optschanged();
9993 if (*argptr != NULL) {
9994 setparam(argptr);
9995 }
Eric Andersencb57d552001-06-28 07:25:16 +00009996 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009997 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009998 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009999}
10000
Denis Vlasenko131ae172007-02-18 13:00:19 +000010001#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010002static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010003change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010004{
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010005 /* Galois LFSR parameter */
10006 /* Taps at 32 31 29 1: */
10007 enum { MASK = 0x8000000b };
10008 /* Another example - taps at 32 31 30 10: */
10009 /* MASK = 0x00400007 */
10010
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010011 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010012 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010013 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010014
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010015 /* LCG has period of 2^32 and alternating lowest bit */
10016 random_LCG = 1664525 * random_LCG + 1013904223;
10017 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10018 t = (random_galois_LFSR << 1);
10019 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10020 t ^= MASK;
10021 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010022 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010023 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010024 * for $RANDOM range. Combining with subtraction is
10025 * just for fun. + and ^ would work equally well. */
10026 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010027 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010028 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010029 vrandom.flags &= ~VNOFUNC;
10030 } else {
10031 /* set/reset */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010032 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010033 }
Eric Andersenef02f822004-03-11 13:34:24 +000010034}
Eric Andersen16767e22004-03-16 05:14:10 +000010035#endif
10036
Denis Vlasenko131ae172007-02-18 13:00:19 +000010037#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010038static int
Eric Andersenc470f442003-07-28 09:56:35 +000010039getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010040{
10041 char *p, *q;
10042 char c = '?';
10043 int done = 0;
10044 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010045 char s[12];
10046 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010047
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010048 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010049 return 1;
10050 optnext = optfirst + *param_optind - 1;
10051
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010052 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010053 p = NULL;
10054 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010055 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010056 if (p == NULL || *p == '\0') {
10057 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010058 p = *optnext;
10059 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010060 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010061 p = NULL;
10062 done = 1;
10063 goto out;
10064 }
10065 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010066 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010067 goto atend;
10068 }
10069
10070 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010071 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010072 if (*q == '\0') {
10073 if (optstr[0] == ':') {
10074 s[0] = c;
10075 s[1] = '\0';
10076 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010077 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010078 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010079 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010080 }
10081 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010082 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010083 }
10084 if (*++q == ':')
10085 q++;
10086 }
10087
10088 if (*++q == ':') {
10089 if (*p == '\0' && (p = *optnext) == NULL) {
10090 if (optstr[0] == ':') {
10091 s[0] = c;
10092 s[1] = '\0';
10093 err |= setvarsafe("OPTARG", s, 0);
10094 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010095 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010096 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010097 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010098 c = '?';
10099 }
Eric Andersenc470f442003-07-28 09:56:35 +000010100 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010101 }
10102
10103 if (p == *optnext)
10104 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010105 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010106 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010107 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010108 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010109 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010110 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010111 *param_optind = optnext - optfirst + 1;
10112 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010113 err |= setvarsafe("OPTIND", s, VNOFUNC);
10114 s[0] = c;
10115 s[1] = '\0';
10116 err |= setvarsafe(optvar, s, 0);
10117 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010118 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010119 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010120 flush_stdout_stderr();
10121 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010122 }
10123 return done;
10124}
Eric Andersenc470f442003-07-28 09:56:35 +000010125
10126/*
10127 * The getopts builtin. Shellparam.optnext points to the next argument
10128 * to be processed. Shellparam.optptr points to the next character to
10129 * be processed in the current argument. If shellparam.optnext is NULL,
10130 * then it's the first time getopts has been called.
10131 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010132static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010133getoptscmd(int argc, char **argv)
10134{
10135 char **optbase;
10136
10137 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010138 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010139 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010140 optbase = shellparam.p;
10141 if (shellparam.optind > shellparam.nparam + 1) {
10142 shellparam.optind = 1;
10143 shellparam.optoff = -1;
10144 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010145 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010146 optbase = &argv[3];
10147 if (shellparam.optind > argc - 2) {
10148 shellparam.optind = 1;
10149 shellparam.optoff = -1;
10150 }
10151 }
10152
10153 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010154 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010155}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010156#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010157
Eric Andersencb57d552001-06-28 07:25:16 +000010158
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010159/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010160
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010161struct heredoc {
10162 struct heredoc *next; /* next here document in list */
10163 union node *here; /* redirection node */
10164 char *eofmark; /* string indicating end of input */
10165 smallint striptabs; /* if set, strip leading tabs */
10166};
10167
10168static smallint tokpushback; /* last token pushed back */
10169static smallint parsebackquote; /* nonzero if we are inside backquotes */
10170static smallint quoteflag; /* set if (part of) last token was quoted */
10171static token_id_t lasttoken; /* last token read (integer id Txxx) */
10172static struct heredoc *heredoclist; /* list of here documents to read */
10173static char *wordtext; /* text of last word returned by readtoken */
10174static struct nodelist *backquotelist;
10175static union node *redirnode;
10176static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010177
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010178/*
10179 * Called when an unexpected token is read during the parse. The argument
10180 * is the token that is expected, or -1 if more than one type of token can
10181 * occur at this point.
10182 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010183static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010184static void
10185raise_error_unexpected_syntax(int token)
10186{
10187 char msg[64];
10188 int l;
10189
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010190 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010191 if (token >= 0)
10192 sprintf(msg + l, " (expecting %s)", tokname(token));
10193 raise_error_syntax(msg);
10194 /* NOTREACHED */
10195}
Eric Andersencb57d552001-06-28 07:25:16 +000010196
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010197#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010198
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010199/* parsing is heavily cross-recursive, need these forward decls */
10200static union node *andor(void);
10201static union node *pipeline(void);
10202static union node *parse_command(void);
10203static void parseheredoc(void);
10204static char peektoken(void);
10205static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010206
Eric Andersenc470f442003-07-28 09:56:35 +000010207static union node *
10208list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010209{
10210 union node *n1, *n2, *n3;
10211 int tok;
10212
Eric Andersenc470f442003-07-28 09:56:35 +000010213 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10214 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010215 return NULL;
10216 n1 = NULL;
10217 for (;;) {
10218 n2 = andor();
10219 tok = readtoken();
10220 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010221 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010222 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010223 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010224 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010225 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010226 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010227 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010228 n2 = n3;
10229 }
10230 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010231 }
10232 }
10233 if (n1 == NULL) {
10234 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010235 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010236 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010237 n3->type = NSEMI;
10238 n3->nbinary.ch1 = n1;
10239 n3->nbinary.ch2 = n2;
10240 n1 = n3;
10241 }
10242 switch (tok) {
10243 case TBACKGND:
10244 case TSEMI:
10245 tok = readtoken();
10246 /* fall through */
10247 case TNL:
10248 if (tok == TNL) {
10249 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010250 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010251 return n1;
10252 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010253 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010254 }
Eric Andersenc470f442003-07-28 09:56:35 +000010255 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010256 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010257 return n1;
10258 break;
10259 case TEOF:
10260 if (heredoclist)
10261 parseheredoc();
10262 else
Eric Andersenc470f442003-07-28 09:56:35 +000010263 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010264 return n1;
10265 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010266 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010267 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010268 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010269 return n1;
10270 }
10271 }
10272}
10273
Eric Andersenc470f442003-07-28 09:56:35 +000010274static union node *
10275andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010276{
Eric Andersencb57d552001-06-28 07:25:16 +000010277 union node *n1, *n2, *n3;
10278 int t;
10279
Eric Andersencb57d552001-06-28 07:25:16 +000010280 n1 = pipeline();
10281 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010282 t = readtoken();
10283 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010284 t = NAND;
10285 } else if (t == TOR) {
10286 t = NOR;
10287 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010288 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010289 return n1;
10290 }
Eric Andersenc470f442003-07-28 09:56:35 +000010291 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010292 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010293 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010294 n3->type = t;
10295 n3->nbinary.ch1 = n1;
10296 n3->nbinary.ch2 = n2;
10297 n1 = n3;
10298 }
10299}
10300
Eric Andersenc470f442003-07-28 09:56:35 +000010301static union node *
10302pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010303{
Eric Andersencb57d552001-06-28 07:25:16 +000010304 union node *n1, *n2, *pipenode;
10305 struct nodelist *lp, *prev;
10306 int negate;
10307
10308 negate = 0;
10309 TRACE(("pipeline: entered\n"));
10310 if (readtoken() == TNOT) {
10311 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010312 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010313 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010314 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010315 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010316 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010317 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010318 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010319 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010320 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010321 pipenode->npipe.cmdlist = lp;
10322 lp->n = n1;
10323 do {
10324 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010325 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010326 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010327 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010328 prev->next = lp;
10329 } while (readtoken() == TPIPE);
10330 lp->next = NULL;
10331 n1 = pipenode;
10332 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010333 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010334 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010335 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010336 n2->type = NNOT;
10337 n2->nnot.com = n1;
10338 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010339 }
10340 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010341}
10342
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010343static union node *
10344makename(void)
10345{
10346 union node *n;
10347
Denis Vlasenko597906c2008-02-20 16:38:54 +000010348 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010349 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010350 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010351 n->narg.text = wordtext;
10352 n->narg.backquote = backquotelist;
10353 return n;
10354}
10355
10356static void
10357fixredir(union node *n, const char *text, int err)
10358{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010359 int fd;
10360
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010361 TRACE(("Fix redir %s %d\n", text, err));
10362 if (!err)
10363 n->ndup.vname = NULL;
10364
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010365 fd = bb_strtou(text, NULL, 10);
10366 if (!errno && fd >= 0)
10367 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010368 else if (LONE_DASH(text))
10369 n->ndup.dupfd = -1;
10370 else {
10371 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010372 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010373 n->ndup.vname = makename();
10374 }
10375}
10376
10377/*
10378 * Returns true if the text contains nothing to expand (no dollar signs
10379 * or backquotes).
10380 */
10381static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010382noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010383{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010384 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010385 char c;
10386
10387 p = text;
10388 while ((c = *p++) != '\0') {
10389 if (c == CTLQUOTEMARK)
10390 continue;
10391 if (c == CTLESC)
10392 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010393 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010394 return 0;
10395 }
10396 return 1;
10397}
10398
10399static void
10400parsefname(void)
10401{
10402 union node *n = redirnode;
10403
10404 if (readtoken() != TWORD)
10405 raise_error_unexpected_syntax(-1);
10406 if (n->type == NHERE) {
10407 struct heredoc *here = heredoc;
10408 struct heredoc *p;
10409 int i;
10410
10411 if (quoteflag == 0)
10412 n->type = NXHERE;
10413 TRACE(("Here document %d\n", n->type));
10414 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010415 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010416 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010417 here->eofmark = wordtext;
10418 here->next = NULL;
10419 if (heredoclist == NULL)
10420 heredoclist = here;
10421 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010422 for (p = heredoclist; p->next; p = p->next)
10423 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424 p->next = here;
10425 }
10426 } else if (n->type == NTOFD || n->type == NFROMFD) {
10427 fixredir(n, wordtext, 0);
10428 } else {
10429 n->nfile.fname = makename();
10430 }
10431}
Eric Andersencb57d552001-06-28 07:25:16 +000010432
Eric Andersenc470f442003-07-28 09:56:35 +000010433static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010434simplecmd(void)
10435{
10436 union node *args, **app;
10437 union node *n = NULL;
10438 union node *vars, **vpp;
10439 union node **rpp, *redir;
10440 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010441#if ENABLE_ASH_BASH_COMPAT
10442 smallint double_brackets_flag = 0;
10443#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010444
10445 args = NULL;
10446 app = &args;
10447 vars = NULL;
10448 vpp = &vars;
10449 redir = NULL;
10450 rpp = &redir;
10451
10452 savecheckkwd = CHKALIAS;
10453 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010454 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010455 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010456 t = readtoken();
10457 switch (t) {
10458#if ENABLE_ASH_BASH_COMPAT
10459 case TAND: /* "&&" */
10460 case TOR: /* "||" */
10461 if (!double_brackets_flag) {
10462 tokpushback = 1;
10463 goto out;
10464 }
10465 wordtext = (char *) (t == TAND ? "-a" : "-o");
10466#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010467 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010468 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010469 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010470 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010471 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010472#if ENABLE_ASH_BASH_COMPAT
10473 if (strcmp("[[", wordtext) == 0)
10474 double_brackets_flag = 1;
10475 else if (strcmp("]]", wordtext) == 0)
10476 double_brackets_flag = 0;
10477#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010478 n->narg.backquote = backquotelist;
10479 if (savecheckkwd && isassignment(wordtext)) {
10480 *vpp = n;
10481 vpp = &n->narg.next;
10482 } else {
10483 *app = n;
10484 app = &n->narg.next;
10485 savecheckkwd = 0;
10486 }
10487 break;
10488 case TREDIR:
10489 *rpp = n = redirnode;
10490 rpp = &n->nfile.next;
10491 parsefname(); /* read name of redirection file */
10492 break;
10493 case TLP:
10494 if (args && app == &args->narg.next
10495 && !vars && !redir
10496 ) {
10497 struct builtincmd *bcmd;
10498 const char *name;
10499
10500 /* We have a function */
10501 if (readtoken() != TRP)
10502 raise_error_unexpected_syntax(TRP);
10503 name = n->narg.text;
10504 if (!goodname(name)
10505 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10506 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010507 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010508 }
10509 n->type = NDEFUN;
10510 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10511 n->narg.next = parse_command();
10512 return n;
10513 }
10514 /* fall through */
10515 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010516 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010517 goto out;
10518 }
10519 }
10520 out:
10521 *app = NULL;
10522 *vpp = NULL;
10523 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010524 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010525 n->type = NCMD;
10526 n->ncmd.args = args;
10527 n->ncmd.assign = vars;
10528 n->ncmd.redirect = redir;
10529 return n;
10530}
10531
10532static union node *
10533parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010534{
Eric Andersencb57d552001-06-28 07:25:16 +000010535 union node *n1, *n2;
10536 union node *ap, **app;
10537 union node *cp, **cpp;
10538 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010539 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010540 int t;
10541
10542 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010543 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010544
Eric Andersencb57d552001-06-28 07:25:16 +000010545 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010546 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010547 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010548 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010549 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010550 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010551 n1->type = NIF;
10552 n1->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 n1->nif.ifpart = list(0);
10556 n2 = n1;
10557 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010558 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010559 n2 = n2->nif.elsepart;
10560 n2->type = NIF;
10561 n2->nif.test = list(0);
10562 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010563 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010564 n2->nif.ifpart = list(0);
10565 }
10566 if (lasttoken == TELSE)
10567 n2->nif.elsepart = list(0);
10568 else {
10569 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010570 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010571 }
Eric Andersenc470f442003-07-28 09:56:35 +000010572 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010573 break;
10574 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010575 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010576 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010577 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010578 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010579 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010580 got = readtoken();
10581 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010582 TRACE(("expecting DO got %s %s\n", tokname(got),
10583 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010584 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010585 }
10586 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010587 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010588 break;
10589 }
10590 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010591 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010592 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010593 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010594 n1->type = NFOR;
10595 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010596 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010597 if (readtoken() == TIN) {
10598 app = &ap;
10599 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010600 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010601 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010602 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010603 n2->narg.text = wordtext;
10604 n2->narg.backquote = backquotelist;
10605 *app = n2;
10606 app = &n2->narg.next;
10607 }
10608 *app = NULL;
10609 n1->nfor.args = ap;
10610 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010611 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010612 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010613 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010614 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010615 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010616 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010617 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n1->nfor.args = n2;
10619 /*
10620 * Newline or semicolon here is optional (but note
10621 * that the original Bourne shell only allowed NL).
10622 */
10623 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010624 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010625 }
Eric Andersenc470f442003-07-28 09:56:35 +000010626 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010627 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010628 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010629 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010630 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010631 break;
10632 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010633 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010634 n1->type = NCASE;
10635 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010636 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010637 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010638 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010639 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010640 n2->narg.text = wordtext;
10641 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010642 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010643 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010644 } while (readtoken() == TNL);
10645 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010646 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010647 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010648 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010649 checkkwd = CHKNL | CHKKWD;
10650 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010651 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010652 if (lasttoken == TLP)
10653 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010654 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010655 cp->type = NCLIST;
10656 app = &cp->nclist.pattern;
10657 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010658 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010659 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010660 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010661 ap->narg.text = wordtext;
10662 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010663 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010664 break;
10665 app = &ap->narg.next;
10666 readtoken();
10667 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010668 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010669 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010670 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010671 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010672
Eric Andersenc470f442003-07-28 09:56:35 +000010673 cpp = &cp->nclist.next;
10674
10675 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010676 t = readtoken();
10677 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010678 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010679 raise_error_unexpected_syntax(TENDCASE);
10680 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010681 }
Eric Andersenc470f442003-07-28 09:56:35 +000010682 }
Eric Andersencb57d552001-06-28 07:25:16 +000010683 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010684 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010685 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010686 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010687 n1->type = NSUBSHELL;
10688 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010689 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010690 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010691 break;
10692 case TBEGIN:
10693 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010694 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010695 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010696 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010697 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010698 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010699 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010700 }
10701
Eric Andersenc470f442003-07-28 09:56:35 +000010702 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010703 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010704
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010705 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010706 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010707 checkkwd = CHKKWD | CHKALIAS;
10708 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 while (readtoken() == TREDIR) {
10710 *rpp = n2 = redirnode;
10711 rpp = &n2->nfile.next;
10712 parsefname();
10713 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010714 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010715 *rpp = NULL;
10716 if (redir) {
10717 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010718 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010719 n2->type = NREDIR;
10720 n2->nredir.n = n1;
10721 n1 = n2;
10722 }
10723 n1->nredir.redirect = redir;
10724 }
Eric Andersencb57d552001-06-28 07:25:16 +000010725 return n1;
10726}
10727
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010728#if ENABLE_ASH_BASH_COMPAT
10729static int decode_dollar_squote(void)
10730{
10731 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10732 int c, cnt;
10733 char *p;
10734 char buf[4];
10735
10736 c = pgetc();
10737 p = strchr(C_escapes, c);
10738 if (p) {
10739 buf[0] = c;
10740 p = buf;
10741 cnt = 3;
10742 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10743 do {
10744 c = pgetc();
10745 *++p = c;
10746 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10747 pungetc();
10748 } else if (c == 'x') { /* \xHH */
10749 do {
10750 c = pgetc();
10751 *++p = c;
10752 } while (isxdigit(c) && --cnt);
10753 pungetc();
10754 if (cnt == 3) { /* \x but next char is "bad" */
10755 c = 'x';
10756 goto unrecognized;
10757 }
10758 } else { /* simple seq like \\ or \t */
10759 p++;
10760 }
10761 *p = '\0';
10762 p = buf;
10763 c = bb_process_escape_sequence((void*)&p);
10764 } else { /* unrecognized "\z": print both chars unless ' or " */
10765 if (c != '\'' && c != '"') {
10766 unrecognized:
10767 c |= 0x100; /* "please encode \, then me" */
10768 }
10769 }
10770 return c;
10771}
10772#endif
10773
Eric Andersencb57d552001-06-28 07:25:16 +000010774/*
10775 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10776 * is not NULL, read a here document. In the latter case, eofmark is the
10777 * word which marks the end of the document and striptabs is true if
10778 * leading tabs should be stripped from the document. The argument firstc
10779 * is the first character of the input token or document.
10780 *
10781 * Because C does not have internal subroutines, I have simulated them
10782 * using goto's to implement the subroutine linkage. The following macros
10783 * will run code that appears at the end of readtoken1.
10784 */
Eric Andersen2870d962001-07-02 17:27:21 +000010785#define CHECKEND() {goto checkend; checkend_return:;}
10786#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10787#define PARSESUB() {goto parsesub; parsesub_return:;}
10788#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10789#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10790#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010791static int
Eric Andersenc470f442003-07-28 09:56:35 +000010792readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010793{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010794 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010795 int c = firstc;
10796 char *out;
10797 int len;
10798 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010799 struct nodelist *bqlist;
10800 smallint quotef;
10801 smallint dblquote;
10802 smallint oldstyle;
10803 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010804#if ENABLE_ASH_EXPAND_PRMT
10805 smallint pssyntax; /* we are expanding a prompt string */
10806#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010807 int varnest; /* levels of variables expansion */
10808 int arinest; /* levels of arithmetic expansion */
10809 int parenlevel; /* levels of parens in arithmetic */
10810 int dqvarnest; /* levels of variables expansion within double quotes */
10811
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010812 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010813
Eric Andersencb57d552001-06-28 07:25:16 +000010814#if __GNUC__
10815 /* Avoid longjmp clobbering */
10816 (void) &out;
10817 (void) &quotef;
10818 (void) &dblquote;
10819 (void) &varnest;
10820 (void) &arinest;
10821 (void) &parenlevel;
10822 (void) &dqvarnest;
10823 (void) &oldstyle;
10824 (void) &prevsyntax;
10825 (void) &syntax;
10826#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010827 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010828 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010829 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010830 oldstyle = 0;
10831 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010832#if ENABLE_ASH_EXPAND_PRMT
10833 pssyntax = (syntax == PSSYNTAX);
10834 if (pssyntax)
10835 syntax = DQSYNTAX;
10836#endif
10837 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010838 varnest = 0;
10839 arinest = 0;
10840 parenlevel = 0;
10841 dqvarnest = 0;
10842
10843 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010844 loop:
10845 /* For each line, until end of word */
10846 {
Eric Andersenc470f442003-07-28 09:56:35 +000010847 CHECKEND(); /* set c to PEOF if at end of here document */
10848 for (;;) { /* until end of line or end of word */
10849 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010850 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010851 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010852 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010853 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010854 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010855 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010856 if (doprompt)
10857 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010858 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010859 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010860 case CWORD:
10861 USTPUTC(c, out);
10862 break;
10863 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010864 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010865 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010866#if ENABLE_ASH_BASH_COMPAT
10867 if (c == '\\' && bash_dollar_squote) {
10868 c = decode_dollar_squote();
10869 if (c & 0x100) {
10870 USTPUTC('\\', out);
10871 c = (unsigned char)c;
10872 }
10873 }
10874#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010875 USTPUTC(c, out);
10876 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010877 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010878 c = pgetc2();
10879 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010880 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010881 USTPUTC('\\', out);
10882 pungetc();
10883 } else if (c == '\n') {
10884 if (doprompt)
10885 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010886 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010887#if ENABLE_ASH_EXPAND_PRMT
10888 if (c == '$' && pssyntax) {
10889 USTPUTC(CTLESC, out);
10890 USTPUTC('\\', out);
10891 }
10892#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010893 if (dblquote && c != '\\'
10894 && c != '`' && c != '$'
10895 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010896 ) {
10897 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010898 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010899 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010900 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010901 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010902 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010903 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010904 }
10905 break;
10906 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010907 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010908 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010909 if (eofmark == NULL) {
10910 USTPUTC(CTLQUOTEMARK, out);
10911 }
Eric Andersencb57d552001-06-28 07:25:16 +000010912 break;
10913 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010914 syntax = DQSYNTAX;
10915 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010916 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010917 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010918 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010919 if (eofmark != NULL && arinest == 0
10920 && varnest == 0
10921 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010922 USTPUTC(c, out);
10923 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010924 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010925 syntax = BASESYNTAX;
10926 dblquote = 0;
10927 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010928 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010929 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010930 }
10931 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010932 case CVAR: /* '$' */
10933 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010934 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010935 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010936 if (varnest > 0) {
10937 varnest--;
10938 if (dqvarnest > 0) {
10939 dqvarnest--;
10940 }
10941 USTPUTC(CTLENDVAR, out);
10942 } else {
10943 USTPUTC(c, out);
10944 }
10945 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010946#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010947 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010948 parenlevel++;
10949 USTPUTC(c, out);
10950 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010951 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010952 if (parenlevel > 0) {
10953 USTPUTC(c, out);
10954 --parenlevel;
10955 } else {
10956 if (pgetc() == ')') {
10957 if (--arinest == 0) {
10958 USTPUTC(CTLENDARI, out);
10959 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010960 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010961 } else
10962 USTPUTC(')', out);
10963 } else {
10964 /*
10965 * unbalanced parens
10966 * (don't 2nd guess - no error)
10967 */
10968 pungetc();
10969 USTPUTC(')', out);
10970 }
10971 }
10972 break;
10973#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010974 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010975 PARSEBACKQOLD();
10976 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010977 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010978 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010979 case CIGN:
10980 break;
10981 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000010982 if (varnest == 0) {
10983#if ENABLE_ASH_BASH_COMPAT
10984 if (c == '&') {
10985 if (pgetc() == '>')
10986 c = 0x100 + '>'; /* flag &> */
10987 pungetc();
10988 }
10989#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010990 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000010991 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000010992#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010993 if (c != PEOA)
10994#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010995 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010996
Eric Andersencb57d552001-06-28 07:25:16 +000010997 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000010998 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010999 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011000 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011001 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011002#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011003 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011004 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011005#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011006 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011007 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011008 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011009 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011010 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011011 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011012 }
11013 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011014 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011015 out = stackblock();
11016 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011017 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011018 && quotef == 0
11019 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011020 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011021 PARSEREDIR(); /* passed as params: out, c */
11022 lasttoken = TREDIR;
11023 return lasttoken;
11024 }
11025 /* else: non-number X seen, interpret it
11026 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011027 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011028 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011029 }
11030 quoteflag = quotef;
11031 backquotelist = bqlist;
11032 grabstackblock(len);
11033 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011034 lasttoken = TWORD;
11035 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011036/* end of readtoken routine */
11037
Eric Andersencb57d552001-06-28 07:25:16 +000011038/*
11039 * Check to see whether we are at the end of the here document. When this
11040 * is called, c is set to the first character of the next input line. If
11041 * we are at the end of the here document, this routine sets the c to PEOF.
11042 */
Eric Andersenc470f442003-07-28 09:56:35 +000011043checkend: {
11044 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011045#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011046 if (c == PEOA) {
11047 c = pgetc2();
11048 }
11049#endif
11050 if (striptabs) {
11051 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011052 c = pgetc2();
11053 }
Eric Andersenc470f442003-07-28 09:56:35 +000011054 }
11055 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011056 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011057 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011058
Eric Andersenc470f442003-07-28 09:56:35 +000011059 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011060 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11061 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011062 if (*p == '\n' && *q == '\0') {
11063 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011064 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011065 needprompt = doprompt;
11066 } else {
11067 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011068 }
11069 }
11070 }
11071 }
Eric Andersenc470f442003-07-28 09:56:35 +000011072 goto checkend_return;
11073}
Eric Andersencb57d552001-06-28 07:25:16 +000011074
Eric Andersencb57d552001-06-28 07:25:16 +000011075/*
11076 * Parse a redirection operator. The variable "out" points to a string
11077 * specifying the fd to be redirected. The variable "c" contains the
11078 * first character of the redirection operator.
11079 */
Eric Andersenc470f442003-07-28 09:56:35 +000011080parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011081 /* out is already checked to be a valid number or "" */
11082 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011083 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011084
Denis Vlasenko597906c2008-02-20 16:38:54 +000011085 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011086 if (c == '>') {
11087 np->nfile.fd = 1;
11088 c = pgetc();
11089 if (c == '>')
11090 np->type = NAPPEND;
11091 else if (c == '|')
11092 np->type = NCLOBBER;
11093 else if (c == '&')
11094 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011095 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011096 else {
11097 np->type = NTO;
11098 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011099 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011100 }
11101#if ENABLE_ASH_BASH_COMPAT
11102 else if (c == 0x100 + '>') { /* this flags &> redirection */
11103 np->nfile.fd = 1;
11104 pgetc(); /* this is '>', no need to check */
11105 np->type = NTO2;
11106 }
11107#endif
11108 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011109 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011110 c = pgetc();
11111 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011112 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011113 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011114 np = stzalloc(sizeof(struct nhere));
11115 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011116 }
11117 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011118 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011119 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011120 c = pgetc();
11121 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011122 heredoc->striptabs = 1;
11123 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011124 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011125 pungetc();
11126 }
11127 break;
11128
11129 case '&':
11130 np->type = NFROMFD;
11131 break;
11132
11133 case '>':
11134 np->type = NFROMTO;
11135 break;
11136
11137 default:
11138 np->type = NFROM;
11139 pungetc();
11140 break;
11141 }
Eric Andersencb57d552001-06-28 07:25:16 +000011142 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011143 if (fd >= 0)
11144 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011145 redirnode = np;
11146 goto parseredir_return;
11147}
Eric Andersencb57d552001-06-28 07:25:16 +000011148
Eric Andersencb57d552001-06-28 07:25:16 +000011149/*
11150 * Parse a substitution. At this point, we have read the dollar sign
11151 * and nothing else.
11152 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011153
11154/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11155 * (assuming ascii char codes, as the original implementation did) */
11156#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011157 (((unsigned)(c) - 33 < 32) \
11158 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011159parsesub: {
11160 int subtype;
11161 int typeloc;
11162 int flags;
11163 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011164 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011165
Eric Andersenc470f442003-07-28 09:56:35 +000011166 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011167 if (c <= PEOA_OR_PEOF
11168 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011169 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011170#if ENABLE_ASH_BASH_COMPAT
11171 if (c == '\'')
11172 bash_dollar_squote = 1;
11173 else
11174#endif
11175 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011176 pungetc();
11177 } else if (c == '(') { /* $(command) or $((arith)) */
11178 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011179#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011180 PARSEARITH();
11181#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011182 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011183#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011184 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011185 pungetc();
11186 PARSEBACKQNEW();
11187 }
11188 } else {
11189 USTPUTC(CTLVAR, out);
11190 typeloc = out - (char *)stackblock();
11191 USTPUTC(VSNORMAL, out);
11192 subtype = VSNORMAL;
11193 if (c == '{') {
11194 c = pgetc();
11195 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011196 c = pgetc();
11197 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011198 c = '#';
11199 else
11200 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011201 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011202 subtype = 0;
11203 }
11204 if (c > PEOA_OR_PEOF && is_name(c)) {
11205 do {
11206 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011207 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011208 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011209 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011210 do {
11211 STPUTC(c, out);
11212 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011213 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011214 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011215 USTPUTC(c, out);
11216 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011217 } else {
11218 badsub:
11219 raise_error_syntax("bad substitution");
11220 }
Eric Andersencb57d552001-06-28 07:25:16 +000011221
Eric Andersenc470f442003-07-28 09:56:35 +000011222 STPUTC('=', out);
11223 flags = 0;
11224 if (subtype == 0) {
11225 switch (c) {
11226 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011227 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011228#if ENABLE_ASH_BASH_COMPAT
11229 if (c == ':' || c == '$' || isdigit(c)) {
11230 pungetc();
11231 subtype = VSSUBSTR;
11232 break;
11233 }
11234#endif
11235 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011236 /*FALLTHROUGH*/
11237 default:
11238 p = strchr(types, c);
11239 if (p == NULL)
11240 goto badsub;
11241 subtype = p - types + VSNORMAL;
11242 break;
11243 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011244 case '#': {
11245 int cc = c;
11246 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11247 c = pgetc();
11248 if (c == cc)
11249 subtype++;
11250 else
11251 pungetc();
11252 break;
11253 }
11254#if ENABLE_ASH_BASH_COMPAT
11255 case '/':
11256 subtype = VSREPLACE;
11257 c = pgetc();
11258 if (c == '/')
11259 subtype++; /* VSREPLACEALL */
11260 else
11261 pungetc();
11262 break;
11263#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011264 }
Eric Andersenc470f442003-07-28 09:56:35 +000011265 } else {
11266 pungetc();
11267 }
11268 if (dblquote || arinest)
11269 flags |= VSQUOTE;
11270 *((char *)stackblock() + typeloc) = subtype | flags;
11271 if (subtype != VSNORMAL) {
11272 varnest++;
11273 if (dblquote || arinest) {
11274 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011275 }
11276 }
11277 }
Eric Andersenc470f442003-07-28 09:56:35 +000011278 goto parsesub_return;
11279}
Eric Andersencb57d552001-06-28 07:25:16 +000011280
Eric Andersencb57d552001-06-28 07:25:16 +000011281/*
11282 * Called to parse command substitutions. Newstyle is set if the command
11283 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11284 * list of commands (passed by reference), and savelen is the number of
11285 * characters on the top of the stack which must be preserved.
11286 */
Eric Andersenc470f442003-07-28 09:56:35 +000011287parsebackq: {
11288 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011289 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011290 union node *n;
11291 char *volatile str;
11292 struct jmploc jmploc;
11293 struct jmploc *volatile savehandler;
11294 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011295 smallint saveprompt = 0;
11296
Eric Andersencb57d552001-06-28 07:25:16 +000011297#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011298 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011299#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011300 savepbq = parsebackquote;
11301 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011302 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011303 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011304 exception_handler = savehandler;
11305 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011306 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011307 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011308 str = NULL;
11309 savelen = out - (char *)stackblock();
11310 if (savelen > 0) {
11311 str = ckmalloc(savelen);
11312 memcpy(str, stackblock(), savelen);
11313 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011314 savehandler = exception_handler;
11315 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011316 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011317 if (oldstyle) {
11318 /* We must read until the closing backquote, giving special
11319 treatment to some slashes, and then push the string and
11320 reread it as input, interpreting it normally. */
11321 char *pout;
11322 int pc;
11323 size_t psavelen;
11324 char *pstr;
11325
11326
11327 STARTSTACKSTR(pout);
11328 for (;;) {
11329 if (needprompt) {
11330 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011331 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011332 pc = pgetc();
11333 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011334 case '`':
11335 goto done;
11336
11337 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011338 pc = pgetc();
11339 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011340 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011341 if (doprompt)
11342 setprompt(2);
11343 /*
11344 * If eating a newline, avoid putting
11345 * the newline into the new character
11346 * stream (via the STPUTC after the
11347 * switch).
11348 */
11349 continue;
11350 }
11351 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011352 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011353 STPUTC('\\', pout);
11354 if (pc > PEOA_OR_PEOF) {
11355 break;
11356 }
11357 /* fall through */
11358
11359 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011360#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011361 case PEOA:
11362#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011363 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011364 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011365
11366 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011367 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011368 needprompt = doprompt;
11369 break;
11370
11371 default:
11372 break;
11373 }
11374 STPUTC(pc, pout);
11375 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011376 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011377 STPUTC('\0', pout);
11378 psavelen = pout - (char *)stackblock();
11379 if (psavelen > 0) {
11380 pstr = grabstackstr(pout);
11381 setinputstring(pstr);
11382 }
11383 }
11384 nlpp = &bqlist;
11385 while (*nlpp)
11386 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011387 *nlpp = stzalloc(sizeof(**nlpp));
11388 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011389 parsebackquote = oldstyle;
11390
11391 if (oldstyle) {
11392 saveprompt = doprompt;
11393 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011394 }
11395
Eric Andersenc470f442003-07-28 09:56:35 +000011396 n = list(2);
11397
11398 if (oldstyle)
11399 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011400 else if (readtoken() != TRP)
11401 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011402
11403 (*nlpp)->n = n;
11404 if (oldstyle) {
11405 /*
11406 * Start reading from old file again, ignoring any pushed back
11407 * tokens left from the backquote parsing
11408 */
11409 popfile();
11410 tokpushback = 0;
11411 }
11412 while (stackblocksize() <= savelen)
11413 growstackblock();
11414 STARTSTACKSTR(out);
11415 if (str) {
11416 memcpy(out, str, savelen);
11417 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011418 INT_OFF;
11419 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011420 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011421 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011422 }
11423 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011424 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011425 if (arinest || dblquote)
11426 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11427 else
11428 USTPUTC(CTLBACKQ, out);
11429 if (oldstyle)
11430 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011431 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011432}
11433
Mike Frysinger98c52642009-04-02 10:02:37 +000011434#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011435/*
11436 * Parse an arithmetic expansion (indicate start of one and set state)
11437 */
Eric Andersenc470f442003-07-28 09:56:35 +000011438parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011439 if (++arinest == 1) {
11440 prevsyntax = syntax;
11441 syntax = ARISYNTAX;
11442 USTPUTC(CTLARI, out);
11443 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011444 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011445 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011446 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011447 } else {
11448 /*
11449 * we collapse embedded arithmetic expansion to
11450 * parenthesis, which should be equivalent
11451 */
11452 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011453 }
Eric Andersenc470f442003-07-28 09:56:35 +000011454 goto parsearith_return;
11455}
11456#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011457
Eric Andersenc470f442003-07-28 09:56:35 +000011458} /* end of readtoken */
11459
Eric Andersencb57d552001-06-28 07:25:16 +000011460/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011461 * Read the next input token.
11462 * If the token is a word, we set backquotelist to the list of cmds in
11463 * backquotes. We set quoteflag to true if any part of the word was
11464 * quoted.
11465 * If the token is TREDIR, then we set redirnode to a structure containing
11466 * the redirection.
11467 * In all cases, the variable startlinno is set to the number of the line
11468 * on which the token starts.
11469 *
11470 * [Change comment: here documents and internal procedures]
11471 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11472 * word parsing code into a separate routine. In this case, readtoken
11473 * doesn't need to have any internal procedures, but parseword does.
11474 * We could also make parseoperator in essence the main routine, and
11475 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011476 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011477#define NEW_xxreadtoken
11478#ifdef NEW_xxreadtoken
11479/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011480static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011481 '\n', '(', ')', /* singles */
11482 '&', '|', ';', /* doubles */
11483 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011484};
Eric Andersencb57d552001-06-28 07:25:16 +000011485
Denis Vlasenko834dee72008-10-07 09:18:30 +000011486#define xxreadtoken_singles 3
11487#define xxreadtoken_doubles 3
11488
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011489static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011490 TNL, TLP, TRP, /* only single occurrence allowed */
11491 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11492 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011493 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011494};
11495
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011496static int
11497xxreadtoken(void)
11498{
11499 int c;
11500
11501 if (tokpushback) {
11502 tokpushback = 0;
11503 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011504 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011505 if (needprompt) {
11506 setprompt(2);
11507 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011508 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011509 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011510 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011511 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011512 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011513
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011514 if (c == '#') {
11515 while ((c = pgetc()) != '\n' && c != PEOF)
11516 continue;
11517 pungetc();
11518 } else if (c == '\\') {
11519 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011520 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011521 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011522 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011523 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011524 if (doprompt)
11525 setprompt(2);
11526 } else {
11527 const char *p;
11528
11529 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11530 if (c != PEOF) {
11531 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011532 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011533 needprompt = doprompt;
11534 }
11535
11536 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011537 if (p == NULL)
11538 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011539
Denis Vlasenko834dee72008-10-07 09:18:30 +000011540 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11541 int cc = pgetc();
11542 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011543 p += xxreadtoken_doubles + 1;
11544 } else {
11545 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011546#if ENABLE_ASH_BASH_COMPAT
11547 if (c == '&' && cc == '>') /* &> */
11548 break; /* return readtoken1(...) */
11549#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011550 }
11551 }
11552 }
11553 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11554 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011555 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011556 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011557
11558 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011559}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011560#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011561#define RETURN(token) return lasttoken = token
11562static int
11563xxreadtoken(void)
11564{
11565 int c;
11566
11567 if (tokpushback) {
11568 tokpushback = 0;
11569 return lasttoken;
11570 }
11571 if (needprompt) {
11572 setprompt(2);
11573 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011574 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011575 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011576 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011577 switch (c) {
11578 case ' ': case '\t':
11579#if ENABLE_ASH_ALIAS
11580 case PEOA:
11581#endif
11582 continue;
11583 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011584 while ((c = pgetc()) != '\n' && c != PEOF)
11585 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011586 pungetc();
11587 continue;
11588 case '\\':
11589 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011590 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591 if (doprompt)
11592 setprompt(2);
11593 continue;
11594 }
11595 pungetc();
11596 goto breakloop;
11597 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011598 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011599 needprompt = doprompt;
11600 RETURN(TNL);
11601 case PEOF:
11602 RETURN(TEOF);
11603 case '&':
11604 if (pgetc() == '&')
11605 RETURN(TAND);
11606 pungetc();
11607 RETURN(TBACKGND);
11608 case '|':
11609 if (pgetc() == '|')
11610 RETURN(TOR);
11611 pungetc();
11612 RETURN(TPIPE);
11613 case ';':
11614 if (pgetc() == ';')
11615 RETURN(TENDCASE);
11616 pungetc();
11617 RETURN(TSEMI);
11618 case '(':
11619 RETURN(TLP);
11620 case ')':
11621 RETURN(TRP);
11622 default:
11623 goto breakloop;
11624 }
11625 }
11626 breakloop:
11627 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11628#undef RETURN
11629}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011630#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011631
11632static int
11633readtoken(void)
11634{
11635 int t;
11636#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011637 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011638#endif
11639
11640#if ENABLE_ASH_ALIAS
11641 top:
11642#endif
11643
11644 t = xxreadtoken();
11645
11646 /*
11647 * eat newlines
11648 */
11649 if (checkkwd & CHKNL) {
11650 while (t == TNL) {
11651 parseheredoc();
11652 t = xxreadtoken();
11653 }
11654 }
11655
11656 if (t != TWORD || quoteflag) {
11657 goto out;
11658 }
11659
11660 /*
11661 * check for keywords
11662 */
11663 if (checkkwd & CHKKWD) {
11664 const char *const *pp;
11665
11666 pp = findkwd(wordtext);
11667 if (pp) {
11668 lasttoken = t = pp - tokname_array;
11669 TRACE(("keyword %s recognized\n", tokname(t)));
11670 goto out;
11671 }
11672 }
11673
11674 if (checkkwd & CHKALIAS) {
11675#if ENABLE_ASH_ALIAS
11676 struct alias *ap;
11677 ap = lookupalias(wordtext, 1);
11678 if (ap != NULL) {
11679 if (*ap->val) {
11680 pushstring(ap->val, ap);
11681 }
11682 goto top;
11683 }
11684#endif
11685 }
11686 out:
11687 checkkwd = 0;
11688#if DEBUG
11689 if (!alreadyseen)
11690 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11691 else
11692 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11693#endif
11694 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011695}
11696
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011697static char
11698peektoken(void)
11699{
11700 int t;
11701
11702 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011703 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011704 return tokname_array[t][0];
11705}
Eric Andersencb57d552001-06-28 07:25:16 +000011706
11707/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011708 * Read and parse a command. Returns NODE_EOF on end of file.
11709 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011710 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011711static union node *
11712parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011713{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011714 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011715
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011716 tokpushback = 0;
11717 doprompt = interact;
11718 if (doprompt)
11719 setprompt(doprompt);
11720 needprompt = 0;
11721 t = readtoken();
11722 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011723 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011724 if (t == TNL)
11725 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011726 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011727 return list(1);
11728}
11729
11730/*
11731 * Input any here documents.
11732 */
11733static void
11734parseheredoc(void)
11735{
11736 struct heredoc *here;
11737 union node *n;
11738
11739 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011740 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011741
11742 while (here) {
11743 if (needprompt) {
11744 setprompt(2);
11745 }
11746 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11747 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011748 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011749 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011750 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011751 n->narg.text = wordtext;
11752 n->narg.backquote = backquotelist;
11753 here->here->nhere.doc = n;
11754 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011755 }
Eric Andersencb57d552001-06-28 07:25:16 +000011756}
11757
11758
11759/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011760 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011761 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011762#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011763static const char *
11764expandstr(const char *ps)
11765{
11766 union node n;
11767
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011768 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11769 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011770 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011771 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011772 popfile();
11773
11774 n.narg.type = NARG;
11775 n.narg.next = NULL;
11776 n.narg.text = wordtext;
11777 n.narg.backquote = backquotelist;
11778
11779 expandarg(&n, NULL, 0);
11780 return stackblock();
11781}
11782#endif
11783
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011784/*
11785 * Execute a command or commands contained in a string.
11786 */
11787static int
11788evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011789{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011790 union node *n;
11791 struct stackmark smark;
11792 int skip;
11793
11794 setinputstring(s);
11795 setstackmark(&smark);
11796
11797 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011798 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011799 evaltree(n, 0);
11800 popstackmark(&smark);
11801 skip = evalskip;
11802 if (skip)
11803 break;
11804 }
11805 popfile();
11806
11807 skip &= mask;
11808 evalskip = skip;
11809 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011810}
11811
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011812/*
11813 * The eval command.
11814 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011815static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011816evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011817{
11818 char *p;
11819 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011820
Denis Vlasenko68404f12008-03-17 09:00:54 +000011821 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011822 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011823 argv += 2;
11824 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011825 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011826 for (;;) {
11827 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011828 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011829 if (p == NULL)
11830 break;
11831 STPUTC(' ', concat);
11832 }
11833 STPUTC('\0', concat);
11834 p = grabstackstr(concat);
11835 }
11836 evalstring(p, ~SKIPEVAL);
11837
11838 }
11839 return exitstatus;
11840}
11841
11842/*
11843 * Read and execute commands. "Top" is nonzero for the top level command
11844 * loop; it turns on prompting if the shell is interactive.
11845 */
11846static int
11847cmdloop(int top)
11848{
11849 union node *n;
11850 struct stackmark smark;
11851 int inter;
11852 int numeof = 0;
11853
11854 TRACE(("cmdloop(%d) called\n", top));
11855 for (;;) {
11856 int skip;
11857
11858 setstackmark(&smark);
11859#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011860 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011861 showjobs(stderr, SHOW_CHANGED);
11862#endif
11863 inter = 0;
11864 if (iflag && top) {
11865 inter++;
11866#if ENABLE_ASH_MAIL
11867 chkmail();
11868#endif
11869 }
11870 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011871#if DEBUG
11872 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011873 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011874#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011875 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011876 if (!top || numeof >= 50)
11877 break;
11878 if (!stoppedjobs()) {
11879 if (!Iflag)
11880 break;
11881 out2str("\nUse \"exit\" to leave shell.\n");
11882 }
11883 numeof++;
11884 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011885 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11886 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011887 numeof = 0;
11888 evaltree(n, 0);
11889 }
11890 popstackmark(&smark);
11891 skip = evalskip;
11892
11893 if (skip) {
11894 evalskip = 0;
11895 return skip & SKIPEVAL;
11896 }
11897 }
11898 return 0;
11899}
11900
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011901/*
11902 * Take commands from a file. To be compatible we should do a path
11903 * search for the file, which is necessary to find sub-commands.
11904 */
11905static char *
11906find_dot_file(char *name)
11907{
11908 char *fullname;
11909 const char *path = pathval();
11910 struct stat statb;
11911
11912 /* don't try this for absolute or relative paths */
11913 if (strchr(name, '/'))
11914 return name;
11915
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011916 /* IIRC standards do not say whether . is to be searched.
11917 * And it is even smaller this way, making it unconditional for now:
11918 */
11919 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11920 fullname = name;
11921 goto try_cur_dir;
11922 }
11923
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011924 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011925 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011926 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11927 /*
11928 * Don't bother freeing here, since it will
11929 * be freed by the caller.
11930 */
11931 return fullname;
11932 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011933 if (fullname != name)
11934 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011935 }
11936
11937 /* not found in the PATH */
11938 ash_msg_and_raise_error("%s: not found", name);
11939 /* NOTREACHED */
11940}
11941
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011942static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011943dotcmd(int argc, char **argv)
11944{
11945 struct strlist *sp;
11946 volatile struct shparam saveparam;
11947 int status = 0;
11948
11949 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011950 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011951
Denis Vlasenko68404f12008-03-17 09:00:54 +000011952 if (argv[1]) { /* That's what SVR2 does */
11953 char *fullname = find_dot_file(argv[1]);
11954 argv += 2;
11955 argc -= 2;
11956 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011957 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011958 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011959 shellparam.nparam = argc;
11960 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011961 };
11962
11963 setinputfile(fullname, INPUT_PUSH_FILE);
11964 commandname = fullname;
11965 cmdloop(0);
11966 popfile();
11967
Denis Vlasenko68404f12008-03-17 09:00:54 +000011968 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011969 freeparam(&shellparam);
11970 shellparam = saveparam;
11971 };
11972 status = exitstatus;
11973 }
11974 return status;
11975}
11976
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011977static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011978exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011979{
11980 if (stoppedjobs())
11981 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011982 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011983 exitstatus = number(argv[1]);
11984 raise_exception(EXEXIT);
11985 /* NOTREACHED */
11986}
11987
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011988/*
11989 * Read a file containing shell functions.
11990 */
11991static void
11992readcmdfile(char *name)
11993{
11994 setinputfile(name, INPUT_PUSH_FILE);
11995 cmdloop(0);
11996 popfile();
11997}
11998
11999
Denis Vlasenkocc571512007-02-23 21:10:35 +000012000/* ============ find_command inplementation */
12001
12002/*
12003 * Resolve a command name. If you change this routine, you may have to
12004 * change the shellexec routine as well.
12005 */
12006static void
12007find_command(char *name, struct cmdentry *entry, int act, const char *path)
12008{
12009 struct tblentry *cmdp;
12010 int idx;
12011 int prev;
12012 char *fullname;
12013 struct stat statb;
12014 int e;
12015 int updatetbl;
12016 struct builtincmd *bcmd;
12017
12018 /* If name contains a slash, don't use PATH or hash table */
12019 if (strchr(name, '/') != NULL) {
12020 entry->u.index = -1;
12021 if (act & DO_ABS) {
12022 while (stat(name, &statb) < 0) {
12023#ifdef SYSV
12024 if (errno == EINTR)
12025 continue;
12026#endif
12027 entry->cmdtype = CMDUNKNOWN;
12028 return;
12029 }
12030 }
12031 entry->cmdtype = CMDNORMAL;
12032 return;
12033 }
12034
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012035/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012036
12037 updatetbl = (path == pathval());
12038 if (!updatetbl) {
12039 act |= DO_ALTPATH;
12040 if (strstr(path, "%builtin") != NULL)
12041 act |= DO_ALTBLTIN;
12042 }
12043
12044 /* If name is in the table, check answer will be ok */
12045 cmdp = cmdlookup(name, 0);
12046 if (cmdp != NULL) {
12047 int bit;
12048
12049 switch (cmdp->cmdtype) {
12050 default:
12051#if DEBUG
12052 abort();
12053#endif
12054 case CMDNORMAL:
12055 bit = DO_ALTPATH;
12056 break;
12057 case CMDFUNCTION:
12058 bit = DO_NOFUNC;
12059 break;
12060 case CMDBUILTIN:
12061 bit = DO_ALTBLTIN;
12062 break;
12063 }
12064 if (act & bit) {
12065 updatetbl = 0;
12066 cmdp = NULL;
12067 } else if (cmdp->rehash == 0)
12068 /* if not invalidated by cd, we're done */
12069 goto success;
12070 }
12071
12072 /* If %builtin not in path, check for builtin next */
12073 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012074 if (bcmd) {
12075 if (IS_BUILTIN_REGULAR(bcmd))
12076 goto builtin_success;
12077 if (act & DO_ALTPATH) {
12078 if (!(act & DO_ALTBLTIN))
12079 goto builtin_success;
12080 } else if (builtinloc <= 0) {
12081 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012082 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012083 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012084
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012085#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012086 {
12087 int applet_no = find_applet_by_name(name);
12088 if (applet_no >= 0) {
12089 entry->cmdtype = CMDNORMAL;
12090 entry->u.index = -2 - applet_no;
12091 return;
12092 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012093 }
12094#endif
12095
Denis Vlasenkocc571512007-02-23 21:10:35 +000012096 /* We have to search path. */
12097 prev = -1; /* where to start */
12098 if (cmdp && cmdp->rehash) { /* doing a rehash */
12099 if (cmdp->cmdtype == CMDBUILTIN)
12100 prev = builtinloc;
12101 else
12102 prev = cmdp->param.index;
12103 }
12104
12105 e = ENOENT;
12106 idx = -1;
12107 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012108 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012109 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012110 /* NB: code below will still use fullname
12111 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012112 idx++;
12113 if (pathopt) {
12114 if (prefix(pathopt, "builtin")) {
12115 if (bcmd)
12116 goto builtin_success;
12117 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012118 }
12119 if ((act & DO_NOFUNC)
12120 || !prefix(pathopt, "func")
12121 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012122 continue;
12123 }
12124 }
12125 /* if rehash, don't redo absolute path names */
12126 if (fullname[0] == '/' && idx <= prev) {
12127 if (idx < prev)
12128 continue;
12129 TRACE(("searchexec \"%s\": no change\n", name));
12130 goto success;
12131 }
12132 while (stat(fullname, &statb) < 0) {
12133#ifdef SYSV
12134 if (errno == EINTR)
12135 continue;
12136#endif
12137 if (errno != ENOENT && errno != ENOTDIR)
12138 e = errno;
12139 goto loop;
12140 }
12141 e = EACCES; /* if we fail, this will be the error */
12142 if (!S_ISREG(statb.st_mode))
12143 continue;
12144 if (pathopt) { /* this is a %func directory */
12145 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012146 /* NB: stalloc will return space pointed by fullname
12147 * (because we don't have any intervening allocations
12148 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012149 readcmdfile(fullname);
12150 cmdp = cmdlookup(name, 0);
12151 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12152 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12153 stunalloc(fullname);
12154 goto success;
12155 }
12156 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12157 if (!updatetbl) {
12158 entry->cmdtype = CMDNORMAL;
12159 entry->u.index = idx;
12160 return;
12161 }
12162 INT_OFF;
12163 cmdp = cmdlookup(name, 1);
12164 cmdp->cmdtype = CMDNORMAL;
12165 cmdp->param.index = idx;
12166 INT_ON;
12167 goto success;
12168 }
12169
12170 /* We failed. If there was an entry for this command, delete it */
12171 if (cmdp && updatetbl)
12172 delete_cmd_entry();
12173 if (act & DO_ERR)
12174 ash_msg("%s: %s", name, errmsg(e, "not found"));
12175 entry->cmdtype = CMDUNKNOWN;
12176 return;
12177
12178 builtin_success:
12179 if (!updatetbl) {
12180 entry->cmdtype = CMDBUILTIN;
12181 entry->u.cmd = bcmd;
12182 return;
12183 }
12184 INT_OFF;
12185 cmdp = cmdlookup(name, 1);
12186 cmdp->cmdtype = CMDBUILTIN;
12187 cmdp->param.cmd = bcmd;
12188 INT_ON;
12189 success:
12190 cmdp->rehash = 0;
12191 entry->cmdtype = cmdp->cmdtype;
12192 entry->u = cmdp->param;
12193}
12194
12195
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012196/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012197
Eric Andersencb57d552001-06-28 07:25:16 +000012198/*
Eric Andersencb57d552001-06-28 07:25:16 +000012199 * The trap builtin.
12200 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012201static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012202trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012203{
12204 char *action;
12205 char **ap;
12206 int signo;
12207
Eric Andersenc470f442003-07-28 09:56:35 +000012208 nextopt(nullstr);
12209 ap = argptr;
12210 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012211 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000012212 if (trap[signo] != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012213 out1fmt("trap -- %s %s\n",
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012214 single_quote(trap[signo]),
12215 get_signame(signo));
Eric Andersencb57d552001-06-28 07:25:16 +000012216 }
12217 }
12218 return 0;
12219 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012220 action = NULL;
12221 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012222 action = *ap++;
12223 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012224 signo = get_signum(*ap);
12225 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012226 ash_msg_and_raise_error("%s: bad trap", *ap);
12227 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012228 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012229 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012230 action = NULL;
12231 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012232 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012233 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012234 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012235 trap[signo] = action;
12236 if (signo != 0)
12237 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012238 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012239 ap++;
12240 }
12241 return 0;
12242}
12243
Eric Andersenc470f442003-07-28 09:56:35 +000012244
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012245/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012246
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012247#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012248/*
12249 * Lists available builtins
12250 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012251static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012252helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012253{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012254 unsigned col;
12255 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012256
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012257 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012258 "Built-in commands:\n"
12259 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012260 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012261 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012262 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012263 if (col > 60) {
12264 out1fmt("\n");
12265 col = 0;
12266 }
12267 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012268#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012269 {
12270 const char *a = applet_names;
12271 while (*a) {
12272 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12273 if (col > 60) {
12274 out1fmt("\n");
12275 col = 0;
12276 }
12277 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012278 }
12279 }
12280#endif
12281 out1fmt("\n\n");
12282 return EXIT_SUCCESS;
12283}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012284#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012285
Eric Andersencb57d552001-06-28 07:25:16 +000012286/*
Eric Andersencb57d552001-06-28 07:25:16 +000012287 * The export and readonly commands.
12288 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012289static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012290exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012291{
12292 struct var *vp;
12293 char *name;
12294 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012295 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012296 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012297
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012298 if (nextopt("p") != 'p') {
12299 aptr = argptr;
12300 name = *aptr;
12301 if (name) {
12302 do {
12303 p = strchr(name, '=');
12304 if (p != NULL) {
12305 p++;
12306 } else {
12307 vp = *findvar(hashvar(name), name);
12308 if (vp) {
12309 vp->flags |= flag;
12310 continue;
12311 }
Eric Andersencb57d552001-06-28 07:25:16 +000012312 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012313 setvar(name, p, flag);
12314 } while ((name = *++aptr) != NULL);
12315 return 0;
12316 }
Eric Andersencb57d552001-06-28 07:25:16 +000012317 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012318 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012319 return 0;
12320}
12321
Eric Andersencb57d552001-06-28 07:25:16 +000012322/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012323 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012324 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012325static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012326unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012327{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012328 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012329
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012330 cmdp = cmdlookup(name, 0);
12331 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12332 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012333}
12334
Eric Andersencb57d552001-06-28 07:25:16 +000012335/*
Eric Andersencb57d552001-06-28 07:25:16 +000012336 * The unset builtin command. We unset the function before we unset the
12337 * variable to allow a function to be unset when there is a readonly variable
12338 * with the same name.
12339 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012340static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012341unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012342{
12343 char **ap;
12344 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012345 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012346 int ret = 0;
12347
12348 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012349 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012350 }
Eric Andersencb57d552001-06-28 07:25:16 +000012351
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012352 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012353 if (flag != 'f') {
12354 i = unsetvar(*ap);
12355 ret |= i;
12356 if (!(i & 2))
12357 continue;
12358 }
12359 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012360 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012361 }
Eric Andersenc470f442003-07-28 09:56:35 +000012362 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012363}
12364
12365
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012366/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012367
Eric Andersenc470f442003-07-28 09:56:35 +000012368#include <sys/times.h>
12369
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012370static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012371 ' ', offsetof(struct tms, tms_utime),
12372 '\n', offsetof(struct tms, tms_stime),
12373 ' ', offsetof(struct tms, tms_cutime),
12374 '\n', offsetof(struct tms, tms_cstime),
12375 0
12376};
Eric Andersencb57d552001-06-28 07:25:16 +000012377
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012378static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012379timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012380{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012381 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012382 const unsigned char *p;
12383 struct tms buf;
12384
12385 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012386 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012387
12388 p = timescmd_str;
12389 do {
12390 t = *(clock_t *)(((char *) &buf) + p[1]);
12391 s = t / clk_tck;
12392 out1fmt("%ldm%ld.%.3lds%c",
12393 s/60, s%60,
12394 ((t - s * clk_tck) * 1000) / clk_tck,
12395 p[0]);
12396 } while (*(p += 2));
12397
Eric Andersencb57d552001-06-28 07:25:16 +000012398 return 0;
12399}
12400
Mike Frysinger98c52642009-04-02 10:02:37 +000012401#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012402/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012403 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12404 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012405 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012406 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012407 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012408static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012409letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012410{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012411 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012412
Denis Vlasenko68404f12008-03-17 09:00:54 +000012413 argv++;
12414 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012415 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012416 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012417 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012418 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012419
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012420 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012421}
Mike Frysinger98c52642009-04-02 10:02:37 +000012422#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012423
Eric Andersenc470f442003-07-28 09:56:35 +000012424
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012425/* ============ miscbltin.c
12426 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012427 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012428 */
12429
12430#undef rflag
12431
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012432#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012433typedef enum __rlimit_resource rlim_t;
12434#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012435
Eric Andersenc470f442003-07-28 09:56:35 +000012436/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012437 * The read builtin. Options:
12438 * -r Do not interpret '\' specially
12439 * -s Turn off echo (tty only)
12440 * -n NCHARS Read NCHARS max
12441 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12442 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12443 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012444 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012445 * TODO: bash also has:
12446 * -a ARRAY Read into array[0],[1],etc
12447 * -d DELIM End on DELIM char, not newline
12448 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012449 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012450static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012451readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012452{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012453 static const char *const arg_REPLY[] = { "REPLY", NULL };
12454
Eric Andersenc470f442003-07-28 09:56:35 +000012455 char **ap;
12456 int backslash;
12457 char c;
12458 int rflag;
12459 char *prompt;
12460 const char *ifs;
12461 char *p;
12462 int startword;
12463 int status;
12464 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012465 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012466#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012467 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012468 int silent = 0;
12469 struct termios tty, old_tty;
12470#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012471#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012472 unsigned end_ms = 0;
12473 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012474#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012475
12476 rflag = 0;
12477 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012478 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012479 IF_ASH_READ_TIMEOUT("t:")
12480 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012481 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012482 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012483 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012484 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012485 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012486#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012487 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012488 nchars = bb_strtou(optionarg, NULL, 10);
12489 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012490 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012491 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012492 break;
12493 case 's':
12494 silent = 1;
12495 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012496#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012497#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012498 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012499 timeout = bb_strtou(optionarg, NULL, 10);
12500 if (errno || timeout > UINT_MAX / 2048)
12501 ash_msg_and_raise_error("invalid timeout");
12502 timeout *= 1000;
12503#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012504 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012505 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012506 /* EINVAL means number is ok, but not terminated by NUL */
12507 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012508 char *p2;
12509 if (*++p) {
12510 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012511 ts.tv_usec = bb_strtou(p, &p2, 10);
12512 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012513 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012514 scale = p2 - p;
12515 /* normalize to usec */
12516 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012517 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012518 while (scale++ < 6)
12519 ts.tv_usec *= 10;
12520 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012521 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012522 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012523 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012524 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012525 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012526 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012527#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012528 break;
12529#endif
12530 case 'r':
12531 rflag = 1;
12532 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012533 case 'u':
12534 fd = bb_strtou(optionarg, NULL, 10);
12535 if (fd < 0 || errno)
12536 ash_msg_and_raise_error("invalid file descriptor");
12537 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012538 default:
12539 break;
12540 }
Eric Andersenc470f442003-07-28 09:56:35 +000012541 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012542 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012543 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012544 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012545 ap = argptr;
12546 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012547 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012548 ifs = bltinlookup("IFS");
12549 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012550 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012551#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012552 tcgetattr(fd, &tty);
12553 old_tty = tty;
12554 if (nchars || silent) {
12555 if (nchars) {
12556 tty.c_lflag &= ~ICANON;
12557 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012558 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012559 if (silent) {
12560 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12561 }
12562 /* if tcgetattr failed, tcsetattr will fail too.
12563 * Ignoring, it's harmless. */
12564 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012565 }
12566#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012567
Eric Andersenc470f442003-07-28 09:56:35 +000012568 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012569 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012570 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571#if ENABLE_ASH_READ_TIMEOUT
12572 if (timeout) /* NB: ensuring end_ms is nonzero */
12573 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12574#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012575 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012576 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012577 const char *is_ifs;
12578
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012579#if ENABLE_ASH_READ_TIMEOUT
12580 if (end_ms) {
12581 struct pollfd pfd[1];
12582 pfd[0].fd = fd;
12583 pfd[0].events = POLLIN;
12584 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12585 if ((int)timeout <= 0 /* already late? */
12586 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12587 ) { /* timed out! */
12588#if ENABLE_ASH_READ_NCHARS
12589 tcsetattr(fd, TCSANOW, &old_tty);
12590#endif
12591 return 1;
12592 }
12593 }
12594#endif
12595 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012596 status = 1;
12597 break;
12598 }
12599 if (c == '\0')
12600 continue;
12601 if (backslash) {
12602 backslash = 0;
12603 if (c != '\n')
12604 goto put;
12605 continue;
12606 }
12607 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012608 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012609 continue;
12610 }
12611 if (c == '\n')
12612 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012613 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012614/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012615 is_ifs = strchr(ifs, c);
12616 if (startword && is_ifs) {
12617 if (isspace(c))
12618 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012619 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012620 startword--;
12621 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012622 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012623 }
12624 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012625 if (ap[1] != NULL && is_ifs) {
12626 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012627 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012628 beg = stackblock();
12629 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012630 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012631 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012632 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012633 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012634 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012635 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012636 put:
12637 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012638 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012639/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012640#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012641 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012642#else
12643 while (1);
12644#endif
12645
12646#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012647 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012648#endif
12649
Eric Andersenc470f442003-07-28 09:56:35 +000012650 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012651 /* Remove trailing space ifs chars */
12652 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012653 *p = '\0';
12654 setvar(*ap, stackblock(), 0);
12655 while (*++ap != NULL)
12656 setvar(*ap, nullstr, 0);
12657 return status;
12658}
12659
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012660static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012661umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012662{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012663 static const char permuser[3] ALIGN1 = "ugo";
12664 static const char permmode[3] ALIGN1 = "rwx";
12665 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012666 S_IRUSR, S_IWUSR, S_IXUSR,
12667 S_IRGRP, S_IWGRP, S_IXGRP,
12668 S_IROTH, S_IWOTH, S_IXOTH
12669 };
12670
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012671 /* TODO: use bb_parse_mode() instead */
12672
Eric Andersenc470f442003-07-28 09:56:35 +000012673 char *ap;
12674 mode_t mask;
12675 int i;
12676 int symbolic_mode = 0;
12677
12678 while (nextopt("S") != '\0') {
12679 symbolic_mode = 1;
12680 }
12681
Denis Vlasenkob012b102007-02-19 22:43:01 +000012682 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012683 mask = umask(0);
12684 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012685 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012686
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012687 ap = *argptr;
12688 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012689 if (symbolic_mode) {
12690 char buf[18];
12691 char *p = buf;
12692
12693 for (i = 0; i < 3; i++) {
12694 int j;
12695
12696 *p++ = permuser[i];
12697 *p++ = '=';
12698 for (j = 0; j < 3; j++) {
12699 if ((mask & permmask[3 * i + j]) == 0) {
12700 *p++ = permmode[j];
12701 }
12702 }
12703 *p++ = ',';
12704 }
12705 *--p = 0;
12706 puts(buf);
12707 } else {
12708 out1fmt("%.4o\n", mask);
12709 }
12710 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012711 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012712 mask = 0;
12713 do {
12714 if (*ap >= '8' || *ap < '0')
Denis Vlasenkob012b102007-02-19 22:43:01 +000012715 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012716 mask = (mask << 3) + (*ap - '0');
12717 } while (*++ap != '\0');
12718 umask(mask);
12719 } else {
12720 mask = ~mask & 0777;
12721 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012722 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012723 }
12724 umask(~mask & 0777);
12725 }
12726 }
12727 return 0;
12728}
12729
12730/*
12731 * ulimit builtin
12732 *
12733 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12734 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12735 * ash by J.T. Conklin.
12736 *
12737 * Public domain.
12738 */
Eric Andersenc470f442003-07-28 09:56:35 +000012739struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012740 uint8_t cmd; /* RLIMIT_xxx fit into it */
12741 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012742 char option;
12743};
12744
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012745static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012746#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012747 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012748#endif
12749#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012750 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012751#endif
12752#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012753 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012754#endif
12755#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012756 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012757#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012758#ifdef RLIMIT_CORE
12759 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012760#endif
12761#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012762 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012763#endif
12764#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012765 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012766#endif
12767#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012768 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012769#endif
12770#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012771 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012772#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012773#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012774 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012775#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012776#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012777 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012778#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012779};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012780static const char limits_name[] =
12781#ifdef RLIMIT_CPU
12782 "time(seconds)" "\0"
12783#endif
12784#ifdef RLIMIT_FSIZE
12785 "file(blocks)" "\0"
12786#endif
12787#ifdef RLIMIT_DATA
12788 "data(kb)" "\0"
12789#endif
12790#ifdef RLIMIT_STACK
12791 "stack(kb)" "\0"
12792#endif
12793#ifdef RLIMIT_CORE
12794 "coredump(blocks)" "\0"
12795#endif
12796#ifdef RLIMIT_RSS
12797 "memory(kb)" "\0"
12798#endif
12799#ifdef RLIMIT_MEMLOCK
12800 "locked memory(kb)" "\0"
12801#endif
12802#ifdef RLIMIT_NPROC
12803 "process" "\0"
12804#endif
12805#ifdef RLIMIT_NOFILE
12806 "nofiles" "\0"
12807#endif
12808#ifdef RLIMIT_AS
12809 "vmemory(kb)" "\0"
12810#endif
12811#ifdef RLIMIT_LOCKS
12812 "locks" "\0"
12813#endif
12814;
Eric Andersenc470f442003-07-28 09:56:35 +000012815
Glenn L McGrath76620622004-01-13 10:19:37 +000012816enum limtype { SOFT = 0x1, HARD = 0x2 };
12817
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012818static void
12819printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012820 const struct limits *l)
12821{
12822 rlim_t val;
12823
12824 val = limit->rlim_max;
12825 if (how & SOFT)
12826 val = limit->rlim_cur;
12827
12828 if (val == RLIM_INFINITY)
12829 out1fmt("unlimited\n");
12830 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012831 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012832 out1fmt("%lld\n", (long long) val);
12833 }
12834}
12835
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012836static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012837ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012838{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012839 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012840 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012841 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012842 const struct limits *l;
12843 int set, all = 0;
12844 int optc, what;
12845 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012846
12847 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012848 while ((optc = nextopt("HSa"
12849#ifdef RLIMIT_CPU
12850 "t"
12851#endif
12852#ifdef RLIMIT_FSIZE
12853 "f"
12854#endif
12855#ifdef RLIMIT_DATA
12856 "d"
12857#endif
12858#ifdef RLIMIT_STACK
12859 "s"
12860#endif
12861#ifdef RLIMIT_CORE
12862 "c"
12863#endif
12864#ifdef RLIMIT_RSS
12865 "m"
12866#endif
12867#ifdef RLIMIT_MEMLOCK
12868 "l"
12869#endif
12870#ifdef RLIMIT_NPROC
12871 "p"
12872#endif
12873#ifdef RLIMIT_NOFILE
12874 "n"
12875#endif
12876#ifdef RLIMIT_AS
12877 "v"
12878#endif
12879#ifdef RLIMIT_LOCKS
12880 "w"
12881#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012882 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012883 switch (optc) {
12884 case 'H':
12885 how = HARD;
12886 break;
12887 case 'S':
12888 how = SOFT;
12889 break;
12890 case 'a':
12891 all = 1;
12892 break;
12893 default:
12894 what = optc;
12895 }
12896
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012897 for (l = limits_tbl; l->option != what; l++)
12898 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012899
12900 set = *argptr ? 1 : 0;
12901 if (set) {
12902 char *p = *argptr;
12903
12904 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012905 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012906 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012907 val = RLIM_INFINITY;
12908 else {
12909 val = (rlim_t) 0;
12910
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012911 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012912 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012913 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012914 if (val < (rlim_t) 0)
12915 break;
12916 }
12917 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012918 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012919 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012920 }
12921 }
12922 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012923 const char *lname = limits_name;
12924 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012925 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012926 out1fmt("%-20s ", lname);
12927 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012928 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012929 }
12930 return 0;
12931 }
12932
12933 getrlimit(l->cmd, &limit);
12934 if (set) {
12935 if (how & HARD)
12936 limit.rlim_max = val;
12937 if (how & SOFT)
12938 limit.rlim_cur = val;
12939 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012940 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012941 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012942 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012943 }
12944 return 0;
12945}
12946
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012947/* ============ main() and helpers */
12948
12949/*
12950 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012951 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012952static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012953static void
12954exitshell(void)
12955{
12956 struct jmploc loc;
12957 char *p;
12958 int status;
12959
12960 status = exitstatus;
12961 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12962 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012963 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012964/* dash bug: it just does _exit(exitstatus) here
12965 * but we have to do setjobctl(0) first!
12966 * (bug is still not fixed in dash-0.5.3 - if you run dash
12967 * under Midnight Commander, on exit from dash MC is backgrounded) */
12968 status = exitstatus;
12969 goto out;
12970 }
12971 exception_handler = &loc;
12972 p = trap[0];
12973 if (p) {
12974 trap[0] = NULL;
12975 evalstring(p, 0);
12976 }
12977 flush_stdout_stderr();
12978 out:
12979 setjobctl(0);
12980 _exit(status);
12981 /* NOTREACHED */
12982}
12983
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012984static void
12985init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012986{
12987 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012988 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012989
12990 /* from trap.c: */
12991 signal(SIGCHLD, SIG_DFL);
12992
12993 /* from var.c: */
12994 {
12995 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012996 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012997 const char *p;
12998 struct stat st1, st2;
12999
13000 initvar();
13001 for (envp = environ; envp && *envp; envp++) {
13002 if (strchr(*envp, '=')) {
13003 setvareq(*envp, VEXPORT|VTEXTFIXED);
13004 }
13005 }
13006
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013007 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013008 setvar("PPID", ppid, 0);
13009
13010 p = lookupvar("PWD");
13011 if (p)
13012 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13013 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13014 p = '\0';
13015 setpwd(p, 0);
13016 }
13017}
13018
13019/*
13020 * Process the shell command line arguments.
13021 */
13022static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013023procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013024{
13025 int i;
13026 const char *xminusc;
13027 char **xargv;
13028
13029 xargv = argv;
13030 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013031 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013032 xargv++;
13033 for (i = 0; i < NOPTS; i++)
13034 optlist[i] = 2;
13035 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013036 if (options(1)) {
13037 /* it already printed err message */
13038 raise_exception(EXERROR);
13039 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013040 xargv = argptr;
13041 xminusc = minusc;
13042 if (*xargv == NULL) {
13043 if (xminusc)
13044 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13045 sflag = 1;
13046 }
13047 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13048 iflag = 1;
13049 if (mflag == 2)
13050 mflag = iflag;
13051 for (i = 0; i < NOPTS; i++)
13052 if (optlist[i] == 2)
13053 optlist[i] = 0;
13054#if DEBUG == 2
13055 debug = 1;
13056#endif
13057 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13058 if (xminusc) {
13059 minusc = *xargv++;
13060 if (*xargv)
13061 goto setarg0;
13062 } else if (!sflag) {
13063 setinputfile(*xargv, 0);
13064 setarg0:
13065 arg0 = *xargv++;
13066 commandname = arg0;
13067 }
13068
13069 shellparam.p = xargv;
13070#if ENABLE_ASH_GETOPTS
13071 shellparam.optind = 1;
13072 shellparam.optoff = -1;
13073#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013074 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013075 while (*xargv) {
13076 shellparam.nparam++;
13077 xargv++;
13078 }
13079 optschanged();
13080}
13081
13082/*
13083 * Read /etc/profile or .profile.
13084 */
13085static void
13086read_profile(const char *name)
13087{
13088 int skip;
13089
13090 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13091 return;
13092 skip = cmdloop(0);
13093 popfile();
13094 if (skip)
13095 exitshell();
13096}
13097
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013098/*
13099 * This routine is called when an error or an interrupt occurs in an
13100 * interactive shell and control is returned to the main command loop.
13101 */
13102static void
13103reset(void)
13104{
13105 /* from eval.c: */
13106 evalskip = 0;
13107 loopnest = 0;
13108 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013109 g_parsefile->left_in_buffer = 0;
13110 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013111 popallfiles();
13112 /* from parser.c: */
13113 tokpushback = 0;
13114 checkkwd = 0;
13115 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013116 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013117}
13118
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013119#if PROFILE
13120static short profile_buf[16384];
13121extern int etext();
13122#endif
13123
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013124/*
13125 * Main routine. We initialize things, parse the arguments, execute
13126 * profiles if we're a login shell, and then call cmdloop to execute
13127 * commands. The setjmp call sets up the location to jump to when an
13128 * exception occurs. When an exception occurs the variable "state"
13129 * is used to figure out how far we had gotten.
13130 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013131int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013132int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013133{
Mike Frysinger98c52642009-04-02 10:02:37 +000013134 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013135 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013136 struct jmploc jmploc;
13137 struct stackmark smark;
13138
Denis Vlasenko01631112007-12-16 17:20:38 +000013139 /* Initialize global data */
13140 INIT_G_misc();
13141 INIT_G_memstack();
13142 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013143#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013144 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013145#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013146 INIT_G_cmdtable();
13147
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013148#if PROFILE
13149 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13150#endif
13151
13152#if ENABLE_FEATURE_EDITING
13153 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13154#endif
13155 state = 0;
13156 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013157 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013158 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013159
13160 reset();
13161
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013162 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013163 if (e == EXERROR)
13164 exitstatus = 2;
13165 s = state;
13166 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13167 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013168 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013169 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013170
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013171 popstackmark(&smark);
13172 FORCE_INT_ON; /* enable interrupts */
13173 if (s == 1)
13174 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013175 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013176 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013177 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013178 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013179 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013180 }
13181 exception_handler = &jmploc;
13182#if DEBUG
13183 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013184 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013185 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013186#endif
13187 rootpid = getpid();
13188
13189#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013190 /* Can use monotonic_ns() for better randomness but for now it is
13191 * not used anywhere else in busybox... so avoid bloat */
13192 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013193#endif
13194 init();
13195 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013196 procargs(argv);
13197
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013198#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13199 if (iflag) {
13200 const char *hp = lookupvar("HISTFILE");
13201
13202 if (hp == NULL) {
13203 hp = lookupvar("HOME");
13204 if (hp != NULL) {
13205 char *defhp = concat_path_file(hp, ".ash_history");
13206 setvar("HISTFILE", defhp, 0);
13207 free(defhp);
13208 }
13209 }
13210 }
13211#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013212 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013213 isloginsh = 1;
13214 if (isloginsh) {
13215 state = 1;
13216 read_profile("/etc/profile");
13217 state1:
13218 state = 2;
13219 read_profile(".profile");
13220 }
13221 state2:
13222 state = 3;
13223 if (
13224#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013225 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013226#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013227 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013228 ) {
13229 shinit = lookupvar("ENV");
13230 if (shinit != NULL && *shinit != '\0') {
13231 read_profile(shinit);
13232 }
13233 }
13234 state3:
13235 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013236 if (minusc) {
13237 /* evalstring pushes parsefile stack.
13238 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013239 * is one of stacked source fds.
13240 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013241 if (!sflag)
13242 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013243 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013244 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013245
13246 if (sflag || minusc == NULL) {
13247#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013248 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013249 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013250 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251 line_input_state->hist_file = hp;
13252 }
13253#endif
13254 state4: /* XXX ??? - why isn't this before the "if" statement */
13255 cmdloop(1);
13256 }
13257#if PROFILE
13258 monitor(0);
13259#endif
13260#ifdef GPROF
13261 {
13262 extern void _mcleanup(void);
13263 _mcleanup();
13264 }
13265#endif
13266 exitshell();
13267 /* NOTREACHED */
13268}
13269
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013270
Eric Andersendf82f612001-06-28 07:46:40 +000013271/*-
13272 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013273 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013274 *
13275 * This code is derived from software contributed to Berkeley by
13276 * Kenneth Almquist.
13277 *
13278 * Redistribution and use in source and binary forms, with or without
13279 * modification, are permitted provided that the following conditions
13280 * are met:
13281 * 1. Redistributions of source code must retain the above copyright
13282 * notice, this list of conditions and the following disclaimer.
13283 * 2. Redistributions in binary form must reproduce the above copyright
13284 * notice, this list of conditions and the following disclaimer in the
13285 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013286 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013287 * may be used to endorse or promote products derived from this software
13288 * without specific prior written permission.
13289 *
13290 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13291 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13292 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13293 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13294 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13295 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13296 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13297 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13298 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13299 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13300 * SUCH DAMAGE.
13301 */