blob: 4aaea2803d86cf4d6275acf0100b69a485c49ffb [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
59#undef USE_FEATURE_SH_STANDALONE
60#undef SKIP_FEATURE_SH_STANDALONE(...)
61#define ENABLE_FEATURE_SH_STANDALONE 0
62#define USE_FEATURE_SH_STANDALONE(...)
63#define SKIP_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
Mike Frysinger98c52642009-04-02 10:02:37 +0000188#if ENABLE_SH_MATH_SUPPORT
189 arith_eval_hooks_t math_hooks;
190#endif
191
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000192 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000193 /*
194 * Sigmode records the current value of the signal handlers for the various
195 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000196 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000197 */
198 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000199#define S_DFL 1 /* default signal handling (SIG_DFL) */
200#define S_CATCH 2 /* signal is caught */
201#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000202#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000203
Denis Vlasenko01631112007-12-16 17:20:38 +0000204 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000205 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000206 char *trap[NSIG];
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000207
208 /* Rarely referenced stuff */
209#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000210 /* Random number generators */
211 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
212 uint32_t random_LCG; /* LCG (fast but weak) */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000213#endif
214 pid_t backgndpid; /* pid of last background process */
215 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000216};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000217extern struct globals_misc *const ash_ptr_to_globals_misc;
218#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000219#define rootpid (G_misc.rootpid )
220#define shlvl (G_misc.shlvl )
221#define minusc (G_misc.minusc )
222#define curdir (G_misc.curdir )
223#define physdir (G_misc.physdir )
224#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000225#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000226#define exception_type (G_misc.exception_type )
Denis Vlasenko01631112007-12-16 17:20:38 +0000227#define suppressint (G_misc.suppressint )
228#define intpending (G_misc.intpending )
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000229//#define exsig (G_misc.exsig )
Denis Vlasenko01631112007-12-16 17:20:38 +0000230#define pendingsig (G_misc.pendingsig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000231#define isloginsh (G_misc.isloginsh )
232#define nullstr (G_misc.nullstr )
233#define optlist (G_misc.optlist )
234#define sigmode (G_misc.sigmode )
235#define gotsig (G_misc.gotsig )
236#define trap (G_misc.trap )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000237#define random_galois_LFSR (G_misc.random_galois_LFSR)
238#define random_LCG (G_misc.random_LCG )
239#define backgndpid (G_misc.backgndpid )
240#define job_warning (G_misc.job_warning)
Mike Frysinger98c52642009-04-02 10:02:37 +0000241#define math_hooks (G_misc.math_hooks )
Denis Vlasenko01631112007-12-16 17:20:38 +0000242#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
244 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000245 curdir = nullstr; \
246 physdir = nullstr; \
247} while (0)
248
249
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000250/* ============ DEBUG */
251#if DEBUG
252static void trace_printf(const char *fmt, ...);
253static void trace_vprintf(const char *fmt, va_list va);
254# define TRACE(param) trace_printf param
255# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000256# define close(fd) do { \
257 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000258 if (close(dfd) < 0) \
259 bb_error_msg("bug on %d: closing %d(%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000260 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000261} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000262#else
263# define TRACE(param)
264# define TRACEV(param)
265#endif
266
267
Denis Vlasenko559691a2008-10-05 18:39:31 +0000268/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000269#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
270
271/* C99 say: "char" declaration may be signed or unsigned by default */
272#define signed_char2int(sc) ((int)(signed char)(sc))
273
Denis Vlasenko559691a2008-10-05 18:39:31 +0000274static int isdigit_str9(const char *str)
275{
276 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
277 while (--maxlen && isdigit(*str))
278 str++;
279 return (*str == '\0');
280}
Denis Vlasenko01631112007-12-16 17:20:38 +0000281
Denis Vlasenko559691a2008-10-05 18:39:31 +0000282
283/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000284/*
Eric Andersen2870d962001-07-02 17:27:21 +0000285 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000286 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000287 * much more efficient and portable. (But hacking the kernel is so much
288 * more fun than worrying about efficiency and portability. :-))
289 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000290#define INT_OFF do { \
291 suppressint++; \
292 xbarrier(); \
293} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000294
295/*
296 * Called to raise an exception. Since C doesn't include exceptions, we
297 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000298 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000299 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000300static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301static void
302raise_exception(int e)
303{
304#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000305 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000306 abort();
307#endif
308 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000309 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000310 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000311}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000312#if DEBUG
313#define raise_exception(e) do { \
314 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
315 raise_exception(e); \
316} while (0)
317#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318
319/*
320 * Called from trap.c when a SIGINT is received. (If the user specifies
321 * that SIGINT is to be trapped or ignored using the trap builtin, then
322 * this routine is not called.) Suppressint is nonzero when interrupts
323 * are held using the INT_OFF macro. (The test for iflag is just
324 * defensive programming.)
325 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000326static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000327static void
328raise_interrupt(void)
329{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000330 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000331
332 intpending = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000333 /* Signal is not automatically unmasked after it is raised,
334 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000335 sigprocmask_allsigs(SIG_UNBLOCK);
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000336 /* pendingsig = 0; - now done in onsig() */
337
Denis Vlasenko4b875702009-03-19 13:30:04 +0000338 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000339 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
340 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000341 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000342 signal(SIGINT, SIG_DFL);
343 raise(SIGINT);
344 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000345 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000347 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348 /* NOTREACHED */
349}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000350#if DEBUG
351#define raise_interrupt() do { \
352 TRACE(("raising interrupt on line %d\n", __LINE__)); \
353 raise_interrupt(); \
354} while (0)
355#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000356
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000357static USE_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000358int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000359{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000360 xbarrier();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361 if (--suppressint == 0 && intpending) {
362 raise_interrupt();
363 }
364}
365#define INT_ON int_on()
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000366static USE_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000367force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000368{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000369 xbarrier();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000370 suppressint = 0;
371 if (intpending)
372 raise_interrupt();
373}
374#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000375
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376#define SAVE_INT(v) ((v) = suppressint)
377
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000378#define RESTORE_INT(v) do { \
379 xbarrier(); \
380 suppressint = (v); \
381 if (suppressint == 0 && intpending) \
382 raise_interrupt(); \
383} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000384
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000385
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000386/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000387
Eric Andersenc470f442003-07-28 09:56:35 +0000388static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000389outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000390{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000391 INT_OFF;
392 fputs(p, file);
393 INT_ON;
394}
395
396static void
397flush_stdout_stderr(void)
398{
399 INT_OFF;
400 fflush(stdout);
401 fflush(stderr);
402 INT_ON;
403}
404
405static void
406flush_stderr(void)
407{
408 INT_OFF;
409 fflush(stderr);
410 INT_ON;
411}
412
413static void
414outcslow(int c, FILE *dest)
415{
416 INT_OFF;
417 putc(c, dest);
418 fflush(dest);
419 INT_ON;
420}
421
422static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
423static int
424out1fmt(const char *fmt, ...)
425{
426 va_list ap;
427 int r;
428
429 INT_OFF;
430 va_start(ap, fmt);
431 r = vprintf(fmt, ap);
432 va_end(ap);
433 INT_ON;
434 return r;
435}
436
437static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
438static int
439fmtstr(char *outbuf, size_t length, const char *fmt, ...)
440{
441 va_list ap;
442 int ret;
443
444 va_start(ap, fmt);
445 INT_OFF;
446 ret = vsnprintf(outbuf, length, fmt, ap);
447 va_end(ap);
448 INT_ON;
449 return ret;
450}
451
452static void
453out1str(const char *p)
454{
455 outstr(p, stdout);
456}
457
458static void
459out2str(const char *p)
460{
461 outstr(p, stderr);
462 flush_stderr();
463}
464
465
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000466/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000467
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000468/* control characters in argument strings */
469#define CTLESC '\201' /* escape next character */
470#define CTLVAR '\202' /* variable defn */
471#define CTLENDVAR '\203'
472#define CTLBACKQ '\204'
473#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
474/* CTLBACKQ | CTLQUOTE == '\205' */
475#define CTLARI '\206' /* arithmetic expression */
476#define CTLENDARI '\207'
477#define CTLQUOTEMARK '\210'
478
479/* variable substitution byte (follows CTLVAR) */
480#define VSTYPE 0x0f /* type of variable substitution */
481#define VSNUL 0x10 /* colon--treat the empty string as unset */
482#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
483
484/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000485#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
486#define VSMINUS 0x2 /* ${var-text} */
487#define VSPLUS 0x3 /* ${var+text} */
488#define VSQUESTION 0x4 /* ${var?message} */
489#define VSASSIGN 0x5 /* ${var=text} */
490#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
491#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
492#define VSTRIMLEFT 0x8 /* ${var#pattern} */
493#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
494#define VSLENGTH 0xa /* ${#var} */
495#if ENABLE_ASH_BASH_COMPAT
496#define VSSUBSTR 0xc /* ${var:position:length} */
497#define VSREPLACE 0xd /* ${var/pattern/replacement} */
498#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
499#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000500
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000501static const char dolatstr[] ALIGN1 = {
502 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
503};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000504
Denis Vlasenko559691a2008-10-05 18:39:31 +0000505#define NCMD 0
506#define NPIPE 1
507#define NREDIR 2
508#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000509#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000510#define NAND 5
511#define NOR 6
512#define NSEMI 7
513#define NIF 8
514#define NWHILE 9
515#define NUNTIL 10
516#define NFOR 11
517#define NCASE 12
518#define NCLIST 13
519#define NDEFUN 14
520#define NARG 15
521#define NTO 16
522#if ENABLE_ASH_BASH_COMPAT
523#define NTO2 17
524#endif
525#define NCLOBBER 18
526#define NFROM 19
527#define NFROMTO 20
528#define NAPPEND 21
529#define NTOFD 22
530#define NFROMFD 23
531#define NHERE 24
532#define NXHERE 25
533#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000534#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535
536union node;
537
538struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000539 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 union node *assign;
541 union node *args;
542 union node *redirect;
543};
544
545struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000546 smallint type;
547 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 struct nodelist *cmdlist;
549};
550
551struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000552 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000553 union node *n;
554 union node *redirect;
555};
556
557struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000558 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000559 union node *ch1;
560 union node *ch2;
561};
562
563struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000564 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000565 union node *test;
566 union node *ifpart;
567 union node *elsepart;
568};
569
570struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000571 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000572 union node *args;
573 union node *body;
574 char *var;
575};
576
577struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000578 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000579 union node *expr;
580 union node *cases;
581};
582
583struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000584 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000585 union node *next;
586 union node *pattern;
587 union node *body;
588};
589
590struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000591 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000592 union node *next;
593 char *text;
594 struct nodelist *backquote;
595};
596
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597/* nfile and ndup layout must match!
598 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
599 * that it is actually NTO2 (>&file), and change its type.
600 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000602 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000603 union node *next;
604 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000605 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 union node *fname;
607 char *expfname;
608};
609
610struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000611 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000612 union node *next;
613 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000614 int dupfd;
615 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000616 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000617};
618
619struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000620 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000621 union node *next;
622 int fd;
623 union node *doc;
624};
625
626struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000627 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000628 union node *com;
629};
630
631union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000632 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000633 struct ncmd ncmd;
634 struct npipe npipe;
635 struct nredir nredir;
636 struct nbinary nbinary;
637 struct nif nif;
638 struct nfor nfor;
639 struct ncase ncase;
640 struct nclist nclist;
641 struct narg narg;
642 struct nfile nfile;
643 struct ndup ndup;
644 struct nhere nhere;
645 struct nnot nnot;
646};
647
648struct nodelist {
649 struct nodelist *next;
650 union node *n;
651};
652
653struct funcnode {
654 int count;
655 union node n;
656};
657
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000658/*
659 * Free a parse tree.
660 */
661static void
662freefunc(struct funcnode *f)
663{
664 if (f && --f->count < 0)
665 free(f);
666}
667
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000668
669/* ============ Debugging output */
670
671#if DEBUG
672
673static FILE *tracefile;
674
675static void
676trace_printf(const char *fmt, ...)
677{
678 va_list va;
679
680 if (debug != 1)
681 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000682 if (DEBUG_TIME)
683 fprintf(tracefile, "%u ", (int) time(NULL));
684 if (DEBUG_PID)
685 fprintf(tracefile, "[%u] ", (int) getpid());
686 if (DEBUG_SIG)
687 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000688 va_start(va, fmt);
689 vfprintf(tracefile, fmt, va);
690 va_end(va);
691}
692
693static void
694trace_vprintf(const char *fmt, va_list va)
695{
696 if (debug != 1)
697 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000698 if (DEBUG_TIME)
699 fprintf(tracefile, "%u ", (int) time(NULL));
700 if (DEBUG_PID)
701 fprintf(tracefile, "[%u] ", (int) getpid());
702 if (DEBUG_SIG)
703 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000704 vfprintf(tracefile, fmt, va);
705}
706
707static void
708trace_puts(const char *s)
709{
710 if (debug != 1)
711 return;
712 fputs(s, tracefile);
713}
714
715static void
716trace_puts_quoted(char *s)
717{
718 char *p;
719 char c;
720
721 if (debug != 1)
722 return;
723 putc('"', tracefile);
724 for (p = s; *p; p++) {
725 switch (*p) {
726 case '\n': c = 'n'; goto backslash;
727 case '\t': c = 't'; goto backslash;
728 case '\r': c = 'r'; goto backslash;
729 case '"': c = '"'; goto backslash;
730 case '\\': c = '\\'; goto backslash;
731 case CTLESC: c = 'e'; goto backslash;
732 case CTLVAR: c = 'v'; goto backslash;
733 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
734 case CTLBACKQ: c = 'q'; goto backslash;
735 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
736 backslash:
737 putc('\\', tracefile);
738 putc(c, tracefile);
739 break;
740 default:
741 if (*p >= ' ' && *p <= '~')
742 putc(*p, tracefile);
743 else {
744 putc('\\', tracefile);
745 putc(*p >> 6 & 03, tracefile);
746 putc(*p >> 3 & 07, tracefile);
747 putc(*p & 07, tracefile);
748 }
749 break;
750 }
751 }
752 putc('"', tracefile);
753}
754
755static void
756trace_puts_args(char **ap)
757{
758 if (debug != 1)
759 return;
760 if (!*ap)
761 return;
762 while (1) {
763 trace_puts_quoted(*ap);
764 if (!*++ap) {
765 putc('\n', tracefile);
766 break;
767 }
768 putc(' ', tracefile);
769 }
770}
771
772static void
773opentrace(void)
774{
775 char s[100];
776#ifdef O_APPEND
777 int flags;
778#endif
779
780 if (debug != 1) {
781 if (tracefile)
782 fflush(tracefile);
783 /* leave open because libedit might be using it */
784 return;
785 }
786 strcpy(s, "./trace");
787 if (tracefile) {
788 if (!freopen(s, "a", tracefile)) {
789 fprintf(stderr, "Can't re-open %s\n", s);
790 debug = 0;
791 return;
792 }
793 } else {
794 tracefile = fopen(s, "a");
795 if (tracefile == NULL) {
796 fprintf(stderr, "Can't open %s\n", s);
797 debug = 0;
798 return;
799 }
800 }
801#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000802 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000803 if (flags >= 0)
804 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
805#endif
806 setlinebuf(tracefile);
807 fputs("\nTracing started.\n", tracefile);
808}
809
810static void
811indent(int amount, char *pfx, FILE *fp)
812{
813 int i;
814
815 for (i = 0; i < amount; i++) {
816 if (pfx && i == amount - 1)
817 fputs(pfx, fp);
818 putc('\t', fp);
819 }
820}
821
822/* little circular references here... */
823static void shtree(union node *n, int ind, char *pfx, FILE *fp);
824
825static void
826sharg(union node *arg, FILE *fp)
827{
828 char *p;
829 struct nodelist *bqlist;
830 int subtype;
831
832 if (arg->type != NARG) {
833 out1fmt("<node type %d>\n", arg->type);
834 abort();
835 }
836 bqlist = arg->narg.backquote;
837 for (p = arg->narg.text; *p; p++) {
838 switch (*p) {
839 case CTLESC:
840 putc(*++p, fp);
841 break;
842 case CTLVAR:
843 putc('$', fp);
844 putc('{', fp);
845 subtype = *++p;
846 if (subtype == VSLENGTH)
847 putc('#', fp);
848
849 while (*p != '=')
850 putc(*p++, fp);
851
852 if (subtype & VSNUL)
853 putc(':', fp);
854
855 switch (subtype & VSTYPE) {
856 case VSNORMAL:
857 putc('}', fp);
858 break;
859 case VSMINUS:
860 putc('-', fp);
861 break;
862 case VSPLUS:
863 putc('+', fp);
864 break;
865 case VSQUESTION:
866 putc('?', fp);
867 break;
868 case VSASSIGN:
869 putc('=', fp);
870 break;
871 case VSTRIMLEFT:
872 putc('#', fp);
873 break;
874 case VSTRIMLEFTMAX:
875 putc('#', fp);
876 putc('#', fp);
877 break;
878 case VSTRIMRIGHT:
879 putc('%', fp);
880 break;
881 case VSTRIMRIGHTMAX:
882 putc('%', fp);
883 putc('%', fp);
884 break;
885 case VSLENGTH:
886 break;
887 default:
888 out1fmt("<subtype %d>", subtype);
889 }
890 break;
891 case CTLENDVAR:
892 putc('}', fp);
893 break;
894 case CTLBACKQ:
895 case CTLBACKQ|CTLQUOTE:
896 putc('$', fp);
897 putc('(', fp);
898 shtree(bqlist->n, -1, NULL, fp);
899 putc(')', fp);
900 break;
901 default:
902 putc(*p, fp);
903 break;
904 }
905 }
906}
907
908static void
909shcmd(union node *cmd, FILE *fp)
910{
911 union node *np;
912 int first;
913 const char *s;
914 int dftfd;
915
916 first = 1;
917 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000918 if (!first)
919 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000920 sharg(np, fp);
921 first = 0;
922 }
923 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 if (!first)
925 putc(' ', fp);
926 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000927 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000928 case NTO: s = ">>"+1; dftfd = 1; break;
929 case NCLOBBER: s = ">|"; dftfd = 1; break;
930 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000931#if ENABLE_ASH_BASH_COMPAT
932 case NTO2:
933#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000935 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000936 case NFROMFD: s = "<&"; break;
937 case NFROMTO: s = "<>"; break;
938 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000939 }
940 if (np->nfile.fd != dftfd)
941 fprintf(fp, "%d", np->nfile.fd);
942 fputs(s, fp);
943 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
944 fprintf(fp, "%d", np->ndup.dupfd);
945 } else {
946 sharg(np->nfile.fname, fp);
947 }
948 first = 0;
949 }
950}
951
952static void
953shtree(union node *n, int ind, char *pfx, FILE *fp)
954{
955 struct nodelist *lp;
956 const char *s;
957
958 if (n == NULL)
959 return;
960
961 indent(ind, pfx, fp);
962 switch (n->type) {
963 case NSEMI:
964 s = "; ";
965 goto binop;
966 case NAND:
967 s = " && ";
968 goto binop;
969 case NOR:
970 s = " || ";
971 binop:
972 shtree(n->nbinary.ch1, ind, NULL, fp);
973 /* if (ind < 0) */
974 fputs(s, fp);
975 shtree(n->nbinary.ch2, ind, NULL, fp);
976 break;
977 case NCMD:
978 shcmd(n, fp);
979 if (ind >= 0)
980 putc('\n', fp);
981 break;
982 case NPIPE:
983 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
984 shcmd(lp->n, fp);
985 if (lp->next)
986 fputs(" | ", fp);
987 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000988 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989 fputs(" &", fp);
990 if (ind >= 0)
991 putc('\n', fp);
992 break;
993 default:
994 fprintf(fp, "<node type %d>", n->type);
995 if (ind >= 0)
996 putc('\n', fp);
997 break;
998 }
999}
1000
1001static void
1002showtree(union node *n)
1003{
1004 trace_puts("showtree called\n");
1005 shtree(n, 1, NULL, stdout);
1006}
1007
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001008#endif /* DEBUG */
1009
1010
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001011/* ============ Parser data */
1012
1013/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001014 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1015 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001016struct strlist {
1017 struct strlist *next;
1018 char *text;
1019};
1020
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001021struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001022
Denis Vlasenkob012b102007-02-19 22:43:01 +00001023struct strpush {
1024 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001025 char *prev_string;
1026 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001027#if ENABLE_ASH_ALIAS
1028 struct alias *ap; /* if push was associated with an alias */
1029#endif
1030 char *string; /* remember the string since it may change */
1031};
1032
1033struct parsefile {
1034 struct parsefile *prev; /* preceding file on stack */
1035 int linno; /* current line */
1036 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001037 int left_in_line; /* number of chars left in this line */
1038 int left_in_buffer; /* number of chars left in this buffer past the line */
1039 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001040 char *buf; /* input buffer */
1041 struct strpush *strpush; /* for pushing strings at this level */
1042 struct strpush basestrpush; /* so pushing one is fast */
1043};
1044
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001045static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001046static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001047static int startlinno; /* line # where last token started */
1048static char *commandname; /* currently executing command */
1049static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001050static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051
1052
1053/* ============ Message printing */
1054
1055static void
1056ash_vmsg(const char *msg, va_list ap)
1057{
1058 fprintf(stderr, "%s: ", arg0);
1059 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001060 if (strcmp(arg0, commandname))
1061 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001062 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001063 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001064 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001065 vfprintf(stderr, msg, ap);
1066 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001067}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001068
1069/*
1070 * Exverror is called to raise the error exception. If the second argument
1071 * is not NULL then error prints an error message using printf style
1072 * formatting. It then raises the error exception.
1073 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001074static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001075static void
1076ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001077{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001078#if DEBUG
1079 if (msg) {
1080 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1081 TRACEV((msg, ap));
1082 TRACE(("\") pid=%d\n", getpid()));
1083 } else
1084 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1085 if (msg)
1086#endif
1087 ash_vmsg(msg, ap);
1088
1089 flush_stdout_stderr();
1090 raise_exception(cond);
1091 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001092}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001093
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001094static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001095static void
1096ash_msg_and_raise_error(const char *msg, ...)
1097{
1098 va_list ap;
1099
1100 va_start(ap, msg);
1101 ash_vmsg_and_raise(EXERROR, msg, ap);
1102 /* NOTREACHED */
1103 va_end(ap);
1104}
1105
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001106static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001107static void
1108ash_msg_and_raise(int cond, const char *msg, ...)
1109{
1110 va_list ap;
1111
1112 va_start(ap, msg);
1113 ash_vmsg_and_raise(cond, msg, ap);
1114 /* NOTREACHED */
1115 va_end(ap);
1116}
1117
1118/*
1119 * error/warning routines for external builtins
1120 */
1121static void
1122ash_msg(const char *fmt, ...)
1123{
1124 va_list ap;
1125
1126 va_start(ap, fmt);
1127 ash_vmsg(fmt, ap);
1128 va_end(ap);
1129}
1130
1131/*
1132 * Return a string describing an error. The returned string may be a
1133 * pointer to a static buffer that will be overwritten on the next call.
1134 * Action describes the operation that got the error.
1135 */
1136static const char *
1137errmsg(int e, const char *em)
1138{
1139 if (e == ENOENT || e == ENOTDIR) {
1140 return em;
1141 }
1142 return strerror(e);
1143}
1144
1145
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001146/* ============ Memory allocation */
1147
1148/*
1149 * It appears that grabstackstr() will barf with such alignments
1150 * because stalloc() will return a string allocated in a new stackblock.
1151 */
1152#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1153enum {
1154 /* Most machines require the value returned from malloc to be aligned
1155 * in some way. The following macro will get this right
1156 * on many machines. */
1157 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1158 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001159 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001160};
1161
1162struct stack_block {
1163 struct stack_block *prev;
1164 char space[MINSIZE];
1165};
1166
1167struct stackmark {
1168 struct stack_block *stackp;
1169 char *stacknxt;
1170 size_t stacknleft;
1171 struct stackmark *marknext;
1172};
1173
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001174
Denis Vlasenko01631112007-12-16 17:20:38 +00001175struct globals_memstack {
1176 struct stack_block *g_stackp; // = &stackbase;
1177 struct stackmark *markp;
1178 char *g_stacknxt; // = stackbase.space;
1179 char *sstrend; // = stackbase.space + MINSIZE;
1180 size_t g_stacknleft; // = MINSIZE;
1181 int herefd; // = -1;
1182 struct stack_block stackbase;
1183};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001184extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1185#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001186#define g_stackp (G_memstack.g_stackp )
1187#define markp (G_memstack.markp )
1188#define g_stacknxt (G_memstack.g_stacknxt )
1189#define sstrend (G_memstack.sstrend )
1190#define g_stacknleft (G_memstack.g_stacknleft)
1191#define herefd (G_memstack.herefd )
1192#define stackbase (G_memstack.stackbase )
1193#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001194 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1195 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001196 g_stackp = &stackbase; \
1197 g_stacknxt = stackbase.space; \
1198 g_stacknleft = MINSIZE; \
1199 sstrend = stackbase.space + MINSIZE; \
1200 herefd = -1; \
1201} while (0)
1202
1203#define stackblock() ((void *)g_stacknxt)
1204#define stackblocksize() g_stacknleft
1205
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001206
1207static void *
1208ckrealloc(void * p, size_t nbytes)
1209{
1210 p = realloc(p, nbytes);
1211 if (!p)
1212 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1213 return p;
1214}
1215
1216static void *
1217ckmalloc(size_t nbytes)
1218{
1219 return ckrealloc(NULL, nbytes);
1220}
1221
Denis Vlasenko597906c2008-02-20 16:38:54 +00001222static void *
1223ckzalloc(size_t nbytes)
1224{
1225 return memset(ckmalloc(nbytes), 0, nbytes);
1226}
1227
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001228/*
1229 * Make a copy of a string in safe storage.
1230 */
1231static char *
1232ckstrdup(const char *s)
1233{
1234 char *p = strdup(s);
1235 if (!p)
1236 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1237 return p;
1238}
1239
1240/*
1241 * Parse trees for commands are allocated in lifo order, so we use a stack
1242 * to make this more efficient, and also to avoid all sorts of exception
1243 * handling code to handle interrupts in the middle of a parse.
1244 *
1245 * The size 504 was chosen because the Ultrix malloc handles that size
1246 * well.
1247 */
1248static void *
1249stalloc(size_t nbytes)
1250{
1251 char *p;
1252 size_t aligned;
1253
1254 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001255 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001256 size_t len;
1257 size_t blocksize;
1258 struct stack_block *sp;
1259
1260 blocksize = aligned;
1261 if (blocksize < MINSIZE)
1262 blocksize = MINSIZE;
1263 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1264 if (len < blocksize)
1265 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1266 INT_OFF;
1267 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001268 sp->prev = g_stackp;
1269 g_stacknxt = sp->space;
1270 g_stacknleft = blocksize;
1271 sstrend = g_stacknxt + blocksize;
1272 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001273 INT_ON;
1274 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001275 p = g_stacknxt;
1276 g_stacknxt += aligned;
1277 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001278 return p;
1279}
1280
Denis Vlasenko597906c2008-02-20 16:38:54 +00001281static void *
1282stzalloc(size_t nbytes)
1283{
1284 return memset(stalloc(nbytes), 0, nbytes);
1285}
1286
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001287static void
1288stunalloc(void *p)
1289{
1290#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001291 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001292 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001293 abort();
1294 }
1295#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001296 g_stacknleft += g_stacknxt - (char *)p;
1297 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001298}
1299
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001300/*
1301 * Like strdup but works with the ash stack.
1302 */
1303static char *
1304ststrdup(const char *p)
1305{
1306 size_t len = strlen(p) + 1;
1307 return memcpy(stalloc(len), p, len);
1308}
1309
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001310static void
1311setstackmark(struct stackmark *mark)
1312{
Denis Vlasenko01631112007-12-16 17:20:38 +00001313 mark->stackp = g_stackp;
1314 mark->stacknxt = g_stacknxt;
1315 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001316 mark->marknext = markp;
1317 markp = mark;
1318}
1319
1320static void
1321popstackmark(struct stackmark *mark)
1322{
1323 struct stack_block *sp;
1324
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001325 if (!mark->stackp)
1326 return;
1327
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001328 INT_OFF;
1329 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001330 while (g_stackp != mark->stackp) {
1331 sp = g_stackp;
1332 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001333 free(sp);
1334 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 g_stacknxt = mark->stacknxt;
1336 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001337 sstrend = mark->stacknxt + mark->stacknleft;
1338 INT_ON;
1339}
1340
1341/*
1342 * When the parser reads in a string, it wants to stick the string on the
1343 * stack and only adjust the stack pointer when it knows how big the
1344 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1345 * of space on top of the stack and stackblocklen returns the length of
1346 * this block. Growstackblock will grow this space by at least one byte,
1347 * possibly moving it (like realloc). Grabstackblock actually allocates the
1348 * part of the block that has been used.
1349 */
1350static void
1351growstackblock(void)
1352{
1353 size_t newlen;
1354
Denis Vlasenko01631112007-12-16 17:20:38 +00001355 newlen = g_stacknleft * 2;
1356 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001357 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1358 if (newlen < 128)
1359 newlen += 128;
1360
Denis Vlasenko01631112007-12-16 17:20:38 +00001361 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001362 struct stack_block *oldstackp;
1363 struct stackmark *xmark;
1364 struct stack_block *sp;
1365 struct stack_block *prevstackp;
1366 size_t grosslen;
1367
1368 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001369 oldstackp = g_stackp;
1370 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001371 prevstackp = sp->prev;
1372 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1373 sp = ckrealloc(sp, grosslen);
1374 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001375 g_stackp = sp;
1376 g_stacknxt = sp->space;
1377 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001378 sstrend = sp->space + newlen;
1379
1380 /*
1381 * Stack marks pointing to the start of the old block
1382 * must be relocated to point to the new block
1383 */
1384 xmark = markp;
1385 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001386 xmark->stackp = g_stackp;
1387 xmark->stacknxt = g_stacknxt;
1388 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001389 xmark = xmark->marknext;
1390 }
1391 INT_ON;
1392 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001393 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001394 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001395 char *p = stalloc(newlen);
1396
1397 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001398 g_stacknxt = memcpy(p, oldspace, oldlen);
1399 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 }
1401}
1402
1403static void
1404grabstackblock(size_t len)
1405{
1406 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001407 g_stacknxt += len;
1408 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001409}
1410
1411/*
1412 * The following routines are somewhat easier to use than the above.
1413 * The user declares a variable of type STACKSTR, which may be declared
1414 * to be a register. The macro STARTSTACKSTR initializes things. Then
1415 * the user uses the macro STPUTC to add characters to the string. In
1416 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1417 * grown as necessary. When the user is done, she can just leave the
1418 * string there and refer to it using stackblock(). Or she can allocate
1419 * the space for it using grabstackstr(). If it is necessary to allow
1420 * someone else to use the stack temporarily and then continue to grow
1421 * the string, the user should use grabstack to allocate the space, and
1422 * then call ungrabstr(p) to return to the previous mode of operation.
1423 *
1424 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1425 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1426 * is space for at least one character.
1427 */
1428static void *
1429growstackstr(void)
1430{
1431 size_t len = stackblocksize();
1432 if (herefd >= 0 && len >= 1024) {
1433 full_write(herefd, stackblock(), len);
1434 return stackblock();
1435 }
1436 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001437 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001438}
1439
1440/*
1441 * Called from CHECKSTRSPACE.
1442 */
1443static char *
1444makestrspace(size_t newlen, char *p)
1445{
Denis Vlasenko01631112007-12-16 17:20:38 +00001446 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001447 size_t size = stackblocksize();
1448
1449 for (;;) {
1450 size_t nleft;
1451
1452 size = stackblocksize();
1453 nleft = size - len;
1454 if (nleft >= newlen)
1455 break;
1456 growstackblock();
1457 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001458 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001459}
1460
1461static char *
1462stack_nputstr(const char *s, size_t n, char *p)
1463{
1464 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001465 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001466 return p;
1467}
1468
1469static char *
1470stack_putstr(const char *s, char *p)
1471{
1472 return stack_nputstr(s, strlen(s), p);
1473}
1474
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001475static char *
1476_STPUTC(int c, char *p)
1477{
1478 if (p == sstrend)
1479 p = growstackstr();
1480 *p++ = c;
1481 return p;
1482}
1483
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001484#define STARTSTACKSTR(p) ((p) = stackblock())
1485#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001486#define CHECKSTRSPACE(n, p) do { \
1487 char *q = (p); \
1488 size_t l = (n); \
1489 size_t m = sstrend - q; \
1490 if (l > m) \
1491 (p) = makestrspace(l, q); \
1492} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001493#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001494#define STACKSTRNUL(p) do { \
1495 if ((p) == sstrend) \
1496 (p) = growstackstr(); \
1497 *(p) = '\0'; \
1498} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001499#define STUNPUTC(p) (--(p))
1500#define STTOPC(p) ((p)[-1])
1501#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001502
1503#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001504#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001505#define stackstrend() ((void *)sstrend)
1506
1507
1508/* ============ String helpers */
1509
1510/*
1511 * prefix -- see if pfx is a prefix of string.
1512 */
1513static char *
1514prefix(const char *string, const char *pfx)
1515{
1516 while (*pfx) {
1517 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001518 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001519 }
1520 return (char *) string;
1521}
1522
1523/*
1524 * Check for a valid number. This should be elsewhere.
1525 */
1526static int
1527is_number(const char *p)
1528{
1529 do {
1530 if (!isdigit(*p))
1531 return 0;
1532 } while (*++p != '\0');
1533 return 1;
1534}
1535
1536/*
1537 * Convert a string of digits to an integer, printing an error message on
1538 * failure.
1539 */
1540static int
1541number(const char *s)
1542{
1543 if (!is_number(s))
1544 ash_msg_and_raise_error(illnum, s);
1545 return atoi(s);
1546}
1547
1548/*
1549 * Produce a possibly single quoted string suitable as input to the shell.
1550 * The return string is allocated on the stack.
1551 */
1552static char *
1553single_quote(const char *s)
1554{
1555 char *p;
1556
1557 STARTSTACKSTR(p);
1558
1559 do {
1560 char *q;
1561 size_t len;
1562
1563 len = strchrnul(s, '\'') - s;
1564
1565 q = p = makestrspace(len + 3, p);
1566
1567 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001568 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001569 *q++ = '\'';
1570 s += len;
1571
1572 STADJUST(q - p, p);
1573
1574 len = strspn(s, "'");
1575 if (!len)
1576 break;
1577
1578 q = p = makestrspace(len + 3, p);
1579
1580 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001581 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001582 *q++ = '"';
1583 s += len;
1584
1585 STADJUST(q - p, p);
1586 } while (*s);
1587
1588 USTPUTC(0, p);
1589
1590 return stackblock();
1591}
1592
1593
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001594/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001595
1596static char **argptr; /* argument list for builtin commands */
1597static char *optionarg; /* set by nextopt (like getopt) */
1598static char *optptr; /* used by nextopt */
1599
1600/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001601 * XXX - should get rid of. Have all builtins use getopt(3).
1602 * The library getopt must have the BSD extension static variable
1603 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001605 * Standard option processing (a la getopt) for builtin routines.
1606 * The only argument that is passed to nextopt is the option string;
1607 * the other arguments are unnecessary. It returns the character,
1608 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001609 */
1610static int
1611nextopt(const char *optstring)
1612{
1613 char *p;
1614 const char *q;
1615 char c;
1616
1617 p = optptr;
1618 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001619 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001620 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001621 if (p == NULL)
1622 return '\0';
1623 if (*p != '-')
1624 return '\0';
1625 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001626 return '\0';
1627 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001628 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001629 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001630 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001631 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001632 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001633 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001634 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001635 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001636 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001637 if (*++q == ':')
1638 q++;
1639 }
1640 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 if (*p == '\0') {
1642 p = *argptr++;
1643 if (p == NULL)
1644 ash_msg_and_raise_error("no arg for -%c option", c);
1645 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001646 optionarg = p;
1647 p = NULL;
1648 }
1649 optptr = p;
1650 return c;
1651}
1652
1653
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001654/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655
Denis Vlasenko01631112007-12-16 17:20:38 +00001656/*
1657 * The parsefile structure pointed to by the global variable parsefile
1658 * contains information about the current file being read.
1659 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001660struct shparam {
1661 int nparam; /* # of positional parameters (without $0) */
1662#if ENABLE_ASH_GETOPTS
1663 int optind; /* next parameter to be processed by getopts */
1664 int optoff; /* used by getopts */
1665#endif
1666 unsigned char malloced; /* if parameter list dynamically allocated */
1667 char **p; /* parameter list */
1668};
1669
1670/*
1671 * Free the list of positional parameters.
1672 */
1673static void
1674freeparam(volatile struct shparam *param)
1675{
Denis Vlasenko01631112007-12-16 17:20:38 +00001676 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001677 char **ap, **ap1;
1678 ap = ap1 = param->p;
1679 while (*ap)
1680 free(*ap++);
1681 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001682 }
1683}
1684
1685#if ENABLE_ASH_GETOPTS
1686static void getoptsreset(const char *value);
1687#endif
1688
1689struct var {
1690 struct var *next; /* next entry in hash list */
1691 int flags; /* flags are defined above */
1692 const char *text; /* name=value */
1693 void (*func)(const char *); /* function to be called when */
1694 /* the variable gets set/unset */
1695};
1696
1697struct localvar {
1698 struct localvar *next; /* next local variable in list */
1699 struct var *vp; /* the variable that was made local */
1700 int flags; /* saved flags */
1701 const char *text; /* saved text */
1702};
1703
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001704/* flags */
1705#define VEXPORT 0x01 /* variable is exported */
1706#define VREADONLY 0x02 /* variable cannot be modified */
1707#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1708#define VTEXTFIXED 0x08 /* text is statically allocated */
1709#define VSTACK 0x10 /* text is allocated on the stack */
1710#define VUNSET 0x20 /* the variable is not set */
1711#define VNOFUNC 0x40 /* don't call the callback function */
1712#define VNOSET 0x80 /* do not set variable - just readonly test */
1713#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001714#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001715# define VDYNAMIC 0x200 /* dynamic variable */
1716#else
1717# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001718#endif
1719
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001720#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001721static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001722#define defifs (defifsvar + 4)
1723#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001724static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001725#endif
1726
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001727
Denis Vlasenko01631112007-12-16 17:20:38 +00001728/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001729#if ENABLE_LOCALE_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001730static void
1731change_lc_all(const char *value)
1732{
1733 if (value && *value != '\0')
1734 setlocale(LC_ALL, value);
1735}
1736static void
1737change_lc_ctype(const char *value)
1738{
1739 if (value && *value != '\0')
1740 setlocale(LC_CTYPE, value);
1741}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001742#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001743#if ENABLE_ASH_MAIL
1744static void chkmail(void);
1745static void changemail(const char *);
1746#endif
1747static void changepath(const char *);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001748#if ENABLE_ASH_RANDOM_SUPPORT
1749static void change_random(const char *);
1750#endif
1751
Denis Vlasenko01631112007-12-16 17:20:38 +00001752static const struct {
1753 int flags;
1754 const char *text;
1755 void (*func)(const char *);
1756} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001757#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001758 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001759#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001760 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001763 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1764 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001766 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1767 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1768 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1769 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001771 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#endif
1773#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001774 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001775#endif
1776#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#endif
1780#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001781 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#endif
1783};
1784
Denis Vlasenko0b769642008-07-24 07:54:57 +00001785struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001786
1787struct globals_var {
1788 struct shparam shellparam; /* $@ current positional parameters */
1789 struct redirtab *redirlist;
1790 int g_nullredirs;
1791 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1792 struct var *vartab[VTABSIZE];
1793 struct var varinit[ARRAY_SIZE(varinit_data)];
1794};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001795extern struct globals_var *const ash_ptr_to_globals_var;
1796#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001797#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001798//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001799#define g_nullredirs (G_var.g_nullredirs )
1800#define preverrout_fd (G_var.preverrout_fd)
1801#define vartab (G_var.vartab )
1802#define varinit (G_var.varinit )
1803#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001804 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001805 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1806 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001807 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1808 varinit[i].flags = varinit_data[i].flags; \
1809 varinit[i].text = varinit_data[i].text; \
1810 varinit[i].func = varinit_data[i].func; \
1811 } \
1812} while (0)
1813
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001814#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001815#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001816# define vmail (&vifs)[1]
1817# define vmpath (&vmail)[1]
1818# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001819#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001820# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001821#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001822#define vps1 (&vpath)[1]
1823#define vps2 (&vps1)[1]
1824#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001825#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001826# define voptind (&vps4)[1]
1827# if ENABLE_ASH_RANDOM_SUPPORT
1828# define vrandom (&voptind)[1]
1829# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001830#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001831# if ENABLE_ASH_RANDOM_SUPPORT
1832# define vrandom (&vps4)[1]
1833# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835
1836/*
1837 * The following macros access the values of the above variables.
1838 * They have to skip over the name. They return the null string
1839 * for unset variables.
1840 */
1841#define ifsval() (vifs.text + 4)
1842#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001843#if ENABLE_ASH_MAIL
1844# define mailval() (vmail.text + 5)
1845# define mpathval() (vmpath.text + 9)
1846# define mpathset() ((vmpath.flags & VUNSET) == 0)
1847#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848#define pathval() (vpath.text + 5)
1849#define ps1val() (vps1.text + 4)
1850#define ps2val() (vps2.text + 4)
1851#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001852#if ENABLE_ASH_GETOPTS
1853# define optindval() (voptind.text + 7)
1854#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001856
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001857#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1858#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1859
Denis Vlasenko01631112007-12-16 17:20:38 +00001860#if ENABLE_ASH_GETOPTS
1861static void
1862getoptsreset(const char *value)
1863{
1864 shellparam.optind = number(value);
1865 shellparam.optoff = -1;
1866}
1867#endif
1868
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869/*
1870 * Return of a legal variable name (a letter or underscore followed by zero or
1871 * more letters, underscores, and digits).
1872 */
1873static char *
1874endofname(const char *name)
1875{
1876 char *p;
1877
1878 p = (char *) name;
1879 if (!is_name(*p))
1880 return p;
1881 while (*++p) {
1882 if (!is_in_name(*p))
1883 break;
1884 }
1885 return p;
1886}
1887
1888/*
1889 * Compares two strings up to the first = or '\0'. The first
1890 * string must be terminated by '='; the second may be terminated by
1891 * either '=' or '\0'.
1892 */
1893static int
1894varcmp(const char *p, const char *q)
1895{
1896 int c, d;
1897
1898 while ((c = *p) == (d = *q)) {
1899 if (!c || c == '=')
1900 goto out;
1901 p++;
1902 q++;
1903 }
1904 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001905 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001906 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001907 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001908 out:
1909 return c - d;
1910}
1911
1912static int
1913varequal(const char *a, const char *b)
1914{
1915 return !varcmp(a, b);
1916}
1917
1918/*
1919 * Find the appropriate entry in the hash table from the name.
1920 */
1921static struct var **
1922hashvar(const char *p)
1923{
1924 unsigned hashval;
1925
1926 hashval = ((unsigned char) *p) << 4;
1927 while (*p && *p != '=')
1928 hashval += (unsigned char) *p++;
1929 return &vartab[hashval % VTABSIZE];
1930}
1931
1932static int
1933vpcmp(const void *a, const void *b)
1934{
1935 return varcmp(*(const char **)a, *(const char **)b);
1936}
1937
1938/*
1939 * This routine initializes the builtin variables.
1940 */
1941static void
1942initvar(void)
1943{
1944 struct var *vp;
1945 struct var *end;
1946 struct var **vpp;
1947
1948 /*
1949 * PS1 depends on uid
1950 */
1951#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1952 vps1.text = "PS1=\\w \\$ ";
1953#else
1954 if (!geteuid())
1955 vps1.text = "PS1=# ";
1956#endif
1957 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001958 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001959 do {
1960 vpp = hashvar(vp->text);
1961 vp->next = *vpp;
1962 *vpp = vp;
1963 } while (++vp < end);
1964}
1965
1966static struct var **
1967findvar(struct var **vpp, const char *name)
1968{
1969 for (; *vpp; vpp = &(*vpp)->next) {
1970 if (varequal((*vpp)->text, name)) {
1971 break;
1972 }
1973 }
1974 return vpp;
1975}
1976
1977/*
1978 * Find the value of a variable. Returns NULL if not set.
1979 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001980static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001981lookupvar(const char *name)
1982{
1983 struct var *v;
1984
1985 v = *findvar(hashvar(name), name);
1986 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001987#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001988 /*
1989 * Dynamic variables are implemented roughly the same way they are
1990 * in bash. Namely, they're "special" so long as they aren't unset.
1991 * As soon as they're unset, they're no longer dynamic, and dynamic
1992 * lookup will no longer happen at that point. -- PFM.
1993 */
1994 if ((v->flags & VDYNAMIC))
1995 (*v->func)(NULL);
1996#endif
1997 if (!(v->flags & VUNSET))
1998 return strchrnul(v->text, '=') + 1;
1999 }
2000 return NULL;
2001}
2002
2003/*
2004 * Search the environment of a builtin command.
2005 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002006static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002007bltinlookup(const char *name)
2008{
2009 struct strlist *sp;
2010
2011 for (sp = cmdenviron; sp; sp = sp->next) {
2012 if (varequal(sp->text, name))
2013 return strchrnul(sp->text, '=') + 1;
2014 }
2015 return lookupvar(name);
2016}
2017
2018/*
2019 * Same as setvar except that the variable and value are passed in
2020 * the first argument as name=value. Since the first argument will
2021 * be actually stored in the table, it should not be a string that
2022 * will go away.
2023 * Called with interrupts off.
2024 */
2025static void
2026setvareq(char *s, int flags)
2027{
2028 struct var *vp, **vpp;
2029
2030 vpp = hashvar(s);
2031 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2032 vp = *findvar(vpp, s);
2033 if (vp) {
2034 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2035 const char *n;
2036
2037 if (flags & VNOSAVE)
2038 free(s);
2039 n = vp->text;
2040 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2041 }
2042
2043 if (flags & VNOSET)
2044 return;
2045
2046 if (vp->func && (flags & VNOFUNC) == 0)
2047 (*vp->func)(strchrnul(s, '=') + 1);
2048
2049 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2050 free((char*)vp->text);
2051
2052 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2053 } else {
2054 if (flags & VNOSET)
2055 return;
2056 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002057 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002058 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002059 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002060 *vpp = vp;
2061 }
2062 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2063 s = ckstrdup(s);
2064 vp->text = s;
2065 vp->flags = flags;
2066}
2067
2068/*
2069 * Set the value of a variable. The flags argument is ored with the
2070 * flags of the variable. If val is NULL, the variable is unset.
2071 */
2072static void
2073setvar(const char *name, const char *val, int flags)
2074{
2075 char *p, *q;
2076 size_t namelen;
2077 char *nameeq;
2078 size_t vallen;
2079
2080 q = endofname(name);
2081 p = strchrnul(q, '=');
2082 namelen = p - name;
2083 if (!namelen || p != q)
2084 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2085 vallen = 0;
2086 if (val == NULL) {
2087 flags |= VUNSET;
2088 } else {
2089 vallen = strlen(val);
2090 }
2091 INT_OFF;
2092 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002093 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002094 if (val) {
2095 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002096 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002097 }
2098 *p = '\0';
2099 setvareq(nameeq, flags | VNOSAVE);
2100 INT_ON;
2101}
2102
2103#if ENABLE_ASH_GETOPTS
2104/*
2105 * Safe version of setvar, returns 1 on success 0 on failure.
2106 */
2107static int
2108setvarsafe(const char *name, const char *val, int flags)
2109{
2110 int err;
2111 volatile int saveint;
2112 struct jmploc *volatile savehandler = exception_handler;
2113 struct jmploc jmploc;
2114
2115 SAVE_INT(saveint);
2116 if (setjmp(jmploc.loc))
2117 err = 1;
2118 else {
2119 exception_handler = &jmploc;
2120 setvar(name, val, flags);
2121 err = 0;
2122 }
2123 exception_handler = savehandler;
2124 RESTORE_INT(saveint);
2125 return err;
2126}
2127#endif
2128
2129/*
2130 * Unset the specified variable.
2131 */
2132static int
2133unsetvar(const char *s)
2134{
2135 struct var **vpp;
2136 struct var *vp;
2137 int retval;
2138
2139 vpp = findvar(hashvar(s), s);
2140 vp = *vpp;
2141 retval = 2;
2142 if (vp) {
2143 int flags = vp->flags;
2144
2145 retval = 1;
2146 if (flags & VREADONLY)
2147 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002148#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002149 vp->flags &= ~VDYNAMIC;
2150#endif
2151 if (flags & VUNSET)
2152 goto ok;
2153 if ((flags & VSTRFIXED) == 0) {
2154 INT_OFF;
2155 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2156 free((char*)vp->text);
2157 *vpp = vp->next;
2158 free(vp);
2159 INT_ON;
2160 } else {
2161 setvar(s, 0, 0);
2162 vp->flags &= ~VEXPORT;
2163 }
2164 ok:
2165 retval = 0;
2166 }
2167 out:
2168 return retval;
2169}
2170
2171/*
2172 * Process a linked list of variable assignments.
2173 */
2174static void
2175listsetvar(struct strlist *list_set_var, int flags)
2176{
2177 struct strlist *lp = list_set_var;
2178
2179 if (!lp)
2180 return;
2181 INT_OFF;
2182 do {
2183 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002184 lp = lp->next;
2185 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002186 INT_ON;
2187}
2188
2189/*
2190 * Generate a list of variables satisfying the given conditions.
2191 */
2192static char **
2193listvars(int on, int off, char ***end)
2194{
2195 struct var **vpp;
2196 struct var *vp;
2197 char **ep;
2198 int mask;
2199
2200 STARTSTACKSTR(ep);
2201 vpp = vartab;
2202 mask = on | off;
2203 do {
2204 for (vp = *vpp; vp; vp = vp->next) {
2205 if ((vp->flags & mask) == on) {
2206 if (ep == stackstrend())
2207 ep = growstackstr();
2208 *ep++ = (char *) vp->text;
2209 }
2210 }
2211 } while (++vpp < vartab + VTABSIZE);
2212 if (ep == stackstrend())
2213 ep = growstackstr();
2214 if (end)
2215 *end = ep;
2216 *ep++ = NULL;
2217 return grabstackstr(ep);
2218}
2219
2220
2221/* ============ Path search helper
2222 *
2223 * The variable path (passed by reference) should be set to the start
2224 * of the path before the first call; padvance will update
2225 * this value as it proceeds. Successive calls to padvance will return
2226 * the possible path expansions in sequence. If an option (indicated by
2227 * a percent sign) appears in the path entry then the global variable
2228 * pathopt will be set to point to it; otherwise pathopt will be set to
2229 * NULL.
2230 */
2231static const char *pathopt; /* set by padvance */
2232
2233static char *
2234padvance(const char **path, const char *name)
2235{
2236 const char *p;
2237 char *q;
2238 const char *start;
2239 size_t len;
2240
2241 if (*path == NULL)
2242 return NULL;
2243 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002244 for (p = start; *p && *p != ':' && *p != '%'; p++)
2245 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2247 while (stackblocksize() < len)
2248 growstackblock();
2249 q = stackblock();
2250 if (p != start) {
2251 memcpy(q, start, p - start);
2252 q += p - start;
2253 *q++ = '/';
2254 }
2255 strcpy(q, name);
2256 pathopt = NULL;
2257 if (*p == '%') {
2258 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002259 while (*p && *p != ':')
2260 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002261 }
2262 if (*p == ':')
2263 *path = p + 1;
2264 else
2265 *path = NULL;
2266 return stalloc(len);
2267}
2268
2269
2270/* ============ Prompt */
2271
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002272static smallint doprompt; /* if set, prompt the user */
2273static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002274
2275#if ENABLE_FEATURE_EDITING
2276static line_input_t *line_input_state;
2277static const char *cmdedit_prompt;
2278static void
2279putprompt(const char *s)
2280{
2281 if (ENABLE_ASH_EXPAND_PRMT) {
2282 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002283 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002284 return;
2285 }
2286 cmdedit_prompt = s;
2287}
2288#else
2289static void
2290putprompt(const char *s)
2291{
2292 out2str(s);
2293}
2294#endif
2295
2296#if ENABLE_ASH_EXPAND_PRMT
2297/* expandstr() needs parsing machinery, so it is far away ahead... */
2298static const char *expandstr(const char *ps);
2299#else
2300#define expandstr(s) s
2301#endif
2302
2303static void
2304setprompt(int whichprompt)
2305{
2306 const char *prompt;
2307#if ENABLE_ASH_EXPAND_PRMT
2308 struct stackmark smark;
2309#endif
2310
2311 needprompt = 0;
2312
2313 switch (whichprompt) {
2314 case 1:
2315 prompt = ps1val();
2316 break;
2317 case 2:
2318 prompt = ps2val();
2319 break;
2320 default: /* 0 */
2321 prompt = nullstr;
2322 }
2323#if ENABLE_ASH_EXPAND_PRMT
2324 setstackmark(&smark);
2325 stalloc(stackblocksize());
2326#endif
2327 putprompt(expandstr(prompt));
2328#if ENABLE_ASH_EXPAND_PRMT
2329 popstackmark(&smark);
2330#endif
2331}
2332
2333
2334/* ============ The cd and pwd commands */
2335
2336#define CD_PHYSICAL 1
2337#define CD_PRINT 2
2338
2339static int docd(const char *, int);
2340
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002341static int
2342cdopt(void)
2343{
2344 int flags = 0;
2345 int i, j;
2346
2347 j = 'L';
2348 while ((i = nextopt("LP"))) {
2349 if (i != j) {
2350 flags ^= CD_PHYSICAL;
2351 j = i;
2352 }
2353 }
2354
2355 return flags;
2356}
2357
2358/*
2359 * Update curdir (the name of the current directory) in response to a
2360 * cd command.
2361 */
2362static const char *
2363updatepwd(const char *dir)
2364{
2365 char *new;
2366 char *p;
2367 char *cdcomppath;
2368 const char *lim;
2369
2370 cdcomppath = ststrdup(dir);
2371 STARTSTACKSTR(new);
2372 if (*dir != '/') {
2373 if (curdir == nullstr)
2374 return 0;
2375 new = stack_putstr(curdir, new);
2376 }
2377 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002378 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002379 if (*dir != '/') {
2380 if (new[-1] != '/')
2381 USTPUTC('/', new);
2382 if (new > lim && *lim == '/')
2383 lim++;
2384 } else {
2385 USTPUTC('/', new);
2386 cdcomppath++;
2387 if (dir[1] == '/' && dir[2] != '/') {
2388 USTPUTC('/', new);
2389 cdcomppath++;
2390 lim++;
2391 }
2392 }
2393 p = strtok(cdcomppath, "/");
2394 while (p) {
2395 switch (*p) {
2396 case '.':
2397 if (p[1] == '.' && p[2] == '\0') {
2398 while (new > lim) {
2399 STUNPUTC(new);
2400 if (new[-1] == '/')
2401 break;
2402 }
2403 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002404 }
2405 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002406 break;
2407 /* fall through */
2408 default:
2409 new = stack_putstr(p, new);
2410 USTPUTC('/', new);
2411 }
2412 p = strtok(0, "/");
2413 }
2414 if (new > lim)
2415 STUNPUTC(new);
2416 *new = 0;
2417 return stackblock();
2418}
2419
2420/*
2421 * Find out what the current directory is. If we already know the current
2422 * directory, this routine returns immediately.
2423 */
2424static char *
2425getpwd(void)
2426{
Denis Vlasenko01631112007-12-16 17:20:38 +00002427 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002428 return dir ? dir : nullstr;
2429}
2430
2431static void
2432setpwd(const char *val, int setold)
2433{
2434 char *oldcur, *dir;
2435
2436 oldcur = dir = curdir;
2437
2438 if (setold) {
2439 setvar("OLDPWD", oldcur, VEXPORT);
2440 }
2441 INT_OFF;
2442 if (physdir != nullstr) {
2443 if (physdir != oldcur)
2444 free(physdir);
2445 physdir = nullstr;
2446 }
2447 if (oldcur == val || !val) {
2448 char *s = getpwd();
2449 physdir = s;
2450 if (!val)
2451 dir = s;
2452 } else
2453 dir = ckstrdup(val);
2454 if (oldcur != dir && oldcur != nullstr) {
2455 free(oldcur);
2456 }
2457 curdir = dir;
2458 INT_ON;
2459 setvar("PWD", dir, VEXPORT);
2460}
2461
2462static void hashcd(void);
2463
2464/*
2465 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2466 * know that the current directory has changed.
2467 */
2468static int
2469docd(const char *dest, int flags)
2470{
2471 const char *dir = 0;
2472 int err;
2473
2474 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2475
2476 INT_OFF;
2477 if (!(flags & CD_PHYSICAL)) {
2478 dir = updatepwd(dest);
2479 if (dir)
2480 dest = dir;
2481 }
2482 err = chdir(dest);
2483 if (err)
2484 goto out;
2485 setpwd(dir, 1);
2486 hashcd();
2487 out:
2488 INT_ON;
2489 return err;
2490}
2491
2492static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002493cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002494{
2495 const char *dest;
2496 const char *path;
2497 const char *p;
2498 char c;
2499 struct stat statb;
2500 int flags;
2501
2502 flags = cdopt();
2503 dest = *argptr;
2504 if (!dest)
2505 dest = bltinlookup(homestr);
2506 else if (LONE_DASH(dest)) {
2507 dest = bltinlookup("OLDPWD");
2508 flags |= CD_PRINT;
2509 }
2510 if (!dest)
2511 dest = nullstr;
2512 if (*dest == '/')
2513 goto step7;
2514 if (*dest == '.') {
2515 c = dest[1];
2516 dotdot:
2517 switch (c) {
2518 case '\0':
2519 case '/':
2520 goto step6;
2521 case '.':
2522 c = dest[2];
2523 if (c != '.')
2524 goto dotdot;
2525 }
2526 }
2527 if (!*dest)
2528 dest = ".";
2529 path = bltinlookup("CDPATH");
2530 if (!path) {
2531 step6:
2532 step7:
2533 p = dest;
2534 goto docd;
2535 }
2536 do {
2537 c = *path;
2538 p = padvance(&path, dest);
2539 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2540 if (c && c != ':')
2541 flags |= CD_PRINT;
2542 docd:
2543 if (!docd(p, flags))
2544 goto out;
2545 break;
2546 }
2547 } while (path);
2548 ash_msg_and_raise_error("can't cd to %s", dest);
2549 /* NOTREACHED */
2550 out:
2551 if (flags & CD_PRINT)
2552 out1fmt(snlfmt, curdir);
2553 return 0;
2554}
2555
2556static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002557pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002558{
2559 int flags;
2560 const char *dir = curdir;
2561
2562 flags = cdopt();
2563 if (flags) {
2564 if (physdir == nullstr)
2565 setpwd(dir, 0);
2566 dir = physdir;
2567 }
2568 out1fmt(snlfmt, dir);
2569 return 0;
2570}
2571
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002572
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002573/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002574
Denis Vlasenko834dee72008-10-07 09:18:30 +00002575
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002576#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002577/* buffer for top level input file */
2578#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002579
Eric Andersenc470f442003-07-28 09:56:35 +00002580/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002581#define CWORD 0 /* character is nothing special */
2582#define CNL 1 /* newline character */
2583#define CBACK 2 /* a backslash character */
2584#define CSQUOTE 3 /* single quote */
2585#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002586#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002587#define CBQUOTE 6 /* backwards single quote */
2588#define CVAR 7 /* a dollar sign */
2589#define CENDVAR 8 /* a '}' character */
2590#define CLP 9 /* a left paren in arithmetic */
2591#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002592#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593#define CCTL 12 /* like CWORD, except it must be escaped */
2594#define CSPCL 13 /* these terminate a word */
2595#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002596
Denis Vlasenko131ae172007-02-18 13:00:19 +00002597#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002598#define SYNBASE 130
2599#define PEOF -130
2600#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define PEOA_OR_PEOF PEOA
2602#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002603#define SYNBASE 129
2604#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002605#define PEOA_OR_PEOF PEOF
2606#endif
2607
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002608/* number syntax index */
2609#define BASESYNTAX 0 /* not in quotes */
2610#define DQSYNTAX 1 /* in double quotes */
2611#define SQSYNTAX 2 /* in single quotes */
2612#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002613#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002614
Denis Vlasenko131ae172007-02-18 13:00:19 +00002615#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002616#define USE_SIT_FUNCTION
2617#endif
2618
Mike Frysinger98c52642009-04-02 10:02:37 +00002619#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002620static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002621#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002622 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002623#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002624 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2625 { CNL, CNL, CNL, CNL }, /* 2, \n */
2626 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2627 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2628 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2629 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2630 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2631 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2632 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2633 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2634 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002635#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002636 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2637 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2638 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002639#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002640};
Eric Andersenc470f442003-07-28 09:56:35 +00002641#else
2642static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002643#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002644 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002645#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002646 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2647 { CNL, CNL, CNL }, /* 2, \n */
2648 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2649 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2650 { CVAR, CVAR, CWORD }, /* 5, $ */
2651 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2652 { CSPCL, CWORD, CWORD }, /* 7, ( */
2653 { CSPCL, CWORD, CWORD }, /* 8, ) */
2654 { CBACK, CBACK, CCTL }, /* 9, \ */
2655 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2656 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002657#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002658 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2659 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2660 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002661#endif
2662};
Mike Frysinger98c52642009-04-02 10:02:37 +00002663#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002664
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002665#ifdef USE_SIT_FUNCTION
2666
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002667static int
2668SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002669{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002670 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002671#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002672 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002673 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2674 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2675 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2676 11, 3 /* "}~" */
2677 };
2678#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002679 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002680 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2681 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2682 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2683 10, 2 /* "}~" */
2684 };
2685#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002686 const char *s;
2687 int indx;
2688
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002689 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002690 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002691 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002692#if ENABLE_ASH_ALIAS
2693 if (c == PEOA) { /* 2^8+1 */
2694 indx = 0;
2695 } else
2696#endif
2697 {
2698 if ((unsigned char)c >= (unsigned char)(CTLESC)
2699 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2700 ) {
2701 return CCTL;
2702 }
2703 s = strchrnul(spec_symbls, c);
2704 if (*s == '\0') {
2705 return CWORD;
2706 }
2707 indx = syntax_index_table[s - spec_symbls];
2708 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002709 return S_I_T[indx][syntax];
2710}
2711
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002712#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002713
Denis Vlasenko131ae172007-02-18 13:00:19 +00002714#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002715#define CSPCL_CIGN_CIGN_CIGN 0
2716#define CSPCL_CWORD_CWORD_CWORD 1
2717#define CNL_CNL_CNL_CNL 2
2718#define CWORD_CCTL_CCTL_CWORD 3
2719#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2720#define CVAR_CVAR_CWORD_CVAR 5
2721#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2722#define CSPCL_CWORD_CWORD_CLP 7
2723#define CSPCL_CWORD_CWORD_CRP 8
2724#define CBACK_CBACK_CCTL_CBACK 9
2725#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2726#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2727#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2728#define CWORD_CWORD_CWORD_CWORD 13
2729#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002730#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002731#define CSPCL_CWORD_CWORD_CWORD 0
2732#define CNL_CNL_CNL_CNL 1
2733#define CWORD_CCTL_CCTL_CWORD 2
2734#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2735#define CVAR_CVAR_CWORD_CVAR 4
2736#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2737#define CSPCL_CWORD_CWORD_CLP 6
2738#define CSPCL_CWORD_CWORD_CRP 7
2739#define CBACK_CBACK_CCTL_CBACK 8
2740#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2741#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2742#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2743#define CWORD_CWORD_CWORD_CWORD 12
2744#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002745#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002746
2747static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002748 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002749 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002750#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002751 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2752#endif
2753 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2755 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2756 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2757 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2758 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2759 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2760 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2761 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002762 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2891 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2892 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2914 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002915 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002916 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2918 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002920 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002921 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2922 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2923 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2926 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2928 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2941 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2942 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2943 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2973 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2974 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2978 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3006 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3007 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3008 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003009};
3010
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003011#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003012
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003013#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003014
Eric Andersen2870d962001-07-02 17:27:21 +00003015
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003016/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003017
Denis Vlasenko131ae172007-02-18 13:00:19 +00003018#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003019
3020#define ALIASINUSE 1
3021#define ALIASDEAD 2
3022
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003023struct alias {
3024 struct alias *next;
3025 char *name;
3026 char *val;
3027 int flag;
3028};
3029
Denis Vlasenko01631112007-12-16 17:20:38 +00003030
3031static struct alias **atab; // [ATABSIZE];
3032#define INIT_G_alias() do { \
3033 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3034} while (0)
3035
Eric Andersen2870d962001-07-02 17:27:21 +00003036
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003037static struct alias **
3038__lookupalias(const char *name) {
3039 unsigned int hashval;
3040 struct alias **app;
3041 const char *p;
3042 unsigned int ch;
3043
3044 p = name;
3045
3046 ch = (unsigned char)*p;
3047 hashval = ch << 4;
3048 while (ch) {
3049 hashval += ch;
3050 ch = (unsigned char)*++p;
3051 }
3052 app = &atab[hashval % ATABSIZE];
3053
3054 for (; *app; app = &(*app)->next) {
3055 if (strcmp(name, (*app)->name) == 0) {
3056 break;
3057 }
3058 }
3059
3060 return app;
3061}
3062
3063static struct alias *
3064lookupalias(const char *name, int check)
3065{
3066 struct alias *ap = *__lookupalias(name);
3067
3068 if (check && ap && (ap->flag & ALIASINUSE))
3069 return NULL;
3070 return ap;
3071}
3072
3073static struct alias *
3074freealias(struct alias *ap)
3075{
3076 struct alias *next;
3077
3078 if (ap->flag & ALIASINUSE) {
3079 ap->flag |= ALIASDEAD;
3080 return ap;
3081 }
3082
3083 next = ap->next;
3084 free(ap->name);
3085 free(ap->val);
3086 free(ap);
3087 return next;
3088}
Eric Andersencb57d552001-06-28 07:25:16 +00003089
Eric Andersenc470f442003-07-28 09:56:35 +00003090static void
3091setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003092{
3093 struct alias *ap, **app;
3094
3095 app = __lookupalias(name);
3096 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003097 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003098 if (ap) {
3099 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003100 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003101 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003102 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003103 ap->flag &= ~ALIASDEAD;
3104 } else {
3105 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003106 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003107 ap->name = ckstrdup(name);
3108 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003109 /*ap->flag = 0; - ckzalloc did it */
3110 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003111 *app = ap;
3112 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003113 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003114}
3115
Eric Andersenc470f442003-07-28 09:56:35 +00003116static int
3117unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003118{
Eric Andersencb57d552001-06-28 07:25:16 +00003119 struct alias **app;
3120
3121 app = __lookupalias(name);
3122
3123 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003124 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003125 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003126 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003127 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003128 }
3129
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003130 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003131}
3132
Eric Andersenc470f442003-07-28 09:56:35 +00003133static void
3134rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003135{
Eric Andersencb57d552001-06-28 07:25:16 +00003136 struct alias *ap, **app;
3137 int i;
3138
Denis Vlasenkob012b102007-02-19 22:43:01 +00003139 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003140 for (i = 0; i < ATABSIZE; i++) {
3141 app = &atab[i];
3142 for (ap = *app; ap; ap = *app) {
3143 *app = freealias(*app);
3144 if (ap == *app) {
3145 app = &ap->next;
3146 }
3147 }
3148 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003149 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003150}
3151
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003152static void
3153printalias(const struct alias *ap)
3154{
3155 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3156}
3157
Eric Andersencb57d552001-06-28 07:25:16 +00003158/*
3159 * TODO - sort output
3160 */
Eric Andersenc470f442003-07-28 09:56:35 +00003161static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003162aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003163{
3164 char *n, *v;
3165 int ret = 0;
3166 struct alias *ap;
3167
Denis Vlasenko68404f12008-03-17 09:00:54 +00003168 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003169 int i;
3170
Denis Vlasenko68404f12008-03-17 09:00:54 +00003171 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003172 for (ap = atab[i]; ap; ap = ap->next) {
3173 printalias(ap);
3174 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003175 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003176 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003177 }
3178 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003179 v = strchr(n+1, '=');
3180 if (v == NULL) { /* n+1: funny ksh stuff */
3181 ap = *__lookupalias(n);
3182 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003183 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003184 ret = 1;
3185 } else
3186 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003187 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003188 *v++ = '\0';
3189 setalias(n, v);
3190 }
3191 }
3192
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003193 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003194}
3195
Eric Andersenc470f442003-07-28 09:56:35 +00003196static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003197unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003198{
3199 int i;
3200
3201 while ((i = nextopt("a")) != '\0') {
3202 if (i == 'a') {
3203 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003204 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003205 }
3206 }
3207 for (i = 0; *argptr; argptr++) {
3208 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003209 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003210 i = 1;
3211 }
3212 }
3213
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003214 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003215}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003216
Denis Vlasenko131ae172007-02-18 13:00:19 +00003217#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003218
Eric Andersenc470f442003-07-28 09:56:35 +00003219
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003220/* ============ jobs.c */
3221
3222/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3223#define FORK_FG 0
3224#define FORK_BG 1
3225#define FORK_NOJOB 2
3226
3227/* mode flags for showjob(s) */
3228#define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3229#define SHOW_PID 0x04 /* include process pid */
3230#define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3231
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003232/*
3233 * A job structure contains information about a job. A job is either a
3234 * single process or a set of processes contained in a pipeline. In the
3235 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3236 * array of pids.
3237 */
3238
3239struct procstat {
3240 pid_t pid; /* process id */
3241 int status; /* last process status from wait() */
3242 char *cmd; /* text of command being run */
3243};
3244
3245struct job {
3246 struct procstat ps0; /* status of process */
3247 struct procstat *ps; /* status or processes when more than one */
3248#if JOBS
3249 int stopstatus; /* status of a stopped job */
3250#endif
3251 uint32_t
3252 nprocs: 16, /* number of processes */
3253 state: 8,
3254#define JOBRUNNING 0 /* at least one proc running */
3255#define JOBSTOPPED 1 /* all procs are stopped */
3256#define JOBDONE 2 /* all procs are completed */
3257#if JOBS
3258 sigint: 1, /* job was killed by SIGINT */
3259 jobctl: 1, /* job running under job control */
3260#endif
3261 waited: 1, /* true if this entry has been waited for */
3262 used: 1, /* true if this entry is in used */
3263 changed: 1; /* true if status has changed */
3264 struct job *prev_job; /* previous job */
3265};
3266
Denis Vlasenko68404f12008-03-17 09:00:54 +00003267static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003268#if !JOBS
3269#define forkshell(job, node, mode) forkshell(job, mode)
3270#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003271static int forkshell(struct job *, union node *, int);
3272static int waitforjob(struct job *);
3273
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003274#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003275enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003276#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003277#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003278static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003279static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003280#endif
3281
3282/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003283 * Ignore a signal.
3284 */
3285static void
3286ignoresig(int signo)
3287{
3288 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3289 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3290 /* No, need to do it */
3291 signal(signo, SIG_IGN);
3292 }
3293 sigmode[signo - 1] = S_HARD_IGN;
3294}
3295
3296/*
3297 * Signal handler. Only one usage site - in setsignal()
3298 */
3299static void
3300onsig(int signo)
3301{
3302 gotsig[signo - 1] = 1;
3303
3304 if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3305 if (!suppressint) {
3306 pendingsig = 0;
3307 raise_interrupt(); /* does not return */
3308 }
3309 intpending = 1;
3310 } else {
3311 pendingsig = signo;
3312 }
3313}
3314
3315/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003316 * Set the signal handler for the specified signal. The routine figures
3317 * out what it should be set to.
3318 */
3319static void
3320setsignal(int signo)
3321{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003322 char *t;
3323 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003324 struct sigaction act;
3325
3326 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003327 new_act = S_DFL;
3328 if (t != NULL) { /* trap for this sig is set */
3329 new_act = S_CATCH;
3330 if (t[0] == '\0') /* trap is "": ignore this sig */
3331 new_act = S_IGN;
3332 }
3333
3334 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003335 switch (signo) {
3336 case SIGINT:
3337 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003338 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 break;
3340 case SIGQUIT:
3341#if DEBUG
3342 if (debug)
3343 break;
3344#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 /* man bash:
3346 * "In all cases, bash ignores SIGQUIT. Non-builtin
3347 * commands run by bash have signal handlers
3348 * set to the values inherited by the shell
3349 * from its parent". */
3350 new_act = S_IGN;
3351 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003352 case SIGTERM:
3353 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003354 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003355 break;
3356#if JOBS
3357 case SIGTSTP:
3358 case SIGTTOU:
3359 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003361 break;
3362#endif
3363 }
3364 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003365//TODO: if !rootshell, we reset SIGQUIT to DFL,
3366//whereas we have to restore it to what shell got on entry
3367//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368
3369 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003370 cur_act = *t;
3371 if (cur_act == 0) {
3372 /* current setting is not yet known */
3373 if (sigaction(signo, NULL, &act)) {
3374 /* pretend it worked; maybe we should give a warning,
3375 * but other shells don't. We don't alter sigmode,
3376 * so we retry every time.
3377 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003378 return;
3379 }
3380 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003381 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382 if (mflag
3383 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3384 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003385 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003386 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003387 }
3388 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003389 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003390 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003391
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003392 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003393 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 case S_CATCH:
3395 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003396 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3397 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398 break;
3399 case S_IGN:
3400 act.sa_handler = SIG_IGN;
3401 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003403 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003404
3405 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406}
3407
3408/* mode flags for set_curjob */
3409#define CUR_DELETE 2
3410#define CUR_RUNNING 1
3411#define CUR_STOPPED 0
3412
3413/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003414#define DOWAIT_NONBLOCK WNOHANG
3415#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003416
3417#if JOBS
3418/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003419static int initialpgrp; //references:2
3420static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003421#endif
3422/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003423static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003424/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003425static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003426/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003427static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003429static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430
3431static void
3432set_curjob(struct job *jp, unsigned mode)
3433{
3434 struct job *jp1;
3435 struct job **jpp, **curp;
3436
3437 /* first remove from list */
3438 jpp = curp = &curjob;
3439 do {
3440 jp1 = *jpp;
3441 if (jp1 == jp)
3442 break;
3443 jpp = &jp1->prev_job;
3444 } while (1);
3445 *jpp = jp1->prev_job;
3446
3447 /* Then re-insert in correct position */
3448 jpp = curp;
3449 switch (mode) {
3450 default:
3451#if DEBUG
3452 abort();
3453#endif
3454 case CUR_DELETE:
3455 /* job being deleted */
3456 break;
3457 case CUR_RUNNING:
3458 /* newly created job or backgrounded job,
3459 put after all stopped jobs. */
3460 do {
3461 jp1 = *jpp;
3462#if JOBS
3463 if (!jp1 || jp1->state != JOBSTOPPED)
3464#endif
3465 break;
3466 jpp = &jp1->prev_job;
3467 } while (1);
3468 /* FALLTHROUGH */
3469#if JOBS
3470 case CUR_STOPPED:
3471#endif
3472 /* newly stopped job - becomes curjob */
3473 jp->prev_job = *jpp;
3474 *jpp = jp;
3475 break;
3476 }
3477}
3478
3479#if JOBS || DEBUG
3480static int
3481jobno(const struct job *jp)
3482{
3483 return jp - jobtab + 1;
3484}
3485#endif
3486
3487/*
3488 * Convert a job name to a job structure.
3489 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003490#if !JOBS
3491#define getjob(name, getctl) getjob(name)
3492#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003493static struct job *
3494getjob(const char *name, int getctl)
3495{
3496 struct job *jp;
3497 struct job *found;
3498 const char *err_msg = "No such job: %s";
3499 unsigned num;
3500 int c;
3501 const char *p;
3502 char *(*match)(const char *, const char *);
3503
3504 jp = curjob;
3505 p = name;
3506 if (!p)
3507 goto currentjob;
3508
3509 if (*p != '%')
3510 goto err;
3511
3512 c = *++p;
3513 if (!c)
3514 goto currentjob;
3515
3516 if (!p[1]) {
3517 if (c == '+' || c == '%') {
3518 currentjob:
3519 err_msg = "No current job";
3520 goto check;
3521 }
3522 if (c == '-') {
3523 if (jp)
3524 jp = jp->prev_job;
3525 err_msg = "No previous job";
3526 check:
3527 if (!jp)
3528 goto err;
3529 goto gotit;
3530 }
3531 }
3532
3533 if (is_number(p)) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00003534// TODO: number() instead? It does error checking...
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003535 num = atoi(p);
3536 if (num < njobs) {
3537 jp = jobtab + num - 1;
3538 if (jp->used)
3539 goto gotit;
3540 goto err;
3541 }
3542 }
3543
3544 match = prefix;
3545 if (*p == '?') {
3546 match = strstr;
3547 p++;
3548 }
3549
3550 found = 0;
3551 while (1) {
3552 if (!jp)
3553 goto err;
3554 if (match(jp->ps[0].cmd, p)) {
3555 if (found)
3556 goto err;
3557 found = jp;
3558 err_msg = "%s: ambiguous";
3559 }
3560 jp = jp->prev_job;
3561 }
3562
3563 gotit:
3564#if JOBS
3565 err_msg = "job %s not created under job control";
3566 if (getctl && jp->jobctl == 0)
3567 goto err;
3568#endif
3569 return jp;
3570 err:
3571 ash_msg_and_raise_error(err_msg, name);
3572}
3573
3574/*
3575 * Mark a job structure as unused.
3576 */
3577static void
3578freejob(struct job *jp)
3579{
3580 struct procstat *ps;
3581 int i;
3582
3583 INT_OFF;
3584 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3585 if (ps->cmd != nullstr)
3586 free(ps->cmd);
3587 }
3588 if (jp->ps != &jp->ps0)
3589 free(jp->ps);
3590 jp->used = 0;
3591 set_curjob(jp, CUR_DELETE);
3592 INT_ON;
3593}
3594
3595#if JOBS
3596static void
3597xtcsetpgrp(int fd, pid_t pgrp)
3598{
3599 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003600 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003601}
3602
3603/*
3604 * Turn job control on and off.
3605 *
3606 * Note: This code assumes that the third arg to ioctl is a character
3607 * pointer, which is true on Berkeley systems but not System V. Since
3608 * System V doesn't have job control yet, this isn't a problem now.
3609 *
3610 * Called with interrupts off.
3611 */
3612static void
3613setjobctl(int on)
3614{
3615 int fd;
3616 int pgrp;
3617
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003618 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003619 return;
3620 if (on) {
3621 int ofd;
3622 ofd = fd = open(_PATH_TTY, O_RDWR);
3623 if (fd < 0) {
3624 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3625 * That sometimes helps to acquire controlling tty.
3626 * Obviously, a workaround for bugs when someone
3627 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003628 fd = 2;
3629 while (!isatty(fd))
3630 if (--fd < 0)
3631 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003632 }
3633 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003634 if (ofd >= 0)
3635 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003636 if (fd < 0)
3637 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003638 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003639 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003640 do { /* while we are in the background */
3641 pgrp = tcgetpgrp(fd);
3642 if (pgrp < 0) {
3643 out:
3644 ash_msg("can't access tty; job control turned off");
3645 mflag = on = 0;
3646 goto close;
3647 }
3648 if (pgrp == getpgrp())
3649 break;
3650 killpg(0, SIGTTIN);
3651 } while (1);
3652 initialpgrp = pgrp;
3653
3654 setsignal(SIGTSTP);
3655 setsignal(SIGTTOU);
3656 setsignal(SIGTTIN);
3657 pgrp = rootpid;
3658 setpgid(0, pgrp);
3659 xtcsetpgrp(fd, pgrp);
3660 } else {
3661 /* turning job control off */
3662 fd = ttyfd;
3663 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003664 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003665 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003666 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003667 setpgid(0, pgrp);
3668 setsignal(SIGTSTP);
3669 setsignal(SIGTTOU);
3670 setsignal(SIGTTIN);
3671 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003672 if (fd >= 0)
3673 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674 fd = -1;
3675 }
3676 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003677 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678}
3679
3680static int
3681killcmd(int argc, char **argv)
3682{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003683 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003684 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003685 do {
3686 if (argv[i][0] == '%') {
3687 struct job *jp = getjob(argv[i], 0);
3688 unsigned pid = jp->ps[0].pid;
3689 /* Enough space for ' -NNN<nul>' */
3690 argv[i] = alloca(sizeof(int)*3 + 3);
3691 /* kill_main has matching code to expect
3692 * leading space. Needed to not confuse
3693 * negative pids with "kill -SIGNAL_NO" syntax */
3694 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003695 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003696 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003697 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003698 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003699}
3700
3701static void
3702showpipe(struct job *jp, FILE *out)
3703{
3704 struct procstat *sp;
3705 struct procstat *spend;
3706
3707 spend = jp->ps + jp->nprocs;
3708 for (sp = jp->ps + 1; sp < spend; sp++)
3709 fprintf(out, " | %s", sp->cmd);
3710 outcslow('\n', out);
3711 flush_stdout_stderr();
3712}
3713
3714
3715static int
3716restartjob(struct job *jp, int mode)
3717{
3718 struct procstat *ps;
3719 int i;
3720 int status;
3721 pid_t pgid;
3722
3723 INT_OFF;
3724 if (jp->state == JOBDONE)
3725 goto out;
3726 jp->state = JOBRUNNING;
3727 pgid = jp->ps->pid;
3728 if (mode == FORK_FG)
3729 xtcsetpgrp(ttyfd, pgid);
3730 killpg(pgid, SIGCONT);
3731 ps = jp->ps;
3732 i = jp->nprocs;
3733 do {
3734 if (WIFSTOPPED(ps->status)) {
3735 ps->status = -1;
3736 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003737 ps++;
3738 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003739 out:
3740 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3741 INT_ON;
3742 return status;
3743}
3744
3745static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003746fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003747{
3748 struct job *jp;
3749 FILE *out;
3750 int mode;
3751 int retval;
3752
3753 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3754 nextopt(nullstr);
3755 argv = argptr;
3756 out = stdout;
3757 do {
3758 jp = getjob(*argv, 1);
3759 if (mode == FORK_BG) {
3760 set_curjob(jp, CUR_RUNNING);
3761 fprintf(out, "[%d] ", jobno(jp));
3762 }
3763 outstr(jp->ps->cmd, out);
3764 showpipe(jp, out);
3765 retval = restartjob(jp, mode);
3766 } while (*argv && *++argv);
3767 return retval;
3768}
3769#endif
3770
3771static int
3772sprint_status(char *s, int status, int sigonly)
3773{
3774 int col;
3775 int st;
3776
3777 col = 0;
3778 if (!WIFEXITED(status)) {
3779#if JOBS
3780 if (WIFSTOPPED(status))
3781 st = WSTOPSIG(status);
3782 else
3783#endif
3784 st = WTERMSIG(status);
3785 if (sigonly) {
3786 if (st == SIGINT || st == SIGPIPE)
3787 goto out;
3788#if JOBS
3789 if (WIFSTOPPED(status))
3790 goto out;
3791#endif
3792 }
3793 st &= 0x7f;
3794 col = fmtstr(s, 32, strsignal(st));
3795 if (WCOREDUMP(status)) {
3796 col += fmtstr(s + col, 16, " (core dumped)");
3797 }
3798 } else if (!sigonly) {
3799 st = WEXITSTATUS(status);
3800 if (st)
3801 col = fmtstr(s, 16, "Done(%d)", st);
3802 else
3803 col = fmtstr(s, 16, "Done");
3804 }
3805 out:
3806 return col;
3807}
3808
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003810dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003811{
3812 int pid;
3813 int status;
3814 struct job *jp;
3815 struct job *thisjob;
3816 int state;
3817
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003818 TRACE(("dowait(0x%x) called\n", wait_flags));
3819
3820 /* Do a wait system call. If job control is compiled in, we accept
3821 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3822 * NB: _not_ safe_waitpid, we need to detect EINTR */
3823 pid = waitpid(-1, &status,
3824 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003825 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3826 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003827 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003828 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003829
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003830 INT_OFF;
3831 thisjob = NULL;
3832 for (jp = curjob; jp; jp = jp->prev_job) {
3833 struct procstat *sp;
3834 struct procstat *spend;
3835 if (jp->state == JOBDONE)
3836 continue;
3837 state = JOBDONE;
3838 spend = jp->ps + jp->nprocs;
3839 sp = jp->ps;
3840 do {
3841 if (sp->pid == pid) {
3842 TRACE(("Job %d: changing status of proc %d "
3843 "from 0x%x to 0x%x\n",
3844 jobno(jp), pid, sp->status, status));
3845 sp->status = status;
3846 thisjob = jp;
3847 }
3848 if (sp->status == -1)
3849 state = JOBRUNNING;
3850#if JOBS
3851 if (state == JOBRUNNING)
3852 continue;
3853 if (WIFSTOPPED(sp->status)) {
3854 jp->stopstatus = sp->status;
3855 state = JOBSTOPPED;
3856 }
3857#endif
3858 } while (++sp < spend);
3859 if (thisjob)
3860 goto gotjob;
3861 }
3862#if JOBS
3863 if (!WIFSTOPPED(status))
3864#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003865 jobless--;
3866 goto out;
3867
3868 gotjob:
3869 if (state != JOBRUNNING) {
3870 thisjob->changed = 1;
3871
3872 if (thisjob->state != state) {
3873 TRACE(("Job %d: changing state from %d to %d\n",
3874 jobno(thisjob), thisjob->state, state));
3875 thisjob->state = state;
3876#if JOBS
3877 if (state == JOBSTOPPED) {
3878 set_curjob(thisjob, CUR_STOPPED);
3879 }
3880#endif
3881 }
3882 }
3883
3884 out:
3885 INT_ON;
3886
3887 if (thisjob && thisjob == job) {
3888 char s[48 + 1];
3889 int len;
3890
3891 len = sprint_status(s, status, 1);
3892 if (len) {
3893 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003894 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003895 out2str(s);
3896 }
3897 }
3898 return pid;
3899}
3900
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003901static int
3902blocking_wait_with_raise_on_sig(struct job *job)
3903{
3904 pid_t pid = dowait(DOWAIT_BLOCK, job);
3905 if (pid <= 0 && pendingsig)
3906 raise_exception(EXSIG);
3907 return pid;
3908}
3909
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003910#if JOBS
3911static void
3912showjob(FILE *out, struct job *jp, int mode)
3913{
3914 struct procstat *ps;
3915 struct procstat *psend;
3916 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003917 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003918 char s[80];
3919
3920 ps = jp->ps;
3921
3922 if (mode & SHOW_PGID) {
3923 /* just output process (group) id of pipeline */
3924 fprintf(out, "%d\n", ps->pid);
3925 return;
3926 }
3927
3928 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003929 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930
3931 if (jp == curjob)
3932 s[col - 2] = '+';
3933 else if (curjob && jp == curjob->prev_job)
3934 s[col - 2] = '-';
3935
3936 if (mode & SHOW_PID)
3937 col += fmtstr(s + col, 16, "%d ", ps->pid);
3938
3939 psend = ps + jp->nprocs;
3940
3941 if (jp->state == JOBRUNNING) {
3942 strcpy(s + col, "Running");
3943 col += sizeof("Running") - 1;
3944 } else {
3945 int status = psend[-1].status;
3946 if (jp->state == JOBSTOPPED)
3947 status = jp->stopstatus;
3948 col += sprint_status(s + col, status, 0);
3949 }
3950
3951 goto start;
3952
3953 do {
3954 /* for each process */
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003955 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003956 start:
3957 fprintf(out, "%s%*c%s",
3958 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3959 );
3960 if (!(mode & SHOW_PID)) {
3961 showpipe(jp, out);
3962 break;
3963 }
3964 if (++ps == psend) {
3965 outcslow('\n', out);
3966 break;
3967 }
3968 } while (1);
3969
3970 jp->changed = 0;
3971
3972 if (jp->state == JOBDONE) {
3973 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3974 freejob(jp);
3975 }
3976}
3977
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978/*
3979 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3980 * statuses have changed since the last call to showjobs.
3981 */
3982static void
3983showjobs(FILE *out, int mode)
3984{
3985 struct job *jp;
3986
3987 TRACE(("showjobs(%x) called\n", mode));
3988
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003989 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003990 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003991 continue;
3992
3993 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003994 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003995 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003996 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003997 }
3998}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003999
4000static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004001jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004002{
4003 int mode, m;
4004
4005 mode = 0;
4006 while ((m = nextopt("lp"))) {
4007 if (m == 'l')
4008 mode = SHOW_PID;
4009 else
4010 mode = SHOW_PGID;
4011 }
4012
4013 argv = argptr;
4014 if (*argv) {
4015 do
4016 showjob(stdout, getjob(*argv,0), mode);
4017 while (*++argv);
4018 } else
4019 showjobs(stdout, mode);
4020
4021 return 0;
4022}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004023#endif /* JOBS */
4024
4025static int
4026getstatus(struct job *job)
4027{
4028 int status;
4029 int retval;
4030
4031 status = job->ps[job->nprocs - 1].status;
4032 retval = WEXITSTATUS(status);
4033 if (!WIFEXITED(status)) {
4034#if JOBS
4035 retval = WSTOPSIG(status);
4036 if (!WIFSTOPPED(status))
4037#endif
4038 {
4039 /* XXX: limits number of signals */
4040 retval = WTERMSIG(status);
4041#if JOBS
4042 if (retval == SIGINT)
4043 job->sigint = 1;
4044#endif
4045 }
4046 retval += 128;
4047 }
4048 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4049 jobno(job), job->nprocs, status, retval));
4050 return retval;
4051}
4052
4053static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004054waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004055{
4056 struct job *job;
4057 int retval;
4058 struct job *jp;
4059
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004060// exsig++;
4061// xbarrier();
4062 if (pendingsig)
4063 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004064
4065 nextopt(nullstr);
4066 retval = 0;
4067
4068 argv = argptr;
4069 if (!*argv) {
4070 /* wait for all jobs */
4071 for (;;) {
4072 jp = curjob;
4073 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004074 if (!jp) /* no running procs */
4075 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076 if (jp->state == JOBRUNNING)
4077 break;
4078 jp->waited = 1;
4079 jp = jp->prev_job;
4080 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004081 /* man bash:
4082 * "When bash is waiting for an asynchronous command via
4083 * the wait builtin, the reception of a signal for which a trap
4084 * has been set will cause the wait builtin to return immediately
4085 * with an exit status greater than 128, immediately after which
4086 * the trap is executed."
4087 * Do we do it that way? */
4088 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004089 }
4090 }
4091
4092 retval = 127;
4093 do {
4094 if (**argv != '%') {
4095 pid_t pid = number(*argv);
4096 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004097 while (1) {
4098 if (!job)
4099 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004100 if (job->ps[job->nprocs - 1].pid == pid)
4101 break;
4102 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004103 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004104 } else
4105 job = getjob(*argv, 0);
4106 /* loop until process terminated or stopped */
4107 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004108 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004109 job->waited = 1;
4110 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004111 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004112 } while (*++argv);
4113
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004114 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004115 return retval;
4116}
4117
4118static struct job *
4119growjobtab(void)
4120{
4121 size_t len;
4122 ptrdiff_t offset;
4123 struct job *jp, *jq;
4124
4125 len = njobs * sizeof(*jp);
4126 jq = jobtab;
4127 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4128
4129 offset = (char *)jp - (char *)jq;
4130 if (offset) {
4131 /* Relocate pointers */
4132 size_t l = len;
4133
4134 jq = (struct job *)((char *)jq + l);
4135 while (l) {
4136 l -= sizeof(*jp);
4137 jq--;
4138#define joff(p) ((struct job *)((char *)(p) + l))
4139#define jmove(p) (p) = (void *)((char *)(p) + offset)
4140 if (joff(jp)->ps == &jq->ps0)
4141 jmove(joff(jp)->ps);
4142 if (joff(jp)->prev_job)
4143 jmove(joff(jp)->prev_job);
4144 }
4145 if (curjob)
4146 jmove(curjob);
4147#undef joff
4148#undef jmove
4149 }
4150
4151 njobs += 4;
4152 jobtab = jp;
4153 jp = (struct job *)((char *)jp + len);
4154 jq = jp + 3;
4155 do {
4156 jq->used = 0;
4157 } while (--jq >= jp);
4158 return jp;
4159}
4160
4161/*
4162 * Return a new job structure.
4163 * Called with interrupts off.
4164 */
4165static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004166makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004167{
4168 int i;
4169 struct job *jp;
4170
4171 for (i = njobs, jp = jobtab; ; jp++) {
4172 if (--i < 0) {
4173 jp = growjobtab();
4174 break;
4175 }
4176 if (jp->used == 0)
4177 break;
4178 if (jp->state != JOBDONE || !jp->waited)
4179 continue;
4180#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004181 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004182 continue;
4183#endif
4184 freejob(jp);
4185 break;
4186 }
4187 memset(jp, 0, sizeof(*jp));
4188#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004189 /* jp->jobctl is a bitfield.
4190 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004191 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004192 jp->jobctl = 1;
4193#endif
4194 jp->prev_job = curjob;
4195 curjob = jp;
4196 jp->used = 1;
4197 jp->ps = &jp->ps0;
4198 if (nprocs > 1) {
4199 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4200 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004201 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004202 jobno(jp)));
4203 return jp;
4204}
4205
4206#if JOBS
4207/*
4208 * Return a string identifying a command (to be printed by the
4209 * jobs command).
4210 */
4211static char *cmdnextc;
4212
4213static void
4214cmdputs(const char *s)
4215{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004216 static const char vstype[VSTYPE + 1][3] = {
4217 "", "}", "-", "+", "?", "=",
4218 "%", "%%", "#", "##"
4219 USE_ASH_BASH_COMPAT(, ":", "/", "//")
4220 };
4221
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004222 const char *p, *str;
4223 char c, cc[2] = " ";
4224 char *nextc;
4225 int subtype = 0;
4226 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004227
4228 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4229 p = s;
4230 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004231 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004232 switch (c) {
4233 case CTLESC:
4234 c = *p++;
4235 break;
4236 case CTLVAR:
4237 subtype = *p++;
4238 if ((subtype & VSTYPE) == VSLENGTH)
4239 str = "${#";
4240 else
4241 str = "${";
4242 if (!(subtype & VSQUOTE) == !(quoted & 1))
4243 goto dostr;
4244 quoted ^= 1;
4245 c = '"';
4246 break;
4247 case CTLENDVAR:
4248 str = "\"}" + !(quoted & 1);
4249 quoted >>= 1;
4250 subtype = 0;
4251 goto dostr;
4252 case CTLBACKQ:
4253 str = "$(...)";
4254 goto dostr;
4255 case CTLBACKQ+CTLQUOTE:
4256 str = "\"$(...)\"";
4257 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004258#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004259 case CTLARI:
4260 str = "$((";
4261 goto dostr;
4262 case CTLENDARI:
4263 str = "))";
4264 goto dostr;
4265#endif
4266 case CTLQUOTEMARK:
4267 quoted ^= 1;
4268 c = '"';
4269 break;
4270 case '=':
4271 if (subtype == 0)
4272 break;
4273 if ((subtype & VSTYPE) != VSNORMAL)
4274 quoted <<= 1;
4275 str = vstype[subtype & VSTYPE];
4276 if (subtype & VSNUL)
4277 c = ':';
4278 else
4279 goto checkstr;
4280 break;
4281 case '\'':
4282 case '\\':
4283 case '"':
4284 case '$':
4285 /* These can only happen inside quotes */
4286 cc[0] = c;
4287 str = cc;
4288 c = '\\';
4289 break;
4290 default:
4291 break;
4292 }
4293 USTPUTC(c, nextc);
4294 checkstr:
4295 if (!str)
4296 continue;
4297 dostr:
4298 while ((c = *str++)) {
4299 USTPUTC(c, nextc);
4300 }
4301 }
4302 if (quoted & 1) {
4303 USTPUTC('"', nextc);
4304 }
4305 *nextc = 0;
4306 cmdnextc = nextc;
4307}
4308
4309/* cmdtxt() and cmdlist() call each other */
4310static void cmdtxt(union node *n);
4311
4312static void
4313cmdlist(union node *np, int sep)
4314{
4315 for (; np; np = np->narg.next) {
4316 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004317 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004318 cmdtxt(np);
4319 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004320 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004321 }
4322}
4323
4324static void
4325cmdtxt(union node *n)
4326{
4327 union node *np;
4328 struct nodelist *lp;
4329 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330
4331 if (!n)
4332 return;
4333 switch (n->type) {
4334 default:
4335#if DEBUG
4336 abort();
4337#endif
4338 case NPIPE:
4339 lp = n->npipe.cmdlist;
4340 for (;;) {
4341 cmdtxt(lp->n);
4342 lp = lp->next;
4343 if (!lp)
4344 break;
4345 cmdputs(" | ");
4346 }
4347 break;
4348 case NSEMI:
4349 p = "; ";
4350 goto binop;
4351 case NAND:
4352 p = " && ";
4353 goto binop;
4354 case NOR:
4355 p = " || ";
4356 binop:
4357 cmdtxt(n->nbinary.ch1);
4358 cmdputs(p);
4359 n = n->nbinary.ch2;
4360 goto donode;
4361 case NREDIR:
4362 case NBACKGND:
4363 n = n->nredir.n;
4364 goto donode;
4365 case NNOT:
4366 cmdputs("!");
4367 n = n->nnot.com;
4368 donode:
4369 cmdtxt(n);
4370 break;
4371 case NIF:
4372 cmdputs("if ");
4373 cmdtxt(n->nif.test);
4374 cmdputs("; then ");
4375 n = n->nif.ifpart;
4376 if (n->nif.elsepart) {
4377 cmdtxt(n);
4378 cmdputs("; else ");
4379 n = n->nif.elsepart;
4380 }
4381 p = "; fi";
4382 goto dotail;
4383 case NSUBSHELL:
4384 cmdputs("(");
4385 n = n->nredir.n;
4386 p = ")";
4387 goto dotail;
4388 case NWHILE:
4389 p = "while ";
4390 goto until;
4391 case NUNTIL:
4392 p = "until ";
4393 until:
4394 cmdputs(p);
4395 cmdtxt(n->nbinary.ch1);
4396 n = n->nbinary.ch2;
4397 p = "; done";
4398 dodo:
4399 cmdputs("; do ");
4400 dotail:
4401 cmdtxt(n);
4402 goto dotail2;
4403 case NFOR:
4404 cmdputs("for ");
4405 cmdputs(n->nfor.var);
4406 cmdputs(" in ");
4407 cmdlist(n->nfor.args, 1);
4408 n = n->nfor.body;
4409 p = "; done";
4410 goto dodo;
4411 case NDEFUN:
4412 cmdputs(n->narg.text);
4413 p = "() { ... }";
4414 goto dotail2;
4415 case NCMD:
4416 cmdlist(n->ncmd.args, 1);
4417 cmdlist(n->ncmd.redirect, 0);
4418 break;
4419 case NARG:
4420 p = n->narg.text;
4421 dotail2:
4422 cmdputs(p);
4423 break;
4424 case NHERE:
4425 case NXHERE:
4426 p = "<<...";
4427 goto dotail2;
4428 case NCASE:
4429 cmdputs("case ");
4430 cmdputs(n->ncase.expr->narg.text);
4431 cmdputs(" in ");
4432 for (np = n->ncase.cases; np; np = np->nclist.next) {
4433 cmdtxt(np->nclist.pattern);
4434 cmdputs(") ");
4435 cmdtxt(np->nclist.body);
4436 cmdputs(";; ");
4437 }
4438 p = "esac";
4439 goto dotail2;
4440 case NTO:
4441 p = ">";
4442 goto redir;
4443 case NCLOBBER:
4444 p = ">|";
4445 goto redir;
4446 case NAPPEND:
4447 p = ">>";
4448 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004449#if ENABLE_ASH_BASH_COMPAT
4450 case NTO2:
4451#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004452 case NTOFD:
4453 p = ">&";
4454 goto redir;
4455 case NFROM:
4456 p = "<";
4457 goto redir;
4458 case NFROMFD:
4459 p = "<&";
4460 goto redir;
4461 case NFROMTO:
4462 p = "<>";
4463 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004464 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004465 cmdputs(p);
4466 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004467 cmdputs(utoa(n->ndup.dupfd));
4468 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004469 }
4470 n = n->nfile.fname;
4471 goto donode;
4472 }
4473}
4474
4475static char *
4476commandtext(union node *n)
4477{
4478 char *name;
4479
4480 STARTSTACKSTR(cmdnextc);
4481 cmdtxt(n);
4482 name = stackblock();
4483 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4484 name, cmdnextc, cmdnextc));
4485 return ckstrdup(name);
4486}
4487#endif /* JOBS */
4488
4489/*
4490 * Fork off a subshell. If we are doing job control, give the subshell its
4491 * own process group. Jp is a job structure that the job is to be added to.
4492 * N is the command that will be evaluated by the child. Both jp and n may
4493 * be NULL. The mode parameter can be one of the following:
4494 * FORK_FG - Fork off a foreground process.
4495 * FORK_BG - Fork off a background process.
4496 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4497 * process group even if job control is on.
4498 *
4499 * When job control is turned off, background processes have their standard
4500 * input redirected to /dev/null (except for the second and later processes
4501 * in a pipeline).
4502 *
4503 * Called with interrupts off.
4504 */
4505/*
4506 * Clear traps on a fork.
4507 */
4508static void
4509clear_traps(void)
4510{
4511 char **tp;
4512
4513 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004514 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004515 INT_OFF;
4516 free(*tp);
4517 *tp = NULL;
4518 if (tp != &trap[0])
4519 setsignal(tp - trap);
4520 INT_ON;
4521 }
4522 }
4523}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004524
4525/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004526static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004527
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004528/* Called after fork(), in child */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004529static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00004530forkchild(struct job *jp, /*union node *n,*/ int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004531{
4532 int oldlvl;
4533
4534 TRACE(("Child shell %d\n", getpid()));
4535 oldlvl = shlvl;
4536 shlvl++;
4537
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004538 /* man bash: "Non-builtin commands run by bash have signal handlers
4539 * set to the values inherited by the shell from its parent".
4540 * Do we do it correctly? */
4541
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004542 closescript();
4543 clear_traps();
4544#if JOBS
4545 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004546 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004547 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4548 pid_t pgrp;
4549
4550 if (jp->nprocs == 0)
4551 pgrp = getpid();
4552 else
4553 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004554 /* this can fail because we are doing it in the parent also */
4555 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004556 if (mode == FORK_FG)
4557 xtcsetpgrp(ttyfd, pgrp);
4558 setsignal(SIGTSTP);
4559 setsignal(SIGTTOU);
4560 } else
4561#endif
4562 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004563 /* man bash: "When job control is not in effect,
4564 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004565 ignoresig(SIGINT);
4566 ignoresig(SIGQUIT);
4567 if (jp->nprocs == 0) {
4568 close(0);
4569 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004570 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004571 }
4572 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004573 if (!oldlvl) {
4574 if (iflag) { /* why if iflag only? */
4575 setsignal(SIGINT);
4576 setsignal(SIGTERM);
4577 }
4578 /* man bash:
4579 * "In all cases, bash ignores SIGQUIT. Non-builtin
4580 * commands run by bash have signal handlers
4581 * set to the values inherited by the shell
4582 * from its parent".
4583 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004584 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004585 }
4586 for (jp = curjob; jp; jp = jp->prev_job)
4587 freejob(jp);
4588 jobless = 0;
4589}
4590
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004591/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004592#if !JOBS
4593#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4594#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004595static void
4596forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4597{
4598 TRACE(("In parent shell: child = %d\n", pid));
4599 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004600 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4601 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004602 jobless++;
4603 return;
4604 }
4605#if JOBS
4606 if (mode != FORK_NOJOB && jp->jobctl) {
4607 int pgrp;
4608
4609 if (jp->nprocs == 0)
4610 pgrp = pid;
4611 else
4612 pgrp = jp->ps[0].pid;
4613 /* This can fail because we are doing it in the child also */
4614 setpgid(pid, pgrp);
4615 }
4616#endif
4617 if (mode == FORK_BG) {
4618 backgndpid = pid; /* set $! */
4619 set_curjob(jp, CUR_RUNNING);
4620 }
4621 if (jp) {
4622 struct procstat *ps = &jp->ps[jp->nprocs++];
4623 ps->pid = pid;
4624 ps->status = -1;
4625 ps->cmd = nullstr;
4626#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004627 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004628 ps->cmd = commandtext(n);
4629#endif
4630 }
4631}
4632
4633static int
4634forkshell(struct job *jp, union node *n, int mode)
4635{
4636 int pid;
4637
4638 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4639 pid = fork();
4640 if (pid < 0) {
4641 TRACE(("Fork failed, errno=%d", errno));
4642 if (jp)
4643 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004644 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004645 }
4646 if (pid == 0)
Denis Vlasenko68404f12008-03-17 09:00:54 +00004647 forkchild(jp, /*n,*/ mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004648 else
4649 forkparent(jp, n, mode, pid);
4650 return pid;
4651}
4652
4653/*
4654 * Wait for job to finish.
4655 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004656 * Under job control we have the problem that while a child process
4657 * is running interrupts generated by the user are sent to the child
4658 * but not to the shell. This means that an infinite loop started by
4659 * an interactive user may be hard to kill. With job control turned off,
4660 * an interactive user may place an interactive program inside a loop.
4661 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004662 * these interrupts to also abort the loop. The approach we take here
4663 * is to have the shell ignore interrupt signals while waiting for a
4664 * foreground process to terminate, and then send itself an interrupt
4665 * signal if the child process was terminated by an interrupt signal.
4666 * Unfortunately, some programs want to do a bit of cleanup and then
4667 * exit on interrupt; unless these processes terminate themselves by
4668 * sending a signal to themselves (instead of calling exit) they will
4669 * confuse this approach.
4670 *
4671 * Called with interrupts off.
4672 */
4673static int
4674waitforjob(struct job *jp)
4675{
4676 int st;
4677
4678 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004679
4680 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004681 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004682 /* In non-interactive shells, we _can_ get
4683 * a keyboard signal here and be EINTRed,
4684 * but we just loop back, waiting for command to complete.
4685 *
4686 * man bash:
4687 * "If bash is waiting for a command to complete and receives
4688 * a signal for which a trap has been set, the trap
4689 * will not be executed until the command completes."
4690 *
4691 * Reality is that even if trap is not set, bash
4692 * will not act on the signal until command completes.
4693 * Try this. sleep5intoff.c:
4694 * #include <signal.h>
4695 * #include <unistd.h>
4696 * int main() {
4697 * sigset_t set;
4698 * sigemptyset(&set);
4699 * sigaddset(&set, SIGINT);
4700 * sigaddset(&set, SIGQUIT);
4701 * sigprocmask(SIG_BLOCK, &set, NULL);
4702 * sleep(5);
4703 * return 0;
4704 * }
4705 * $ bash -c './sleep5intoff; echo hi'
4706 * ^C^C^C^C <--- pressing ^C once a second
4707 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004708 * $ bash -c './sleep5intoff; echo hi'
4709 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4710 * $ _
4711 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004712 dowait(DOWAIT_BLOCK, jp);
4713 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004714 INT_ON;
4715
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004716 st = getstatus(jp);
4717#if JOBS
4718 if (jp->jobctl) {
4719 xtcsetpgrp(ttyfd, rootpid);
4720 /*
4721 * This is truly gross.
4722 * If we're doing job control, then we did a TIOCSPGRP which
4723 * caused us (the shell) to no longer be in the controlling
4724 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4725 * intuit from the subprocess exit status whether a SIGINT
4726 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4727 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004728 if (jp->sigint) /* TODO: do the same with all signals */
4729 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004730 }
4731 if (jp->state == JOBDONE)
4732#endif
4733 freejob(jp);
4734 return st;
4735}
4736
4737/*
4738 * return 1 if there are stopped jobs, otherwise 0
4739 */
4740static int
4741stoppedjobs(void)
4742{
4743 struct job *jp;
4744 int retval;
4745
4746 retval = 0;
4747 if (job_warning)
4748 goto out;
4749 jp = curjob;
4750 if (jp && jp->state == JOBSTOPPED) {
4751 out2str("You have stopped jobs.\n");
4752 job_warning = 2;
4753 retval++;
4754 }
4755 out:
4756 return retval;
4757}
4758
4759
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004760/* ============ redir.c
4761 *
4762 * Code for dealing with input/output redirection.
4763 */
4764
4765#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004766#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004767
4768/*
4769 * Open a file in noclobber mode.
4770 * The code was copied from bash.
4771 */
4772static int
4773noclobberopen(const char *fname)
4774{
4775 int r, fd;
4776 struct stat finfo, finfo2;
4777
4778 /*
4779 * If the file exists and is a regular file, return an error
4780 * immediately.
4781 */
4782 r = stat(fname, &finfo);
4783 if (r == 0 && S_ISREG(finfo.st_mode)) {
4784 errno = EEXIST;
4785 return -1;
4786 }
4787
4788 /*
4789 * If the file was not present (r != 0), make sure we open it
4790 * exclusively so that if it is created before we open it, our open
4791 * will fail. Make sure that we do not truncate an existing file.
4792 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4793 * file was not a regular file, we leave O_EXCL off.
4794 */
4795 if (r != 0)
4796 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4797 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4798
4799 /* If the open failed, return the file descriptor right away. */
4800 if (fd < 0)
4801 return fd;
4802
4803 /*
4804 * OK, the open succeeded, but the file may have been changed from a
4805 * non-regular file to a regular file between the stat and the open.
4806 * We are assuming that the O_EXCL open handles the case where FILENAME
4807 * did not exist and is symlinked to an existing file between the stat
4808 * and open.
4809 */
4810
4811 /*
4812 * If we can open it and fstat the file descriptor, and neither check
4813 * revealed that it was a regular file, and the file has not been
4814 * replaced, return the file descriptor.
4815 */
4816 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4817 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4818 return fd;
4819
4820 /* The file has been replaced. badness. */
4821 close(fd);
4822 errno = EEXIST;
4823 return -1;
4824}
4825
4826/*
4827 * Handle here documents. Normally we fork off a process to write the
4828 * data to a pipe. If the document is short, we can stuff the data in
4829 * the pipe without forking.
4830 */
4831/* openhere needs this forward reference */
4832static void expandhere(union node *arg, int fd);
4833static int
4834openhere(union node *redir)
4835{
4836 int pip[2];
4837 size_t len = 0;
4838
4839 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004840 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004841 if (redir->type == NHERE) {
4842 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004843 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004844 full_write(pip[1], redir->nhere.doc->narg.text, len);
4845 goto out;
4846 }
4847 }
4848 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004849 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004850 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004851 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4852 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4853 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4854 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004855 signal(SIGPIPE, SIG_DFL);
4856 if (redir->type == NHERE)
4857 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004858 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004859 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004860 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004861 }
4862 out:
4863 close(pip[1]);
4864 return pip[0];
4865}
4866
4867static int
4868openredirect(union node *redir)
4869{
4870 char *fname;
4871 int f;
4872
4873 switch (redir->nfile.type) {
4874 case NFROM:
4875 fname = redir->nfile.expfname;
4876 f = open(fname, O_RDONLY);
4877 if (f < 0)
4878 goto eopen;
4879 break;
4880 case NFROMTO:
4881 fname = redir->nfile.expfname;
4882 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4883 if (f < 0)
4884 goto ecreate;
4885 break;
4886 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004887#if ENABLE_ASH_BASH_COMPAT
4888 case NTO2:
4889#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004890 /* Take care of noclobber mode. */
4891 if (Cflag) {
4892 fname = redir->nfile.expfname;
4893 f = noclobberopen(fname);
4894 if (f < 0)
4895 goto ecreate;
4896 break;
4897 }
4898 /* FALLTHROUGH */
4899 case NCLOBBER:
4900 fname = redir->nfile.expfname;
4901 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4902 if (f < 0)
4903 goto ecreate;
4904 break;
4905 case NAPPEND:
4906 fname = redir->nfile.expfname;
4907 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4908 if (f < 0)
4909 goto ecreate;
4910 break;
4911 default:
4912#if DEBUG
4913 abort();
4914#endif
4915 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004916/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004917// case NTOFD:
4918// case NFROMFD:
4919// f = -1;
4920// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004921 case NHERE:
4922 case NXHERE:
4923 f = openhere(redir);
4924 break;
4925 }
4926
4927 return f;
4928 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004929 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004930 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004931 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932}
4933
4934/*
4935 * Copy a file descriptor to be >= to. Returns -1
4936 * if the source file descriptor is closed, EMPTY if there are no unused
4937 * file descriptors left.
4938 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004939/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4940 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004941enum {
4942 COPYFD_EXACT = (int)~(INT_MAX),
4943 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4944};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004945static int
4946copyfd(int from, int to)
4947{
4948 int newfd;
4949
Denis Vlasenko5a867312008-07-24 19:46:38 +00004950 if (to & COPYFD_EXACT) {
4951 to &= ~COPYFD_EXACT;
4952 /*if (from != to)*/
4953 newfd = dup2(from, to);
4954 } else {
4955 newfd = fcntl(from, F_DUPFD, to);
4956 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004957 if (newfd < 0) {
4958 if (errno == EMFILE)
4959 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004960 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004961 ash_msg_and_raise_error("%d: %m", from);
4962 }
4963 return newfd;
4964}
4965
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004966/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004967struct two_fd_t {
4968 int orig, copy;
4969};
Denis Vlasenko0b769642008-07-24 07:54:57 +00004970struct redirtab {
4971 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00004972 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004973 int pair_count;
4974 struct two_fd_t two_fd[0];
Denis Vlasenko0b769642008-07-24 07:54:57 +00004975};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004976#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00004977
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004978static int need_to_remember(struct redirtab *rp, int fd)
4979{
4980 int i;
4981
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00004982 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004983 return 0;
4984
4985 for (i = 0; i < rp->pair_count; i++) {
4986 if (rp->two_fd[i].orig == fd) {
4987 /* already remembered */
4988 return 0;
4989 }
4990 }
4991 return 1;
4992}
4993
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00004994/* "hidden" fd is a fd used to read scripts, or a copy of such */
4995static int is_hidden_fd(struct redirtab *rp, int fd)
4996{
4997 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00004998 struct parsefile *pf;
4999
5000 if (fd == -1)
5001 return 0;
5002 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005003 while (pf) {
5004 if (fd == pf->fd) {
5005 return 1;
5006 }
5007 pf = pf->prev;
5008 }
5009 if (!rp)
5010 return 0;
5011 fd |= COPYFD_RESTORE;
5012 for (i = 0; i < rp->pair_count; i++) {
5013 if (rp->two_fd[i].copy == fd) {
5014 return 1;
5015 }
5016 }
5017 return 0;
5018}
5019
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005020/*
5021 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5022 * old file descriptors are stashed away so that the redirection can be
5023 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5024 * standard output, and the standard error if it becomes a duplicate of
5025 * stdout, is saved in memory.
5026 */
5027/* flags passed to redirect */
5028#define REDIR_PUSH 01 /* save previous values of file descriptors */
5029#define REDIR_SAVEFD2 03 /* set preverrout */
5030static void
5031redirect(union node *redir, int flags)
5032{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005033 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005034 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005035 int i;
5036 int fd;
5037 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005038 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005039
Denis Vlasenko01631112007-12-16 17:20:38 +00005040 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005041 if (!redir) {
5042 return;
5043 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005045 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005046 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005047 INT_OFF;
5048 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005049 union node *tmp = redir;
5050 do {
5051 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005052#if ENABLE_ASH_BASH_COMPAT
5053 if (redir->nfile.type == NTO2)
5054 sv_pos++;
5055#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005056 tmp = tmp->nfile.next;
5057 } while (tmp);
5058 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005059 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005060 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005061 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005062 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005063 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005064 while (sv_pos > 0) {
5065 sv_pos--;
5066 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5067 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005068 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005069
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005070 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005071 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005072 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005073 int right_fd = redir->ndup.dupfd;
5074 /* redirect from/to same file descriptor? */
5075 if (right_fd == fd)
5076 continue;
5077 /* echo >&10 and 10 is a fd opened to the sh script? */
5078 if (is_hidden_fd(sv, right_fd)) {
5079 errno = EBADF; /* as if it is closed */
5080 ash_msg_and_raise_error("%d: %m", right_fd);
5081 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005082 newfd = -1;
5083 } else {
5084 newfd = openredirect(redir); /* always >= 0 */
5085 if (fd == newfd) {
5086 /* Descriptor wasn't open before redirect.
5087 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005088 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005089 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005090 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005091 continue;
5092 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005093 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005094#if ENABLE_ASH_BASH_COMPAT
5095 redirect_more:
5096#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005097 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005098 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005100/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5101 * are closed in popredir() in the child, preventing them from leaking
5102 * into child. (popredir() also cleans up the mess in case of failures)
5103 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005104 if (i == -1) {
5105 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005106 if (i != EBADF) {
5107 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005108 if (newfd >= 0)
5109 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005110 errno = i;
5111 ash_msg_and_raise_error("%d: %m", fd);
5112 /* NOTREACHED */
5113 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005114 /* EBADF: it is not open - good, remember to close it */
5115 remember_to_close:
5116 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005117 } else { /* fd is open, save its copy */
5118 /* "exec fd>&-" should not close fds
5119 * which point to script file(s).
5120 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005121 if (is_hidden_fd(sv, fd))
5122 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005123 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005124 if (fd == 2)
5125 copied_fd2 = i;
5126 sv->two_fd[sv_pos].orig = fd;
5127 sv->two_fd[sv_pos].copy = i;
5128 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005130 if (newfd < 0) {
5131 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005132 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005133 /* Don't want to trigger debugging */
5134 if (fd != -1)
5135 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005136 } else {
5137 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005138 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005139 } else if (fd != newfd) { /* move newfd to fd */
5140 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005141#if ENABLE_ASH_BASH_COMPAT
5142 if (!(redir->nfile.type == NTO2 && fd == 2))
5143#endif
5144 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005145 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005146#if ENABLE_ASH_BASH_COMPAT
5147 if (redir->nfile.type == NTO2 && fd == 1) {
5148 /* We already redirected it to fd 1, now copy it to 2 */
5149 newfd = 1;
5150 fd = 2;
5151 goto redirect_more;
5152 }
5153#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005154 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005155
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005156 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005157 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5158 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005159}
5160
5161/*
5162 * Undo the effects of the last redirection.
5163 */
5164static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005165popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005166{
5167 struct redirtab *rp;
5168 int i;
5169
Denis Vlasenko01631112007-12-16 17:20:38 +00005170 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005171 return;
5172 INT_OFF;
5173 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 for (i = 0; i < rp->pair_count; i++) {
5175 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005176 int copy = rp->two_fd[i].copy;
5177 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005178 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005179 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005180 continue;
5181 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005182 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005183 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005184 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005185 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005186 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005187 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005188 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005189 }
5190 }
5191 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005192 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005193 free(rp);
5194 INT_ON;
5195}
5196
5197/*
5198 * Undo all redirections. Called on error or interrupt.
5199 */
5200
5201/*
5202 * Discard all saved file descriptors.
5203 */
5204static void
5205clearredir(int drop)
5206{
5207 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005208 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005209 if (!redirlist)
5210 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005211 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005212 }
5213}
5214
5215static int
5216redirectsafe(union node *redir, int flags)
5217{
5218 int err;
5219 volatile int saveint;
5220 struct jmploc *volatile savehandler = exception_handler;
5221 struct jmploc jmploc;
5222
5223 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005224 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5225 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005226 if (!err) {
5227 exception_handler = &jmploc;
5228 redirect(redir, flags);
5229 }
5230 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005231 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005232 longjmp(exception_handler->loc, 1);
5233 RESTORE_INT(saveint);
5234 return err;
5235}
5236
5237
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005238/* ============ Routines to expand arguments to commands
5239 *
5240 * We have to deal with backquotes, shell variables, and file metacharacters.
5241 */
5242
Mike Frysinger98c52642009-04-02 10:02:37 +00005243#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005244static arith_t dash_arith(const char *);
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005245#endif
5246
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005247/*
5248 * expandarg flags
5249 */
5250#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5251#define EXP_TILDE 0x2 /* do normal tilde expansion */
5252#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5253#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5254#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5255#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5256#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5257#define EXP_WORD 0x80 /* expand word in parameter expansion */
5258#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5259/*
5260 * _rmescape() flags
5261 */
5262#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5263#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5264#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5265#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5266#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5267
5268/*
5269 * Structure specifying which parts of the string should be searched
5270 * for IFS characters.
5271 */
5272struct ifsregion {
5273 struct ifsregion *next; /* next region in list */
5274 int begoff; /* offset of start of region */
5275 int endoff; /* offset of end of region */
5276 int nulonly; /* search for nul bytes only */
5277};
5278
5279struct arglist {
5280 struct strlist *list;
5281 struct strlist **lastp;
5282};
5283
5284/* output of current string */
5285static char *expdest;
5286/* list of back quote expressions */
5287static struct nodelist *argbackq;
5288/* first struct in list of ifs regions */
5289static struct ifsregion ifsfirst;
5290/* last struct in list */
5291static struct ifsregion *ifslastp;
5292/* holds expanded arg list */
5293static struct arglist exparg;
5294
5295/*
5296 * Our own itoa().
5297 */
5298static int
5299cvtnum(arith_t num)
5300{
5301 int len;
5302
5303 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005304 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005305 STADJUST(len, expdest);
5306 return len;
5307}
5308
5309static size_t
5310esclen(const char *start, const char *p)
5311{
5312 size_t esc = 0;
5313
5314 while (p > start && *--p == CTLESC) {
5315 esc++;
5316 }
5317 return esc;
5318}
5319
5320/*
5321 * Remove any CTLESC characters from a string.
5322 */
5323static char *
5324_rmescapes(char *str, int flag)
5325{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005326 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005327
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005328 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005329 unsigned inquotes;
5330 int notescaped;
5331 int globbing;
5332
5333 p = strpbrk(str, qchars);
5334 if (!p) {
5335 return str;
5336 }
5337 q = p;
5338 r = str;
5339 if (flag & RMESCAPE_ALLOC) {
5340 size_t len = p - str;
5341 size_t fulllen = len + strlen(p) + 1;
5342
5343 if (flag & RMESCAPE_GROW) {
5344 r = makestrspace(fulllen, expdest);
5345 } else if (flag & RMESCAPE_HEAP) {
5346 r = ckmalloc(fulllen);
5347 } else {
5348 r = stalloc(fulllen);
5349 }
5350 q = r;
5351 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005352 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005353 }
5354 }
5355 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5356 globbing = flag & RMESCAPE_GLOB;
5357 notescaped = globbing;
5358 while (*p) {
5359 if (*p == CTLQUOTEMARK) {
5360 inquotes = ~inquotes;
5361 p++;
5362 notescaped = globbing;
5363 continue;
5364 }
5365 if (*p == '\\') {
5366 /* naked back slash */
5367 notescaped = 0;
5368 goto copy;
5369 }
5370 if (*p == CTLESC) {
5371 p++;
5372 if (notescaped && inquotes && *p != '/') {
5373 *q++ = '\\';
5374 }
5375 }
5376 notescaped = globbing;
5377 copy:
5378 *q++ = *p++;
5379 }
5380 *q = '\0';
5381 if (flag & RMESCAPE_GROW) {
5382 expdest = r;
5383 STADJUST(q - r + 1, expdest);
5384 }
5385 return r;
5386}
5387#define rmescapes(p) _rmescapes((p), 0)
5388
5389#define pmatch(a, b) !fnmatch((a), (b), 0)
5390
5391/*
5392 * Prepare a pattern for a expmeta (internal glob(3)) call.
5393 *
5394 * Returns an stalloced string.
5395 */
5396static char *
5397preglob(const char *pattern, int quoted, int flag)
5398{
5399 flag |= RMESCAPE_GLOB;
5400 if (quoted) {
5401 flag |= RMESCAPE_QUOTED;
5402 }
5403 return _rmescapes((char *)pattern, flag);
5404}
5405
5406/*
5407 * Put a string on the stack.
5408 */
5409static void
5410memtodest(const char *p, size_t len, int syntax, int quotes)
5411{
5412 char *q = expdest;
5413
5414 q = makestrspace(len * 2, q);
5415
5416 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005417 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005418 if (!c)
5419 continue;
5420 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5421 USTPUTC(CTLESC, q);
5422 USTPUTC(c, q);
5423 }
5424
5425 expdest = q;
5426}
5427
5428static void
5429strtodest(const char *p, int syntax, int quotes)
5430{
5431 memtodest(p, strlen(p), syntax, quotes);
5432}
5433
5434/*
5435 * Record the fact that we have to scan this region of the
5436 * string for IFS characters.
5437 */
5438static void
5439recordregion(int start, int end, int nulonly)
5440{
5441 struct ifsregion *ifsp;
5442
5443 if (ifslastp == NULL) {
5444 ifsp = &ifsfirst;
5445 } else {
5446 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005447 ifsp = ckzalloc(sizeof(*ifsp));
5448 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005449 ifslastp->next = ifsp;
5450 INT_ON;
5451 }
5452 ifslastp = ifsp;
5453 ifslastp->begoff = start;
5454 ifslastp->endoff = end;
5455 ifslastp->nulonly = nulonly;
5456}
5457
5458static void
5459removerecordregions(int endoff)
5460{
5461 if (ifslastp == NULL)
5462 return;
5463
5464 if (ifsfirst.endoff > endoff) {
5465 while (ifsfirst.next != NULL) {
5466 struct ifsregion *ifsp;
5467 INT_OFF;
5468 ifsp = ifsfirst.next->next;
5469 free(ifsfirst.next);
5470 ifsfirst.next = ifsp;
5471 INT_ON;
5472 }
5473 if (ifsfirst.begoff > endoff)
5474 ifslastp = NULL;
5475 else {
5476 ifslastp = &ifsfirst;
5477 ifsfirst.endoff = endoff;
5478 }
5479 return;
5480 }
5481
5482 ifslastp = &ifsfirst;
5483 while (ifslastp->next && ifslastp->next->begoff < endoff)
5484 ifslastp=ifslastp->next;
5485 while (ifslastp->next != NULL) {
5486 struct ifsregion *ifsp;
5487 INT_OFF;
5488 ifsp = ifslastp->next->next;
5489 free(ifslastp->next);
5490 ifslastp->next = ifsp;
5491 INT_ON;
5492 }
5493 if (ifslastp->endoff > endoff)
5494 ifslastp->endoff = endoff;
5495}
5496
5497static char *
5498exptilde(char *startp, char *p, int flag)
5499{
5500 char c;
5501 char *name;
5502 struct passwd *pw;
5503 const char *home;
5504 int quotes = flag & (EXP_FULL | EXP_CASE);
5505 int startloc;
5506
5507 name = p + 1;
5508
5509 while ((c = *++p) != '\0') {
5510 switch (c) {
5511 case CTLESC:
5512 return startp;
5513 case CTLQUOTEMARK:
5514 return startp;
5515 case ':':
5516 if (flag & EXP_VARTILDE)
5517 goto done;
5518 break;
5519 case '/':
5520 case CTLENDVAR:
5521 goto done;
5522 }
5523 }
5524 done:
5525 *p = '\0';
5526 if (*name == '\0') {
5527 home = lookupvar(homestr);
5528 } else {
5529 pw = getpwnam(name);
5530 if (pw == NULL)
5531 goto lose;
5532 home = pw->pw_dir;
5533 }
5534 if (!home || !*home)
5535 goto lose;
5536 *p = c;
5537 startloc = expdest - (char *)stackblock();
5538 strtodest(home, SQSYNTAX, quotes);
5539 recordregion(startloc, expdest - (char *)stackblock(), 0);
5540 return p;
5541 lose:
5542 *p = c;
5543 return startp;
5544}
5545
5546/*
5547 * Execute a command inside back quotes. If it's a builtin command, we
5548 * want to save its output in a block obtained from malloc. Otherwise
5549 * we fork off a subprocess and get the output of the command via a pipe.
5550 * Should be called with interrupts off.
5551 */
5552struct backcmd { /* result of evalbackcmd */
5553 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005554 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005555 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005556 struct job *jp; /* job structure for command */
5557};
5558
5559/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005560static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005561#define EV_EXIT 01 /* exit after evaluating tree */
5562static void evaltree(union node *, int);
5563
5564static void
5565evalbackcmd(union node *n, struct backcmd *result)
5566{
5567 int saveherefd;
5568
5569 result->fd = -1;
5570 result->buf = NULL;
5571 result->nleft = 0;
5572 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005573 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005574 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005575
5576 saveherefd = herefd;
5577 herefd = -1;
5578
5579 {
5580 int pip[2];
5581 struct job *jp;
5582
5583 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005584 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005585 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005586 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5587 FORCE_INT_ON;
5588 close(pip[0]);
5589 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005590 /*close(1);*/
5591 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005592 close(pip[1]);
5593 }
5594 eflag = 0;
5595 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5596 /* NOTREACHED */
5597 }
5598 close(pip[1]);
5599 result->fd = pip[0];
5600 result->jp = jp;
5601 }
5602 herefd = saveherefd;
5603 out:
5604 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5605 result->fd, result->buf, result->nleft, result->jp));
5606}
5607
5608/*
5609 * Expand stuff in backwards quotes.
5610 */
5611static void
5612expbackq(union node *cmd, int quoted, int quotes)
5613{
5614 struct backcmd in;
5615 int i;
5616 char buf[128];
5617 char *p;
5618 char *dest;
5619 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005620 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005621 struct stackmark smark;
5622
5623 INT_OFF;
5624 setstackmark(&smark);
5625 dest = expdest;
5626 startloc = dest - (char *)stackblock();
5627 grabstackstr(dest);
5628 evalbackcmd(cmd, &in);
5629 popstackmark(&smark);
5630
5631 p = in.buf;
5632 i = in.nleft;
5633 if (i == 0)
5634 goto read;
5635 for (;;) {
5636 memtodest(p, i, syntax, quotes);
5637 read:
5638 if (in.fd < 0)
5639 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005640 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005641 TRACE(("expbackq: read returns %d\n", i));
5642 if (i <= 0)
5643 break;
5644 p = buf;
5645 }
5646
Denis Vlasenko60818682007-09-28 22:07:23 +00005647 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005648 if (in.fd >= 0) {
5649 close(in.fd);
5650 back_exitstatus = waitforjob(in.jp);
5651 }
5652 INT_ON;
5653
5654 /* Eat all trailing newlines */
5655 dest = expdest;
5656 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5657 STUNPUTC(dest);
5658 expdest = dest;
5659
5660 if (quoted == 0)
5661 recordregion(startloc, dest - (char *)stackblock(), 0);
5662 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5663 (dest - (char *)stackblock()) - startloc,
5664 (dest - (char *)stackblock()) - startloc,
5665 stackblock() + startloc));
5666}
5667
Mike Frysinger98c52642009-04-02 10:02:37 +00005668#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669/*
5670 * Expand arithmetic expression. Backup to start of expression,
5671 * evaluate, place result in (backed up) result, adjust string position.
5672 */
5673static void
5674expari(int quotes)
5675{
5676 char *p, *start;
5677 int begoff;
5678 int flag;
5679 int len;
5680
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005681 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682
5683 /*
5684 * This routine is slightly over-complicated for
5685 * efficiency. Next we scan backwards looking for the
5686 * start of arithmetic.
5687 */
5688 start = stackblock();
5689 p = expdest - 1;
5690 *p = '\0';
5691 p--;
5692 do {
5693 int esc;
5694
5695 while (*p != CTLARI) {
5696 p--;
5697#if DEBUG
5698 if (p < start) {
5699 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5700 }
5701#endif
5702 }
5703
5704 esc = esclen(start, p);
5705 if (!(esc % 2)) {
5706 break;
5707 }
5708
5709 p -= esc + 1;
5710 } while (1);
5711
5712 begoff = p - start;
5713
5714 removerecordregions(begoff);
5715
5716 flag = p[1];
5717
5718 expdest = p;
5719
5720 if (quotes)
5721 rmescapes(p + 2);
5722
5723 len = cvtnum(dash_arith(p + 2));
5724
5725 if (flag != '"')
5726 recordregion(begoff, begoff + len, 0);
5727}
5728#endif
5729
5730/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005731static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005732
5733/*
5734 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5735 * characters to allow for further processing. Otherwise treat
5736 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005737 *
5738 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5739 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5740 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005741 */
5742static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005743argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005744{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005745 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005746 '=',
5747 ':',
5748 CTLQUOTEMARK,
5749 CTLENDVAR,
5750 CTLESC,
5751 CTLVAR,
5752 CTLBACKQ,
5753 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005754#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005755 CTLENDARI,
5756#endif
5757 0
5758 };
5759 const char *reject = spclchars;
5760 int c;
5761 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5762 int breakall = flag & EXP_WORD;
5763 int inquotes;
5764 size_t length;
5765 int startloc;
5766
5767 if (!(flag & EXP_VARTILDE)) {
5768 reject += 2;
5769 } else if (flag & EXP_VARTILDE2) {
5770 reject++;
5771 }
5772 inquotes = 0;
5773 length = 0;
5774 if (flag & EXP_TILDE) {
5775 char *q;
5776
5777 flag &= ~EXP_TILDE;
5778 tilde:
5779 q = p;
5780 if (*q == CTLESC && (flag & EXP_QWORD))
5781 q++;
5782 if (*q == '~')
5783 p = exptilde(p, q, flag);
5784 }
5785 start:
5786 startloc = expdest - (char *)stackblock();
5787 for (;;) {
5788 length += strcspn(p + length, reject);
5789 c = p[length];
5790 if (c && (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005791#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005792 || c == CTLENDARI
5793#endif
5794 )) {
5795 /* c == '=' || c == ':' || c == CTLENDARI */
5796 length++;
5797 }
5798 if (length > 0) {
5799 int newloc;
5800 expdest = stack_nputstr(p, length, expdest);
5801 newloc = expdest - (char *)stackblock();
5802 if (breakall && !inquotes && newloc > startloc) {
5803 recordregion(startloc, newloc, 0);
5804 }
5805 startloc = newloc;
5806 }
5807 p += length + 1;
5808 length = 0;
5809
5810 switch (c) {
5811 case '\0':
5812 goto breakloop;
5813 case '=':
5814 if (flag & EXP_VARTILDE2) {
5815 p--;
5816 continue;
5817 }
5818 flag |= EXP_VARTILDE2;
5819 reject++;
5820 /* fall through */
5821 case ':':
5822 /*
5823 * sort of a hack - expand tildes in variable
5824 * assignments (after the first '=' and after ':'s).
5825 */
5826 if (*--p == '~') {
5827 goto tilde;
5828 }
5829 continue;
5830 }
5831
5832 switch (c) {
5833 case CTLENDVAR: /* ??? */
5834 goto breakloop;
5835 case CTLQUOTEMARK:
5836 /* "$@" syntax adherence hack */
5837 if (
5838 !inquotes &&
5839 !memcmp(p, dolatstr, 4) &&
5840 (p[4] == CTLQUOTEMARK || (
5841 p[4] == CTLENDVAR &&
5842 p[5] == CTLQUOTEMARK
5843 ))
5844 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005845 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005846 goto start;
5847 }
5848 inquotes = !inquotes;
5849 addquote:
5850 if (quotes) {
5851 p--;
5852 length++;
5853 startloc++;
5854 }
5855 break;
5856 case CTLESC:
5857 startloc++;
5858 length++;
5859 goto addquote;
5860 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005861 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005862 goto start;
5863 case CTLBACKQ:
5864 c = 0;
5865 case CTLBACKQ|CTLQUOTE:
5866 expbackq(argbackq->n, c, quotes);
5867 argbackq = argbackq->next;
5868 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005869#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005870 case CTLENDARI:
5871 p--;
5872 expari(quotes);
5873 goto start;
5874#endif
5875 }
5876 }
5877 breakloop:
5878 ;
5879}
5880
5881static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005882scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 int zero)
5884{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005885// This commented out code was added by James Simmons <jsimmons@infradead.org>
5886// as part of a larger change when he added support for ${var/a/b}.
5887// However, it broke # and % operators:
5888//
5889//var=ababcdcd
5890// ok bad
5891//echo ${var#ab} abcdcd abcdcd
5892//echo ${var##ab} abcdcd abcdcd
5893//echo ${var#a*b} abcdcd ababcdcd (!)
5894//echo ${var##a*b} cdcd cdcd
5895//echo ${var#?} babcdcd ababcdcd (!)
5896//echo ${var##?} babcdcd babcdcd
5897//echo ${var#*} ababcdcd babcdcd (!)
5898//echo ${var##*}
5899//echo ${var%cd} ababcd ababcd
5900//echo ${var%%cd} ababcd abab (!)
5901//echo ${var%c*d} ababcd ababcd
5902//echo ${var%%c*d} abab ababcdcd (!)
5903//echo ${var%?} ababcdc ababcdc
5904//echo ${var%%?} ababcdc ababcdcd (!)
5905//echo ${var%*} ababcdcd ababcdcd
5906//echo ${var%%*}
5907//
5908// Commenting it back out helped. Remove it completely if it really
5909// is not needed.
5910
5911 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005912 char c;
5913
5914 loc = startp;
5915 loc2 = rmesc;
5916 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005917 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005918 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005919
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005920 c = *loc2;
5921 if (zero) {
5922 *loc2 = '\0';
5923 s = rmesc;
5924 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005925 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005926
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005927// // chop off end if its '*'
5928// full = strrchr(str, '*');
5929// if (full && full != str)
5930// match--;
5931//
5932// // If str starts with '*' replace with s.
5933// if ((*str == '*') && strlen(s) >= match) {
5934// full = xstrdup(s);
5935// strncpy(full+strlen(s)-match+1, str+1, match-1);
5936// } else
5937// full = xstrndup(str, match);
5938// match = strncmp(s, full, strlen(full));
5939// free(full);
5940//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005941 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005942 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005943 return loc;
5944 if (quotes && *loc == CTLESC)
5945 loc++;
5946 loc++;
5947 loc2++;
5948 } while (c);
5949 return 0;
5950}
5951
5952static char *
5953scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5954 int zero)
5955{
5956 int esc = 0;
5957 char *loc;
5958 char *loc2;
5959
5960 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5961 int match;
5962 char c = *loc2;
5963 const char *s = loc2;
5964 if (zero) {
5965 *loc2 = '\0';
5966 s = rmesc;
5967 }
5968 match = pmatch(str, s);
5969 *loc2 = c;
5970 if (match)
5971 return loc;
5972 loc--;
5973 if (quotes) {
5974 if (--esc < 0) {
5975 esc = esclen(startp, loc);
5976 }
5977 if (esc % 2) {
5978 esc--;
5979 loc--;
5980 }
5981 }
5982 }
5983 return 0;
5984}
5985
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005986static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005987static void
5988varunset(const char *end, const char *var, const char *umsg, int varflags)
5989{
5990 const char *msg;
5991 const char *tail;
5992
5993 tail = nullstr;
5994 msg = "parameter not set";
5995 if (umsg) {
5996 if (*end == CTLENDVAR) {
5997 if (varflags & VSNUL)
5998 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005999 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006000 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006001 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006002 }
6003 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6004}
6005
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006006#if ENABLE_ASH_BASH_COMPAT
6007static char *
6008parse_sub_pattern(char *arg, int inquotes)
6009{
6010 char *idx, *repl = NULL;
6011 unsigned char c;
6012
Denis Vlasenko2659c632008-06-14 06:04:59 +00006013 idx = arg;
6014 while (1) {
6015 c = *arg;
6016 if (!c)
6017 break;
6018 if (c == '/') {
6019 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006020 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006021 repl = idx + 1;
6022 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006023 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006024 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006025 *idx++ = c;
6026 if (!inquotes && c == '\\' && arg[1] == '\\')
6027 arg++; /* skip both \\, not just first one */
6028 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006029 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006030 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006031
6032 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006033}
6034#endif /* ENABLE_ASH_BASH_COMPAT */
6035
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006036static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006037subevalvar(char *p, char *str, int strloc, int subtype,
6038 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006039{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006040 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006041 char *startp;
6042 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006043 char *rmesc, *rmescend;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006044 USE_ASH_BASH_COMPAT(char *repl = NULL;)
6045 USE_ASH_BASH_COMPAT(char null = '\0';)
6046 USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
6047 int saveherefd = herefd;
6048 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006049 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006050 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006051
6052 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006053 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6054 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006055 STPUTC('\0', expdest);
6056 herefd = saveherefd;
6057 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006058 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006059
6060 switch (subtype) {
6061 case VSASSIGN:
6062 setvar(str, startp, 0);
6063 amount = startp - expdest;
6064 STADJUST(amount, expdest);
6065 return startp;
6066
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006067#if ENABLE_ASH_BASH_COMPAT
6068 case VSSUBSTR:
6069 loc = str = stackblock() + strloc;
6070// TODO: number() instead? It does error checking...
6071 pos = atoi(loc);
6072 len = str - startp - 1;
6073
6074 /* *loc != '\0', guaranteed by parser */
6075 if (quotes) {
6076 char *ptr;
6077
6078 /* We must adjust the length by the number of escapes we find. */
6079 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006080 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006081 len--;
6082 ptr++;
6083 }
6084 }
6085 }
6086 orig_len = len;
6087
6088 if (*loc++ == ':') {
6089// TODO: number() instead? It does error checking...
6090 len = atoi(loc);
6091 } else {
6092 len = orig_len;
6093 while (*loc && *loc != ':')
6094 loc++;
6095 if (*loc++ == ':')
6096// TODO: number() instead? It does error checking...
6097 len = atoi(loc);
6098 }
6099 if (pos >= orig_len) {
6100 pos = 0;
6101 len = 0;
6102 }
6103 if (len > (orig_len - pos))
6104 len = orig_len - pos;
6105
6106 for (str = startp; pos; str++, pos--) {
6107 if (quotes && *str == CTLESC)
6108 str++;
6109 }
6110 for (loc = startp; len; len--) {
6111 if (quotes && *str == CTLESC)
6112 *loc++ = *str++;
6113 *loc++ = *str++;
6114 }
6115 *loc = '\0';
6116 amount = loc - expdest;
6117 STADJUST(amount, expdest);
6118 return loc;
6119#endif
6120
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006121 case VSQUESTION:
6122 varunset(p, str, startp, varflags);
6123 /* NOTREACHED */
6124 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006125 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006126
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006127 /* We'll comeback here if we grow the stack while handling
6128 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6129 * stack will need rebasing, and we'll need to remove our work
6130 * areas each time
6131 */
6132 USE_ASH_BASH_COMPAT(restart:)
6133
6134 amount = expdest - ((char *)stackblock() + resetloc);
6135 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006136 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006137
6138 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006139 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006140 if (quotes) {
6141 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6142 if (rmesc != startp) {
6143 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006144 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145 }
6146 }
6147 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006148 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006150 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006152#if ENABLE_ASH_BASH_COMPAT
6153 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6154 char *idx, *end, *restart_detect;
6155
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006156 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6158 if (!repl)
6159 repl = &null;
6160 }
6161
6162 /* If there's no pattern to match, return the expansion unmolested */
6163 if (*str == '\0')
6164 return 0;
6165
6166 len = 0;
6167 idx = startp;
6168 end = str - 1;
6169 while (idx < end) {
6170 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6171 if (!loc) {
6172 /* No match, advance */
6173 restart_detect = stackblock();
6174 STPUTC(*idx, expdest);
6175 if (quotes && *idx == CTLESC) {
6176 idx++;
6177 len++;
6178 STPUTC(*idx, expdest);
6179 }
6180 if (stackblock() != restart_detect)
6181 goto restart;
6182 idx++;
6183 len++;
6184 rmesc++;
6185 continue;
6186 }
6187
6188 if (subtype == VSREPLACEALL) {
6189 while (idx < loc) {
6190 if (quotes && *idx == CTLESC)
6191 idx++;
6192 idx++;
6193 rmesc++;
6194 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006195 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006196 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006197 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198
6199 for (loc = repl; *loc; loc++) {
6200 restart_detect = stackblock();
6201 STPUTC(*loc, expdest);
6202 if (stackblock() != restart_detect)
6203 goto restart;
6204 len++;
6205 }
6206
6207 if (subtype == VSREPLACE) {
6208 while (*idx) {
6209 restart_detect = stackblock();
6210 STPUTC(*idx, expdest);
6211 if (stackblock() != restart_detect)
6212 goto restart;
6213 len++;
6214 idx++;
6215 }
6216 break;
6217 }
6218 }
6219
6220 /* We've put the replaced text into a buffer at workloc, now
6221 * move it to the right place and adjust the stack.
6222 */
6223 startp = stackblock() + startloc;
6224 STPUTC('\0', expdest);
6225 memmove(startp, stackblock() + workloc, len);
6226 startp[len++] = '\0';
6227 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6228 STADJUST(-amount, expdest);
6229 return startp;
6230 }
6231#endif /* ENABLE_ASH_BASH_COMPAT */
6232
6233 subtype -= VSTRIMRIGHT;
6234#if DEBUG
6235 if (subtype < 0 || subtype > 7)
6236 abort();
6237#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006238 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6239 zero = subtype >> 1;
6240 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6241 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6242
6243 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6244 if (loc) {
6245 if (zero) {
6246 memmove(startp, loc, str - loc);
6247 loc = startp + (str - loc) - 1;
6248 }
6249 *loc = '\0';
6250 amount = loc - expdest;
6251 STADJUST(amount, expdest);
6252 }
6253 return loc;
6254}
6255
6256/*
6257 * Add the value of a specialized variable to the stack string.
6258 */
6259static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006260varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006261{
6262 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006263 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 int i;
6265 int sep = 0;
6266 int sepq = 0;
6267 ssize_t len = 0;
6268 char **ap;
6269 int syntax;
6270 int quoted = varflags & VSQUOTE;
6271 int subtype = varflags & VSTYPE;
6272 int quotes = flags & (EXP_FULL | EXP_CASE);
6273
6274 if (quoted && (flags & EXP_FULL))
6275 sep = 1 << CHAR_BIT;
6276
6277 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6278 switch (*name) {
6279 case '$':
6280 num = rootpid;
6281 goto numvar;
6282 case '?':
6283 num = exitstatus;
6284 goto numvar;
6285 case '#':
6286 num = shellparam.nparam;
6287 goto numvar;
6288 case '!':
6289 num = backgndpid;
6290 if (num == 0)
6291 return -1;
6292 numvar:
6293 len = cvtnum(num);
6294 break;
6295 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006296 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006297 for (i = NOPTS - 1; i >= 0; i--) {
6298 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006299 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006300 len++;
6301 }
6302 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006303 break;
6304 case '@':
6305 if (sep)
6306 goto param;
6307 /* fall through */
6308 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006309 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006310 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6311 sepq = 1;
6312 param:
6313 ap = shellparam.p;
6314 if (!ap)
6315 return -1;
6316 while ((p = *ap++)) {
6317 size_t partlen;
6318
6319 partlen = strlen(p);
6320 len += partlen;
6321
6322 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6323 memtodest(p, partlen, syntax, quotes);
6324
6325 if (*ap && sep) {
6326 char *q;
6327
6328 len++;
6329 if (subtype == VSPLUS || subtype == VSLENGTH) {
6330 continue;
6331 }
6332 q = expdest;
6333 if (sepq)
6334 STPUTC(CTLESC, q);
6335 STPUTC(sep, q);
6336 expdest = q;
6337 }
6338 }
6339 return len;
6340 case '0':
6341 case '1':
6342 case '2':
6343 case '3':
6344 case '4':
6345 case '5':
6346 case '6':
6347 case '7':
6348 case '8':
6349 case '9':
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006350// TODO: number() instead? It does error checking...
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006351 num = atoi(name);
6352 if (num < 0 || num > shellparam.nparam)
6353 return -1;
6354 p = num ? shellparam.p[num - 1] : arg0;
6355 goto value;
6356 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006357 /* NB: name has form "VAR=..." */
6358
6359 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6360 * which should be considered before we check variables. */
6361 if (var_str_list) {
6362 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6363 p = NULL;
6364 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006365 char *str, *eq;
6366 str = var_str_list->text;
6367 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006368 if (!eq) /* stop at first non-assignment */
6369 break;
6370 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006371 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006372 && strncmp(str, name, name_len) == 0) {
6373 p = eq;
6374 /* goto value; - WRONG! */
6375 /* think "A=1 A=2 B=$A" */
6376 }
6377 var_str_list = var_str_list->next;
6378 } while (var_str_list);
6379 if (p)
6380 goto value;
6381 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006382 p = lookupvar(name);
6383 value:
6384 if (!p)
6385 return -1;
6386
6387 len = strlen(p);
6388 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6389 memtodest(p, len, syntax, quotes);
6390 return len;
6391 }
6392
6393 if (subtype == VSPLUS || subtype == VSLENGTH)
6394 STADJUST(-len, expdest);
6395 return len;
6396}
6397
6398/*
6399 * Expand a variable, and return a pointer to the next character in the
6400 * input string.
6401 */
6402static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006403evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006404{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006405 char varflags;
6406 char subtype;
6407 char quoted;
6408 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006409 char *var;
6410 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006411 int startloc;
6412 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006413
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006414 varflags = *p++;
6415 subtype = varflags & VSTYPE;
6416 quoted = varflags & VSQUOTE;
6417 var = p;
6418 easy = (!quoted || (*var == '@' && shellparam.nparam));
6419 startloc = expdest - (char *)stackblock();
6420 p = strchr(p, '=') + 1;
6421
6422 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006423 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006424 if (varflags & VSNUL)
6425 varlen--;
6426
6427 if (subtype == VSPLUS) {
6428 varlen = -1 - varlen;
6429 goto vsplus;
6430 }
6431
6432 if (subtype == VSMINUS) {
6433 vsplus:
6434 if (varlen < 0) {
6435 argstr(
6436 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006437 (quoted ? EXP_QWORD : EXP_WORD),
6438 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006439 );
6440 goto end;
6441 }
6442 if (easy)
6443 goto record;
6444 goto end;
6445 }
6446
6447 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6448 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006449 if (subevalvar(p, var, /* strloc: */ 0,
6450 subtype, startloc, varflags,
6451 /* quotes: */ 0,
6452 var_str_list)
6453 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006454 varflags &= ~VSNUL;
6455 /*
6456 * Remove any recorded regions beyond
6457 * start of variable
6458 */
6459 removerecordregions(startloc);
6460 goto again;
6461 }
6462 goto end;
6463 }
6464 if (easy)
6465 goto record;
6466 goto end;
6467 }
6468
6469 if (varlen < 0 && uflag)
6470 varunset(p, var, 0, 0);
6471
6472 if (subtype == VSLENGTH) {
6473 cvtnum(varlen > 0 ? varlen : 0);
6474 goto record;
6475 }
6476
6477 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006478 if (easy)
6479 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006480 goto end;
6481 }
6482
6483#if DEBUG
6484 switch (subtype) {
6485 case VSTRIMLEFT:
6486 case VSTRIMLEFTMAX:
6487 case VSTRIMRIGHT:
6488 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006489#if ENABLE_ASH_BASH_COMPAT
6490 case VSSUBSTR:
6491 case VSREPLACE:
6492 case VSREPLACEALL:
6493#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006494 break;
6495 default:
6496 abort();
6497 }
6498#endif
6499
6500 if (varlen >= 0) {
6501 /*
6502 * Terminate the string and start recording the pattern
6503 * right after it
6504 */
6505 STPUTC('\0', expdest);
6506 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006507 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6508 startloc, varflags,
6509 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6510 var_str_list)
6511 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006512 int amount = expdest - (
6513 (char *)stackblock() + patloc - 1
6514 );
6515 STADJUST(-amount, expdest);
6516 }
6517 /* Remove any recorded regions beyond start of variable */
6518 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006519 record:
6520 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006521 }
6522
6523 end:
6524 if (subtype != VSNORMAL) { /* skip to end of alternative */
6525 int nesting = 1;
6526 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006527 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006528 if (c == CTLESC)
6529 p++;
6530 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6531 if (varlen >= 0)
6532 argbackq = argbackq->next;
6533 } else if (c == CTLVAR) {
6534 if ((*p++ & VSTYPE) != VSNORMAL)
6535 nesting++;
6536 } else if (c == CTLENDVAR) {
6537 if (--nesting == 0)
6538 break;
6539 }
6540 }
6541 }
6542 return p;
6543}
6544
6545/*
6546 * Break the argument string into pieces based upon IFS and add the
6547 * strings to the argument list. The regions of the string to be
6548 * searched for IFS characters have been stored by recordregion.
6549 */
6550static void
6551ifsbreakup(char *string, struct arglist *arglist)
6552{
6553 struct ifsregion *ifsp;
6554 struct strlist *sp;
6555 char *start;
6556 char *p;
6557 char *q;
6558 const char *ifs, *realifs;
6559 int ifsspc;
6560 int nulonly;
6561
6562 start = string;
6563 if (ifslastp != NULL) {
6564 ifsspc = 0;
6565 nulonly = 0;
6566 realifs = ifsset() ? ifsval() : defifs;
6567 ifsp = &ifsfirst;
6568 do {
6569 p = string + ifsp->begoff;
6570 nulonly = ifsp->nulonly;
6571 ifs = nulonly ? nullstr : realifs;
6572 ifsspc = 0;
6573 while (p < string + ifsp->endoff) {
6574 q = p;
6575 if (*p == CTLESC)
6576 p++;
6577 if (!strchr(ifs, *p)) {
6578 p++;
6579 continue;
6580 }
6581 if (!nulonly)
6582 ifsspc = (strchr(defifs, *p) != NULL);
6583 /* Ignore IFS whitespace at start */
6584 if (q == start && ifsspc) {
6585 p++;
6586 start = p;
6587 continue;
6588 }
6589 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006590 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006591 sp->text = start;
6592 *arglist->lastp = sp;
6593 arglist->lastp = &sp->next;
6594 p++;
6595 if (!nulonly) {
6596 for (;;) {
6597 if (p >= string + ifsp->endoff) {
6598 break;
6599 }
6600 q = p;
6601 if (*p == CTLESC)
6602 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006603 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006604 p = q;
6605 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006606 }
6607 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006608 if (ifsspc) {
6609 p++;
6610 ifsspc = 0;
6611 } else {
6612 p = q;
6613 break;
6614 }
6615 } else
6616 p++;
6617 }
6618 }
6619 start = p;
6620 } /* while */
6621 ifsp = ifsp->next;
6622 } while (ifsp != NULL);
6623 if (nulonly)
6624 goto add;
6625 }
6626
6627 if (!*start)
6628 return;
6629
6630 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006631 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006632 sp->text = start;
6633 *arglist->lastp = sp;
6634 arglist->lastp = &sp->next;
6635}
6636
6637static void
6638ifsfree(void)
6639{
6640 struct ifsregion *p;
6641
6642 INT_OFF;
6643 p = ifsfirst.next;
6644 do {
6645 struct ifsregion *ifsp;
6646 ifsp = p->next;
6647 free(p);
6648 p = ifsp;
6649 } while (p);
6650 ifslastp = NULL;
6651 ifsfirst.next = NULL;
6652 INT_ON;
6653}
6654
6655/*
6656 * Add a file name to the list.
6657 */
6658static void
6659addfname(const char *name)
6660{
6661 struct strlist *sp;
6662
Denis Vlasenko597906c2008-02-20 16:38:54 +00006663 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006664 sp->text = ststrdup(name);
6665 *exparg.lastp = sp;
6666 exparg.lastp = &sp->next;
6667}
6668
6669static char *expdir;
6670
6671/*
6672 * Do metacharacter (i.e. *, ?, [...]) expansion.
6673 */
6674static void
6675expmeta(char *enddir, char *name)
6676{
6677 char *p;
6678 const char *cp;
6679 char *start;
6680 char *endname;
6681 int metaflag;
6682 struct stat statb;
6683 DIR *dirp;
6684 struct dirent *dp;
6685 int atend;
6686 int matchdot;
6687
6688 metaflag = 0;
6689 start = name;
6690 for (p = name; *p; p++) {
6691 if (*p == '*' || *p == '?')
6692 metaflag = 1;
6693 else if (*p == '[') {
6694 char *q = p + 1;
6695 if (*q == '!')
6696 q++;
6697 for (;;) {
6698 if (*q == '\\')
6699 q++;
6700 if (*q == '/' || *q == '\0')
6701 break;
6702 if (*++q == ']') {
6703 metaflag = 1;
6704 break;
6705 }
6706 }
6707 } else if (*p == '\\')
6708 p++;
6709 else if (*p == '/') {
6710 if (metaflag)
6711 goto out;
6712 start = p + 1;
6713 }
6714 }
6715 out:
6716 if (metaflag == 0) { /* we've reached the end of the file name */
6717 if (enddir != expdir)
6718 metaflag++;
6719 p = name;
6720 do {
6721 if (*p == '\\')
6722 p++;
6723 *enddir++ = *p;
6724 } while (*p++);
6725 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6726 addfname(expdir);
6727 return;
6728 }
6729 endname = p;
6730 if (name < start) {
6731 p = name;
6732 do {
6733 if (*p == '\\')
6734 p++;
6735 *enddir++ = *p++;
6736 } while (p < start);
6737 }
6738 if (enddir == expdir) {
6739 cp = ".";
6740 } else if (enddir == expdir + 1 && *expdir == '/') {
6741 cp = "/";
6742 } else {
6743 cp = expdir;
6744 enddir[-1] = '\0';
6745 }
6746 dirp = opendir(cp);
6747 if (dirp == NULL)
6748 return;
6749 if (enddir != expdir)
6750 enddir[-1] = '/';
6751 if (*endname == 0) {
6752 atend = 1;
6753 } else {
6754 atend = 0;
6755 *endname++ = '\0';
6756 }
6757 matchdot = 0;
6758 p = start;
6759 if (*p == '\\')
6760 p++;
6761 if (*p == '.')
6762 matchdot++;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00006763 while (!intpending && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006764 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006765 continue;
6766 if (pmatch(start, dp->d_name)) {
6767 if (atend) {
6768 strcpy(enddir, dp->d_name);
6769 addfname(expdir);
6770 } else {
6771 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6772 continue;
6773 p[-1] = '/';
6774 expmeta(p, endname);
6775 }
6776 }
6777 }
6778 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006779 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006780 endname[-1] = '/';
6781}
6782
6783static struct strlist *
6784msort(struct strlist *list, int len)
6785{
6786 struct strlist *p, *q = NULL;
6787 struct strlist **lpp;
6788 int half;
6789 int n;
6790
6791 if (len <= 1)
6792 return list;
6793 half = len >> 1;
6794 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006795 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006796 q = p;
6797 p = p->next;
6798 }
6799 q->next = NULL; /* terminate first half of list */
6800 q = msort(list, half); /* sort first half of list */
6801 p = msort(p, len - half); /* sort second half */
6802 lpp = &list;
6803 for (;;) {
6804#if ENABLE_LOCALE_SUPPORT
6805 if (strcoll(p->text, q->text) < 0)
6806#else
6807 if (strcmp(p->text, q->text) < 0)
6808#endif
6809 {
6810 *lpp = p;
6811 lpp = &p->next;
6812 p = *lpp;
6813 if (p == NULL) {
6814 *lpp = q;
6815 break;
6816 }
6817 } else {
6818 *lpp = q;
6819 lpp = &q->next;
6820 q = *lpp;
6821 if (q == NULL) {
6822 *lpp = p;
6823 break;
6824 }
6825 }
6826 }
6827 return list;
6828}
6829
6830/*
6831 * Sort the results of file name expansion. It calculates the number of
6832 * strings to sort and then calls msort (short for merge sort) to do the
6833 * work.
6834 */
6835static struct strlist *
6836expsort(struct strlist *str)
6837{
6838 int len;
6839 struct strlist *sp;
6840
6841 len = 0;
6842 for (sp = str; sp; sp = sp->next)
6843 len++;
6844 return msort(str, len);
6845}
6846
6847static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006848expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006849{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006850 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006851 '*', '?', '[', 0
6852 };
6853 /* TODO - EXP_REDIR */
6854
6855 while (str) {
6856 struct strlist **savelastp;
6857 struct strlist *sp;
6858 char *p;
6859
6860 if (fflag)
6861 goto nometa;
6862 if (!strpbrk(str->text, metachars))
6863 goto nometa;
6864 savelastp = exparg.lastp;
6865
6866 INT_OFF;
6867 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6868 {
6869 int i = strlen(str->text);
6870 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6871 }
6872
6873 expmeta(expdir, p);
6874 free(expdir);
6875 if (p != str->text)
6876 free(p);
6877 INT_ON;
6878 if (exparg.lastp == savelastp) {
6879 /*
6880 * no matches
6881 */
6882 nometa:
6883 *exparg.lastp = str;
6884 rmescapes(str->text);
6885 exparg.lastp = &str->next;
6886 } else {
6887 *exparg.lastp = NULL;
6888 *savelastp = sp = expsort(*savelastp);
6889 while (sp->next != NULL)
6890 sp = sp->next;
6891 exparg.lastp = &sp->next;
6892 }
6893 str = str->next;
6894 }
6895}
6896
6897/*
6898 * Perform variable substitution and command substitution on an argument,
6899 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6900 * perform splitting and file name expansion. When arglist is NULL, perform
6901 * here document expansion.
6902 */
6903static void
6904expandarg(union node *arg, struct arglist *arglist, int flag)
6905{
6906 struct strlist *sp;
6907 char *p;
6908
6909 argbackq = arg->narg.backquote;
6910 STARTSTACKSTR(expdest);
6911 ifsfirst.next = NULL;
6912 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006913 argstr(arg->narg.text, flag,
6914 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006915 p = _STPUTC('\0', expdest);
6916 expdest = p - 1;
6917 if (arglist == NULL) {
6918 return; /* here document expanded */
6919 }
6920 p = grabstackstr(p);
6921 exparg.lastp = &exparg.list;
6922 /*
6923 * TODO - EXP_REDIR
6924 */
6925 if (flag & EXP_FULL) {
6926 ifsbreakup(p, &exparg);
6927 *exparg.lastp = NULL;
6928 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00006929 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006930 } else {
6931 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6932 rmescapes(p);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006933 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006934 sp->text = p;
6935 *exparg.lastp = sp;
6936 exparg.lastp = &sp->next;
6937 }
6938 if (ifsfirst.next)
6939 ifsfree();
6940 *exparg.lastp = NULL;
6941 if (exparg.list) {
6942 *arglist->lastp = exparg.list;
6943 arglist->lastp = exparg.lastp;
6944 }
6945}
6946
6947/*
6948 * Expand shell variables and backquotes inside a here document.
6949 */
6950static void
6951expandhere(union node *arg, int fd)
6952{
6953 herefd = fd;
6954 expandarg(arg, (struct arglist *)NULL, 0);
6955 full_write(fd, stackblock(), expdest - (char *)stackblock());
6956}
6957
6958/*
6959 * Returns true if the pattern matches the string.
6960 */
6961static int
6962patmatch(char *pattern, const char *string)
6963{
6964 return pmatch(preglob(pattern, 0, 0), string);
6965}
6966
6967/*
6968 * See if a pattern matches in a case statement.
6969 */
6970static int
6971casematch(union node *pattern, char *val)
6972{
6973 struct stackmark smark;
6974 int result;
6975
6976 setstackmark(&smark);
6977 argbackq = pattern->narg.backquote;
6978 STARTSTACKSTR(expdest);
6979 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006980 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6981 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006982 STACKSTRNUL(expdest);
6983 result = patmatch(stackblock(), val);
6984 popstackmark(&smark);
6985 return result;
6986}
6987
6988
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006989/* ============ find_command */
6990
6991struct builtincmd {
6992 const char *name;
6993 int (*builtin)(int, char **);
6994 /* unsigned flags; */
6995};
6996#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00006997/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006998 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006999#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007000#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007001
7002struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007003 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007004 union param {
7005 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007006 /* index >= 0 for commands without path (slashes) */
7007 /* (TODO: what exactly does the value mean? PATH position?) */
7008 /* index == -1 for commands with slashes */
7009 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007010 const struct builtincmd *cmd;
7011 struct funcnode *func;
7012 } u;
7013};
7014/* values of cmdtype */
7015#define CMDUNKNOWN -1 /* no entry in table for command */
7016#define CMDNORMAL 0 /* command is an executable program */
7017#define CMDFUNCTION 1 /* command is a shell function */
7018#define CMDBUILTIN 2 /* command is a shell builtin */
7019
7020/* action to find_command() */
7021#define DO_ERR 0x01 /* prints errors */
7022#define DO_ABS 0x02 /* checks absolute paths */
7023#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7024#define DO_ALTPATH 0x08 /* using alternate path */
7025#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7026
7027static void find_command(char *, struct cmdentry *, int, const char *);
7028
7029
7030/* ============ Hashing commands */
7031
7032/*
7033 * When commands are first encountered, they are entered in a hash table.
7034 * This ensures that a full path search will not have to be done for them
7035 * on each invocation.
7036 *
7037 * We should investigate converting to a linear search, even though that
7038 * would make the command name "hash" a misnomer.
7039 */
7040
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007041struct tblentry {
7042 struct tblentry *next; /* next entry in hash chain */
7043 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007044 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007045 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007046 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007047};
7048
Denis Vlasenko01631112007-12-16 17:20:38 +00007049static struct tblentry **cmdtable;
7050#define INIT_G_cmdtable() do { \
7051 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7052} while (0)
7053
7054static int builtinloc = -1; /* index in path of %builtin, or -1 */
7055
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007056
7057static void
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007058tryexec(USE_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007059{
7060 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007061
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007062#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007063 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007064 if (APPLET_IS_NOEXEC(applet_no)) {
7065 while (*envp)
7066 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007067 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007068 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007069 /* re-exec ourselves with the new arguments */
7070 execve(bb_busybox_exec_path, argv, envp);
7071 /* If they called chroot or otherwise made the binary no longer
7072 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007073 }
7074#endif
7075
7076 repeat:
7077#ifdef SYSV
7078 do {
7079 execve(cmd, argv, envp);
7080 } while (errno == EINTR);
7081#else
7082 execve(cmd, argv, envp);
7083#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007084 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007085 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007086 return;
7087 }
7088 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007089 char **ap;
7090 char **new;
7091
7092 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007093 continue;
7094 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007095 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007096 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007097 ap += 2;
7098 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007099 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007100 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007101 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007102 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007103 goto repeat;
7104 }
7105}
7106
7107/*
7108 * Exec a program. Never returns. If you change this routine, you may
7109 * have to change the find_command routine as well.
7110 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007111static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007112static void
7113shellexec(char **argv, const char *path, int idx)
7114{
7115 char *cmdname;
7116 int e;
7117 char **envp;
7118 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007119#if ENABLE_FEATURE_SH_STANDALONE
7120 int applet_no = -1;
7121#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007122
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007123 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007124 envp = listvars(VEXPORT, VUNSET, 0);
7125 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007126#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007127 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007128#endif
7129 ) {
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007130 tryexec(USE_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007131 e = errno;
7132 } else {
7133 e = ENOENT;
7134 while ((cmdname = padvance(&path, argv[0])) != NULL) {
7135 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007136 tryexec(USE_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007137 if (errno != ENOENT && errno != ENOTDIR)
7138 e = errno;
7139 }
7140 stunalloc(cmdname);
7141 }
7142 }
7143
7144 /* Map to POSIX errors */
7145 switch (e) {
7146 case EACCES:
7147 exerrno = 126;
7148 break;
7149 case ENOENT:
7150 exerrno = 127;
7151 break;
7152 default:
7153 exerrno = 2;
7154 break;
7155 }
7156 exitstatus = exerrno;
7157 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007158 argv[0], e, suppressint));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007159 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7160 /* NOTREACHED */
7161}
7162
7163static void
7164printentry(struct tblentry *cmdp)
7165{
7166 int idx;
7167 const char *path;
7168 char *name;
7169
7170 idx = cmdp->param.index;
7171 path = pathval();
7172 do {
7173 name = padvance(&path, cmdp->cmdname);
7174 stunalloc(name);
7175 } while (--idx >= 0);
7176 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7177}
7178
7179/*
7180 * Clear out command entries. The argument specifies the first entry in
7181 * PATH which has changed.
7182 */
7183static void
7184clearcmdentry(int firstchange)
7185{
7186 struct tblentry **tblp;
7187 struct tblentry **pp;
7188 struct tblentry *cmdp;
7189
7190 INT_OFF;
7191 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7192 pp = tblp;
7193 while ((cmdp = *pp) != NULL) {
7194 if ((cmdp->cmdtype == CMDNORMAL &&
7195 cmdp->param.index >= firstchange)
7196 || (cmdp->cmdtype == CMDBUILTIN &&
7197 builtinloc >= firstchange)
7198 ) {
7199 *pp = cmdp->next;
7200 free(cmdp);
7201 } else {
7202 pp = &cmdp->next;
7203 }
7204 }
7205 }
7206 INT_ON;
7207}
7208
7209/*
7210 * Locate a command in the command hash table. If "add" is nonzero,
7211 * add the command to the table if it is not already present. The
7212 * variable "lastcmdentry" is set to point to the address of the link
7213 * pointing to the entry, so that delete_cmd_entry can delete the
7214 * entry.
7215 *
7216 * Interrupts must be off if called with add != 0.
7217 */
7218static struct tblentry **lastcmdentry;
7219
7220static struct tblentry *
7221cmdlookup(const char *name, int add)
7222{
7223 unsigned int hashval;
7224 const char *p;
7225 struct tblentry *cmdp;
7226 struct tblentry **pp;
7227
7228 p = name;
7229 hashval = (unsigned char)*p << 4;
7230 while (*p)
7231 hashval += (unsigned char)*p++;
7232 hashval &= 0x7FFF;
7233 pp = &cmdtable[hashval % CMDTABLESIZE];
7234 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7235 if (strcmp(cmdp->cmdname, name) == 0)
7236 break;
7237 pp = &cmdp->next;
7238 }
7239 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007240 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7241 + strlen(name)
7242 /* + 1 - already done because
7243 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007244 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007245 cmdp->cmdtype = CMDUNKNOWN;
7246 strcpy(cmdp->cmdname, name);
7247 }
7248 lastcmdentry = pp;
7249 return cmdp;
7250}
7251
7252/*
7253 * Delete the command entry returned on the last lookup.
7254 */
7255static void
7256delete_cmd_entry(void)
7257{
7258 struct tblentry *cmdp;
7259
7260 INT_OFF;
7261 cmdp = *lastcmdentry;
7262 *lastcmdentry = cmdp->next;
7263 if (cmdp->cmdtype == CMDFUNCTION)
7264 freefunc(cmdp->param.func);
7265 free(cmdp);
7266 INT_ON;
7267}
7268
7269/*
7270 * Add a new command entry, replacing any existing command entry for
7271 * the same name - except special builtins.
7272 */
7273static void
7274addcmdentry(char *name, struct cmdentry *entry)
7275{
7276 struct tblentry *cmdp;
7277
7278 cmdp = cmdlookup(name, 1);
7279 if (cmdp->cmdtype == CMDFUNCTION) {
7280 freefunc(cmdp->param.func);
7281 }
7282 cmdp->cmdtype = entry->cmdtype;
7283 cmdp->param = entry->u;
7284 cmdp->rehash = 0;
7285}
7286
7287static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007288hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007289{
7290 struct tblentry **pp;
7291 struct tblentry *cmdp;
7292 int c;
7293 struct cmdentry entry;
7294 char *name;
7295
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007296 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007297 clearcmdentry(0);
7298 return 0;
7299 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007300
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007301 if (*argptr == NULL) {
7302 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7303 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7304 if (cmdp->cmdtype == CMDNORMAL)
7305 printentry(cmdp);
7306 }
7307 }
7308 return 0;
7309 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007310
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007311 c = 0;
7312 while ((name = *argptr) != NULL) {
7313 cmdp = cmdlookup(name, 0);
7314 if (cmdp != NULL
7315 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007316 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7317 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007318 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007319 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007320 find_command(name, &entry, DO_ERR, pathval());
7321 if (entry.cmdtype == CMDUNKNOWN)
7322 c = 1;
7323 argptr++;
7324 }
7325 return c;
7326}
7327
7328/*
7329 * Called when a cd is done. Marks all commands so the next time they
7330 * are executed they will be rehashed.
7331 */
7332static void
7333hashcd(void)
7334{
7335 struct tblentry **pp;
7336 struct tblentry *cmdp;
7337
7338 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7339 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007340 if (cmdp->cmdtype == CMDNORMAL
7341 || (cmdp->cmdtype == CMDBUILTIN
7342 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7343 && builtinloc > 0)
7344 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007345 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007346 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007347 }
7348 }
7349}
7350
7351/*
7352 * Fix command hash table when PATH changed.
7353 * Called before PATH is changed. The argument is the new value of PATH;
7354 * pathval() still returns the old value at this point.
7355 * Called with interrupts off.
7356 */
7357static void
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007358changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007359{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007360 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007361 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007362 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007363 int idx_bltin;
7364
7365 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007366 firstchange = 9999; /* assume no change */
7367 idx = 0;
7368 idx_bltin = -1;
7369 for (;;) {
7370 if (*old != *new) {
7371 firstchange = idx;
7372 if ((*old == '\0' && *new == ':')
7373 || (*old == ':' && *new == '\0'))
7374 firstchange++;
7375 old = new; /* ignore subsequent differences */
7376 }
7377 if (*new == '\0')
7378 break;
7379 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7380 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007381 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007382 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007383 new++, old++;
7384 }
7385 if (builtinloc < 0 && idx_bltin >= 0)
7386 builtinloc = idx_bltin; /* zap builtins */
7387 if (builtinloc >= 0 && idx_bltin < 0)
7388 firstchange = 0;
7389 clearcmdentry(firstchange);
7390 builtinloc = idx_bltin;
7391}
7392
7393#define TEOF 0
7394#define TNL 1
7395#define TREDIR 2
7396#define TWORD 3
7397#define TSEMI 4
7398#define TBACKGND 5
7399#define TAND 6
7400#define TOR 7
7401#define TPIPE 8
7402#define TLP 9
7403#define TRP 10
7404#define TENDCASE 11
7405#define TENDBQUOTE 12
7406#define TNOT 13
7407#define TCASE 14
7408#define TDO 15
7409#define TDONE 16
7410#define TELIF 17
7411#define TELSE 18
7412#define TESAC 19
7413#define TFI 20
7414#define TFOR 21
7415#define TIF 22
7416#define TIN 23
7417#define TTHEN 24
7418#define TUNTIL 25
7419#define TWHILE 26
7420#define TBEGIN 27
7421#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007422typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007423
7424/* first char is indicating which tokens mark the end of a list */
7425static const char *const tokname_array[] = {
7426 "\1end of file",
7427 "\0newline",
7428 "\0redirection",
7429 "\0word",
7430 "\0;",
7431 "\0&",
7432 "\0&&",
7433 "\0||",
7434 "\0|",
7435 "\0(",
7436 "\1)",
7437 "\1;;",
7438 "\1`",
7439#define KWDOFFSET 13
7440 /* the following are keywords */
7441 "\0!",
7442 "\0case",
7443 "\1do",
7444 "\1done",
7445 "\1elif",
7446 "\1else",
7447 "\1esac",
7448 "\1fi",
7449 "\0for",
7450 "\0if",
7451 "\0in",
7452 "\1then",
7453 "\0until",
7454 "\0while",
7455 "\0{",
7456 "\1}",
7457};
7458
7459static const char *
7460tokname(int tok)
7461{
7462 static char buf[16];
7463
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007464//try this:
7465//if (tok < TSEMI) return tokname_array[tok] + 1;
7466//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7467//return buf;
7468
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007469 if (tok >= TSEMI)
7470 buf[0] = '"';
7471 sprintf(buf + (tok >= TSEMI), "%s%c",
7472 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7473 return buf;
7474}
7475
7476/* Wrapper around strcmp for qsort/bsearch/... */
7477static int
7478pstrcmp(const void *a, const void *b)
7479{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007480 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007481}
7482
7483static const char *const *
7484findkwd(const char *s)
7485{
7486 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007487 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7488 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007489}
7490
7491/*
7492 * Locate and print what a word is...
7493 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007494static int
7495describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007496{
7497 struct cmdentry entry;
7498 struct tblentry *cmdp;
7499#if ENABLE_ASH_ALIAS
7500 const struct alias *ap;
7501#endif
7502 const char *path = pathval();
7503
7504 if (describe_command_verbose) {
7505 out1str(command);
7506 }
7507
7508 /* First look at the keywords */
7509 if (findkwd(command)) {
7510 out1str(describe_command_verbose ? " is a shell keyword" : command);
7511 goto out;
7512 }
7513
7514#if ENABLE_ASH_ALIAS
7515 /* Then look at the aliases */
7516 ap = lookupalias(command, 0);
7517 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007518 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007519 out1str("alias ");
7520 printalias(ap);
7521 return 0;
7522 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007523 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007524 goto out;
7525 }
7526#endif
7527 /* Then check if it is a tracked alias */
7528 cmdp = cmdlookup(command, 0);
7529 if (cmdp != NULL) {
7530 entry.cmdtype = cmdp->cmdtype;
7531 entry.u = cmdp->param;
7532 } else {
7533 /* Finally use brute force */
7534 find_command(command, &entry, DO_ABS, path);
7535 }
7536
7537 switch (entry.cmdtype) {
7538 case CMDNORMAL: {
7539 int j = entry.u.index;
7540 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007541 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007542 p = command;
7543 } else {
7544 do {
7545 p = padvance(&path, command);
7546 stunalloc(p);
7547 } while (--j >= 0);
7548 }
7549 if (describe_command_verbose) {
7550 out1fmt(" is%s %s",
7551 (cmdp ? " a tracked alias for" : nullstr), p
7552 );
7553 } else {
7554 out1str(p);
7555 }
7556 break;
7557 }
7558
7559 case CMDFUNCTION:
7560 if (describe_command_verbose) {
7561 out1str(" is a shell function");
7562 } else {
7563 out1str(command);
7564 }
7565 break;
7566
7567 case CMDBUILTIN:
7568 if (describe_command_verbose) {
7569 out1fmt(" is a %sshell builtin",
7570 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7571 "special " : nullstr
7572 );
7573 } else {
7574 out1str(command);
7575 }
7576 break;
7577
7578 default:
7579 if (describe_command_verbose) {
7580 out1str(": not found\n");
7581 }
7582 return 127;
7583 }
7584 out:
7585 outstr("\n", stdout);
7586 return 0;
7587}
7588
7589static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007590typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007591{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007592 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007593 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007594 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007595
Denis Vlasenko46846e22007-05-20 13:08:31 +00007596 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007597 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007598 i++;
7599 verbose = 0;
7600 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007601 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007602 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007603 }
7604 return err;
7605}
7606
7607#if ENABLE_ASH_CMDCMD
7608static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007609commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007610{
7611 int c;
7612 enum {
7613 VERIFY_BRIEF = 1,
7614 VERIFY_VERBOSE = 2,
7615 } verify = 0;
7616
7617 while ((c = nextopt("pvV")) != '\0')
7618 if (c == 'V')
7619 verify |= VERIFY_VERBOSE;
7620 else if (c == 'v')
7621 verify |= VERIFY_BRIEF;
7622#if DEBUG
7623 else if (c != 'p')
7624 abort();
7625#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007626 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7627 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007628 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007629 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007630
7631 return 0;
7632}
7633#endif
7634
7635
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007636/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007637
Denis Vlasenko340299a2008-11-21 10:36:36 +00007638static int funcblocksize; /* size of structures in function */
7639static int funcstringsize; /* size of strings in node */
7640static void *funcblock; /* block to allocate function from */
7641static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007642
Eric Andersencb57d552001-06-28 07:25:16 +00007643/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007644#define EV_EXIT 01 /* exit after evaluating tree */
7645#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007646#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007647
Denis Vlasenko340299a2008-11-21 10:36:36 +00007648static const short nodesize[N_NUMBER] = {
7649 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7650 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7651 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7652 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7653 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7654 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7655 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7656 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7657 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7658 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7659 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7660 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7661 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7662 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7663 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7664 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7665 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007666#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007667 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007668#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007669 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7670 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7671 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7672 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7673 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7674 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7675 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7676 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7677 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007678};
7679
7680static void calcsize(union node *n);
7681
7682static void
7683sizenodelist(struct nodelist *lp)
7684{
7685 while (lp) {
7686 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7687 calcsize(lp->n);
7688 lp = lp->next;
7689 }
7690}
7691
7692static void
7693calcsize(union node *n)
7694{
7695 if (n == NULL)
7696 return;
7697 funcblocksize += nodesize[n->type];
7698 switch (n->type) {
7699 case NCMD:
7700 calcsize(n->ncmd.redirect);
7701 calcsize(n->ncmd.args);
7702 calcsize(n->ncmd.assign);
7703 break;
7704 case NPIPE:
7705 sizenodelist(n->npipe.cmdlist);
7706 break;
7707 case NREDIR:
7708 case NBACKGND:
7709 case NSUBSHELL:
7710 calcsize(n->nredir.redirect);
7711 calcsize(n->nredir.n);
7712 break;
7713 case NAND:
7714 case NOR:
7715 case NSEMI:
7716 case NWHILE:
7717 case NUNTIL:
7718 calcsize(n->nbinary.ch2);
7719 calcsize(n->nbinary.ch1);
7720 break;
7721 case NIF:
7722 calcsize(n->nif.elsepart);
7723 calcsize(n->nif.ifpart);
7724 calcsize(n->nif.test);
7725 break;
7726 case NFOR:
7727 funcstringsize += strlen(n->nfor.var) + 1;
7728 calcsize(n->nfor.body);
7729 calcsize(n->nfor.args);
7730 break;
7731 case NCASE:
7732 calcsize(n->ncase.cases);
7733 calcsize(n->ncase.expr);
7734 break;
7735 case NCLIST:
7736 calcsize(n->nclist.body);
7737 calcsize(n->nclist.pattern);
7738 calcsize(n->nclist.next);
7739 break;
7740 case NDEFUN:
7741 case NARG:
7742 sizenodelist(n->narg.backquote);
7743 funcstringsize += strlen(n->narg.text) + 1;
7744 calcsize(n->narg.next);
7745 break;
7746 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007747#if ENABLE_ASH_BASH_COMPAT
7748 case NTO2:
7749#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007750 case NCLOBBER:
7751 case NFROM:
7752 case NFROMTO:
7753 case NAPPEND:
7754 calcsize(n->nfile.fname);
7755 calcsize(n->nfile.next);
7756 break;
7757 case NTOFD:
7758 case NFROMFD:
7759 calcsize(n->ndup.vname);
7760 calcsize(n->ndup.next);
7761 break;
7762 case NHERE:
7763 case NXHERE:
7764 calcsize(n->nhere.doc);
7765 calcsize(n->nhere.next);
7766 break;
7767 case NNOT:
7768 calcsize(n->nnot.com);
7769 break;
7770 };
7771}
7772
7773static char *
7774nodeckstrdup(char *s)
7775{
7776 char *rtn = funcstring;
7777
7778 strcpy(funcstring, s);
7779 funcstring += strlen(s) + 1;
7780 return rtn;
7781}
7782
7783static union node *copynode(union node *);
7784
7785static struct nodelist *
7786copynodelist(struct nodelist *lp)
7787{
7788 struct nodelist *start;
7789 struct nodelist **lpp;
7790
7791 lpp = &start;
7792 while (lp) {
7793 *lpp = funcblock;
7794 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7795 (*lpp)->n = copynode(lp->n);
7796 lp = lp->next;
7797 lpp = &(*lpp)->next;
7798 }
7799 *lpp = NULL;
7800 return start;
7801}
7802
7803static union node *
7804copynode(union node *n)
7805{
7806 union node *new;
7807
7808 if (n == NULL)
7809 return NULL;
7810 new = funcblock;
7811 funcblock = (char *) funcblock + nodesize[n->type];
7812
7813 switch (n->type) {
7814 case NCMD:
7815 new->ncmd.redirect = copynode(n->ncmd.redirect);
7816 new->ncmd.args = copynode(n->ncmd.args);
7817 new->ncmd.assign = copynode(n->ncmd.assign);
7818 break;
7819 case NPIPE:
7820 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007821 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007822 break;
7823 case NREDIR:
7824 case NBACKGND:
7825 case NSUBSHELL:
7826 new->nredir.redirect = copynode(n->nredir.redirect);
7827 new->nredir.n = copynode(n->nredir.n);
7828 break;
7829 case NAND:
7830 case NOR:
7831 case NSEMI:
7832 case NWHILE:
7833 case NUNTIL:
7834 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7835 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7836 break;
7837 case NIF:
7838 new->nif.elsepart = copynode(n->nif.elsepart);
7839 new->nif.ifpart = copynode(n->nif.ifpart);
7840 new->nif.test = copynode(n->nif.test);
7841 break;
7842 case NFOR:
7843 new->nfor.var = nodeckstrdup(n->nfor.var);
7844 new->nfor.body = copynode(n->nfor.body);
7845 new->nfor.args = copynode(n->nfor.args);
7846 break;
7847 case NCASE:
7848 new->ncase.cases = copynode(n->ncase.cases);
7849 new->ncase.expr = copynode(n->ncase.expr);
7850 break;
7851 case NCLIST:
7852 new->nclist.body = copynode(n->nclist.body);
7853 new->nclist.pattern = copynode(n->nclist.pattern);
7854 new->nclist.next = copynode(n->nclist.next);
7855 break;
7856 case NDEFUN:
7857 case NARG:
7858 new->narg.backquote = copynodelist(n->narg.backquote);
7859 new->narg.text = nodeckstrdup(n->narg.text);
7860 new->narg.next = copynode(n->narg.next);
7861 break;
7862 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007863#if ENABLE_ASH_BASH_COMPAT
7864 case NTO2:
7865#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007866 case NCLOBBER:
7867 case NFROM:
7868 case NFROMTO:
7869 case NAPPEND:
7870 new->nfile.fname = copynode(n->nfile.fname);
7871 new->nfile.fd = n->nfile.fd;
7872 new->nfile.next = copynode(n->nfile.next);
7873 break;
7874 case NTOFD:
7875 case NFROMFD:
7876 new->ndup.vname = copynode(n->ndup.vname);
7877 new->ndup.dupfd = n->ndup.dupfd;
7878 new->ndup.fd = n->ndup.fd;
7879 new->ndup.next = copynode(n->ndup.next);
7880 break;
7881 case NHERE:
7882 case NXHERE:
7883 new->nhere.doc = copynode(n->nhere.doc);
7884 new->nhere.fd = n->nhere.fd;
7885 new->nhere.next = copynode(n->nhere.next);
7886 break;
7887 case NNOT:
7888 new->nnot.com = copynode(n->nnot.com);
7889 break;
7890 };
7891 new->type = n->type;
7892 return new;
7893}
7894
7895/*
7896 * Make a copy of a parse tree.
7897 */
7898static struct funcnode *
7899copyfunc(union node *n)
7900{
7901 struct funcnode *f;
7902 size_t blocksize;
7903
7904 funcblocksize = offsetof(struct funcnode, n);
7905 funcstringsize = 0;
7906 calcsize(n);
7907 blocksize = funcblocksize;
7908 f = ckmalloc(blocksize + funcstringsize);
7909 funcblock = (char *) f + offsetof(struct funcnode, n);
7910 funcstring = (char *) f + blocksize;
7911 copynode(n);
7912 f->count = 0;
7913 return f;
7914}
7915
7916/*
7917 * Define a shell function.
7918 */
7919static void
7920defun(char *name, union node *func)
7921{
7922 struct cmdentry entry;
7923
7924 INT_OFF;
7925 entry.cmdtype = CMDFUNCTION;
7926 entry.u.func = copyfunc(func);
7927 addcmdentry(name, &entry);
7928 INT_ON;
7929}
7930
Denis Vlasenko4b875702009-03-19 13:30:04 +00007931/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007932#define SKIPBREAK (1 << 0)
7933#define SKIPCONT (1 << 1)
7934#define SKIPFUNC (1 << 2)
7935#define SKIPFILE (1 << 3)
7936#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00007937static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007938static int skipcount; /* number of levels to skip */
7939static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007940static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007941
Denis Vlasenko4b875702009-03-19 13:30:04 +00007942/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007943static int evalstring(char *s, int mask);
7944
Denis Vlasenko4b875702009-03-19 13:30:04 +00007945/* Called to execute a trap.
7946 * Single callsite - at the end of evaltree().
7947 * If we return non-zero, exaltree raises EXEXIT exception.
7948 *
7949 * Perhaps we should avoid entering new trap handlers
7950 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007951 */
7952static int
7953dotrap(void)
7954{
Denis Vlasenko4b875702009-03-19 13:30:04 +00007955 uint8_t *g;
7956 int sig;
7957 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007958
7959 savestatus = exitstatus;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00007960 pendingsig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007961 xbarrier();
7962
Denis Vlasenko653d8e72009-03-19 21:59:35 +00007963 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00007964 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
7965 int want_exexit;
7966 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007967
Denis Vlasenko4b875702009-03-19 13:30:04 +00007968 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007969 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00007970 t = trap[sig];
7971 /* non-trapped SIGINT is handled separately by raise_interrupt,
7972 * don't upset it by resetting gotsig[SIGINT-1] */
7973 if (sig == SIGINT && !t)
7974 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00007975
7976 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00007977 *g = 0;
7978 if (!t)
7979 continue;
7980 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007981 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00007982 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00007983 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00007984 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00007985 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007986 }
7987
Denis Vlasenko653d8e72009-03-19 21:59:35 +00007988 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007989 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007990}
7991
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007992/* forward declarations - evaluation is fairly recursive business... */
Eric Andersenc470f442003-07-28 09:56:35 +00007993static void evalloop(union node *, int);
7994static void evalfor(union node *, int);
7995static void evalcase(union node *, int);
7996static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00007997static void expredir(union node *);
Eric Andersenc470f442003-07-28 09:56:35 +00007998static void evalpipe(union node *, int);
7999static void evalcommand(union node *, int);
8000static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008001static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008002
Eric Andersen62483552001-07-10 06:09:16 +00008003/*
Eric Andersenc470f442003-07-28 09:56:35 +00008004 * Evaluate a parse tree. The value is left in the global variable
8005 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008006 */
Eric Andersenc470f442003-07-28 09:56:35 +00008007static void
8008evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008009{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008010 struct jmploc *volatile savehandler = exception_handler;
8011 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008012 int checkexit = 0;
8013 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008014 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008015 int int_level;
8016
8017 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008018
Eric Andersenc470f442003-07-28 09:56:35 +00008019 if (n == NULL) {
8020 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008021 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008022 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008023 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008024
8025 exception_handler = &jmploc;
8026 {
8027 int err = setjmp(jmploc.loc);
8028 if (err) {
8029 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008030 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008031 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8032 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008033 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008034 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008035 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008036 TRACE(("exception %d in evaltree, propagating err=%d\n",
8037 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008038 exception_handler = savehandler;
8039 longjmp(exception_handler->loc, err);
8040 }
8041 }
8042
Eric Andersenc470f442003-07-28 09:56:35 +00008043 switch (n->type) {
8044 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008045#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008046 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008047 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008048 break;
8049#endif
8050 case NNOT:
8051 evaltree(n->nnot.com, EV_TESTED);
8052 status = !exitstatus;
8053 goto setstatus;
8054 case NREDIR:
8055 expredir(n->nredir.redirect);
8056 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8057 if (!status) {
8058 evaltree(n->nredir.n, flags & EV_TESTED);
8059 status = exitstatus;
8060 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008061 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008062 goto setstatus;
8063 case NCMD:
8064 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008065 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008066 if (eflag && !(flags & EV_TESTED))
8067 checkexit = ~0;
8068 goto calleval;
8069 case NFOR:
8070 evalfn = evalfor;
8071 goto calleval;
8072 case NWHILE:
8073 case NUNTIL:
8074 evalfn = evalloop;
8075 goto calleval;
8076 case NSUBSHELL:
8077 case NBACKGND:
8078 evalfn = evalsubshell;
8079 goto calleval;
8080 case NPIPE:
8081 evalfn = evalpipe;
8082 goto checkexit;
8083 case NCASE:
8084 evalfn = evalcase;
8085 goto calleval;
8086 case NAND:
8087 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008088 case NSEMI: {
8089
Eric Andersenc470f442003-07-28 09:56:35 +00008090#if NAND + 1 != NOR
8091#error NAND + 1 != NOR
8092#endif
8093#if NOR + 1 != NSEMI
8094#error NOR + 1 != NSEMI
8095#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008096 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008097 evaltree(
8098 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008099 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008100 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008101 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008102 break;
8103 if (!evalskip) {
8104 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008105 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008106 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008107 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008108 evalfn(n, flags);
8109 break;
8110 }
8111 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008112 }
Eric Andersenc470f442003-07-28 09:56:35 +00008113 case NIF:
8114 evaltree(n->nif.test, EV_TESTED);
8115 if (evalskip)
8116 break;
8117 if (exitstatus == 0) {
8118 n = n->nif.ifpart;
8119 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008120 }
8121 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008122 n = n->nif.elsepart;
8123 goto evaln;
8124 }
8125 goto success;
8126 case NDEFUN:
8127 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008128 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008129 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008130 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008131 exitstatus = status;
8132 break;
8133 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008134
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008135 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136 exception_handler = savehandler;
8137 out1:
8138 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008139 evalskip |= SKIPEVAL;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00008140 else if (pendingsig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008141 goto exexit;
8142
8143 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008144 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008145 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008146 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008147
8148 RESTORE_INT(int_level);
8149 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008150}
8151
Eric Andersenc470f442003-07-28 09:56:35 +00008152#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8153static
8154#endif
8155void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8156
Eric Andersenc470f442003-07-28 09:56:35 +00008157static void
8158evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008159{
8160 int status;
8161
8162 loopnest++;
8163 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008164 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008165 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008166 int i;
8167
Eric Andersencb57d552001-06-28 07:25:16 +00008168 evaltree(n->nbinary.ch1, EV_TESTED);
8169 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008170 skipping:
8171 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008172 evalskip = 0;
8173 continue;
8174 }
8175 if (evalskip == SKIPBREAK && --skipcount <= 0)
8176 evalskip = 0;
8177 break;
8178 }
Eric Andersenc470f442003-07-28 09:56:35 +00008179 i = exitstatus;
8180 if (n->type != NWHILE)
8181 i = !i;
8182 if (i != 0)
8183 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008184 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008185 status = exitstatus;
8186 if (evalskip)
8187 goto skipping;
8188 }
8189 loopnest--;
8190 exitstatus = status;
8191}
8192
Eric Andersenc470f442003-07-28 09:56:35 +00008193static void
8194evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008195{
8196 struct arglist arglist;
8197 union node *argp;
8198 struct strlist *sp;
8199 struct stackmark smark;
8200
8201 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008202 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008203 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008204 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008205 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008206 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008207 if (evalskip)
8208 goto out;
8209 }
8210 *arglist.lastp = NULL;
8211
8212 exitstatus = 0;
8213 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008214 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008215 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008216 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008217 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008218 if (evalskip) {
8219 if (evalskip == SKIPCONT && --skipcount <= 0) {
8220 evalskip = 0;
8221 continue;
8222 }
8223 if (evalskip == SKIPBREAK && --skipcount <= 0)
8224 evalskip = 0;
8225 break;
8226 }
8227 }
8228 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008229 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008230 popstackmark(&smark);
8231}
8232
Eric Andersenc470f442003-07-28 09:56:35 +00008233static void
8234evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008235{
8236 union node *cp;
8237 union node *patp;
8238 struct arglist arglist;
8239 struct stackmark smark;
8240
8241 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008242 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008243 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008244 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008245 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008246 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8247 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008248 if (casematch(patp, arglist.list->text)) {
8249 if (evalskip == 0) {
8250 evaltree(cp->nclist.body, flags);
8251 }
8252 goto out;
8253 }
8254 }
8255 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008256 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008257 popstackmark(&smark);
8258}
8259
Eric Andersenc470f442003-07-28 09:56:35 +00008260/*
8261 * Kick off a subshell to evaluate a tree.
8262 */
Eric Andersenc470f442003-07-28 09:56:35 +00008263static void
8264evalsubshell(union node *n, int flags)
8265{
8266 struct job *jp;
8267 int backgnd = (n->type == NBACKGND);
8268 int status;
8269
8270 expredir(n->nredir.redirect);
8271 if (!backgnd && flags & EV_EXIT && !trap[0])
8272 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008273 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008274 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008275 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008276 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008277 flags |= EV_EXIT;
8278 if (backgnd)
8279 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008280 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008281 redirect(n->nredir.redirect, 0);
8282 evaltreenr(n->nredir.n, flags);
8283 /* never returns */
8284 }
8285 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008286 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008287 status = waitforjob(jp);
8288 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008289 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008290}
8291
Eric Andersenc470f442003-07-28 09:56:35 +00008292/*
8293 * Compute the names of the files in a redirection list.
8294 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008295static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008296static void
8297expredir(union node *n)
8298{
8299 union node *redir;
8300
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008301 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008302 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008303
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008304 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008305 fn.lastp = &fn.list;
8306 switch (redir->type) {
8307 case NFROMTO:
8308 case NFROM:
8309 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008310#if ENABLE_ASH_BASH_COMPAT
8311 case NTO2:
8312#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008313 case NCLOBBER:
8314 case NAPPEND:
8315 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008316#if ENABLE_ASH_BASH_COMPAT
8317 store_expfname:
8318#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008319 redir->nfile.expfname = fn.list->text;
8320 break;
8321 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008322 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008323 if (redir->ndup.vname) {
8324 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008325 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008326 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008327#if ENABLE_ASH_BASH_COMPAT
8328//FIXME: we used expandarg with different args!
8329 if (!isdigit_str9(fn.list->text)) {
8330 /* >&file, not >&fd */
8331 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8332 ash_msg_and_raise_error("redir error");
8333 redir->type = NTO2;
8334 goto store_expfname;
8335 }
8336#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008337 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008338 }
8339 break;
8340 }
8341 }
8342}
8343
Eric Andersencb57d552001-06-28 07:25:16 +00008344/*
Eric Andersencb57d552001-06-28 07:25:16 +00008345 * Evaluate a pipeline. All the processes in the pipeline are children
8346 * of the process creating the pipeline. (This differs from some versions
8347 * of the shell, which make the last process in a pipeline the parent
8348 * of all the rest.)
8349 */
Eric Andersenc470f442003-07-28 09:56:35 +00008350static void
8351evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008352{
8353 struct job *jp;
8354 struct nodelist *lp;
8355 int pipelen;
8356 int prevfd;
8357 int pip[2];
8358
Eric Andersenc470f442003-07-28 09:56:35 +00008359 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008360 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008361 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008362 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008363 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008364 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008365 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008366 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008367 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008368 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008369 pip[1] = -1;
8370 if (lp->next) {
8371 if (pipe(pip) < 0) {
8372 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008373 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008374 }
8375 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008376 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008377 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008378 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008379 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008380 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008381 if (prevfd > 0) {
8382 dup2(prevfd, 0);
8383 close(prevfd);
8384 }
8385 if (pip[1] > 1) {
8386 dup2(pip[1], 1);
8387 close(pip[1]);
8388 }
Eric Andersenc470f442003-07-28 09:56:35 +00008389 evaltreenr(lp->n, flags);
8390 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008391 }
8392 if (prevfd >= 0)
8393 close(prevfd);
8394 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008395 /* Don't want to trigger debugging */
8396 if (pip[1] != -1)
8397 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008398 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008399 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008400 exitstatus = waitforjob(jp);
8401 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008402 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008403 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008404}
8405
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008406/*
8407 * Controls whether the shell is interactive or not.
8408 */
8409static void
8410setinteractive(int on)
8411{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008412 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008413
8414 if (++on == is_interactive)
8415 return;
8416 is_interactive = on;
8417 setsignal(SIGINT);
8418 setsignal(SIGQUIT);
8419 setsignal(SIGTERM);
8420#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8421 if (is_interactive > 1) {
8422 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008423 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008424
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008425 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008426 out1fmt(
8427 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008428 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008429 "Enter 'help' for a list of built-in commands."
8430 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008431 bb_banner);
8432 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008433 }
8434 }
8435#endif
8436}
8437
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008438static void
8439optschanged(void)
8440{
8441#if DEBUG
8442 opentrace();
8443#endif
8444 setinteractive(iflag);
8445 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008446#if ENABLE_FEATURE_EDITING_VI
8447 if (viflag)
8448 line_input_state->flags |= VI_MODE;
8449 else
8450 line_input_state->flags &= ~VI_MODE;
8451#else
8452 viflag = 0; /* forcibly keep the option off */
8453#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008454}
8455
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008456static struct localvar *localvars;
8457
8458/*
8459 * Called after a function returns.
8460 * Interrupts must be off.
8461 */
8462static void
8463poplocalvars(void)
8464{
8465 struct localvar *lvp;
8466 struct var *vp;
8467
8468 while ((lvp = localvars) != NULL) {
8469 localvars = lvp->next;
8470 vp = lvp->vp;
8471 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
8472 if (vp == NULL) { /* $- saved */
8473 memcpy(optlist, lvp->text, sizeof(optlist));
8474 free((char*)lvp->text);
8475 optschanged();
8476 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8477 unsetvar(vp->text);
8478 } else {
8479 if (vp->func)
8480 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8481 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8482 free((char*)vp->text);
8483 vp->flags = lvp->flags;
8484 vp->text = lvp->text;
8485 }
8486 free(lvp);
8487 }
8488}
8489
8490static int
8491evalfun(struct funcnode *func, int argc, char **argv, int flags)
8492{
8493 volatile struct shparam saveparam;
8494 struct localvar *volatile savelocalvars;
8495 struct jmploc *volatile savehandler;
8496 struct jmploc jmploc;
8497 int e;
8498
8499 saveparam = shellparam;
8500 savelocalvars = localvars;
8501 e = setjmp(jmploc.loc);
8502 if (e) {
8503 goto funcdone;
8504 }
8505 INT_OFF;
8506 savehandler = exception_handler;
8507 exception_handler = &jmploc;
8508 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008509 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008510 func->count++;
8511 funcnest++;
8512 INT_ON;
8513 shellparam.nparam = argc - 1;
8514 shellparam.p = argv + 1;
8515#if ENABLE_ASH_GETOPTS
8516 shellparam.optind = 1;
8517 shellparam.optoff = -1;
8518#endif
8519 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008520 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008521 INT_OFF;
8522 funcnest--;
8523 freefunc(func);
8524 poplocalvars();
8525 localvars = savelocalvars;
8526 freeparam(&shellparam);
8527 shellparam = saveparam;
8528 exception_handler = savehandler;
8529 INT_ON;
8530 evalskip &= ~SKIPFUNC;
8531 return e;
8532}
8533
Denis Vlasenko131ae172007-02-18 13:00:19 +00008534#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008535static char **
8536parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008537{
8538 char *cp, c;
8539
8540 for (;;) {
8541 cp = *++argv;
8542 if (!cp)
8543 return 0;
8544 if (*cp++ != '-')
8545 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008546 c = *cp++;
8547 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008548 break;
8549 if (c == '-' && !*cp) {
8550 argv++;
8551 break;
8552 }
8553 do {
8554 switch (c) {
8555 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008556 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008557 break;
8558 default:
8559 /* run 'typecmd' for other options */
8560 return 0;
8561 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008562 c = *cp++;
8563 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008564 }
8565 return argv;
8566}
8567#endif
8568
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008569/*
8570 * Make a variable a local variable. When a variable is made local, it's
8571 * value and flags are saved in a localvar structure. The saved values
8572 * will be restored when the shell function returns. We handle the name
8573 * "-" as a special case.
8574 */
8575static void
8576mklocal(char *name)
8577{
8578 struct localvar *lvp;
8579 struct var **vpp;
8580 struct var *vp;
8581
8582 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008583 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008584 if (LONE_DASH(name)) {
8585 char *p;
8586 p = ckmalloc(sizeof(optlist));
8587 lvp->text = memcpy(p, optlist, sizeof(optlist));
8588 vp = NULL;
8589 } else {
8590 char *eq;
8591
8592 vpp = hashvar(name);
8593 vp = *findvar(vpp, name);
8594 eq = strchr(name, '=');
8595 if (vp == NULL) {
8596 if (eq)
8597 setvareq(name, VSTRFIXED);
8598 else
8599 setvar(name, NULL, VSTRFIXED);
8600 vp = *vpp; /* the new variable */
8601 lvp->flags = VUNSET;
8602 } else {
8603 lvp->text = vp->text;
8604 lvp->flags = vp->flags;
8605 vp->flags |= VSTRFIXED|VTEXTFIXED;
8606 if (eq)
8607 setvareq(name, 0);
8608 }
8609 }
8610 lvp->vp = vp;
8611 lvp->next = localvars;
8612 localvars = lvp;
8613 INT_ON;
8614}
8615
8616/*
8617 * The "local" command.
8618 */
8619static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008620localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008621{
8622 char *name;
8623
8624 argv = argptr;
8625 while ((name = *argv++) != NULL) {
8626 mklocal(name);
8627 }
8628 return 0;
8629}
8630
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008631static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008632falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008633{
8634 return 1;
8635}
8636
8637static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008638truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008639{
8640 return 0;
8641}
8642
8643static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008644execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008645{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008646 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008647 iflag = 0; /* exit on error */
8648 mflag = 0;
8649 optschanged();
8650 shellexec(argv + 1, pathval(), 0);
8651 }
8652 return 0;
8653}
8654
8655/*
8656 * The return command.
8657 */
8658static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008659returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008660{
8661 /*
8662 * If called outside a function, do what ksh does;
8663 * skip the rest of the file.
8664 */
8665 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8666 return argv[1] ? number(argv[1]) : exitstatus;
8667}
8668
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008669/* Forward declarations for builtintab[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008670static int breakcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008671static int dotcmd(int, char **);
8672static int evalcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008673static int exitcmd(int, char **);
8674static int exportcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008675#if ENABLE_ASH_GETOPTS
8676static int getoptscmd(int, char **);
8677#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008678#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008679static int helpcmd(int, char **);
Denis Vlasenko52764022007-02-24 13:42:56 +00008680#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008681#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008682static int letcmd(int, char **);
8683#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008684static int readcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008685static int setcmd(int, char **);
8686static int shiftcmd(int, char **);
8687static int timescmd(int, char **);
8688static int trapcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008689static int umaskcmd(int, char **);
8690static int unsetcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008691static int ulimitcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008692
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008693#define BUILTIN_NOSPEC "0"
8694#define BUILTIN_SPECIAL "1"
8695#define BUILTIN_REGULAR "2"
8696#define BUILTIN_SPEC_REG "3"
8697#define BUILTIN_ASSIGN "4"
8698#define BUILTIN_SPEC_ASSG "5"
8699#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008700#define BUILTIN_SPEC_REG_ASSG "7"
8701
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008702/* We do not handle [[ expr ]] bashism bash-compatibly,
8703 * we make it a synonym of [ expr ].
8704 * Basically, word splitting and pathname expansion should NOT be performed
8705 * Examples:
8706 * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
8707 * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
8708 * Additional operators:
8709 * || and && should work as -o and -a
8710 * =~ regexp match
8711 * Apart from the above, [[ expr ]] should work as [ expr ]
8712 */
8713
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008714#define echocmd echo_main
8715#define printfcmd printf_main
8716#define testcmd test_main
Denis Vlasenko468aea22008-04-01 14:47:57 +00008717
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008718/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008719static const struct builtincmd builtintab[] = {
8720 { BUILTIN_SPEC_REG ".", dotcmd },
8721 { BUILTIN_SPEC_REG ":", truecmd },
8722#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008723 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008724#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008725 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008726#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008727#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008728#if ENABLE_ASH_ALIAS
8729 { BUILTIN_REG_ASSG "alias", aliascmd },
8730#endif
8731#if JOBS
8732 { BUILTIN_REGULAR "bg", fg_bgcmd },
8733#endif
8734 { BUILTIN_SPEC_REG "break", breakcmd },
8735 { BUILTIN_REGULAR "cd", cdcmd },
8736 { BUILTIN_NOSPEC "chdir", cdcmd },
8737#if ENABLE_ASH_CMDCMD
8738 { BUILTIN_REGULAR "command", commandcmd },
8739#endif
8740 { BUILTIN_SPEC_REG "continue", breakcmd },
8741#if ENABLE_ASH_BUILTIN_ECHO
8742 { BUILTIN_REGULAR "echo", echocmd },
8743#endif
8744 { BUILTIN_SPEC_REG "eval", evalcmd },
8745 { BUILTIN_SPEC_REG "exec", execcmd },
8746 { BUILTIN_SPEC_REG "exit", exitcmd },
8747 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8748 { BUILTIN_REGULAR "false", falsecmd },
8749#if JOBS
8750 { BUILTIN_REGULAR "fg", fg_bgcmd },
8751#endif
8752#if ENABLE_ASH_GETOPTS
8753 { BUILTIN_REGULAR "getopts", getoptscmd },
8754#endif
8755 { BUILTIN_NOSPEC "hash", hashcmd },
8756#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8757 { BUILTIN_NOSPEC "help", helpcmd },
8758#endif
8759#if JOBS
8760 { BUILTIN_REGULAR "jobs", jobscmd },
8761 { BUILTIN_REGULAR "kill", killcmd },
8762#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008763#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008764 { BUILTIN_NOSPEC "let", letcmd },
8765#endif
8766 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008767#if ENABLE_ASH_BUILTIN_PRINTF
8768 { BUILTIN_REGULAR "printf", printfcmd },
8769#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008770 { BUILTIN_NOSPEC "pwd", pwdcmd },
8771 { BUILTIN_REGULAR "read", readcmd },
8772 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8773 { BUILTIN_SPEC_REG "return", returncmd },
8774 { BUILTIN_SPEC_REG "set", setcmd },
8775 { BUILTIN_SPEC_REG "shift", shiftcmd },
8776 { BUILTIN_SPEC_REG "source", dotcmd },
8777#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008778 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008779#endif
8780 { BUILTIN_SPEC_REG "times", timescmd },
8781 { BUILTIN_SPEC_REG "trap", trapcmd },
8782 { BUILTIN_REGULAR "true", truecmd },
8783 { BUILTIN_NOSPEC "type", typecmd },
8784 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8785 { BUILTIN_REGULAR "umask", umaskcmd },
8786#if ENABLE_ASH_ALIAS
8787 { BUILTIN_REGULAR "unalias", unaliascmd },
8788#endif
8789 { BUILTIN_SPEC_REG "unset", unsetcmd },
8790 { BUILTIN_REGULAR "wait", waitcmd },
8791};
8792
Denis Vlasenko80591b02008-03-25 07:49:43 +00008793/* Should match the above table! */
8794#define COMMANDCMD (builtintab + \
8795 2 + \
8796 1 * ENABLE_ASH_BUILTIN_TEST + \
8797 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8798 1 * ENABLE_ASH_ALIAS + \
8799 1 * ENABLE_ASH_JOB_CONTROL + \
8800 3)
8801#define EXECCMD (builtintab + \
8802 2 + \
8803 1 * ENABLE_ASH_BUILTIN_TEST + \
8804 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8805 1 * ENABLE_ASH_ALIAS + \
8806 1 * ENABLE_ASH_JOB_CONTROL + \
8807 3 + \
8808 1 * ENABLE_ASH_CMDCMD + \
8809 1 + \
8810 ENABLE_ASH_BUILTIN_ECHO + \
8811 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008812
8813/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008814 * Search the table of builtin commands.
8815 */
8816static struct builtincmd *
8817find_builtin(const char *name)
8818{
8819 struct builtincmd *bp;
8820
8821 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008822 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008823 pstrcmp
8824 );
8825 return bp;
8826}
8827
8828/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008829 * Execute a simple command.
8830 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008831static int
8832isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008833{
8834 const char *q = endofname(p);
8835 if (p == q)
8836 return 0;
8837 return *q == '=';
8838}
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008839static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008840bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008841{
8842 /* Preserve exitstatus of a previous possible redirection
8843 * as POSIX mandates */
8844 return back_exitstatus;
8845}
Eric Andersenc470f442003-07-28 09:56:35 +00008846static void
8847evalcommand(union node *cmd, int flags)
8848{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008849 static const struct builtincmd null_bltin = {
8850 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008851 };
Eric Andersenc470f442003-07-28 09:56:35 +00008852 struct stackmark smark;
8853 union node *argp;
8854 struct arglist arglist;
8855 struct arglist varlist;
8856 char **argv;
8857 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008858 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008859 struct cmdentry cmdentry;
8860 struct job *jp;
8861 char *lastarg;
8862 const char *path;
8863 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008864 int status;
8865 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008866 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008867 smallint cmd_is_exec;
8868 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008869
8870 /* First expand the arguments. */
8871 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8872 setstackmark(&smark);
8873 back_exitstatus = 0;
8874
8875 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008876 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008877 varlist.lastp = &varlist.list;
8878 *varlist.lastp = NULL;
8879 arglist.lastp = &arglist.list;
8880 *arglist.lastp = NULL;
8881
8882 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008883 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008884 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8885 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8886 }
8887
Eric Andersenc470f442003-07-28 09:56:35 +00008888 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8889 struct strlist **spp;
8890
8891 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008892 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008893 expandarg(argp, &arglist, EXP_VARTILDE);
8894 else
8895 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8896
Eric Andersenc470f442003-07-28 09:56:35 +00008897 for (sp = *spp; sp; sp = sp->next)
8898 argc++;
8899 }
8900
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008901 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008902 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008903 TRACE(("evalcommand arg: %s\n", sp->text));
8904 *nargv++ = sp->text;
8905 }
8906 *nargv = NULL;
8907
8908 lastarg = NULL;
8909 if (iflag && funcnest == 0 && argc > 0)
8910 lastarg = nargv[-1];
8911
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008912 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008913 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008914 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008915
8916 path = vpath.text;
8917 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8918 struct strlist **spp;
8919 char *p;
8920
8921 spp = varlist.lastp;
8922 expandarg(argp, &varlist, EXP_VARTILDE);
8923
8924 /*
8925 * Modify the command lookup path, if a PATH= assignment
8926 * is present
8927 */
8928 p = (*spp)->text;
8929 if (varequal(p, path))
8930 path = p;
8931 }
8932
8933 /* Print the command if xflag is set. */
8934 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008935 int n;
8936 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008937
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008938 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008939 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008940
8941 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008942 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008943 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008944 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008945 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008946 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008947 p--;
8948 }
8949 }
8950 sp = arglist.list;
8951 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008952 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008953 }
8954
8955 cmd_is_exec = 0;
8956 spclbltin = -1;
8957
8958 /* Now locate the command. */
8959 if (argc) {
8960 const char *oldpath;
8961 int cmd_flag = DO_ERR;
8962
8963 path += 5;
8964 oldpath = path;
8965 for (;;) {
8966 find_command(argv[0], &cmdentry, cmd_flag, path);
8967 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008968 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00008969 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00008970 goto bail;
8971 }
8972
8973 /* implement bltin and command here */
8974 if (cmdentry.cmdtype != CMDBUILTIN)
8975 break;
8976 if (spclbltin < 0)
8977 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8978 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008979 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008980#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00008981 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00008982 path = oldpath;
8983 nargv = parse_command_args(argv, &path);
8984 if (!nargv)
8985 break;
8986 argc -= nargv - argv;
8987 argv = nargv;
8988 cmd_flag |= DO_NOFUNC;
8989 } else
8990#endif
8991 break;
8992 }
8993 }
8994
8995 if (status) {
8996 /* We have a redirection error. */
8997 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008998 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008999 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009000 exitstatus = status;
9001 goto out;
9002 }
9003
9004 /* Execute the command. */
9005 switch (cmdentry.cmdtype) {
9006 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009007
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009008#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009009/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9010 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009011 {
9012 /* find_command() encodes applet_no as (-2 - applet_no) */
9013 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009014 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009015 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009016 /* run <applet>_main() */
9017 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009018 break;
9019 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009020 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009021#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009022 /* Fork off a child process if necessary. */
9023 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009024 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009025 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009026 if (forkshell(jp, cmd, FORK_FG) != 0) {
9027 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009028 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009029 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009030 break;
9031 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009032 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009033 }
9034 listsetvar(varlist.list, VEXPORT|VSTACK);
9035 shellexec(argv, path, cmdentry.u.index);
9036 /* NOTREACHED */
9037
9038 case CMDBUILTIN:
9039 cmdenviron = varlist.list;
9040 if (cmdenviron) {
9041 struct strlist *list = cmdenviron;
9042 int i = VNOSET;
9043 if (spclbltin > 0 || argc == 0) {
9044 i = 0;
9045 if (cmd_is_exec && argc > 1)
9046 i = VEXPORT;
9047 }
9048 listsetvar(list, i);
9049 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009050 /* Tight loop with builtins only:
9051 * "while kill -0 $child; do true; done"
9052 * will never exit even if $child died, unless we do this
9053 * to reap the zombie and make kill detect that it's gone: */
9054 dowait(DOWAIT_NONBLOCK, NULL);
9055
Eric Andersenc470f442003-07-28 09:56:35 +00009056 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9057 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009058 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009059 if (i == EXEXIT)
9060 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009061 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009062 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009063 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009064 if (i == EXSIG)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009065 exit_status = 128 + pendingsig;
Eric Andersenc470f442003-07-28 09:56:35 +00009066 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009067 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009068 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009069 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009070 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009071 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009072 }
9073 break;
9074
9075 case CMDFUNCTION:
9076 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009077 /* See above for the rationale */
9078 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009079 if (evalfun(cmdentry.u.func, argc, argv, flags))
9080 goto raise;
9081 break;
9082 }
9083
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009084 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009085 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009086 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009087 /* dsl: I think this is intended to be used to support
9088 * '_' in 'vi' command mode during line editing...
9089 * However I implemented that within libedit itself.
9090 */
9091 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009092 }
Eric Andersenc470f442003-07-28 09:56:35 +00009093 popstackmark(&smark);
9094}
9095
9096static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009097evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9098{
Eric Andersenc470f442003-07-28 09:56:35 +00009099 char *volatile savecmdname;
9100 struct jmploc *volatile savehandler;
9101 struct jmploc jmploc;
9102 int i;
9103
9104 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009105 i = setjmp(jmploc.loc);
9106 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009107 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009108 savehandler = exception_handler;
9109 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009110 commandname = argv[0];
9111 argptr = argv + 1;
9112 optptr = NULL; /* initialize nextopt */
9113 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009114 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009115 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009116 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009117 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009118 commandname = savecmdname;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009119// exsig = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009120 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009121
9122 return i;
9123}
9124
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009125static int
9126goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009127{
9128 return !*endofname(p);
9129}
9130
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009131
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009132/*
9133 * Search for a command. This is called before we fork so that the
9134 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009135 * the child. The check for "goodname" is an overly conservative
9136 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009137 */
Eric Andersenc470f442003-07-28 09:56:35 +00009138static void
9139prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009140{
9141 struct cmdentry entry;
9142
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009143 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9144 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009145}
9146
Eric Andersencb57d552001-06-28 07:25:16 +00009147
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009148/* ============ Builtin commands
9149 *
9150 * Builtin commands whose functions are closely tied to evaluation
9151 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009152 */
9153
9154/*
Eric Andersencb57d552001-06-28 07:25:16 +00009155 * Handle break and continue commands. Break, continue, and return are
9156 * all handled by setting the evalskip flag. The evaluation routines
9157 * above all check this flag, and if it is set they start skipping
9158 * commands rather than executing them. The variable skipcount is
9159 * the number of loops to break/continue, or the number of function
9160 * levels to return. (The latter is always 1.) It should probably
9161 * be an error to break out of more loops than exist, but it isn't
9162 * in the standard shell so we don't make it one here.
9163 */
Eric Andersenc470f442003-07-28 09:56:35 +00009164static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009165breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009166{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009167 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009168
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009169 if (n <= 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009170 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009171 if (n > loopnest)
9172 n = loopnest;
9173 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009174 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009175 skipcount = n;
9176 }
9177 return 0;
9178}
9179
Eric Andersenc470f442003-07-28 09:56:35 +00009180
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009181/* ============ input.c
9182 *
Eric Andersen90898442003-08-06 11:20:52 +00009183 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009184 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009185
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009186enum {
9187 INPUT_PUSH_FILE = 1,
9188 INPUT_NOFILE_OK = 2,
9189};
Eric Andersencb57d552001-06-28 07:25:16 +00009190
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009191static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009192/* values of checkkwd variable */
9193#define CHKALIAS 0x1
9194#define CHKKWD 0x2
9195#define CHKNL 0x4
9196
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009197/*
9198 * Push a string back onto the input at this current parsefile level.
9199 * We handle aliases this way.
9200 */
9201#if !ENABLE_ASH_ALIAS
9202#define pushstring(s, ap) pushstring(s)
9203#endif
9204static void
9205pushstring(char *s, struct alias *ap)
9206{
9207 struct strpush *sp;
9208 int len;
9209
9210 len = strlen(s);
9211 INT_OFF;
9212 if (g_parsefile->strpush) {
9213 sp = ckzalloc(sizeof(*sp));
9214 sp->prev = g_parsefile->strpush;
9215 } else {
9216 sp = &(g_parsefile->basestrpush);
9217 }
9218 g_parsefile->strpush = sp;
9219 sp->prev_string = g_parsefile->next_to_pgetc;
9220 sp->prev_left_in_line = g_parsefile->left_in_line;
9221#if ENABLE_ASH_ALIAS
9222 sp->ap = ap;
9223 if (ap) {
9224 ap->flag |= ALIASINUSE;
9225 sp->string = s;
9226 }
9227#endif
9228 g_parsefile->next_to_pgetc = s;
9229 g_parsefile->left_in_line = len;
9230 INT_ON;
9231}
9232
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009233static void
9234popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009235{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009236 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009237
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009238 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009239#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009240 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009241 if (g_parsefile->next_to_pgetc[-1] == ' '
9242 || g_parsefile->next_to_pgetc[-1] == '\t'
9243 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009244 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009245 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009246 if (sp->string != sp->ap->val) {
9247 free(sp->string);
9248 }
9249 sp->ap->flag &= ~ALIASINUSE;
9250 if (sp->ap->flag & ALIASDEAD) {
9251 unalias(sp->ap->name);
9252 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009253 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009254#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009255 g_parsefile->next_to_pgetc = sp->prev_string;
9256 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009257 g_parsefile->strpush = sp->prev;
9258 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009259 free(sp);
9260 INT_ON;
9261}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009262
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009263//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9264//it peeks whether it is &>, and then pushes back both chars.
9265//This function needs to save last *next_to_pgetc to buf[0]
9266//to make two pungetc() reliable. Currently,
9267// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009268static int
9269preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009270{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009271 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009272 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009273
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009274 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009275#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009276 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009277 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009278 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009279 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009280#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009281 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009282#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009283 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9284 if (nr == 0) {
9285 /* Ctrl+C pressed */
9286 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009287 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009288 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009289 raise(SIGINT);
9290 return 1;
9291 }
Eric Andersenc470f442003-07-28 09:56:35 +00009292 goto retry;
9293 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009294 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009295 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009296 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009297 }
Eric Andersencb57d552001-06-28 07:25:16 +00009298 }
9299#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009300 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009301#endif
9302
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009303#if 0
9304/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009305 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009306 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009307 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009308 if (flags >= 0 && (flags & O_NONBLOCK)) {
9309 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009310 if (fcntl(0, F_SETFL, flags) >= 0) {
9311 out2str("sh: turning off NDELAY mode\n");
9312 goto retry;
9313 }
9314 }
9315 }
9316 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009317#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009318 return nr;
9319}
9320
9321/*
9322 * Refill the input buffer and return the next input character:
9323 *
9324 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009325 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9326 * or we are reading from a string so we can't refill the buffer,
9327 * return EOF.
Eric Andersencb57d552001-06-28 07:25:16 +00009328 * 3) If the is more stuff in this buffer, use it else call read to fill it.
9329 * 4) Process input up to the next newline, deleting nul characters.
9330 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009331//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9332#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009333/*
9334 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9335 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9336 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9337 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9338 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009339static int
Eric Andersenc470f442003-07-28 09:56:35 +00009340preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009341{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009342 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009343 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009344
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009345 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009346#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009347 if (g_parsefile->left_in_line == -1
9348 && g_parsefile->strpush->ap
9349 && g_parsefile->next_to_pgetc[-1] != ' '
9350 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009351 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009352 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009353 return PEOA;
9354 }
Eric Andersen2870d962001-07-02 17:27:21 +00009355#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009356 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009357 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009358 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9359 g_parsefile->left_in_line,
9360 g_parsefile->next_to_pgetc,
9361 g_parsefile->next_to_pgetc);
9362 if (--g_parsefile->left_in_line >= 0)
9363 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009364 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009365 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009366 * "pgetc" needs refilling.
9367 */
9368
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009369 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009370 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009371 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009372 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009373 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009374 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009375 /* even in failure keep left_in_line and next_to_pgetc
9376 * in lock step, for correct multi-layer pungetc.
9377 * left_in_line was decremented before preadbuffer(),
9378 * must inc next_to_pgetc: */
9379 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009380 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009381 }
Eric Andersencb57d552001-06-28 07:25:16 +00009382
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009383 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009384 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009385 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009386 again:
9387 more = preadfd();
9388 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009389 /* don't try reading again */
9390 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009391 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009392 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009393 return PEOF;
9394 }
9395 }
9396
Denis Vlasenko727752d2008-11-28 03:41:47 +00009397 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009398 * Set g_parsefile->left_in_line
9399 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009400 * NUL chars are deleted.
9401 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009402 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009403 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009404 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009405
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009406 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009407
Denis Vlasenko727752d2008-11-28 03:41:47 +00009408 c = *q;
9409 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009410 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009411 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009412 q++;
9413 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009414 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009415 break;
9416 }
Eric Andersencb57d552001-06-28 07:25:16 +00009417 }
9418
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009419 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009420 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9421 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009422 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009423 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009424 }
9425 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009426 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009427
Eric Andersencb57d552001-06-28 07:25:16 +00009428 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009429 char save = *q;
9430 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009431 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009432 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009433 }
9434
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009435 pgetc_debug("preadbuffer at %d:%p'%s'",
9436 g_parsefile->left_in_line,
9437 g_parsefile->next_to_pgetc,
9438 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009439 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009440}
9441
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009442#define pgetc_as_macro() \
9443 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009444 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009445 : preadbuffer() \
9446 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009447
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009448static int
9449pgetc(void)
9450{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009451 pgetc_debug("pgetc_fast at %d:%p'%s'",
9452 g_parsefile->left_in_line,
9453 g_parsefile->next_to_pgetc,
9454 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009455 return pgetc_as_macro();
9456}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009457
9458#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009459#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009460#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009461#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009462#endif
9463
9464/*
9465 * Same as pgetc(), but ignores PEOA.
9466 */
9467#if ENABLE_ASH_ALIAS
9468static int
9469pgetc2(void)
9470{
9471 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009472 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009473 pgetc_debug("pgetc_fast at %d:%p'%s'",
9474 g_parsefile->left_in_line,
9475 g_parsefile->next_to_pgetc,
9476 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009477 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009478 } while (c == PEOA);
9479 return c;
9480}
9481#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009482#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009483#endif
9484
9485/*
9486 * Read a line from the script.
9487 */
9488static char *
9489pfgets(char *line, int len)
9490{
9491 char *p = line;
9492 int nleft = len;
9493 int c;
9494
9495 while (--nleft > 0) {
9496 c = pgetc2();
9497 if (c == PEOF) {
9498 if (p == line)
9499 return NULL;
9500 break;
9501 }
9502 *p++ = c;
9503 if (c == '\n')
9504 break;
9505 }
9506 *p = '\0';
9507 return line;
9508}
9509
Eric Andersenc470f442003-07-28 09:56:35 +00009510/*
9511 * Undo the last call to pgetc. Only one character may be pushed back.
9512 * PEOF may be pushed back.
9513 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009514static void
Eric Andersenc470f442003-07-28 09:56:35 +00009515pungetc(void)
9516{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009517 g_parsefile->left_in_line++;
9518 g_parsefile->next_to_pgetc--;
9519 pgetc_debug("pushed back to %d:%p'%s'",
9520 g_parsefile->left_in_line,
9521 g_parsefile->next_to_pgetc,
9522 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009523}
9524
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009525/*
9526 * To handle the "." command, a stack of input files is used. Pushfile
9527 * adds a new entry to the stack and popfile restores the previous level.
9528 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009529static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009530pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009531{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009532 struct parsefile *pf;
9533
Denis Vlasenko597906c2008-02-20 16:38:54 +00009534 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009535 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009536 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009537 /*pf->strpush = NULL; - ckzalloc did it */
9538 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009539 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009540}
9541
9542static void
9543popfile(void)
9544{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009545 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009546
Denis Vlasenkob012b102007-02-19 22:43:01 +00009547 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009548 if (pf->fd >= 0)
9549 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009550 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009551 while (pf->strpush)
9552 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009553 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009554 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009555 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009556}
9557
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009558/*
9559 * Return to top level.
9560 */
9561static void
9562popallfiles(void)
9563{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009564 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009565 popfile();
9566}
9567
9568/*
9569 * Close the file(s) that the shell is reading commands from. Called
9570 * after a fork is done.
9571 */
9572static void
9573closescript(void)
9574{
9575 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009576 if (g_parsefile->fd > 0) {
9577 close(g_parsefile->fd);
9578 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009579 }
9580}
9581
9582/*
9583 * Like setinputfile, but takes an open file descriptor. Call this with
9584 * interrupts off.
9585 */
9586static void
9587setinputfd(int fd, int push)
9588{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009589 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009590 if (push) {
9591 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009592 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009593 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009594 g_parsefile->fd = fd;
9595 if (g_parsefile->buf == NULL)
9596 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009597 g_parsefile->left_in_buffer = 0;
9598 g_parsefile->left_in_line = 0;
9599 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009600}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009601
Eric Andersenc470f442003-07-28 09:56:35 +00009602/*
9603 * Set the input to take input from a file. If push is set, push the
9604 * old input onto the stack first.
9605 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009606static int
9607setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009608{
9609 int fd;
9610 int fd2;
9611
Denis Vlasenkob012b102007-02-19 22:43:01 +00009612 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009613 fd = open(fname, O_RDONLY);
9614 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009615 if (flags & INPUT_NOFILE_OK)
9616 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009617 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009618 }
Eric Andersenc470f442003-07-28 09:56:35 +00009619 if (fd < 10) {
9620 fd2 = copyfd(fd, 10);
9621 close(fd);
9622 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009623 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009624 fd = fd2;
9625 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009626 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009627 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009628 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009629 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009630}
9631
Eric Andersencb57d552001-06-28 07:25:16 +00009632/*
9633 * Like setinputfile, but takes input from a string.
9634 */
Eric Andersenc470f442003-07-28 09:56:35 +00009635static void
9636setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009637{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009638 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009639 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009640 g_parsefile->next_to_pgetc = string;
9641 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009642 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009643 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009644 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009645}
9646
9647
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009648/* ============ mail.c
9649 *
9650 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009651 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009652
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009653#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009654
Eric Andersencb57d552001-06-28 07:25:16 +00009655#define MAXMBOXES 10
9656
Eric Andersenc470f442003-07-28 09:56:35 +00009657/* times of mailboxes */
9658static time_t mailtime[MAXMBOXES];
9659/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009660static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009661
Eric Andersencb57d552001-06-28 07:25:16 +00009662/*
Eric Andersenc470f442003-07-28 09:56:35 +00009663 * Print appropriate message(s) if mail has arrived.
9664 * If mail_var_path_changed is set,
9665 * then the value of MAIL has mail_var_path_changed,
9666 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009667 */
Eric Andersenc470f442003-07-28 09:56:35 +00009668static void
9669chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009670{
Eric Andersencb57d552001-06-28 07:25:16 +00009671 const char *mpath;
9672 char *p;
9673 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009674 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009675 struct stackmark smark;
9676 struct stat statb;
9677
Eric Andersencb57d552001-06-28 07:25:16 +00009678 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009679 mpath = mpathset() ? mpathval() : mailval();
9680 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Eric Andersencb57d552001-06-28 07:25:16 +00009681 p = padvance(&mpath, nullstr);
9682 if (p == NULL)
9683 break;
9684 if (*p == '\0')
9685 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009686 for (q = p; *q; q++)
9687 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009688#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009689 if (q[-1] != '/')
9690 abort();
9691#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009692 q[-1] = '\0'; /* delete trailing '/' */
9693 if (stat(p, &statb) < 0) {
9694 *mtp = 0;
9695 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009696 }
Eric Andersenc470f442003-07-28 09:56:35 +00009697 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9698 fprintf(
9699 stderr, snlfmt,
9700 pathopt ? pathopt : "you have mail"
9701 );
9702 }
9703 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009704 }
Eric Andersenc470f442003-07-28 09:56:35 +00009705 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009706 popstackmark(&smark);
9707}
Eric Andersencb57d552001-06-28 07:25:16 +00009708
Eric Andersenc470f442003-07-28 09:56:35 +00009709static void
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009710changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009711{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009712 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009713}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009714
Denis Vlasenko131ae172007-02-18 13:00:19 +00009715#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009716
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009717
9718/* ============ ??? */
9719
Eric Andersencb57d552001-06-28 07:25:16 +00009720/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009721 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009722 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009723static void
9724setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009725{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009726 char **newparam;
9727 char **ap;
9728 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009729
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009730 for (nparam = 0; argv[nparam]; nparam++)
9731 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009732 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9733 while (*argv) {
9734 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009735 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009736 *ap = NULL;
9737 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009738 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009739 shellparam.nparam = nparam;
9740 shellparam.p = newparam;
9741#if ENABLE_ASH_GETOPTS
9742 shellparam.optind = 1;
9743 shellparam.optoff = -1;
9744#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009745}
9746
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009747/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009748 * Process shell options. The global variable argptr contains a pointer
9749 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009750 *
9751 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9752 * For a non-interactive shell, an error condition encountered
9753 * by a special built-in ... shall cause the shell to write a diagnostic message
9754 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009755 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009756 * ...
9757 * Utility syntax error (option or operand error) Shall exit
9758 * ...
9759 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9760 * we see that bash does not do that (set "finishes" with error code 1 instead,
9761 * and shell continues), and people rely on this behavior!
9762 * Testcase:
9763 * set -o barfoo 2>/dev/null
9764 * echo $?
9765 *
9766 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009767 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009768static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009769plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009770{
9771 int i;
9772
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009773 if (name) {
9774 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009775 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009776 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009777 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009778 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009779 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009780 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009781 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009782 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009783 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009784 if (val) {
9785 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9786 } else {
9787 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9788 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009789 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009790 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009791}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009792static void
9793setoption(int flag, int val)
9794{
9795 int i;
9796
9797 for (i = 0; i < NOPTS; i++) {
9798 if (optletters(i) == flag) {
9799 optlist[i] = val;
9800 return;
9801 }
9802 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009803 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009804 /* NOTREACHED */
9805}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009806static int
Eric Andersenc470f442003-07-28 09:56:35 +00009807options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009808{
9809 char *p;
9810 int val;
9811 int c;
9812
9813 if (cmdline)
9814 minusc = NULL;
9815 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009816 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009817 if (c != '-' && c != '+')
9818 break;
9819 argptr++;
9820 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009821 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009822 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009823 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009824 if (!cmdline) {
9825 /* "-" means turn off -x and -v */
9826 if (p[0] == '\0')
9827 xflag = vflag = 0;
9828 /* "--" means reset params */
9829 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009830 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009831 }
Eric Andersenc470f442003-07-28 09:56:35 +00009832 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009833 }
Eric Andersencb57d552001-06-28 07:25:16 +00009834 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009835 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009836 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009837 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009838 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009839 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009840 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009841 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009842 /* it already printed err message */
9843 return 1; /* error */
9844 }
Eric Andersencb57d552001-06-28 07:25:16 +00009845 if (*argptr)
9846 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009847 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9848 isloginsh = 1;
9849 /* bash does not accept +-login, we also won't */
9850 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009851 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009852 isloginsh = 1;
9853 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009854 } else {
9855 setoption(c, val);
9856 }
9857 }
9858 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009859 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009860}
9861
Eric Andersencb57d552001-06-28 07:25:16 +00009862/*
Eric Andersencb57d552001-06-28 07:25:16 +00009863 * The shift builtin command.
9864 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009865static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009866shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009867{
9868 int n;
9869 char **ap1, **ap2;
9870
9871 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009872 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009873 n = number(argv[1]);
9874 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009875 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009876 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009877 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009878 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009879 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009880 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009881 }
9882 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009883 while ((*ap2++ = *ap1++) != NULL)
9884 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009885#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009886 shellparam.optind = 1;
9887 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009888#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009889 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009890 return 0;
9891}
9892
Eric Andersencb57d552001-06-28 07:25:16 +00009893/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009894 * POSIX requires that 'set' (but not export or readonly) output the
9895 * variables in lexicographic order - by the locale's collating order (sigh).
9896 * Maybe we could keep them in an ordered balanced binary tree
9897 * instead of hashed lists.
9898 * For now just roll 'em through qsort for printing...
9899 */
9900static int
9901showvars(const char *sep_prefix, int on, int off)
9902{
9903 const char *sep;
9904 char **ep, **epend;
9905
9906 ep = listvars(on, off, &epend);
9907 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9908
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009909 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009910
9911 for (; ep < epend; ep++) {
9912 const char *p;
9913 const char *q;
9914
9915 p = strchrnul(*ep, '=');
9916 q = nullstr;
9917 if (*p)
9918 q = single_quote(++p);
9919 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9920 }
9921 return 0;
9922}
9923
9924/*
Eric Andersencb57d552001-06-28 07:25:16 +00009925 * The set command builtin.
9926 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009927static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009928setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00009929{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009930 int retval;
9931
Denis Vlasenko68404f12008-03-17 09:00:54 +00009932 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +00009933 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009934 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009935 retval = 1;
9936 if (!options(0)) { /* if no parse error... */
9937 retval = 0;
9938 optschanged();
9939 if (*argptr != NULL) {
9940 setparam(argptr);
9941 }
Eric Andersencb57d552001-06-28 07:25:16 +00009942 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009943 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009944 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009945}
9946
Denis Vlasenko131ae172007-02-18 13:00:19 +00009947#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009948static void
9949change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +00009950{
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009951 /* Galois LFSR parameter */
9952 /* Taps at 32 31 29 1: */
9953 enum { MASK = 0x8000000b };
9954 /* Another example - taps at 32 31 30 10: */
9955 /* MASK = 0x00400007 */
9956
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009957 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +00009958 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009959 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +00009960
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009961 /* LCG has period of 2^32 and alternating lowest bit */
9962 random_LCG = 1664525 * random_LCG + 1013904223;
9963 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
9964 t = (random_galois_LFSR << 1);
9965 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
9966 t ^= MASK;
9967 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +00009968 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009969 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +00009970 * for $RANDOM range. Combining with subtraction is
9971 * just for fun. + and ^ would work equally well. */
9972 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +00009973 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009974 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +00009975 vrandom.flags &= ~VNOFUNC;
9976 } else {
9977 /* set/reset */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009978 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +00009979 }
Eric Andersenef02f822004-03-11 13:34:24 +00009980}
Eric Andersen16767e22004-03-16 05:14:10 +00009981#endif
9982
Denis Vlasenko131ae172007-02-18 13:00:19 +00009983#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009984static int
Eric Andersenc470f442003-07-28 09:56:35 +00009985getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009986{
9987 char *p, *q;
9988 char c = '?';
9989 int done = 0;
9990 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +00009991 char s[12];
9992 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +00009993
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009994 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +00009995 return 1;
9996 optnext = optfirst + *param_optind - 1;
9997
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009998 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009999 p = NULL;
10000 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010001 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010002 if (p == NULL || *p == '\0') {
10003 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010004 p = *optnext;
10005 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010006 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010007 p = NULL;
10008 done = 1;
10009 goto out;
10010 }
10011 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010012 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010013 goto atend;
10014 }
10015
10016 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010017 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010018 if (*q == '\0') {
10019 if (optstr[0] == ':') {
10020 s[0] = c;
10021 s[1] = '\0';
10022 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010023 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010024 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010025 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010026 }
10027 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010028 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010029 }
10030 if (*++q == ':')
10031 q++;
10032 }
10033
10034 if (*++q == ':') {
10035 if (*p == '\0' && (p = *optnext) == NULL) {
10036 if (optstr[0] == ':') {
10037 s[0] = c;
10038 s[1] = '\0';
10039 err |= setvarsafe("OPTARG", s, 0);
10040 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010041 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010042 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010043 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010044 c = '?';
10045 }
Eric Andersenc470f442003-07-28 09:56:35 +000010046 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010047 }
10048
10049 if (p == *optnext)
10050 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010051 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010052 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010053 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010054 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010055 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010056 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010057 *param_optind = optnext - optfirst + 1;
10058 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010059 err |= setvarsafe("OPTIND", s, VNOFUNC);
10060 s[0] = c;
10061 s[1] = '\0';
10062 err |= setvarsafe(optvar, s, 0);
10063 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010064 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010065 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010066 flush_stdout_stderr();
10067 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010068 }
10069 return done;
10070}
Eric Andersenc470f442003-07-28 09:56:35 +000010071
10072/*
10073 * The getopts builtin. Shellparam.optnext points to the next argument
10074 * to be processed. Shellparam.optptr points to the next character to
10075 * be processed in the current argument. If shellparam.optnext is NULL,
10076 * then it's the first time getopts has been called.
10077 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010078static int
Eric Andersenc470f442003-07-28 09:56:35 +000010079getoptscmd(int argc, char **argv)
10080{
10081 char **optbase;
10082
10083 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010084 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010085 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010086 optbase = shellparam.p;
10087 if (shellparam.optind > shellparam.nparam + 1) {
10088 shellparam.optind = 1;
10089 shellparam.optoff = -1;
10090 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010091 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010092 optbase = &argv[3];
10093 if (shellparam.optind > argc - 2) {
10094 shellparam.optind = 1;
10095 shellparam.optoff = -1;
10096 }
10097 }
10098
10099 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010100 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010101}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010102#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010103
Eric Andersencb57d552001-06-28 07:25:16 +000010104
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010105/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010106
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010107struct heredoc {
10108 struct heredoc *next; /* next here document in list */
10109 union node *here; /* redirection node */
10110 char *eofmark; /* string indicating end of input */
10111 smallint striptabs; /* if set, strip leading tabs */
10112};
10113
10114static smallint tokpushback; /* last token pushed back */
10115static smallint parsebackquote; /* nonzero if we are inside backquotes */
10116static smallint quoteflag; /* set if (part of) last token was quoted */
10117static token_id_t lasttoken; /* last token read (integer id Txxx) */
10118static struct heredoc *heredoclist; /* list of here documents to read */
10119static char *wordtext; /* text of last word returned by readtoken */
10120static struct nodelist *backquotelist;
10121static union node *redirnode;
10122static struct heredoc *heredoc;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010123/*
10124 * NEOF is returned by parsecmd when it encounters an end of file. It
10125 * must be distinct from NULL, so we use the address of a variable that
10126 * happens to be handy.
10127 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010128#define NEOF ((union node *)&tokpushback)
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010129
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010130static void raise_error_syntax(const char *) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010131static void
10132raise_error_syntax(const char *msg)
10133{
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010134 ash_msg_and_raise_error("syntax error: %s", msg);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010135 /* NOTREACHED */
10136}
10137
10138/*
10139 * Called when an unexpected token is read during the parse. The argument
10140 * is the token that is expected, or -1 if more than one type of token can
10141 * occur at this point.
10142 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010143static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010144static void
10145raise_error_unexpected_syntax(int token)
10146{
10147 char msg[64];
10148 int l;
10149
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010150 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010151 if (token >= 0)
10152 sprintf(msg + l, " (expecting %s)", tokname(token));
10153 raise_error_syntax(msg);
10154 /* NOTREACHED */
10155}
Eric Andersencb57d552001-06-28 07:25:16 +000010156
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010157#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010158
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010159/* parsing is heavily cross-recursive, need these forward decls */
10160static union node *andor(void);
10161static union node *pipeline(void);
10162static union node *parse_command(void);
10163static void parseheredoc(void);
10164static char peektoken(void);
10165static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010166
Eric Andersenc470f442003-07-28 09:56:35 +000010167static union node *
10168list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010169{
10170 union node *n1, *n2, *n3;
10171 int tok;
10172
Eric Andersenc470f442003-07-28 09:56:35 +000010173 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10174 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010175 return NULL;
10176 n1 = NULL;
10177 for (;;) {
10178 n2 = andor();
10179 tok = readtoken();
10180 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010181 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010182 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010183 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010184 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010185 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010186 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010187 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010188 n2 = n3;
10189 }
10190 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010191 }
10192 }
10193 if (n1 == NULL) {
10194 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010195 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010196 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010197 n3->type = NSEMI;
10198 n3->nbinary.ch1 = n1;
10199 n3->nbinary.ch2 = n2;
10200 n1 = n3;
10201 }
10202 switch (tok) {
10203 case TBACKGND:
10204 case TSEMI:
10205 tok = readtoken();
10206 /* fall through */
10207 case TNL:
10208 if (tok == TNL) {
10209 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010210 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010211 return n1;
10212 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010213 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010214 }
Eric Andersenc470f442003-07-28 09:56:35 +000010215 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010216 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010217 return n1;
10218 break;
10219 case TEOF:
10220 if (heredoclist)
10221 parseheredoc();
10222 else
Eric Andersenc470f442003-07-28 09:56:35 +000010223 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010224 return n1;
10225 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010226 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010227 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010228 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010229 return n1;
10230 }
10231 }
10232}
10233
Eric Andersenc470f442003-07-28 09:56:35 +000010234static union node *
10235andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010236{
Eric Andersencb57d552001-06-28 07:25:16 +000010237 union node *n1, *n2, *n3;
10238 int t;
10239
Eric Andersencb57d552001-06-28 07:25:16 +000010240 n1 = pipeline();
10241 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010242 t = readtoken();
10243 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010244 t = NAND;
10245 } else if (t == TOR) {
10246 t = NOR;
10247 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010248 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010249 return n1;
10250 }
Eric Andersenc470f442003-07-28 09:56:35 +000010251 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010252 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010253 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010254 n3->type = t;
10255 n3->nbinary.ch1 = n1;
10256 n3->nbinary.ch2 = n2;
10257 n1 = n3;
10258 }
10259}
10260
Eric Andersenc470f442003-07-28 09:56:35 +000010261static union node *
10262pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010263{
Eric Andersencb57d552001-06-28 07:25:16 +000010264 union node *n1, *n2, *pipenode;
10265 struct nodelist *lp, *prev;
10266 int negate;
10267
10268 negate = 0;
10269 TRACE(("pipeline: entered\n"));
10270 if (readtoken() == TNOT) {
10271 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010272 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010273 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010274 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010275 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010276 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010277 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010278 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010279 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010280 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010281 pipenode->npipe.cmdlist = lp;
10282 lp->n = n1;
10283 do {
10284 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010285 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010286 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010287 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010288 prev->next = lp;
10289 } while (readtoken() == TPIPE);
10290 lp->next = NULL;
10291 n1 = pipenode;
10292 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010293 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010294 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010295 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010296 n2->type = NNOT;
10297 n2->nnot.com = n1;
10298 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010299 }
10300 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010301}
10302
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010303static union node *
10304makename(void)
10305{
10306 union node *n;
10307
Denis Vlasenko597906c2008-02-20 16:38:54 +000010308 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010309 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010310 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010311 n->narg.text = wordtext;
10312 n->narg.backquote = backquotelist;
10313 return n;
10314}
10315
10316static void
10317fixredir(union node *n, const char *text, int err)
10318{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010319 int fd;
10320
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010321 TRACE(("Fix redir %s %d\n", text, err));
10322 if (!err)
10323 n->ndup.vname = NULL;
10324
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010325 fd = bb_strtou(text, NULL, 10);
10326 if (!errno && fd >= 0)
10327 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010328 else if (LONE_DASH(text))
10329 n->ndup.dupfd = -1;
10330 else {
10331 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010332 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010333 n->ndup.vname = makename();
10334 }
10335}
10336
10337/*
10338 * Returns true if the text contains nothing to expand (no dollar signs
10339 * or backquotes).
10340 */
10341static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010342noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010343{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010344 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010345 char c;
10346
10347 p = text;
10348 while ((c = *p++) != '\0') {
10349 if (c == CTLQUOTEMARK)
10350 continue;
10351 if (c == CTLESC)
10352 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010353 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010354 return 0;
10355 }
10356 return 1;
10357}
10358
10359static void
10360parsefname(void)
10361{
10362 union node *n = redirnode;
10363
10364 if (readtoken() != TWORD)
10365 raise_error_unexpected_syntax(-1);
10366 if (n->type == NHERE) {
10367 struct heredoc *here = heredoc;
10368 struct heredoc *p;
10369 int i;
10370
10371 if (quoteflag == 0)
10372 n->type = NXHERE;
10373 TRACE(("Here document %d\n", n->type));
10374 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010375 raise_error_syntax("illegal eof marker for << redirection");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010376 rmescapes(wordtext);
10377 here->eofmark = wordtext;
10378 here->next = NULL;
10379 if (heredoclist == NULL)
10380 heredoclist = here;
10381 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010382 for (p = heredoclist; p->next; p = p->next)
10383 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010384 p->next = here;
10385 }
10386 } else if (n->type == NTOFD || n->type == NFROMFD) {
10387 fixredir(n, wordtext, 0);
10388 } else {
10389 n->nfile.fname = makename();
10390 }
10391}
Eric Andersencb57d552001-06-28 07:25:16 +000010392
Eric Andersenc470f442003-07-28 09:56:35 +000010393static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010394simplecmd(void)
10395{
10396 union node *args, **app;
10397 union node *n = NULL;
10398 union node *vars, **vpp;
10399 union node **rpp, *redir;
10400 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010401#if ENABLE_ASH_BASH_COMPAT
10402 smallint double_brackets_flag = 0;
10403#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010404
10405 args = NULL;
10406 app = &args;
10407 vars = NULL;
10408 vpp = &vars;
10409 redir = NULL;
10410 rpp = &redir;
10411
10412 savecheckkwd = CHKALIAS;
10413 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010414 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010415 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010416 t = readtoken();
10417 switch (t) {
10418#if ENABLE_ASH_BASH_COMPAT
10419 case TAND: /* "&&" */
10420 case TOR: /* "||" */
10421 if (!double_brackets_flag) {
10422 tokpushback = 1;
10423 goto out;
10424 }
10425 wordtext = (char *) (t == TAND ? "-a" : "-o");
10426#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010427 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010428 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010429 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010430 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010431 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010432#if ENABLE_ASH_BASH_COMPAT
10433 if (strcmp("[[", wordtext) == 0)
10434 double_brackets_flag = 1;
10435 else if (strcmp("]]", wordtext) == 0)
10436 double_brackets_flag = 0;
10437#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010438 n->narg.backquote = backquotelist;
10439 if (savecheckkwd && isassignment(wordtext)) {
10440 *vpp = n;
10441 vpp = &n->narg.next;
10442 } else {
10443 *app = n;
10444 app = &n->narg.next;
10445 savecheckkwd = 0;
10446 }
10447 break;
10448 case TREDIR:
10449 *rpp = n = redirnode;
10450 rpp = &n->nfile.next;
10451 parsefname(); /* read name of redirection file */
10452 break;
10453 case TLP:
10454 if (args && app == &args->narg.next
10455 && !vars && !redir
10456 ) {
10457 struct builtincmd *bcmd;
10458 const char *name;
10459
10460 /* We have a function */
10461 if (readtoken() != TRP)
10462 raise_error_unexpected_syntax(TRP);
10463 name = n->narg.text;
10464 if (!goodname(name)
10465 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10466 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010467 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010468 }
10469 n->type = NDEFUN;
10470 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10471 n->narg.next = parse_command();
10472 return n;
10473 }
10474 /* fall through */
10475 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010476 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010477 goto out;
10478 }
10479 }
10480 out:
10481 *app = NULL;
10482 *vpp = NULL;
10483 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010484 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010485 n->type = NCMD;
10486 n->ncmd.args = args;
10487 n->ncmd.assign = vars;
10488 n->ncmd.redirect = redir;
10489 return n;
10490}
10491
10492static union node *
10493parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010494{
Eric Andersencb57d552001-06-28 07:25:16 +000010495 union node *n1, *n2;
10496 union node *ap, **app;
10497 union node *cp, **cpp;
10498 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010499 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010500 int t;
10501
10502 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010503 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010504
Eric Andersencb57d552001-06-28 07:25:16 +000010505 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010506 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010507 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010508 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010509 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010510 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010511 n1->type = NIF;
10512 n1->nif.test = list(0);
10513 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010514 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010515 n1->nif.ifpart = list(0);
10516 n2 = n1;
10517 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010518 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010519 n2 = n2->nif.elsepart;
10520 n2->type = NIF;
10521 n2->nif.test = list(0);
10522 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010523 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010524 n2->nif.ifpart = list(0);
10525 }
10526 if (lasttoken == TELSE)
10527 n2->nif.elsepart = list(0);
10528 else {
10529 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010530 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010531 }
Eric Andersenc470f442003-07-28 09:56:35 +000010532 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010533 break;
10534 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010535 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010536 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010537 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010538 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010539 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010540 got = readtoken();
10541 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010542 TRACE(("expecting DO got %s %s\n", tokname(got),
10543 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010544 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010545 }
10546 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010547 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010548 break;
10549 }
10550 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010551 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010552 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010553 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010554 n1->type = NFOR;
10555 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010556 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010557 if (readtoken() == TIN) {
10558 app = &ap;
10559 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010560 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010561 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010562 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010563 n2->narg.text = wordtext;
10564 n2->narg.backquote = backquotelist;
10565 *app = n2;
10566 app = &n2->narg.next;
10567 }
10568 *app = NULL;
10569 n1->nfor.args = ap;
10570 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010571 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010572 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010573 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010574 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010575 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010576 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010577 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010578 n1->nfor.args = n2;
10579 /*
10580 * Newline or semicolon here is optional (but note
10581 * that the original Bourne shell only allowed NL).
10582 */
10583 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010584 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010585 }
Eric Andersenc470f442003-07-28 09:56:35 +000010586 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010587 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010588 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010589 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010590 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010591 break;
10592 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010593 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010594 n1->type = NCASE;
10595 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010596 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010597 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010598 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010599 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010600 n2->narg.text = wordtext;
10601 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010602 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010603 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010604 } while (readtoken() == TNL);
10605 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010606 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010607 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010608 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010609 checkkwd = CHKNL | CHKKWD;
10610 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010611 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010612 if (lasttoken == TLP)
10613 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010614 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010615 cp->type = NCLIST;
10616 app = &cp->nclist.pattern;
10617 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010618 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010619 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010620 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010621 ap->narg.text = wordtext;
10622 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010623 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010624 break;
10625 app = &ap->narg.next;
10626 readtoken();
10627 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010628 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010629 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010630 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010631 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010632
Eric Andersenc470f442003-07-28 09:56:35 +000010633 cpp = &cp->nclist.next;
10634
10635 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010636 t = readtoken();
10637 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010638 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010639 raise_error_unexpected_syntax(TENDCASE);
10640 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010641 }
Eric Andersenc470f442003-07-28 09:56:35 +000010642 }
Eric Andersencb57d552001-06-28 07:25:16 +000010643 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010644 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010645 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010646 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010647 n1->type = NSUBSHELL;
10648 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010649 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010650 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010651 break;
10652 case TBEGIN:
10653 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010654 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010655 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010656 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010657 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010658 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010659 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010660 }
10661
Eric Andersenc470f442003-07-28 09:56:35 +000010662 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010663 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010664
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010665 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010666 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010667 checkkwd = CHKKWD | CHKALIAS;
10668 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010669 while (readtoken() == TREDIR) {
10670 *rpp = n2 = redirnode;
10671 rpp = &n2->nfile.next;
10672 parsefname();
10673 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010674 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010675 *rpp = NULL;
10676 if (redir) {
10677 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010678 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010679 n2->type = NREDIR;
10680 n2->nredir.n = n1;
10681 n1 = n2;
10682 }
10683 n1->nredir.redirect = redir;
10684 }
Eric Andersencb57d552001-06-28 07:25:16 +000010685 return n1;
10686}
10687
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010688#if ENABLE_ASH_BASH_COMPAT
10689static int decode_dollar_squote(void)
10690{
10691 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10692 int c, cnt;
10693 char *p;
10694 char buf[4];
10695
10696 c = pgetc();
10697 p = strchr(C_escapes, c);
10698 if (p) {
10699 buf[0] = c;
10700 p = buf;
10701 cnt = 3;
10702 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10703 do {
10704 c = pgetc();
10705 *++p = c;
10706 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10707 pungetc();
10708 } else if (c == 'x') { /* \xHH */
10709 do {
10710 c = pgetc();
10711 *++p = c;
10712 } while (isxdigit(c) && --cnt);
10713 pungetc();
10714 if (cnt == 3) { /* \x but next char is "bad" */
10715 c = 'x';
10716 goto unrecognized;
10717 }
10718 } else { /* simple seq like \\ or \t */
10719 p++;
10720 }
10721 *p = '\0';
10722 p = buf;
10723 c = bb_process_escape_sequence((void*)&p);
10724 } else { /* unrecognized "\z": print both chars unless ' or " */
10725 if (c != '\'' && c != '"') {
10726 unrecognized:
10727 c |= 0x100; /* "please encode \, then me" */
10728 }
10729 }
10730 return c;
10731}
10732#endif
10733
Eric Andersencb57d552001-06-28 07:25:16 +000010734/*
10735 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10736 * is not NULL, read a here document. In the latter case, eofmark is the
10737 * word which marks the end of the document and striptabs is true if
10738 * leading tabs should be stripped from the document. The argument firstc
10739 * is the first character of the input token or document.
10740 *
10741 * Because C does not have internal subroutines, I have simulated them
10742 * using goto's to implement the subroutine linkage. The following macros
10743 * will run code that appears at the end of readtoken1.
10744 */
Eric Andersen2870d962001-07-02 17:27:21 +000010745#define CHECKEND() {goto checkend; checkend_return:;}
10746#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10747#define PARSESUB() {goto parsesub; parsesub_return:;}
10748#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10749#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10750#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010751static int
Eric Andersenc470f442003-07-28 09:56:35 +000010752readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010753{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010754 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010755 int c = firstc;
10756 char *out;
10757 int len;
10758 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010759 struct nodelist *bqlist;
10760 smallint quotef;
10761 smallint dblquote;
10762 smallint oldstyle;
10763 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010764#if ENABLE_ASH_EXPAND_PRMT
10765 smallint pssyntax; /* we are expanding a prompt string */
10766#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010767 int varnest; /* levels of variables expansion */
10768 int arinest; /* levels of arithmetic expansion */
10769 int parenlevel; /* levels of parens in arithmetic */
10770 int dqvarnest; /* levels of variables expansion within double quotes */
10771
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010772 USE_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10773
Eric Andersencb57d552001-06-28 07:25:16 +000010774#if __GNUC__
10775 /* Avoid longjmp clobbering */
10776 (void) &out;
10777 (void) &quotef;
10778 (void) &dblquote;
10779 (void) &varnest;
10780 (void) &arinest;
10781 (void) &parenlevel;
10782 (void) &dqvarnest;
10783 (void) &oldstyle;
10784 (void) &prevsyntax;
10785 (void) &syntax;
10786#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010787 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010788 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010789 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010790 oldstyle = 0;
10791 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010792#if ENABLE_ASH_EXPAND_PRMT
10793 pssyntax = (syntax == PSSYNTAX);
10794 if (pssyntax)
10795 syntax = DQSYNTAX;
10796#endif
10797 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010798 varnest = 0;
10799 arinest = 0;
10800 parenlevel = 0;
10801 dqvarnest = 0;
10802
10803 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010804 loop:
10805 /* For each line, until end of word */
10806 {
Eric Andersenc470f442003-07-28 09:56:35 +000010807 CHECKEND(); /* set c to PEOF if at end of here document */
10808 for (;;) { /* until end of line or end of word */
10809 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010810 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010811 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010812 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010813 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010814 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010815 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010816 if (doprompt)
10817 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010818 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010819 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010820 case CWORD:
10821 USTPUTC(c, out);
10822 break;
10823 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010824 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010825 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010826#if ENABLE_ASH_BASH_COMPAT
10827 if (c == '\\' && bash_dollar_squote) {
10828 c = decode_dollar_squote();
10829 if (c & 0x100) {
10830 USTPUTC('\\', out);
10831 c = (unsigned char)c;
10832 }
10833 }
10834#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010835 USTPUTC(c, out);
10836 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010837 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010838 c = pgetc2();
10839 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010840 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010841 USTPUTC('\\', out);
10842 pungetc();
10843 } else if (c == '\n') {
10844 if (doprompt)
10845 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010846 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010847#if ENABLE_ASH_EXPAND_PRMT
10848 if (c == '$' && pssyntax) {
10849 USTPUTC(CTLESC, out);
10850 USTPUTC('\\', out);
10851 }
10852#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010853 if (dblquote && c != '\\'
10854 && c != '`' && c != '$'
10855 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010856 ) {
10857 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010858 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010859 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010860 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010861 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010862 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010863 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010864 }
10865 break;
10866 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010867 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010868 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010869 if (eofmark == NULL) {
10870 USTPUTC(CTLQUOTEMARK, out);
10871 }
Eric Andersencb57d552001-06-28 07:25:16 +000010872 break;
10873 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010874 syntax = DQSYNTAX;
10875 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010876 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010877 case CENDQUOTE:
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010878 USE_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010879 if (eofmark != NULL && arinest == 0
10880 && varnest == 0
10881 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010882 USTPUTC(c, out);
10883 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010884 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010885 syntax = BASESYNTAX;
10886 dblquote = 0;
10887 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010888 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010889 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010890 }
10891 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010892 case CVAR: /* '$' */
10893 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010894 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010895 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010896 if (varnest > 0) {
10897 varnest--;
10898 if (dqvarnest > 0) {
10899 dqvarnest--;
10900 }
10901 USTPUTC(CTLENDVAR, out);
10902 } else {
10903 USTPUTC(c, out);
10904 }
10905 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010906#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010907 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010908 parenlevel++;
10909 USTPUTC(c, out);
10910 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010911 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010912 if (parenlevel > 0) {
10913 USTPUTC(c, out);
10914 --parenlevel;
10915 } else {
10916 if (pgetc() == ')') {
10917 if (--arinest == 0) {
10918 USTPUTC(CTLENDARI, out);
10919 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010920 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010921 } else
10922 USTPUTC(')', out);
10923 } else {
10924 /*
10925 * unbalanced parens
10926 * (don't 2nd guess - no error)
10927 */
10928 pungetc();
10929 USTPUTC(')', out);
10930 }
10931 }
10932 break;
10933#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010934 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010935 PARSEBACKQOLD();
10936 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010937 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010938 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010939 case CIGN:
10940 break;
10941 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000010942 if (varnest == 0) {
10943#if ENABLE_ASH_BASH_COMPAT
10944 if (c == '&') {
10945 if (pgetc() == '>')
10946 c = 0x100 + '>'; /* flag &> */
10947 pungetc();
10948 }
10949#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010950 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000010951 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000010952#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010953 if (c != PEOA)
10954#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010955 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010956
Eric Andersencb57d552001-06-28 07:25:16 +000010957 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000010958 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010959 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000010960 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010961 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000010962#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010963 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010964 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000010965#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010966 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010967 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000010968 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010969 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000010970 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000010971 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000010972 }
10973 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010974 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000010975 out = stackblock();
10976 if (eofmark == NULL) {
Denis Vlasenko834dee72008-10-07 09:18:30 +000010977 if ((c == '>' || c == '<' USE_ASH_BASH_COMPAT( || c == 0x100 + '>'))
10978 && quotef == 0
10979 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010980 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010981 PARSEREDIR(); /* passed as params: out, c */
10982 lasttoken = TREDIR;
10983 return lasttoken;
10984 }
10985 /* else: non-number X seen, interpret it
10986 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000010987 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010988 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000010989 }
10990 quoteflag = quotef;
10991 backquotelist = bqlist;
10992 grabstackblock(len);
10993 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010994 lasttoken = TWORD;
10995 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000010996/* end of readtoken routine */
10997
Eric Andersencb57d552001-06-28 07:25:16 +000010998/*
10999 * Check to see whether we are at the end of the here document. When this
11000 * is called, c is set to the first character of the next input line. If
11001 * we are at the end of the here document, this routine sets the c to PEOF.
11002 */
Eric Andersenc470f442003-07-28 09:56:35 +000011003checkend: {
11004 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011005#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011006 if (c == PEOA) {
11007 c = pgetc2();
11008 }
11009#endif
11010 if (striptabs) {
11011 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011012 c = pgetc2();
11013 }
Eric Andersenc470f442003-07-28 09:56:35 +000011014 }
11015 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011016 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011017 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011018
Eric Andersenc470f442003-07-28 09:56:35 +000011019 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011020 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11021 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011022 if (*p == '\n' && *q == '\0') {
11023 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011024 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011025 needprompt = doprompt;
11026 } else {
11027 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011028 }
11029 }
11030 }
11031 }
Eric Andersenc470f442003-07-28 09:56:35 +000011032 goto checkend_return;
11033}
Eric Andersencb57d552001-06-28 07:25:16 +000011034
Eric Andersencb57d552001-06-28 07:25:16 +000011035/*
11036 * Parse a redirection operator. The variable "out" points to a string
11037 * specifying the fd to be redirected. The variable "c" contains the
11038 * first character of the redirection operator.
11039 */
Eric Andersenc470f442003-07-28 09:56:35 +000011040parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011041 /* out is already checked to be a valid number or "" */
11042 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011043 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011044
Denis Vlasenko597906c2008-02-20 16:38:54 +000011045 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011046 if (c == '>') {
11047 np->nfile.fd = 1;
11048 c = pgetc();
11049 if (c == '>')
11050 np->type = NAPPEND;
11051 else if (c == '|')
11052 np->type = NCLOBBER;
11053 else if (c == '&')
11054 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011055 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011056 else {
11057 np->type = NTO;
11058 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011059 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011060 }
11061#if ENABLE_ASH_BASH_COMPAT
11062 else if (c == 0x100 + '>') { /* this flags &> redirection */
11063 np->nfile.fd = 1;
11064 pgetc(); /* this is '>', no need to check */
11065 np->type = NTO2;
11066 }
11067#endif
11068 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011069 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011070 c = pgetc();
11071 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011072 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011073 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011074 np = stzalloc(sizeof(struct nhere));
11075 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011076 }
11077 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011078 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011079 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011080 c = pgetc();
11081 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011082 heredoc->striptabs = 1;
11083 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011084 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011085 pungetc();
11086 }
11087 break;
11088
11089 case '&':
11090 np->type = NFROMFD;
11091 break;
11092
11093 case '>':
11094 np->type = NFROMTO;
11095 break;
11096
11097 default:
11098 np->type = NFROM;
11099 pungetc();
11100 break;
11101 }
Eric Andersencb57d552001-06-28 07:25:16 +000011102 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011103 if (fd >= 0)
11104 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011105 redirnode = np;
11106 goto parseredir_return;
11107}
Eric Andersencb57d552001-06-28 07:25:16 +000011108
Eric Andersencb57d552001-06-28 07:25:16 +000011109/*
11110 * Parse a substitution. At this point, we have read the dollar sign
11111 * and nothing else.
11112 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011113
11114/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11115 * (assuming ascii char codes, as the original implementation did) */
11116#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011117 (((unsigned)(c) - 33 < 32) \
11118 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011119parsesub: {
11120 int subtype;
11121 int typeloc;
11122 int flags;
11123 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011124 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011125
Eric Andersenc470f442003-07-28 09:56:35 +000011126 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011127 if (c <= PEOA_OR_PEOF
11128 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011129 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011130#if ENABLE_ASH_BASH_COMPAT
11131 if (c == '\'')
11132 bash_dollar_squote = 1;
11133 else
11134#endif
11135 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011136 pungetc();
11137 } else if (c == '(') { /* $(command) or $((arith)) */
11138 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011139#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011140 PARSEARITH();
11141#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011142 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011143#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011144 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011145 pungetc();
11146 PARSEBACKQNEW();
11147 }
11148 } else {
11149 USTPUTC(CTLVAR, out);
11150 typeloc = out - (char *)stackblock();
11151 USTPUTC(VSNORMAL, out);
11152 subtype = VSNORMAL;
11153 if (c == '{') {
11154 c = pgetc();
11155 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011156 c = pgetc();
11157 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011158 c = '#';
11159 else
11160 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011161 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011162 subtype = 0;
11163 }
11164 if (c > PEOA_OR_PEOF && is_name(c)) {
11165 do {
11166 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011167 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011168 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011169 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011170 do {
11171 STPUTC(c, out);
11172 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011173 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011174 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011175 USTPUTC(c, out);
11176 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011177 } else {
11178 badsub:
11179 raise_error_syntax("bad substitution");
11180 }
Eric Andersencb57d552001-06-28 07:25:16 +000011181
Eric Andersenc470f442003-07-28 09:56:35 +000011182 STPUTC('=', out);
11183 flags = 0;
11184 if (subtype == 0) {
11185 switch (c) {
11186 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011187 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011188#if ENABLE_ASH_BASH_COMPAT
11189 if (c == ':' || c == '$' || isdigit(c)) {
11190 pungetc();
11191 subtype = VSSUBSTR;
11192 break;
11193 }
11194#endif
11195 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011196 /*FALLTHROUGH*/
11197 default:
11198 p = strchr(types, c);
11199 if (p == NULL)
11200 goto badsub;
11201 subtype = p - types + VSNORMAL;
11202 break;
11203 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011204 case '#': {
11205 int cc = c;
11206 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11207 c = pgetc();
11208 if (c == cc)
11209 subtype++;
11210 else
11211 pungetc();
11212 break;
11213 }
11214#if ENABLE_ASH_BASH_COMPAT
11215 case '/':
11216 subtype = VSREPLACE;
11217 c = pgetc();
11218 if (c == '/')
11219 subtype++; /* VSREPLACEALL */
11220 else
11221 pungetc();
11222 break;
11223#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011224 }
Eric Andersenc470f442003-07-28 09:56:35 +000011225 } else {
11226 pungetc();
11227 }
11228 if (dblquote || arinest)
11229 flags |= VSQUOTE;
11230 *((char *)stackblock() + typeloc) = subtype | flags;
11231 if (subtype != VSNORMAL) {
11232 varnest++;
11233 if (dblquote || arinest) {
11234 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011235 }
11236 }
11237 }
Eric Andersenc470f442003-07-28 09:56:35 +000011238 goto parsesub_return;
11239}
Eric Andersencb57d552001-06-28 07:25:16 +000011240
Eric Andersencb57d552001-06-28 07:25:16 +000011241/*
11242 * Called to parse command substitutions. Newstyle is set if the command
11243 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11244 * list of commands (passed by reference), and savelen is the number of
11245 * characters on the top of the stack which must be preserved.
11246 */
Eric Andersenc470f442003-07-28 09:56:35 +000011247parsebackq: {
11248 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011249 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011250 union node *n;
11251 char *volatile str;
11252 struct jmploc jmploc;
11253 struct jmploc *volatile savehandler;
11254 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011255 smallint saveprompt = 0;
11256
Eric Andersencb57d552001-06-28 07:25:16 +000011257#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011258 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011259#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011260 savepbq = parsebackquote;
11261 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011262 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011263 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011264 exception_handler = savehandler;
11265 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011266 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011267 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011268 str = NULL;
11269 savelen = out - (char *)stackblock();
11270 if (savelen > 0) {
11271 str = ckmalloc(savelen);
11272 memcpy(str, stackblock(), savelen);
11273 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011274 savehandler = exception_handler;
11275 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011276 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011277 if (oldstyle) {
11278 /* We must read until the closing backquote, giving special
11279 treatment to some slashes, and then push the string and
11280 reread it as input, interpreting it normally. */
11281 char *pout;
11282 int pc;
11283 size_t psavelen;
11284 char *pstr;
11285
11286
11287 STARTSTACKSTR(pout);
11288 for (;;) {
11289 if (needprompt) {
11290 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011291 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011292 pc = pgetc();
11293 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011294 case '`':
11295 goto done;
11296
11297 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011298 pc = pgetc();
11299 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011300 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011301 if (doprompt)
11302 setprompt(2);
11303 /*
11304 * If eating a newline, avoid putting
11305 * the newline into the new character
11306 * stream (via the STPUTC after the
11307 * switch).
11308 */
11309 continue;
11310 }
11311 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011312 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011313 STPUTC('\\', pout);
11314 if (pc > PEOA_OR_PEOF) {
11315 break;
11316 }
11317 /* fall through */
11318
11319 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011320#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011321 case PEOA:
11322#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011323 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011324 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011325
11326 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011327 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011328 needprompt = doprompt;
11329 break;
11330
11331 default:
11332 break;
11333 }
11334 STPUTC(pc, pout);
11335 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011336 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011337 STPUTC('\0', pout);
11338 psavelen = pout - (char *)stackblock();
11339 if (psavelen > 0) {
11340 pstr = grabstackstr(pout);
11341 setinputstring(pstr);
11342 }
11343 }
11344 nlpp = &bqlist;
11345 while (*nlpp)
11346 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011347 *nlpp = stzalloc(sizeof(**nlpp));
11348 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011349 parsebackquote = oldstyle;
11350
11351 if (oldstyle) {
11352 saveprompt = doprompt;
11353 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011354 }
11355
Eric Andersenc470f442003-07-28 09:56:35 +000011356 n = list(2);
11357
11358 if (oldstyle)
11359 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011360 else if (readtoken() != TRP)
11361 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011362
11363 (*nlpp)->n = n;
11364 if (oldstyle) {
11365 /*
11366 * Start reading from old file again, ignoring any pushed back
11367 * tokens left from the backquote parsing
11368 */
11369 popfile();
11370 tokpushback = 0;
11371 }
11372 while (stackblocksize() <= savelen)
11373 growstackblock();
11374 STARTSTACKSTR(out);
11375 if (str) {
11376 memcpy(out, str, savelen);
11377 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011378 INT_OFF;
11379 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011380 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011381 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011382 }
11383 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011384 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011385 if (arinest || dblquote)
11386 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11387 else
11388 USTPUTC(CTLBACKQ, out);
11389 if (oldstyle)
11390 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011391 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011392}
11393
Mike Frysinger98c52642009-04-02 10:02:37 +000011394#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011395/*
11396 * Parse an arithmetic expansion (indicate start of one and set state)
11397 */
Eric Andersenc470f442003-07-28 09:56:35 +000011398parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011399 if (++arinest == 1) {
11400 prevsyntax = syntax;
11401 syntax = ARISYNTAX;
11402 USTPUTC(CTLARI, out);
11403 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011404 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011405 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011406 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011407 } else {
11408 /*
11409 * we collapse embedded arithmetic expansion to
11410 * parenthesis, which should be equivalent
11411 */
11412 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011413 }
Eric Andersenc470f442003-07-28 09:56:35 +000011414 goto parsearith_return;
11415}
11416#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011417
Eric Andersenc470f442003-07-28 09:56:35 +000011418} /* end of readtoken */
11419
Eric Andersencb57d552001-06-28 07:25:16 +000011420/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011421 * Read the next input token.
11422 * If the token is a word, we set backquotelist to the list of cmds in
11423 * backquotes. We set quoteflag to true if any part of the word was
11424 * quoted.
11425 * If the token is TREDIR, then we set redirnode to a structure containing
11426 * the redirection.
11427 * In all cases, the variable startlinno is set to the number of the line
11428 * on which the token starts.
11429 *
11430 * [Change comment: here documents and internal procedures]
11431 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11432 * word parsing code into a separate routine. In this case, readtoken
11433 * doesn't need to have any internal procedures, but parseword does.
11434 * We could also make parseoperator in essence the main routine, and
11435 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011436 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011437#define NEW_xxreadtoken
11438#ifdef NEW_xxreadtoken
11439/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011440static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011441 '\n', '(', ')', /* singles */
11442 '&', '|', ';', /* doubles */
11443 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011444};
Eric Andersencb57d552001-06-28 07:25:16 +000011445
Denis Vlasenko834dee72008-10-07 09:18:30 +000011446#define xxreadtoken_singles 3
11447#define xxreadtoken_doubles 3
11448
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011449static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011450 TNL, TLP, TRP, /* only single occurrence allowed */
11451 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11452 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011453 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011454};
11455
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011456static int
11457xxreadtoken(void)
11458{
11459 int c;
11460
11461 if (tokpushback) {
11462 tokpushback = 0;
11463 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011464 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011465 if (needprompt) {
11466 setprompt(2);
11467 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011468 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011469 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011470 c = pgetc_fast();
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011471 if (c == ' ' || c == '\t' USE_ASH_ALIAS( || c == PEOA))
11472 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011473
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011474 if (c == '#') {
11475 while ((c = pgetc()) != '\n' && c != PEOF)
11476 continue;
11477 pungetc();
11478 } else if (c == '\\') {
11479 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011480 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011481 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011482 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011483 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011484 if (doprompt)
11485 setprompt(2);
11486 } else {
11487 const char *p;
11488
11489 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11490 if (c != PEOF) {
11491 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011492 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011493 needprompt = doprompt;
11494 }
11495
11496 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011497 if (p == NULL)
11498 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011499
Denis Vlasenko834dee72008-10-07 09:18:30 +000011500 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11501 int cc = pgetc();
11502 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011503 p += xxreadtoken_doubles + 1;
11504 } else {
11505 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011506#if ENABLE_ASH_BASH_COMPAT
11507 if (c == '&' && cc == '>') /* &> */
11508 break; /* return readtoken1(...) */
11509#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011510 }
11511 }
11512 }
11513 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11514 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011515 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011516 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011517
11518 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011519}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011520#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011521#define RETURN(token) return lasttoken = token
11522static int
11523xxreadtoken(void)
11524{
11525 int c;
11526
11527 if (tokpushback) {
11528 tokpushback = 0;
11529 return lasttoken;
11530 }
11531 if (needprompt) {
11532 setprompt(2);
11533 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011534 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011535 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011536 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011537 switch (c) {
11538 case ' ': case '\t':
11539#if ENABLE_ASH_ALIAS
11540 case PEOA:
11541#endif
11542 continue;
11543 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011544 while ((c = pgetc()) != '\n' && c != PEOF)
11545 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011546 pungetc();
11547 continue;
11548 case '\\':
11549 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011550 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011551 if (doprompt)
11552 setprompt(2);
11553 continue;
11554 }
11555 pungetc();
11556 goto breakloop;
11557 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011558 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011559 needprompt = doprompt;
11560 RETURN(TNL);
11561 case PEOF:
11562 RETURN(TEOF);
11563 case '&':
11564 if (pgetc() == '&')
11565 RETURN(TAND);
11566 pungetc();
11567 RETURN(TBACKGND);
11568 case '|':
11569 if (pgetc() == '|')
11570 RETURN(TOR);
11571 pungetc();
11572 RETURN(TPIPE);
11573 case ';':
11574 if (pgetc() == ';')
11575 RETURN(TENDCASE);
11576 pungetc();
11577 RETURN(TSEMI);
11578 case '(':
11579 RETURN(TLP);
11580 case ')':
11581 RETURN(TRP);
11582 default:
11583 goto breakloop;
11584 }
11585 }
11586 breakloop:
11587 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11588#undef RETURN
11589}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011590#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591
11592static int
11593readtoken(void)
11594{
11595 int t;
11596#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011597 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011598#endif
11599
11600#if ENABLE_ASH_ALIAS
11601 top:
11602#endif
11603
11604 t = xxreadtoken();
11605
11606 /*
11607 * eat newlines
11608 */
11609 if (checkkwd & CHKNL) {
11610 while (t == TNL) {
11611 parseheredoc();
11612 t = xxreadtoken();
11613 }
11614 }
11615
11616 if (t != TWORD || quoteflag) {
11617 goto out;
11618 }
11619
11620 /*
11621 * check for keywords
11622 */
11623 if (checkkwd & CHKKWD) {
11624 const char *const *pp;
11625
11626 pp = findkwd(wordtext);
11627 if (pp) {
11628 lasttoken = t = pp - tokname_array;
11629 TRACE(("keyword %s recognized\n", tokname(t)));
11630 goto out;
11631 }
11632 }
11633
11634 if (checkkwd & CHKALIAS) {
11635#if ENABLE_ASH_ALIAS
11636 struct alias *ap;
11637 ap = lookupalias(wordtext, 1);
11638 if (ap != NULL) {
11639 if (*ap->val) {
11640 pushstring(ap->val, ap);
11641 }
11642 goto top;
11643 }
11644#endif
11645 }
11646 out:
11647 checkkwd = 0;
11648#if DEBUG
11649 if (!alreadyseen)
11650 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11651 else
11652 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11653#endif
11654 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011655}
11656
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011657static char
11658peektoken(void)
11659{
11660 int t;
11661
11662 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011663 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011664 return tokname_array[t][0];
11665}
Eric Andersencb57d552001-06-28 07:25:16 +000011666
11667/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011668 * Read and parse a command. Returns NEOF on end of file. (NULL is a
11669 * valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011670 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011671static union node *
11672parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011673{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011674 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011675
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011676 tokpushback = 0;
11677 doprompt = interact;
11678 if (doprompt)
11679 setprompt(doprompt);
11680 needprompt = 0;
11681 t = readtoken();
11682 if (t == TEOF)
11683 return NEOF;
11684 if (t == TNL)
11685 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011686 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011687 return list(1);
11688}
11689
11690/*
11691 * Input any here documents.
11692 */
11693static void
11694parseheredoc(void)
11695{
11696 struct heredoc *here;
11697 union node *n;
11698
11699 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011700 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011701
11702 while (here) {
11703 if (needprompt) {
11704 setprompt(2);
11705 }
11706 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11707 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011708 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011709 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011710 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011711 n->narg.text = wordtext;
11712 n->narg.backquote = backquotelist;
11713 here->here->nhere.doc = n;
11714 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011715 }
Eric Andersencb57d552001-06-28 07:25:16 +000011716}
11717
11718
11719/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011720 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011721 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011722#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011723static const char *
11724expandstr(const char *ps)
11725{
11726 union node n;
11727
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011728 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11729 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011730 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011731 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011732 popfile();
11733
11734 n.narg.type = NARG;
11735 n.narg.next = NULL;
11736 n.narg.text = wordtext;
11737 n.narg.backquote = backquotelist;
11738
11739 expandarg(&n, NULL, 0);
11740 return stackblock();
11741}
11742#endif
11743
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011744/*
11745 * Execute a command or commands contained in a string.
11746 */
11747static int
11748evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011749{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011750 union node *n;
11751 struct stackmark smark;
11752 int skip;
11753
11754 setinputstring(s);
11755 setstackmark(&smark);
11756
11757 skip = 0;
11758 while ((n = parsecmd(0)) != NEOF) {
11759 evaltree(n, 0);
11760 popstackmark(&smark);
11761 skip = evalskip;
11762 if (skip)
11763 break;
11764 }
11765 popfile();
11766
11767 skip &= mask;
11768 evalskip = skip;
11769 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011770}
11771
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011772/*
11773 * The eval command.
11774 */
11775static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011776evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011777{
11778 char *p;
11779 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011780
Denis Vlasenko68404f12008-03-17 09:00:54 +000011781 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011782 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011783 argv += 2;
11784 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011785 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011786 for (;;) {
11787 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011788 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011789 if (p == NULL)
11790 break;
11791 STPUTC(' ', concat);
11792 }
11793 STPUTC('\0', concat);
11794 p = grabstackstr(concat);
11795 }
11796 evalstring(p, ~SKIPEVAL);
11797
11798 }
11799 return exitstatus;
11800}
11801
11802/*
11803 * Read and execute commands. "Top" is nonzero for the top level command
11804 * loop; it turns on prompting if the shell is interactive.
11805 */
11806static int
11807cmdloop(int top)
11808{
11809 union node *n;
11810 struct stackmark smark;
11811 int inter;
11812 int numeof = 0;
11813
11814 TRACE(("cmdloop(%d) called\n", top));
11815 for (;;) {
11816 int skip;
11817
11818 setstackmark(&smark);
11819#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011820 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011821 showjobs(stderr, SHOW_CHANGED);
11822#endif
11823 inter = 0;
11824 if (iflag && top) {
11825 inter++;
11826#if ENABLE_ASH_MAIL
11827 chkmail();
11828#endif
11829 }
11830 n = parsecmd(inter);
11831 /* showtree(n); DEBUG */
11832 if (n == NEOF) {
11833 if (!top || numeof >= 50)
11834 break;
11835 if (!stoppedjobs()) {
11836 if (!Iflag)
11837 break;
11838 out2str("\nUse \"exit\" to leave shell.\n");
11839 }
11840 numeof++;
11841 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011842 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11843 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011844 numeof = 0;
11845 evaltree(n, 0);
11846 }
11847 popstackmark(&smark);
11848 skip = evalskip;
11849
11850 if (skip) {
11851 evalskip = 0;
11852 return skip & SKIPEVAL;
11853 }
11854 }
11855 return 0;
11856}
11857
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011858/*
11859 * Take commands from a file. To be compatible we should do a path
11860 * search for the file, which is necessary to find sub-commands.
11861 */
11862static char *
11863find_dot_file(char *name)
11864{
11865 char *fullname;
11866 const char *path = pathval();
11867 struct stat statb;
11868
11869 /* don't try this for absolute or relative paths */
11870 if (strchr(name, '/'))
11871 return name;
11872
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011873 /* IIRC standards do not say whether . is to be searched.
11874 * And it is even smaller this way, making it unconditional for now:
11875 */
11876 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11877 fullname = name;
11878 goto try_cur_dir;
11879 }
11880
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011881 while ((fullname = padvance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011882 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011883 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11884 /*
11885 * Don't bother freeing here, since it will
11886 * be freed by the caller.
11887 */
11888 return fullname;
11889 }
11890 stunalloc(fullname);
11891 }
11892
11893 /* not found in the PATH */
11894 ash_msg_and_raise_error("%s: not found", name);
11895 /* NOTREACHED */
11896}
11897
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011898static int
11899dotcmd(int argc, char **argv)
11900{
11901 struct strlist *sp;
11902 volatile struct shparam saveparam;
11903 int status = 0;
11904
11905 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011906 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011907
Denis Vlasenko68404f12008-03-17 09:00:54 +000011908 if (argv[1]) { /* That's what SVR2 does */
11909 char *fullname = find_dot_file(argv[1]);
11910 argv += 2;
11911 argc -= 2;
11912 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011913 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011914 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011915 shellparam.nparam = argc;
11916 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011917 };
11918
11919 setinputfile(fullname, INPUT_PUSH_FILE);
11920 commandname = fullname;
11921 cmdloop(0);
11922 popfile();
11923
Denis Vlasenko68404f12008-03-17 09:00:54 +000011924 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011925 freeparam(&shellparam);
11926 shellparam = saveparam;
11927 };
11928 status = exitstatus;
11929 }
11930 return status;
11931}
11932
11933static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011934exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011935{
11936 if (stoppedjobs())
11937 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011938 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011939 exitstatus = number(argv[1]);
11940 raise_exception(EXEXIT);
11941 /* NOTREACHED */
11942}
11943
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011944/*
11945 * Read a file containing shell functions.
11946 */
11947static void
11948readcmdfile(char *name)
11949{
11950 setinputfile(name, INPUT_PUSH_FILE);
11951 cmdloop(0);
11952 popfile();
11953}
11954
11955
Denis Vlasenkocc571512007-02-23 21:10:35 +000011956/* ============ find_command inplementation */
11957
11958/*
11959 * Resolve a command name. If you change this routine, you may have to
11960 * change the shellexec routine as well.
11961 */
11962static void
11963find_command(char *name, struct cmdentry *entry, int act, const char *path)
11964{
11965 struct tblentry *cmdp;
11966 int idx;
11967 int prev;
11968 char *fullname;
11969 struct stat statb;
11970 int e;
11971 int updatetbl;
11972 struct builtincmd *bcmd;
11973
11974 /* If name contains a slash, don't use PATH or hash table */
11975 if (strchr(name, '/') != NULL) {
11976 entry->u.index = -1;
11977 if (act & DO_ABS) {
11978 while (stat(name, &statb) < 0) {
11979#ifdef SYSV
11980 if (errno == EINTR)
11981 continue;
11982#endif
11983 entry->cmdtype = CMDUNKNOWN;
11984 return;
11985 }
11986 }
11987 entry->cmdtype = CMDNORMAL;
11988 return;
11989 }
11990
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011991/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011992
11993 updatetbl = (path == pathval());
11994 if (!updatetbl) {
11995 act |= DO_ALTPATH;
11996 if (strstr(path, "%builtin") != NULL)
11997 act |= DO_ALTBLTIN;
11998 }
11999
12000 /* If name is in the table, check answer will be ok */
12001 cmdp = cmdlookup(name, 0);
12002 if (cmdp != NULL) {
12003 int bit;
12004
12005 switch (cmdp->cmdtype) {
12006 default:
12007#if DEBUG
12008 abort();
12009#endif
12010 case CMDNORMAL:
12011 bit = DO_ALTPATH;
12012 break;
12013 case CMDFUNCTION:
12014 bit = DO_NOFUNC;
12015 break;
12016 case CMDBUILTIN:
12017 bit = DO_ALTBLTIN;
12018 break;
12019 }
12020 if (act & bit) {
12021 updatetbl = 0;
12022 cmdp = NULL;
12023 } else if (cmdp->rehash == 0)
12024 /* if not invalidated by cd, we're done */
12025 goto success;
12026 }
12027
12028 /* If %builtin not in path, check for builtin next */
12029 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012030 if (bcmd) {
12031 if (IS_BUILTIN_REGULAR(bcmd))
12032 goto builtin_success;
12033 if (act & DO_ALTPATH) {
12034 if (!(act & DO_ALTBLTIN))
12035 goto builtin_success;
12036 } else if (builtinloc <= 0) {
12037 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012038 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012039 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012040
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012041#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012042 {
12043 int applet_no = find_applet_by_name(name);
12044 if (applet_no >= 0) {
12045 entry->cmdtype = CMDNORMAL;
12046 entry->u.index = -2 - applet_no;
12047 return;
12048 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012049 }
12050#endif
12051
Denis Vlasenkocc571512007-02-23 21:10:35 +000012052 /* We have to search path. */
12053 prev = -1; /* where to start */
12054 if (cmdp && cmdp->rehash) { /* doing a rehash */
12055 if (cmdp->cmdtype == CMDBUILTIN)
12056 prev = builtinloc;
12057 else
12058 prev = cmdp->param.index;
12059 }
12060
12061 e = ENOENT;
12062 idx = -1;
12063 loop:
12064 while ((fullname = padvance(&path, name)) != NULL) {
12065 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012066 /* NB: code below will still use fullname
12067 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012068 idx++;
12069 if (pathopt) {
12070 if (prefix(pathopt, "builtin")) {
12071 if (bcmd)
12072 goto builtin_success;
12073 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012074 }
12075 if ((act & DO_NOFUNC)
12076 || !prefix(pathopt, "func")
12077 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012078 continue;
12079 }
12080 }
12081 /* if rehash, don't redo absolute path names */
12082 if (fullname[0] == '/' && idx <= prev) {
12083 if (idx < prev)
12084 continue;
12085 TRACE(("searchexec \"%s\": no change\n", name));
12086 goto success;
12087 }
12088 while (stat(fullname, &statb) < 0) {
12089#ifdef SYSV
12090 if (errno == EINTR)
12091 continue;
12092#endif
12093 if (errno != ENOENT && errno != ENOTDIR)
12094 e = errno;
12095 goto loop;
12096 }
12097 e = EACCES; /* if we fail, this will be the error */
12098 if (!S_ISREG(statb.st_mode))
12099 continue;
12100 if (pathopt) { /* this is a %func directory */
12101 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012102 /* NB: stalloc will return space pointed by fullname
12103 * (because we don't have any intervening allocations
12104 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012105 readcmdfile(fullname);
12106 cmdp = cmdlookup(name, 0);
12107 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12108 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12109 stunalloc(fullname);
12110 goto success;
12111 }
12112 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12113 if (!updatetbl) {
12114 entry->cmdtype = CMDNORMAL;
12115 entry->u.index = idx;
12116 return;
12117 }
12118 INT_OFF;
12119 cmdp = cmdlookup(name, 1);
12120 cmdp->cmdtype = CMDNORMAL;
12121 cmdp->param.index = idx;
12122 INT_ON;
12123 goto success;
12124 }
12125
12126 /* We failed. If there was an entry for this command, delete it */
12127 if (cmdp && updatetbl)
12128 delete_cmd_entry();
12129 if (act & DO_ERR)
12130 ash_msg("%s: %s", name, errmsg(e, "not found"));
12131 entry->cmdtype = CMDUNKNOWN;
12132 return;
12133
12134 builtin_success:
12135 if (!updatetbl) {
12136 entry->cmdtype = CMDBUILTIN;
12137 entry->u.cmd = bcmd;
12138 return;
12139 }
12140 INT_OFF;
12141 cmdp = cmdlookup(name, 1);
12142 cmdp->cmdtype = CMDBUILTIN;
12143 cmdp->param.cmd = bcmd;
12144 INT_ON;
12145 success:
12146 cmdp->rehash = 0;
12147 entry->cmdtype = cmdp->cmdtype;
12148 entry->u = cmdp->param;
12149}
12150
12151
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012152/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012153
Eric Andersencb57d552001-06-28 07:25:16 +000012154/*
Eric Andersencb57d552001-06-28 07:25:16 +000012155 * The trap builtin.
12156 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012157static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012158trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012159{
12160 char *action;
12161 char **ap;
12162 int signo;
12163
Eric Andersenc470f442003-07-28 09:56:35 +000012164 nextopt(nullstr);
12165 ap = argptr;
12166 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012167 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000012168 if (trap[signo] != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012169 out1fmt("trap -- %s %s\n",
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012170 single_quote(trap[signo]),
12171 get_signame(signo));
Eric Andersencb57d552001-06-28 07:25:16 +000012172 }
12173 }
12174 return 0;
12175 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012176 action = NULL;
12177 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012178 action = *ap++;
12179 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012180 signo = get_signum(*ap);
12181 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012182 ash_msg_and_raise_error("%s: bad trap", *ap);
12183 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012184 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012185 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012186 action = NULL;
12187 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012188 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012189 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012190 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012191 trap[signo] = action;
12192 if (signo != 0)
12193 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012194 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012195 ap++;
12196 }
12197 return 0;
12198}
12199
Eric Andersenc470f442003-07-28 09:56:35 +000012200
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012201/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012202
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012203#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012204/*
12205 * Lists available builtins
12206 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012207static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012208helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012209{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012210 unsigned col;
12211 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012212
12213 out1fmt("\nBuilt-in commands:\n-------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012214 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012215 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012216 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012217 if (col > 60) {
12218 out1fmt("\n");
12219 col = 0;
12220 }
12221 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012222#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012223 {
12224 const char *a = applet_names;
12225 while (*a) {
12226 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12227 if (col > 60) {
12228 out1fmt("\n");
12229 col = 0;
12230 }
12231 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012232 }
12233 }
12234#endif
12235 out1fmt("\n\n");
12236 return EXIT_SUCCESS;
12237}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012238#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012239
Eric Andersencb57d552001-06-28 07:25:16 +000012240/*
Eric Andersencb57d552001-06-28 07:25:16 +000012241 * The export and readonly commands.
12242 */
Eric Andersenc470f442003-07-28 09:56:35 +000012243static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012244exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012245{
12246 struct var *vp;
12247 char *name;
12248 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012249 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012250 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012251
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012252 if (nextopt("p") != 'p') {
12253 aptr = argptr;
12254 name = *aptr;
12255 if (name) {
12256 do {
12257 p = strchr(name, '=');
12258 if (p != NULL) {
12259 p++;
12260 } else {
12261 vp = *findvar(hashvar(name), name);
12262 if (vp) {
12263 vp->flags |= flag;
12264 continue;
12265 }
Eric Andersencb57d552001-06-28 07:25:16 +000012266 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012267 setvar(name, p, flag);
12268 } while ((name = *++aptr) != NULL);
12269 return 0;
12270 }
Eric Andersencb57d552001-06-28 07:25:16 +000012271 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012272 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012273 return 0;
12274}
12275
Eric Andersencb57d552001-06-28 07:25:16 +000012276/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012277 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012278 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012279static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012280unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012281{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012282 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012283
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012284 cmdp = cmdlookup(name, 0);
12285 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12286 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012287}
12288
Eric Andersencb57d552001-06-28 07:25:16 +000012289/*
Eric Andersencb57d552001-06-28 07:25:16 +000012290 * The unset builtin command. We unset the function before we unset the
12291 * variable to allow a function to be unset when there is a readonly variable
12292 * with the same name.
12293 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012294static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012295unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012296{
12297 char **ap;
12298 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012299 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012300 int ret = 0;
12301
12302 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012303 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012304 }
Eric Andersencb57d552001-06-28 07:25:16 +000012305
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012306 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012307 if (flag != 'f') {
12308 i = unsetvar(*ap);
12309 ret |= i;
12310 if (!(i & 2))
12311 continue;
12312 }
12313 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012314 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012315 }
Eric Andersenc470f442003-07-28 09:56:35 +000012316 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012317}
12318
12319
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012320/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012321
Eric Andersenc470f442003-07-28 09:56:35 +000012322#include <sys/times.h>
12323
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012324static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012325 ' ', offsetof(struct tms, tms_utime),
12326 '\n', offsetof(struct tms, tms_stime),
12327 ' ', offsetof(struct tms, tms_cutime),
12328 '\n', offsetof(struct tms, tms_cstime),
12329 0
12330};
Eric Andersencb57d552001-06-28 07:25:16 +000012331
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012332static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012333timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012334{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012335 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012336 const unsigned char *p;
12337 struct tms buf;
12338
12339 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012340 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012341
12342 p = timescmd_str;
12343 do {
12344 t = *(clock_t *)(((char *) &buf) + p[1]);
12345 s = t / clk_tck;
12346 out1fmt("%ldm%ld.%.3lds%c",
12347 s/60, s%60,
12348 ((t - s * clk_tck) * 1000) / clk_tck,
12349 p[0]);
12350 } while (*(p += 2));
12351
Eric Andersencb57d552001-06-28 07:25:16 +000012352 return 0;
12353}
12354
Mike Frysinger98c52642009-04-02 10:02:37 +000012355#if ENABLE_SH_MATH_SUPPORT
Eric Andersened9ecf72004-06-22 08:29:45 +000012356static arith_t
Eric Andersenc470f442003-07-28 09:56:35 +000012357dash_arith(const char *s)
Eric Andersen74bcd162001-07-30 21:41:37 +000012358{
Eric Andersened9ecf72004-06-22 08:29:45 +000012359 arith_t result;
Eric Andersenc470f442003-07-28 09:56:35 +000012360 int errcode = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000012361
Denis Vlasenkob012b102007-02-19 22:43:01 +000012362 INT_OFF;
Mike Frysinger98c52642009-04-02 10:02:37 +000012363 result = arith(s, &errcode, &math_hooks);
Eric Andersenc470f442003-07-28 09:56:35 +000012364 if (errcode < 0) {
Eric Andersen90898442003-08-06 11:20:52 +000012365 if (errcode == -3)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012366 ash_msg_and_raise_error("exponent less than 0");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012367 if (errcode == -2)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012368 ash_msg_and_raise_error("divide by zero");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012369 if (errcode == -5)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012370 ash_msg_and_raise_error("expression recursion loop detected");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012371 raise_error_syntax(s);
Eric Andersenc470f442003-07-28 09:56:35 +000012372 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012373 INT_ON;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000012374
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012375 return result;
Eric Andersen74bcd162001-07-30 21:41:37 +000012376}
Eric Andersenc470f442003-07-28 09:56:35 +000012377
Eric Andersenc470f442003-07-28 09:56:35 +000012378/*
Eric Andersen90898442003-08-06 11:20:52 +000012379 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12380 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12381 *
12382 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012383 */
12384static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012385letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012386{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012387 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012388
Denis Vlasenko68404f12008-03-17 09:00:54 +000012389 argv++;
12390 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012391 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012392 do {
12393 i = dash_arith(*argv);
12394 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012395
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012396 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012397}
Mike Frysinger98c52642009-04-02 10:02:37 +000012398#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012399
Eric Andersenc470f442003-07-28 09:56:35 +000012400
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012401/* ============ miscbltin.c
12402 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012403 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012404 */
12405
12406#undef rflag
12407
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012408#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012409typedef enum __rlimit_resource rlim_t;
12410#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012411
Eric Andersenc470f442003-07-28 09:56:35 +000012412/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012413 * The read builtin. Options:
12414 * -r Do not interpret '\' specially
12415 * -s Turn off echo (tty only)
12416 * -n NCHARS Read NCHARS max
12417 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12418 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12419 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012420 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012421 * TODO: bash also has:
12422 * -a ARRAY Read into array[0],[1],etc
12423 * -d DELIM End on DELIM char, not newline
12424 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012425 */
Eric Andersenc470f442003-07-28 09:56:35 +000012426static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012427readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012428{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012429 static const char *const arg_REPLY[] = { "REPLY", NULL };
12430
Eric Andersenc470f442003-07-28 09:56:35 +000012431 char **ap;
12432 int backslash;
12433 char c;
12434 int rflag;
12435 char *prompt;
12436 const char *ifs;
12437 char *p;
12438 int startword;
12439 int status;
12440 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012441 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012442#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012443 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012444 int silent = 0;
12445 struct termios tty, old_tty;
12446#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012447#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012448 unsigned end_ms = 0;
12449 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012450#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012451
12452 rflag = 0;
12453 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012454 while ((i = nextopt("p:u:r"
12455 USE_ASH_READ_TIMEOUT("t:")
12456 USE_ASH_READ_NCHARS("n:s")
12457 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012458 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012459 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012460 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012461 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012462#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012463 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012464 nchars = bb_strtou(optionarg, NULL, 10);
12465 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012466 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012467 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012468 break;
12469 case 's':
12470 silent = 1;
12471 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012472#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012473#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012474 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012475 timeout = bb_strtou(optionarg, NULL, 10);
12476 if (errno || timeout > UINT_MAX / 2048)
12477 ash_msg_and_raise_error("invalid timeout");
12478 timeout *= 1000;
12479#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012480 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012481 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012482 /* EINVAL means number is ok, but not terminated by NUL */
12483 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012484 char *p2;
12485 if (*++p) {
12486 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012487 ts.tv_usec = bb_strtou(p, &p2, 10);
12488 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012489 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012490 scale = p2 - p;
12491 /* normalize to usec */
12492 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012493 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012494 while (scale++ < 6)
12495 ts.tv_usec *= 10;
12496 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012497 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012498 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012499 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012500 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012501 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012502 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012503#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012504 break;
12505#endif
12506 case 'r':
12507 rflag = 1;
12508 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012509 case 'u':
12510 fd = bb_strtou(optionarg, NULL, 10);
12511 if (fd < 0 || errno)
12512 ash_msg_and_raise_error("invalid file descriptor");
12513 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012514 default:
12515 break;
12516 }
Eric Andersenc470f442003-07-28 09:56:35 +000012517 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012518 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012519 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012520 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012521 ap = argptr;
12522 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012523 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012524 ifs = bltinlookup("IFS");
12525 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012526 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012527#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012528 tcgetattr(fd, &tty);
12529 old_tty = tty;
12530 if (nchars || silent) {
12531 if (nchars) {
12532 tty.c_lflag &= ~ICANON;
12533 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012534 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012535 if (silent) {
12536 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12537 }
12538 /* if tcgetattr failed, tcsetattr will fail too.
12539 * Ignoring, it's harmless. */
12540 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012541 }
12542#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012543
Eric Andersenc470f442003-07-28 09:56:35 +000012544 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012545 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012546 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012547#if ENABLE_ASH_READ_TIMEOUT
12548 if (timeout) /* NB: ensuring end_ms is nonzero */
12549 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12550#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012551 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012552 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012553 const char *is_ifs;
12554
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012555#if ENABLE_ASH_READ_TIMEOUT
12556 if (end_ms) {
12557 struct pollfd pfd[1];
12558 pfd[0].fd = fd;
12559 pfd[0].events = POLLIN;
12560 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12561 if ((int)timeout <= 0 /* already late? */
12562 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12563 ) { /* timed out! */
12564#if ENABLE_ASH_READ_NCHARS
12565 tcsetattr(fd, TCSANOW, &old_tty);
12566#endif
12567 return 1;
12568 }
12569 }
12570#endif
12571 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012572 status = 1;
12573 break;
12574 }
12575 if (c == '\0')
12576 continue;
12577 if (backslash) {
12578 backslash = 0;
12579 if (c != '\n')
12580 goto put;
12581 continue;
12582 }
12583 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012584 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012585 continue;
12586 }
12587 if (c == '\n')
12588 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012589 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012590/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012591 is_ifs = strchr(ifs, c);
12592 if (startword && is_ifs) {
12593 if (isspace(c))
12594 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012595 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012596 startword--;
12597 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012598 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012599 }
12600 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012601 if (ap[1] != NULL && is_ifs) {
12602 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012603 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012604 beg = stackblock();
12605 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012606 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012607 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012608 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012609 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012610 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012611 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012612 put:
12613 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012614 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012615/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012616#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012617 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012618#else
12619 while (1);
12620#endif
12621
12622#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012623 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012624#endif
12625
Eric Andersenc470f442003-07-28 09:56:35 +000012626 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012627 /* Remove trailing space ifs chars */
12628 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012629 *p = '\0';
12630 setvar(*ap, stackblock(), 0);
12631 while (*++ap != NULL)
12632 setvar(*ap, nullstr, 0);
12633 return status;
12634}
12635
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012636static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012637umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012638{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012639 static const char permuser[3] ALIGN1 = "ugo";
12640 static const char permmode[3] ALIGN1 = "rwx";
12641 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012642 S_IRUSR, S_IWUSR, S_IXUSR,
12643 S_IRGRP, S_IWGRP, S_IXGRP,
12644 S_IROTH, S_IWOTH, S_IXOTH
12645 };
12646
12647 char *ap;
12648 mode_t mask;
12649 int i;
12650 int symbolic_mode = 0;
12651
12652 while (nextopt("S") != '\0') {
12653 symbolic_mode = 1;
12654 }
12655
Denis Vlasenkob012b102007-02-19 22:43:01 +000012656 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012657 mask = umask(0);
12658 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012659 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012660
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012661 ap = *argptr;
12662 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012663 if (symbolic_mode) {
12664 char buf[18];
12665 char *p = buf;
12666
12667 for (i = 0; i < 3; i++) {
12668 int j;
12669
12670 *p++ = permuser[i];
12671 *p++ = '=';
12672 for (j = 0; j < 3; j++) {
12673 if ((mask & permmask[3 * i + j]) == 0) {
12674 *p++ = permmode[j];
12675 }
12676 }
12677 *p++ = ',';
12678 }
12679 *--p = 0;
12680 puts(buf);
12681 } else {
12682 out1fmt("%.4o\n", mask);
12683 }
12684 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012685 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012686 mask = 0;
12687 do {
12688 if (*ap >= '8' || *ap < '0')
Denis Vlasenkob012b102007-02-19 22:43:01 +000012689 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012690 mask = (mask << 3) + (*ap - '0');
12691 } while (*++ap != '\0');
12692 umask(mask);
12693 } else {
12694 mask = ~mask & 0777;
12695 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012696 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012697 }
12698 umask(~mask & 0777);
12699 }
12700 }
12701 return 0;
12702}
12703
12704/*
12705 * ulimit builtin
12706 *
12707 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12708 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12709 * ash by J.T. Conklin.
12710 *
12711 * Public domain.
12712 */
12713
12714struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012715 uint8_t cmd; /* RLIMIT_xxx fit into it */
12716 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012717 char option;
12718};
12719
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012720static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012721#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012722 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012723#endif
12724#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012725 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012726#endif
12727#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012728 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012729#endif
12730#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012731 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012732#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012733#ifdef RLIMIT_CORE
12734 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012735#endif
12736#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012737 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012738#endif
12739#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012740 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012741#endif
12742#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012743 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012744#endif
12745#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012746 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012747#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012748#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012749 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012750#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012751#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012752 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012753#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012754};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012755static const char limits_name[] =
12756#ifdef RLIMIT_CPU
12757 "time(seconds)" "\0"
12758#endif
12759#ifdef RLIMIT_FSIZE
12760 "file(blocks)" "\0"
12761#endif
12762#ifdef RLIMIT_DATA
12763 "data(kb)" "\0"
12764#endif
12765#ifdef RLIMIT_STACK
12766 "stack(kb)" "\0"
12767#endif
12768#ifdef RLIMIT_CORE
12769 "coredump(blocks)" "\0"
12770#endif
12771#ifdef RLIMIT_RSS
12772 "memory(kb)" "\0"
12773#endif
12774#ifdef RLIMIT_MEMLOCK
12775 "locked memory(kb)" "\0"
12776#endif
12777#ifdef RLIMIT_NPROC
12778 "process" "\0"
12779#endif
12780#ifdef RLIMIT_NOFILE
12781 "nofiles" "\0"
12782#endif
12783#ifdef RLIMIT_AS
12784 "vmemory(kb)" "\0"
12785#endif
12786#ifdef RLIMIT_LOCKS
12787 "locks" "\0"
12788#endif
12789;
Eric Andersenc470f442003-07-28 09:56:35 +000012790
Glenn L McGrath76620622004-01-13 10:19:37 +000012791enum limtype { SOFT = 0x1, HARD = 0x2 };
12792
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012793static void
12794printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012795 const struct limits *l)
12796{
12797 rlim_t val;
12798
12799 val = limit->rlim_max;
12800 if (how & SOFT)
12801 val = limit->rlim_cur;
12802
12803 if (val == RLIM_INFINITY)
12804 out1fmt("unlimited\n");
12805 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012806 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012807 out1fmt("%lld\n", (long long) val);
12808 }
12809}
12810
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012811static int
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012812ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012813{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012814 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012815 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012816 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012817 const struct limits *l;
12818 int set, all = 0;
12819 int optc, what;
12820 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012821
12822 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012823 while ((optc = nextopt("HSa"
12824#ifdef RLIMIT_CPU
12825 "t"
12826#endif
12827#ifdef RLIMIT_FSIZE
12828 "f"
12829#endif
12830#ifdef RLIMIT_DATA
12831 "d"
12832#endif
12833#ifdef RLIMIT_STACK
12834 "s"
12835#endif
12836#ifdef RLIMIT_CORE
12837 "c"
12838#endif
12839#ifdef RLIMIT_RSS
12840 "m"
12841#endif
12842#ifdef RLIMIT_MEMLOCK
12843 "l"
12844#endif
12845#ifdef RLIMIT_NPROC
12846 "p"
12847#endif
12848#ifdef RLIMIT_NOFILE
12849 "n"
12850#endif
12851#ifdef RLIMIT_AS
12852 "v"
12853#endif
12854#ifdef RLIMIT_LOCKS
12855 "w"
12856#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012857 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012858 switch (optc) {
12859 case 'H':
12860 how = HARD;
12861 break;
12862 case 'S':
12863 how = SOFT;
12864 break;
12865 case 'a':
12866 all = 1;
12867 break;
12868 default:
12869 what = optc;
12870 }
12871
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012872 for (l = limits_tbl; l->option != what; l++)
12873 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012874
12875 set = *argptr ? 1 : 0;
12876 if (set) {
12877 char *p = *argptr;
12878
12879 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012880 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012881 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012882 val = RLIM_INFINITY;
12883 else {
12884 val = (rlim_t) 0;
12885
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012886 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012887 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012888 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012889 if (val < (rlim_t) 0)
12890 break;
12891 }
12892 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012893 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012894 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012895 }
12896 }
12897 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012898 const char *lname = limits_name;
12899 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012900 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012901 out1fmt("%-20s ", lname);
12902 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012903 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012904 }
12905 return 0;
12906 }
12907
12908 getrlimit(l->cmd, &limit);
12909 if (set) {
12910 if (how & HARD)
12911 limit.rlim_max = val;
12912 if (how & SOFT)
12913 limit.rlim_cur = val;
12914 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012915 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012916 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012917 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012918 }
12919 return 0;
12920}
12921
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012922/* ============ main() and helpers */
12923
12924/*
12925 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012926 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012927static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012928static void
12929exitshell(void)
12930{
12931 struct jmploc loc;
12932 char *p;
12933 int status;
12934
12935 status = exitstatus;
12936 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12937 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012938 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012939/* dash bug: it just does _exit(exitstatus) here
12940 * but we have to do setjobctl(0) first!
12941 * (bug is still not fixed in dash-0.5.3 - if you run dash
12942 * under Midnight Commander, on exit from dash MC is backgrounded) */
12943 status = exitstatus;
12944 goto out;
12945 }
12946 exception_handler = &loc;
12947 p = trap[0];
12948 if (p) {
12949 trap[0] = NULL;
12950 evalstring(p, 0);
12951 }
12952 flush_stdout_stderr();
12953 out:
12954 setjobctl(0);
12955 _exit(status);
12956 /* NOTREACHED */
12957}
12958
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012959static void
12960init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012961{
12962 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012963 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012964
12965 /* from trap.c: */
12966 signal(SIGCHLD, SIG_DFL);
12967
12968 /* from var.c: */
12969 {
12970 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012971 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012972 const char *p;
12973 struct stat st1, st2;
12974
12975 initvar();
12976 for (envp = environ; envp && *envp; envp++) {
12977 if (strchr(*envp, '=')) {
12978 setvareq(*envp, VEXPORT|VTEXTFIXED);
12979 }
12980 }
12981
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012982 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012983 setvar("PPID", ppid, 0);
12984
12985 p = lookupvar("PWD");
12986 if (p)
12987 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12988 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12989 p = '\0';
12990 setpwd(p, 0);
12991 }
12992}
12993
12994/*
12995 * Process the shell command line arguments.
12996 */
12997static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012998procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012999{
13000 int i;
13001 const char *xminusc;
13002 char **xargv;
13003
13004 xargv = argv;
13005 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013006 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013007 xargv++;
13008 for (i = 0; i < NOPTS; i++)
13009 optlist[i] = 2;
13010 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013011 if (options(1)) {
13012 /* it already printed err message */
13013 raise_exception(EXERROR);
13014 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013015 xargv = argptr;
13016 xminusc = minusc;
13017 if (*xargv == NULL) {
13018 if (xminusc)
13019 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13020 sflag = 1;
13021 }
13022 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13023 iflag = 1;
13024 if (mflag == 2)
13025 mflag = iflag;
13026 for (i = 0; i < NOPTS; i++)
13027 if (optlist[i] == 2)
13028 optlist[i] = 0;
13029#if DEBUG == 2
13030 debug = 1;
13031#endif
13032 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13033 if (xminusc) {
13034 minusc = *xargv++;
13035 if (*xargv)
13036 goto setarg0;
13037 } else if (!sflag) {
13038 setinputfile(*xargv, 0);
13039 setarg0:
13040 arg0 = *xargv++;
13041 commandname = arg0;
13042 }
13043
13044 shellparam.p = xargv;
13045#if ENABLE_ASH_GETOPTS
13046 shellparam.optind = 1;
13047 shellparam.optoff = -1;
13048#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013049 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013050 while (*xargv) {
13051 shellparam.nparam++;
13052 xargv++;
13053 }
13054 optschanged();
13055}
13056
13057/*
13058 * Read /etc/profile or .profile.
13059 */
13060static void
13061read_profile(const char *name)
13062{
13063 int skip;
13064
13065 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13066 return;
13067 skip = cmdloop(0);
13068 popfile();
13069 if (skip)
13070 exitshell();
13071}
13072
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013073/*
13074 * This routine is called when an error or an interrupt occurs in an
13075 * interactive shell and control is returned to the main command loop.
13076 */
13077static void
13078reset(void)
13079{
13080 /* from eval.c: */
13081 evalskip = 0;
13082 loopnest = 0;
13083 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013084 g_parsefile->left_in_buffer = 0;
13085 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013086 popallfiles();
13087 /* from parser.c: */
13088 tokpushback = 0;
13089 checkkwd = 0;
13090 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013091 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013092}
13093
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013094#if PROFILE
13095static short profile_buf[16384];
13096extern int etext();
13097#endif
13098
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013099/*
13100 * Main routine. We initialize things, parse the arguments, execute
13101 * profiles if we're a login shell, and then call cmdloop to execute
13102 * commands. The setjmp call sets up the location to jump to when an
13103 * exception occurs. When an exception occurs the variable "state"
13104 * is used to figure out how far we had gotten.
13105 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013106int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013107int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013108{
Mike Frysinger98c52642009-04-02 10:02:37 +000013109 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013110 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013111 struct jmploc jmploc;
13112 struct stackmark smark;
13113
Denis Vlasenko01631112007-12-16 17:20:38 +000013114 /* Initialize global data */
13115 INIT_G_misc();
13116 INIT_G_memstack();
13117 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013118#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013119 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013120#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013121 INIT_G_cmdtable();
Mike Frysinger98c52642009-04-02 10:02:37 +000013122#if ENABLE_SH_MATH_SUPPORT
13123 math_hooks.lookupvar = lookupvar;
13124 math_hooks.setvar = setvar;
13125 math_hooks.endofname = endofname;
13126#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013127
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013128#if PROFILE
13129 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13130#endif
13131
13132#if ENABLE_FEATURE_EDITING
13133 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13134#endif
13135 state = 0;
13136 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013137 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013138 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013139
13140 reset();
13141
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013142 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013143 if (e == EXERROR)
13144 exitstatus = 2;
13145 s = state;
13146 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13147 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013148 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013149 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013150
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013151 popstackmark(&smark);
13152 FORCE_INT_ON; /* enable interrupts */
13153 if (s == 1)
13154 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013155 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013156 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013157 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013158 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013159 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013160 }
13161 exception_handler = &jmploc;
13162#if DEBUG
13163 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013164 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013165 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013166#endif
13167 rootpid = getpid();
13168
13169#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013170 /* Can use monotonic_ns() for better randomness but for now it is
13171 * not used anywhere else in busybox... so avoid bloat */
13172 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013173#endif
13174 init();
13175 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013176 procargs(argv);
13177
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013178#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13179 if (iflag) {
13180 const char *hp = lookupvar("HISTFILE");
13181
13182 if (hp == NULL) {
13183 hp = lookupvar("HOME");
13184 if (hp != NULL) {
13185 char *defhp = concat_path_file(hp, ".ash_history");
13186 setvar("HISTFILE", defhp, 0);
13187 free(defhp);
13188 }
13189 }
13190 }
13191#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013192 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013193 isloginsh = 1;
13194 if (isloginsh) {
13195 state = 1;
13196 read_profile("/etc/profile");
13197 state1:
13198 state = 2;
13199 read_profile(".profile");
13200 }
13201 state2:
13202 state = 3;
13203 if (
13204#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013205 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013206#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013207 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013208 ) {
13209 shinit = lookupvar("ENV");
13210 if (shinit != NULL && *shinit != '\0') {
13211 read_profile(shinit);
13212 }
13213 }
13214 state3:
13215 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013216 if (minusc) {
13217 /* evalstring pushes parsefile stack.
13218 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013219 * is one of stacked source fds.
13220 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013221 if (!sflag)
13222 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013223 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013224 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013225
13226 if (sflag || minusc == NULL) {
13227#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013228 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013229 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013230 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013231 line_input_state->hist_file = hp;
13232 }
13233#endif
13234 state4: /* XXX ??? - why isn't this before the "if" statement */
13235 cmdloop(1);
13236 }
13237#if PROFILE
13238 monitor(0);
13239#endif
13240#ifdef GPROF
13241 {
13242 extern void _mcleanup(void);
13243 _mcleanup();
13244 }
13245#endif
13246 exitshell();
13247 /* NOTREACHED */
13248}
13249
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013250
Eric Andersendf82f612001-06-28 07:46:40 +000013251/*-
13252 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013253 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013254 *
13255 * This code is derived from software contributed to Berkeley by
13256 * Kenneth Almquist.
13257 *
13258 * Redistribution and use in source and binary forms, with or without
13259 * modification, are permitted provided that the following conditions
13260 * are met:
13261 * 1. Redistributions of source code must retain the above copyright
13262 * notice, this list of conditions and the following disclaimer.
13263 * 2. Redistributions in binary form must reproduce the above copyright
13264 * notice, this list of conditions and the following disclaimer in the
13265 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013266 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013267 * may be used to endorse or promote products derived from this software
13268 * without specific prior written permission.
13269 *
13270 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13271 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13272 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13273 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13274 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13275 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13276 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13277 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13278 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13279 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13280 * SUCH DAMAGE.
13281 */