blob: 5671a524b44795fff63669c4a69dcf5b99b94081 [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020016 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000039#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000040#include <paths.h>
41#include <setjmp.h>
42#include <fnmatch.h>
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020043#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010044
45#include "shell_common.h"
Denys Vlasenko26777aa2010-11-22 23:49:10 +010046#if ENABLE_SH_MATH_SUPPORT
47# include "math.h"
48#endif
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020049#if ENABLE_ASH_RANDOM_SUPPORT
50# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020051#else
52# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020053#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000054
Denys Vlasenko1fcbff22010-06-26 02:40:08 +020055#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +010056#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000057/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020058# undef CONFIG_FEATURE_SH_STANDALONE
59# undef ENABLE_FEATURE_SH_STANDALONE
60# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010061# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020062# define ENABLE_FEATURE_SH_STANDALONE 0
63# define IF_FEATURE_SH_STANDALONE(...)
64# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000065#endif
66
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000067#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000068# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000069#endif
70
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010071#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000072# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000073#endif
74
Denys Vlasenko771f1992010-07-16 14:31:34 +020075//applet:IF_ASH(APPLET(ash, _BB_DIR_BIN, _BB_SUID_DROP))
76//applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, _BB_DIR_BIN, _BB_SUID_DROP, sh))
77//applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, _BB_DIR_BIN, _BB_SUID_DROP, bash))
78
Denys Vlasenkod383b492010-09-06 10:22:13 +020079//kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
Denys Vlasenko771f1992010-07-16 14:31:34 +020080//kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
81
82//config:config ASH
83//config: bool "ash"
84//config: default y
85//config: depends on !NOMMU
86//config: help
87//config: Tha 'ash' shell adds about 60k in the default configuration and is
88//config: the most complete and most pedantically correct shell included with
89//config: busybox. This shell is actually a derivative of the Debian 'dash'
90//config: shell (by Herbert Xu), which was created by porting the 'ash' shell
91//config: (written by Kenneth Almquist) from NetBSD.
92//config:
93//config:config ASH_BASH_COMPAT
94//config: bool "bash-compatible extensions"
95//config: default y
96//config: depends on ASH
97//config: help
98//config: Enable bash-compatible extensions.
99//config:
100//config:config ASH_JOB_CONTROL
101//config: bool "Job control"
102//config: default y
103//config: depends on ASH
104//config: help
105//config: Enable job control in the ash shell.
106//config:
107//config:config ASH_ALIAS
108//config: bool "alias support"
109//config: default y
110//config: depends on ASH
111//config: help
112//config: Enable alias support in the ash shell.
113//config:
114//config:config ASH_GETOPTS
115//config: bool "Builtin getopt to parse positional parameters"
116//config: default y
117//config: depends on ASH
118//config: help
119//config: Enable getopts builtin in the ash shell.
120//config:
121//config:config ASH_BUILTIN_ECHO
122//config: bool "Builtin version of 'echo'"
123//config: default y
124//config: depends on ASH
125//config: help
126//config: Enable support for echo, builtin to ash.
127//config:
128//config:config ASH_BUILTIN_PRINTF
129//config: bool "Builtin version of 'printf'"
130//config: default y
131//config: depends on ASH
132//config: help
133//config: Enable support for printf, builtin to ash.
134//config:
135//config:config ASH_BUILTIN_TEST
136//config: bool "Builtin version of 'test'"
137//config: default y
138//config: depends on ASH
139//config: help
140//config: Enable support for test, builtin to ash.
141//config:
142//config:config ASH_CMDCMD
143//config: bool "'command' command to override shell builtins"
144//config: default y
145//config: depends on ASH
146//config: help
147//config: Enable support for the ash 'command' builtin, which allows
148//config: you to run the specified command with the specified arguments,
149//config: even when there is an ash builtin command with the same name.
150//config:
151//config:config ASH_MAIL
152//config: bool "Check for new mail on interactive shells"
153//config: default n
154//config: depends on ASH
155//config: help
156//config: Enable "check for new mail" in the ash shell.
157//config:
158//config:config ASH_OPTIMIZE_FOR_SIZE
159//config: bool "Optimize for size instead of speed"
160//config: default y
161//config: depends on ASH
162//config: help
163//config: Compile ash for reduced size at the price of speed.
164//config:
165//config:config ASH_RANDOM_SUPPORT
166//config: bool "Pseudorandom generator and $RANDOM variable"
167//config: default y
168//config: depends on ASH
169//config: help
170//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
171//config: Each read of "$RANDOM" will generate a new pseudorandom value.
172//config: You can reset the generator by using a specified start value.
173//config: After "unset RANDOM" the generator will switch off and this
174//config: variable will no longer have special treatment.
175//config:
176//config:config ASH_EXPAND_PRMT
177//config: bool "Expand prompt string"
178//config: default y
179//config: depends on ASH
180//config: help
181//config: "PS#" may contain volatile content, such as backquote commands.
182//config: This option recreates the prompt string from the environment
183//config: variable each time it is displayed.
Denys Vlasenko51ca7762010-07-16 17:16:40 +0200184//config:
Denys Vlasenko771f1992010-07-16 14:31:34 +0200185
186//usage:#define ash_trivial_usage NOUSAGE_STR
187//usage:#define ash_full_usage ""
188//usage:#define sh_trivial_usage NOUSAGE_STR
189//usage:#define sh_full_usage ""
190//usage:#define bash_trivial_usage NOUSAGE_STR
191//usage:#define bash_full_usage ""
192
Denis Vlasenkob012b102007-02-19 22:43:01 +0000193
Denis Vlasenko01631112007-12-16 17:20:38 +0000194/* ============ Hash table sizes. Configurable. */
195
196#define VTABSIZE 39
197#define ATABSIZE 39
198#define CMDTABLESIZE 31 /* should be prime */
199
200
Denis Vlasenkob012b102007-02-19 22:43:01 +0000201/* ============ Shell options */
202
203static const char *const optletters_optnames[] = {
204 "e" "errexit",
205 "f" "noglob",
206 "I" "ignoreeof",
207 "i" "interactive",
208 "m" "monitor",
209 "n" "noexec",
210 "s" "stdin",
211 "x" "xtrace",
212 "v" "verbose",
213 "C" "noclobber",
214 "a" "allexport",
215 "b" "notify",
216 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100217 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100218#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100219 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100220#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000221#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000222 ,"\0" "nolog"
223 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000224#endif
225};
226
Denys Vlasenko285ad152009-12-04 23:02:27 +0100227#define optletters(n) optletters_optnames[n][0]
228#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000229
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000230enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000231
Eric Andersenc470f442003-07-28 09:56:35 +0000232
Denis Vlasenkob012b102007-02-19 22:43:01 +0000233/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000234
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200235#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000236
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000237/*
Eric Andersenc470f442003-07-28 09:56:35 +0000238 * We enclose jmp_buf in a structure so that we can declare pointers to
239 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000240 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000241 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000242 * exception handlers, the user should save the value of handler on entry
243 * to an inner scope, set handler to point to a jmploc structure for the
244 * inner scope, and restore handler on exit from the scope.
245 */
Eric Andersenc470f442003-07-28 09:56:35 +0000246struct jmploc {
247 jmp_buf loc;
248};
Denis Vlasenko01631112007-12-16 17:20:38 +0000249
250struct globals_misc {
251 /* pid of main shell */
252 int rootpid;
253 /* shell level: 0 for the main shell, 1 for its children, and so on */
254 int shlvl;
255#define rootshell (!shlvl)
256 char *minusc; /* argument to -c option */
257
258 char *curdir; // = nullstr; /* current working directory */
259 char *physdir; // = nullstr; /* physical working directory */
260
261 char *arg0; /* value of $0 */
262
263 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000264
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200265 volatile int suppress_int; /* counter */
266 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000267 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200268 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000269 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000270 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000271#define EXINT 0 /* SIGINT received */
272#define EXERROR 1 /* a generic error */
273#define EXSHELLPROC 2 /* execute a shell procedure */
274#define EXEXEC 3 /* command execution failed */
275#define EXEXIT 4 /* exit the shell */
276#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000277
Denis Vlasenko01631112007-12-16 17:20:38 +0000278 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000279 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000280
281 char optlist[NOPTS];
282#define eflag optlist[0]
283#define fflag optlist[1]
284#define Iflag optlist[2]
285#define iflag optlist[3]
286#define mflag optlist[4]
287#define nflag optlist[5]
288#define sflag optlist[6]
289#define xflag optlist[7]
290#define vflag optlist[8]
291#define Cflag optlist[9]
292#define aflag optlist[10]
293#define bflag optlist[11]
294#define uflag optlist[12]
295#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100296#if ENABLE_ASH_BASH_COMPAT
297# define pipefail optlist[14]
298#else
299# define pipefail 0
300#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000301#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100302# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
303# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000304#endif
305
306 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000307 /*
308 * Sigmode records the current value of the signal handlers for the various
309 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000310 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000311 */
312 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000313#define S_DFL 1 /* default signal handling (SIG_DFL) */
314#define S_CATCH 2 /* signal is caught */
315#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000316#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000317
Denis Vlasenko01631112007-12-16 17:20:38 +0000318 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000319 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200320 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000321 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200322 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000323
324 /* Rarely referenced stuff */
325#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200326 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000327#endif
328 pid_t backgndpid; /* pid of last background process */
329 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000330};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000331extern struct globals_misc *const ash_ptr_to_globals_misc;
332#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000333#define rootpid (G_misc.rootpid )
334#define shlvl (G_misc.shlvl )
335#define minusc (G_misc.minusc )
336#define curdir (G_misc.curdir )
337#define physdir (G_misc.physdir )
338#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000339#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000340#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200341#define suppress_int (G_misc.suppress_int )
342#define pending_int (G_misc.pending_int )
343#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000344#define isloginsh (G_misc.isloginsh )
345#define nullstr (G_misc.nullstr )
346#define optlist (G_misc.optlist )
347#define sigmode (G_misc.sigmode )
348#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200349#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000350#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200351#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200352#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000353#define backgndpid (G_misc.backgndpid )
354#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000355#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000356 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
357 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000358 curdir = nullstr; \
359 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200360 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000361} while (0)
362
363
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000364/* ============ DEBUG */
365#if DEBUG
366static void trace_printf(const char *fmt, ...);
367static void trace_vprintf(const char *fmt, va_list va);
368# define TRACE(param) trace_printf param
369# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000370# define close(fd) do { \
371 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000372 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200373 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000374 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000375} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000376#else
377# define TRACE(param)
378# define TRACEV(param)
379#endif
380
381
Denis Vlasenko559691a2008-10-05 18:39:31 +0000382/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000383#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
384
Denis Vlasenko559691a2008-10-05 18:39:31 +0000385static int isdigit_str9(const char *str)
386{
387 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
388 while (--maxlen && isdigit(*str))
389 str++;
390 return (*str == '\0');
391}
Denis Vlasenko01631112007-12-16 17:20:38 +0000392
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200393static const char *var_end(const char *var)
394{
395 while (*var)
396 if (*var++ == '=')
397 break;
398 return var;
399}
400
Denis Vlasenko559691a2008-10-05 18:39:31 +0000401
402/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000403/*
Eric Andersen2870d962001-07-02 17:27:21 +0000404 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000405 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000406 * much more efficient and portable. (But hacking the kernel is so much
407 * more fun than worrying about efficiency and portability. :-))
408 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000409#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200410 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000411 xbarrier(); \
412} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000413
414/*
415 * Called to raise an exception. Since C doesn't include exceptions, we
416 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000417 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000418 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000419static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000420static void
421raise_exception(int e)
422{
423#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000424 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000425 abort();
426#endif
427 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000428 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000429 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000430}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000431#if DEBUG
432#define raise_exception(e) do { \
433 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
434 raise_exception(e); \
435} while (0)
436#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000437
438/*
439 * Called from trap.c when a SIGINT is received. (If the user specifies
440 * that SIGINT is to be trapped or ignored using the trap builtin, then
441 * this routine is not called.) Suppressint is nonzero when interrupts
442 * are held using the INT_OFF macro. (The test for iflag is just
443 * defensive programming.)
444 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000445static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000446static void
447raise_interrupt(void)
448{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000449 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000450
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200451 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000452 /* Signal is not automatically unmasked after it is raised,
453 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000454 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200455 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000456
Denis Vlasenko4b875702009-03-19 13:30:04 +0000457 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000458 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
459 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000460 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000461 signal(SIGINT, SIG_DFL);
462 raise(SIGINT);
463 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000464 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000465 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000466 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000467 /* NOTREACHED */
468}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000469#if DEBUG
470#define raise_interrupt() do { \
471 TRACE(("raising interrupt on line %d\n", __LINE__)); \
472 raise_interrupt(); \
473} while (0)
474#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000475
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000476static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000477int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000478{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000479 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200480 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000481 raise_interrupt();
482 }
483}
484#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000485static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000486force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000487{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000488 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200489 suppress_int = 0;
490 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000491 raise_interrupt();
492}
493#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000494
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200495#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000496
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000497#define RESTORE_INT(v) do { \
498 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200499 suppress_int = (v); \
500 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000501 raise_interrupt(); \
502} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000503
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000504
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000505/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000506
Eric Andersenc470f442003-07-28 09:56:35 +0000507static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000508outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000509{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000510 INT_OFF;
511 fputs(p, file);
512 INT_ON;
513}
514
515static void
516flush_stdout_stderr(void)
517{
518 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100519 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000520 INT_ON;
521}
522
523static void
524outcslow(int c, FILE *dest)
525{
526 INT_OFF;
527 putc(c, dest);
528 fflush(dest);
529 INT_ON;
530}
531
532static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
533static int
534out1fmt(const char *fmt, ...)
535{
536 va_list ap;
537 int r;
538
539 INT_OFF;
540 va_start(ap, fmt);
541 r = vprintf(fmt, ap);
542 va_end(ap);
543 INT_ON;
544 return r;
545}
546
547static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
548static int
549fmtstr(char *outbuf, size_t length, const char *fmt, ...)
550{
551 va_list ap;
552 int ret;
553
554 va_start(ap, fmt);
555 INT_OFF;
556 ret = vsnprintf(outbuf, length, fmt, ap);
557 va_end(ap);
558 INT_ON;
559 return ret;
560}
561
562static void
563out1str(const char *p)
564{
565 outstr(p, stdout);
566}
567
568static void
569out2str(const char *p)
570{
571 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100572 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000573}
574
575
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000576/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000577
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000578/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100579#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200580#define CTLESC ((unsigned char)'\201') /* escape next character */
581#define CTLVAR ((unsigned char)'\202') /* variable defn */
582#define CTLENDVAR ((unsigned char)'\203')
583#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000584#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
585/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200586#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
587#define CTLENDARI ((unsigned char)'\207')
588#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100589#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000590
591/* variable substitution byte (follows CTLVAR) */
592#define VSTYPE 0x0f /* type of variable substitution */
593#define VSNUL 0x10 /* colon--treat the empty string as unset */
594#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
595
596/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000597#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
598#define VSMINUS 0x2 /* ${var-text} */
599#define VSPLUS 0x3 /* ${var+text} */
600#define VSQUESTION 0x4 /* ${var?message} */
601#define VSASSIGN 0x5 /* ${var=text} */
602#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
603#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
604#define VSTRIMLEFT 0x8 /* ${var#pattern} */
605#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
606#define VSLENGTH 0xa /* ${#var} */
607#if ENABLE_ASH_BASH_COMPAT
608#define VSSUBSTR 0xc /* ${var:position:length} */
609#define VSREPLACE 0xd /* ${var/pattern/replacement} */
610#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
611#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000612
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000613static const char dolatstr[] ALIGN1 = {
614 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
615};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000616
Denis Vlasenko559691a2008-10-05 18:39:31 +0000617#define NCMD 0
618#define NPIPE 1
619#define NREDIR 2
620#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000621#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000622#define NAND 5
623#define NOR 6
624#define NSEMI 7
625#define NIF 8
626#define NWHILE 9
627#define NUNTIL 10
628#define NFOR 11
629#define NCASE 12
630#define NCLIST 13
631#define NDEFUN 14
632#define NARG 15
633#define NTO 16
634#if ENABLE_ASH_BASH_COMPAT
635#define NTO2 17
636#endif
637#define NCLOBBER 18
638#define NFROM 19
639#define NFROMTO 20
640#define NAPPEND 21
641#define NTOFD 22
642#define NFROMFD 23
643#define NHERE 24
644#define NXHERE 25
645#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000646#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000647
648union node;
649
650struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000651 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000652 union node *assign;
653 union node *args;
654 union node *redirect;
655};
656
657struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000658 smallint type;
659 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000660 struct nodelist *cmdlist;
661};
662
663struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000664 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000665 union node *n;
666 union node *redirect;
667};
668
669struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000670 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000671 union node *ch1;
672 union node *ch2;
673};
674
675struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000676 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000677 union node *test;
678 union node *ifpart;
679 union node *elsepart;
680};
681
682struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000683 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000684 union node *args;
685 union node *body;
686 char *var;
687};
688
689struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000690 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000691 union node *expr;
692 union node *cases;
693};
694
695struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000696 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000697 union node *next;
698 union node *pattern;
699 union node *body;
700};
701
702struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000703 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000704 union node *next;
705 char *text;
706 struct nodelist *backquote;
707};
708
Denis Vlasenko559691a2008-10-05 18:39:31 +0000709/* nfile and ndup layout must match!
710 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
711 * that it is actually NTO2 (>&file), and change its type.
712 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000713struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000714 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000715 union node *next;
716 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000717 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000718 union node *fname;
719 char *expfname;
720};
721
722struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000723 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000724 union node *next;
725 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000726 int dupfd;
727 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000728 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000729};
730
731struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000732 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000733 union node *next;
734 int fd;
735 union node *doc;
736};
737
738struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000739 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000740 union node *com;
741};
742
743union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000744 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000745 struct ncmd ncmd;
746 struct npipe npipe;
747 struct nredir nredir;
748 struct nbinary nbinary;
749 struct nif nif;
750 struct nfor nfor;
751 struct ncase ncase;
752 struct nclist nclist;
753 struct narg narg;
754 struct nfile nfile;
755 struct ndup ndup;
756 struct nhere nhere;
757 struct nnot nnot;
758};
759
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200760/*
761 * NODE_EOF is returned by parsecmd when it encounters an end of file.
762 * It must be distinct from NULL.
763 */
764#define NODE_EOF ((union node *) -1L)
765
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000766struct nodelist {
767 struct nodelist *next;
768 union node *n;
769};
770
771struct funcnode {
772 int count;
773 union node n;
774};
775
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000776/*
777 * Free a parse tree.
778 */
779static void
780freefunc(struct funcnode *f)
781{
782 if (f && --f->count < 0)
783 free(f);
784}
785
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000786
787/* ============ Debugging output */
788
789#if DEBUG
790
791static FILE *tracefile;
792
793static void
794trace_printf(const char *fmt, ...)
795{
796 va_list va;
797
798 if (debug != 1)
799 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000800 if (DEBUG_TIME)
801 fprintf(tracefile, "%u ", (int) time(NULL));
802 if (DEBUG_PID)
803 fprintf(tracefile, "[%u] ", (int) getpid());
804 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200805 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000806 va_start(va, fmt);
807 vfprintf(tracefile, fmt, va);
808 va_end(va);
809}
810
811static void
812trace_vprintf(const char *fmt, va_list va)
813{
814 if (debug != 1)
815 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000816 if (DEBUG_TIME)
817 fprintf(tracefile, "%u ", (int) time(NULL));
818 if (DEBUG_PID)
819 fprintf(tracefile, "[%u] ", (int) getpid());
820 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200821 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000822 vfprintf(tracefile, fmt, va);
823}
824
825static void
826trace_puts(const char *s)
827{
828 if (debug != 1)
829 return;
830 fputs(s, tracefile);
831}
832
833static void
834trace_puts_quoted(char *s)
835{
836 char *p;
837 char c;
838
839 if (debug != 1)
840 return;
841 putc('"', tracefile);
842 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100843 switch ((unsigned char)*p) {
844 case '\n': c = 'n'; goto backslash;
845 case '\t': c = 't'; goto backslash;
846 case '\r': c = 'r'; goto backslash;
847 case '\"': c = '\"'; goto backslash;
848 case '\\': c = '\\'; goto backslash;
849 case CTLESC: c = 'e'; goto backslash;
850 case CTLVAR: c = 'v'; goto backslash;
851 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
852 case CTLBACKQ: c = 'q'; goto backslash;
853 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000854 backslash:
855 putc('\\', tracefile);
856 putc(c, tracefile);
857 break;
858 default:
859 if (*p >= ' ' && *p <= '~')
860 putc(*p, tracefile);
861 else {
862 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100863 putc((*p >> 6) & 03, tracefile);
864 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000865 putc(*p & 07, tracefile);
866 }
867 break;
868 }
869 }
870 putc('"', tracefile);
871}
872
873static void
874trace_puts_args(char **ap)
875{
876 if (debug != 1)
877 return;
878 if (!*ap)
879 return;
880 while (1) {
881 trace_puts_quoted(*ap);
882 if (!*++ap) {
883 putc('\n', tracefile);
884 break;
885 }
886 putc(' ', tracefile);
887 }
888}
889
890static void
891opentrace(void)
892{
893 char s[100];
894#ifdef O_APPEND
895 int flags;
896#endif
897
898 if (debug != 1) {
899 if (tracefile)
900 fflush(tracefile);
901 /* leave open because libedit might be using it */
902 return;
903 }
904 strcpy(s, "./trace");
905 if (tracefile) {
906 if (!freopen(s, "a", tracefile)) {
907 fprintf(stderr, "Can't re-open %s\n", s);
908 debug = 0;
909 return;
910 }
911 } else {
912 tracefile = fopen(s, "a");
913 if (tracefile == NULL) {
914 fprintf(stderr, "Can't open %s\n", s);
915 debug = 0;
916 return;
917 }
918 }
919#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000920 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000921 if (flags >= 0)
922 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
923#endif
924 setlinebuf(tracefile);
925 fputs("\nTracing started.\n", tracefile);
926}
927
928static void
929indent(int amount, char *pfx, FILE *fp)
930{
931 int i;
932
933 for (i = 0; i < amount; i++) {
934 if (pfx && i == amount - 1)
935 fputs(pfx, fp);
936 putc('\t', fp);
937 }
938}
939
940/* little circular references here... */
941static void shtree(union node *n, int ind, char *pfx, FILE *fp);
942
943static void
944sharg(union node *arg, FILE *fp)
945{
946 char *p;
947 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100948 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000949
950 if (arg->type != NARG) {
951 out1fmt("<node type %d>\n", arg->type);
952 abort();
953 }
954 bqlist = arg->narg.backquote;
955 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100956 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000957 case CTLESC:
Dan Fandrich77d48722010-09-07 23:38:28 -0700958 p++;
959 putc(*p, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000960 break;
961 case CTLVAR:
962 putc('$', fp);
963 putc('{', fp);
964 subtype = *++p;
965 if (subtype == VSLENGTH)
966 putc('#', fp);
967
Dan Fandrich77d48722010-09-07 23:38:28 -0700968 while (*p != '=') {
969 putc(*p, fp);
970 p++;
971 }
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000972
973 if (subtype & VSNUL)
974 putc(':', fp);
975
976 switch (subtype & VSTYPE) {
977 case VSNORMAL:
978 putc('}', fp);
979 break;
980 case VSMINUS:
981 putc('-', fp);
982 break;
983 case VSPLUS:
984 putc('+', fp);
985 break;
986 case VSQUESTION:
987 putc('?', fp);
988 break;
989 case VSASSIGN:
990 putc('=', fp);
991 break;
992 case VSTRIMLEFT:
993 putc('#', fp);
994 break;
995 case VSTRIMLEFTMAX:
996 putc('#', fp);
997 putc('#', fp);
998 break;
999 case VSTRIMRIGHT:
1000 putc('%', fp);
1001 break;
1002 case VSTRIMRIGHTMAX:
1003 putc('%', fp);
1004 putc('%', fp);
1005 break;
1006 case VSLENGTH:
1007 break;
1008 default:
1009 out1fmt("<subtype %d>", subtype);
1010 }
1011 break;
1012 case CTLENDVAR:
1013 putc('}', fp);
1014 break;
1015 case CTLBACKQ:
1016 case CTLBACKQ|CTLQUOTE:
1017 putc('$', fp);
1018 putc('(', fp);
1019 shtree(bqlist->n, -1, NULL, fp);
1020 putc(')', fp);
1021 break;
1022 default:
1023 putc(*p, fp);
1024 break;
1025 }
1026 }
1027}
1028
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02001029static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001030shcmd(union node *cmd, FILE *fp)
1031{
1032 union node *np;
1033 int first;
1034 const char *s;
1035 int dftfd;
1036
1037 first = 1;
1038 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001039 if (!first)
1040 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001041 sharg(np, fp);
1042 first = 0;
1043 }
1044 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001045 if (!first)
1046 putc(' ', fp);
1047 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001048 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001049 case NTO: s = ">>"+1; dftfd = 1; break;
1050 case NCLOBBER: s = ">|"; dftfd = 1; break;
1051 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001052#if ENABLE_ASH_BASH_COMPAT
1053 case NTO2:
1054#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001055 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001056 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001057 case NFROMFD: s = "<&"; break;
1058 case NFROMTO: s = "<>"; break;
1059 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001060 }
1061 if (np->nfile.fd != dftfd)
1062 fprintf(fp, "%d", np->nfile.fd);
1063 fputs(s, fp);
1064 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1065 fprintf(fp, "%d", np->ndup.dupfd);
1066 } else {
1067 sharg(np->nfile.fname, fp);
1068 }
1069 first = 0;
1070 }
1071}
1072
1073static void
1074shtree(union node *n, int ind, char *pfx, FILE *fp)
1075{
1076 struct nodelist *lp;
1077 const char *s;
1078
1079 if (n == NULL)
1080 return;
1081
1082 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +02001083
1084 if (n == NODE_EOF) {
1085 fputs("<EOF>", fp);
1086 return;
1087 }
1088
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001089 switch (n->type) {
1090 case NSEMI:
1091 s = "; ";
1092 goto binop;
1093 case NAND:
1094 s = " && ";
1095 goto binop;
1096 case NOR:
1097 s = " || ";
1098 binop:
1099 shtree(n->nbinary.ch1, ind, NULL, fp);
1100 /* if (ind < 0) */
1101 fputs(s, fp);
1102 shtree(n->nbinary.ch2, ind, NULL, fp);
1103 break;
1104 case NCMD:
1105 shcmd(n, fp);
1106 if (ind >= 0)
1107 putc('\n', fp);
1108 break;
1109 case NPIPE:
1110 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02001111 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001112 if (lp->next)
1113 fputs(" | ", fp);
1114 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00001115 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001116 fputs(" &", fp);
1117 if (ind >= 0)
1118 putc('\n', fp);
1119 break;
1120 default:
1121 fprintf(fp, "<node type %d>", n->type);
1122 if (ind >= 0)
1123 putc('\n', fp);
1124 break;
1125 }
1126}
1127
1128static void
1129showtree(union node *n)
1130{
1131 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001132 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001133}
1134
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001135#endif /* DEBUG */
1136
1137
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001138/* ============ Parser data */
1139
1140/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001141 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1142 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001143struct strlist {
1144 struct strlist *next;
1145 char *text;
1146};
1147
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001148struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001149
Denis Vlasenkob012b102007-02-19 22:43:01 +00001150struct strpush {
1151 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001152 char *prev_string;
1153 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001154#if ENABLE_ASH_ALIAS
1155 struct alias *ap; /* if push was associated with an alias */
1156#endif
1157 char *string; /* remember the string since it may change */
1158};
1159
1160struct parsefile {
1161 struct parsefile *prev; /* preceding file on stack */
1162 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001163 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001164 int left_in_line; /* number of chars left in this line */
1165 int left_in_buffer; /* number of chars left in this buffer past the line */
1166 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001167 char *buf; /* input buffer */
1168 struct strpush *strpush; /* for pushing strings at this level */
1169 struct strpush basestrpush; /* so pushing one is fast */
1170};
1171
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001172static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001173static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001174static int startlinno; /* line # where last token started */
1175static char *commandname; /* currently executing command */
1176static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001177static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001178
1179
1180/* ============ Message printing */
1181
1182static void
1183ash_vmsg(const char *msg, va_list ap)
1184{
1185 fprintf(stderr, "%s: ", arg0);
1186 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001187 if (strcmp(arg0, commandname))
1188 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001189 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001190 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001191 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001192 vfprintf(stderr, msg, ap);
1193 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001194}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001195
1196/*
1197 * Exverror is called to raise the error exception. If the second argument
1198 * is not NULL then error prints an error message using printf style
1199 * formatting. It then raises the error exception.
1200 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001201static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001202static void
1203ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001204{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001205#if DEBUG
1206 if (msg) {
1207 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1208 TRACEV((msg, ap));
1209 TRACE(("\") pid=%d\n", getpid()));
1210 } else
1211 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1212 if (msg)
1213#endif
1214 ash_vmsg(msg, ap);
1215
1216 flush_stdout_stderr();
1217 raise_exception(cond);
1218 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001219}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001220
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001221static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001222static void
1223ash_msg_and_raise_error(const char *msg, ...)
1224{
1225 va_list ap;
1226
1227 va_start(ap, msg);
1228 ash_vmsg_and_raise(EXERROR, msg, ap);
1229 /* NOTREACHED */
1230 va_end(ap);
1231}
1232
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001233static void raise_error_syntax(const char *) NORETURN;
1234static void
1235raise_error_syntax(const char *msg)
1236{
1237 ash_msg_and_raise_error("syntax error: %s", msg);
1238 /* NOTREACHED */
1239}
1240
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001241static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001242static void
1243ash_msg_and_raise(int cond, const char *msg, ...)
1244{
1245 va_list ap;
1246
1247 va_start(ap, msg);
1248 ash_vmsg_and_raise(cond, msg, ap);
1249 /* NOTREACHED */
1250 va_end(ap);
1251}
1252
1253/*
1254 * error/warning routines for external builtins
1255 */
1256static void
1257ash_msg(const char *fmt, ...)
1258{
1259 va_list ap;
1260
1261 va_start(ap, fmt);
1262 ash_vmsg(fmt, ap);
1263 va_end(ap);
1264}
1265
1266/*
1267 * Return a string describing an error. The returned string may be a
1268 * pointer to a static buffer that will be overwritten on the next call.
1269 * Action describes the operation that got the error.
1270 */
1271static const char *
1272errmsg(int e, const char *em)
1273{
1274 if (e == ENOENT || e == ENOTDIR) {
1275 return em;
1276 }
1277 return strerror(e);
1278}
1279
1280
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001281/* ============ Memory allocation */
1282
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001283#if 0
1284/* I consider these wrappers nearly useless:
1285 * ok, they return you to nearest exception handler, but
1286 * how much memory do you leak in the process, making
1287 * memory starvation worse?
1288 */
1289static void *
1290ckrealloc(void * p, size_t nbytes)
1291{
1292 p = realloc(p, nbytes);
1293 if (!p)
1294 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1295 return p;
1296}
1297
1298static void *
1299ckmalloc(size_t nbytes)
1300{
1301 return ckrealloc(NULL, nbytes);
1302}
1303
1304static void *
1305ckzalloc(size_t nbytes)
1306{
1307 return memset(ckmalloc(nbytes), 0, nbytes);
1308}
1309
1310static char *
1311ckstrdup(const char *s)
1312{
1313 char *p = strdup(s);
1314 if (!p)
1315 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1316 return p;
1317}
1318#else
1319/* Using bbox equivalents. They exit if out of memory */
1320# define ckrealloc xrealloc
1321# define ckmalloc xmalloc
1322# define ckzalloc xzalloc
1323# define ckstrdup xstrdup
1324#endif
1325
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001326/*
1327 * It appears that grabstackstr() will barf with such alignments
1328 * because stalloc() will return a string allocated in a new stackblock.
1329 */
1330#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1331enum {
1332 /* Most machines require the value returned from malloc to be aligned
1333 * in some way. The following macro will get this right
1334 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001335 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001336 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001337 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338};
1339
1340struct stack_block {
1341 struct stack_block *prev;
1342 char space[MINSIZE];
1343};
1344
1345struct stackmark {
1346 struct stack_block *stackp;
1347 char *stacknxt;
1348 size_t stacknleft;
1349 struct stackmark *marknext;
1350};
1351
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001352
Denis Vlasenko01631112007-12-16 17:20:38 +00001353struct globals_memstack {
1354 struct stack_block *g_stackp; // = &stackbase;
1355 struct stackmark *markp;
1356 char *g_stacknxt; // = stackbase.space;
1357 char *sstrend; // = stackbase.space + MINSIZE;
1358 size_t g_stacknleft; // = MINSIZE;
1359 int herefd; // = -1;
1360 struct stack_block stackbase;
1361};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001362extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1363#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001364#define g_stackp (G_memstack.g_stackp )
1365#define markp (G_memstack.markp )
1366#define g_stacknxt (G_memstack.g_stacknxt )
1367#define sstrend (G_memstack.sstrend )
1368#define g_stacknleft (G_memstack.g_stacknleft)
1369#define herefd (G_memstack.herefd )
1370#define stackbase (G_memstack.stackbase )
1371#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001372 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1373 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001374 g_stackp = &stackbase; \
1375 g_stacknxt = stackbase.space; \
1376 g_stacknleft = MINSIZE; \
1377 sstrend = stackbase.space + MINSIZE; \
1378 herefd = -1; \
1379} while (0)
1380
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001381
Denis Vlasenko01631112007-12-16 17:20:38 +00001382#define stackblock() ((void *)g_stacknxt)
1383#define stackblocksize() g_stacknleft
1384
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001385/*
1386 * Parse trees for commands are allocated in lifo order, so we use a stack
1387 * to make this more efficient, and also to avoid all sorts of exception
1388 * handling code to handle interrupts in the middle of a parse.
1389 *
1390 * The size 504 was chosen because the Ultrix malloc handles that size
1391 * well.
1392 */
1393static void *
1394stalloc(size_t nbytes)
1395{
1396 char *p;
1397 size_t aligned;
1398
1399 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001400 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001401 size_t len;
1402 size_t blocksize;
1403 struct stack_block *sp;
1404
1405 blocksize = aligned;
1406 if (blocksize < MINSIZE)
1407 blocksize = MINSIZE;
1408 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1409 if (len < blocksize)
1410 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1411 INT_OFF;
1412 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001413 sp->prev = g_stackp;
1414 g_stacknxt = sp->space;
1415 g_stacknleft = blocksize;
1416 sstrend = g_stacknxt + blocksize;
1417 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001418 INT_ON;
1419 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 p = g_stacknxt;
1421 g_stacknxt += aligned;
1422 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001423 return p;
1424}
1425
Denis Vlasenko597906c2008-02-20 16:38:54 +00001426static void *
1427stzalloc(size_t nbytes)
1428{
1429 return memset(stalloc(nbytes), 0, nbytes);
1430}
1431
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001432static void
1433stunalloc(void *p)
1434{
1435#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001436 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001437 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001438 abort();
1439 }
1440#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001441 g_stacknleft += g_stacknxt - (char *)p;
1442 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001443}
1444
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001445/*
1446 * Like strdup but works with the ash stack.
1447 */
1448static char *
1449ststrdup(const char *p)
1450{
1451 size_t len = strlen(p) + 1;
1452 return memcpy(stalloc(len), p, len);
1453}
1454
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001455static void
1456setstackmark(struct stackmark *mark)
1457{
Denis Vlasenko01631112007-12-16 17:20:38 +00001458 mark->stackp = g_stackp;
1459 mark->stacknxt = g_stacknxt;
1460 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001461 mark->marknext = markp;
1462 markp = mark;
1463}
1464
1465static void
1466popstackmark(struct stackmark *mark)
1467{
1468 struct stack_block *sp;
1469
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001470 if (!mark->stackp)
1471 return;
1472
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001473 INT_OFF;
1474 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001475 while (g_stackp != mark->stackp) {
1476 sp = g_stackp;
1477 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001478 free(sp);
1479 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001480 g_stacknxt = mark->stacknxt;
1481 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001482 sstrend = mark->stacknxt + mark->stacknleft;
1483 INT_ON;
1484}
1485
1486/*
1487 * When the parser reads in a string, it wants to stick the string on the
1488 * stack and only adjust the stack pointer when it knows how big the
1489 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1490 * of space on top of the stack and stackblocklen returns the length of
1491 * this block. Growstackblock will grow this space by at least one byte,
1492 * possibly moving it (like realloc). Grabstackblock actually allocates the
1493 * part of the block that has been used.
1494 */
1495static void
1496growstackblock(void)
1497{
1498 size_t newlen;
1499
Denis Vlasenko01631112007-12-16 17:20:38 +00001500 newlen = g_stacknleft * 2;
1501 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001502 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1503 if (newlen < 128)
1504 newlen += 128;
1505
Denis Vlasenko01631112007-12-16 17:20:38 +00001506 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001507 struct stack_block *oldstackp;
1508 struct stackmark *xmark;
1509 struct stack_block *sp;
1510 struct stack_block *prevstackp;
1511 size_t grosslen;
1512
1513 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001514 oldstackp = g_stackp;
1515 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001516 prevstackp = sp->prev;
1517 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1518 sp = ckrealloc(sp, grosslen);
1519 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001520 g_stackp = sp;
1521 g_stacknxt = sp->space;
1522 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001523 sstrend = sp->space + newlen;
1524
1525 /*
1526 * Stack marks pointing to the start of the old block
1527 * must be relocated to point to the new block
1528 */
1529 xmark = markp;
1530 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001531 xmark->stackp = g_stackp;
1532 xmark->stacknxt = g_stacknxt;
1533 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001534 xmark = xmark->marknext;
1535 }
1536 INT_ON;
1537 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001538 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001539 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001540 char *p = stalloc(newlen);
1541
1542 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001543 g_stacknxt = memcpy(p, oldspace, oldlen);
1544 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001545 }
1546}
1547
1548static void
1549grabstackblock(size_t len)
1550{
1551 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001552 g_stacknxt += len;
1553 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001554}
1555
1556/*
1557 * The following routines are somewhat easier to use than the above.
1558 * The user declares a variable of type STACKSTR, which may be declared
1559 * to be a register. The macro STARTSTACKSTR initializes things. Then
1560 * the user uses the macro STPUTC to add characters to the string. In
1561 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1562 * grown as necessary. When the user is done, she can just leave the
1563 * string there and refer to it using stackblock(). Or she can allocate
1564 * the space for it using grabstackstr(). If it is necessary to allow
1565 * someone else to use the stack temporarily and then continue to grow
1566 * the string, the user should use grabstack to allocate the space, and
1567 * then call ungrabstr(p) to return to the previous mode of operation.
1568 *
1569 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1570 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1571 * is space for at least one character.
1572 */
1573static void *
1574growstackstr(void)
1575{
1576 size_t len = stackblocksize();
1577 if (herefd >= 0 && len >= 1024) {
1578 full_write(herefd, stackblock(), len);
1579 return stackblock();
1580 }
1581 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001582 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001583}
1584
1585/*
1586 * Called from CHECKSTRSPACE.
1587 */
1588static char *
1589makestrspace(size_t newlen, char *p)
1590{
Denis Vlasenko01631112007-12-16 17:20:38 +00001591 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001592 size_t size = stackblocksize();
1593
1594 for (;;) {
1595 size_t nleft;
1596
1597 size = stackblocksize();
1598 nleft = size - len;
1599 if (nleft >= newlen)
1600 break;
1601 growstackblock();
1602 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001603 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001604}
1605
1606static char *
1607stack_nputstr(const char *s, size_t n, char *p)
1608{
1609 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001610 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001611 return p;
1612}
1613
1614static char *
1615stack_putstr(const char *s, char *p)
1616{
1617 return stack_nputstr(s, strlen(s), p);
1618}
1619
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001620static char *
1621_STPUTC(int c, char *p)
1622{
1623 if (p == sstrend)
1624 p = growstackstr();
1625 *p++ = c;
1626 return p;
1627}
1628
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001629#define STARTSTACKSTR(p) ((p) = stackblock())
1630#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001631#define CHECKSTRSPACE(n, p) do { \
1632 char *q = (p); \
1633 size_t l = (n); \
1634 size_t m = sstrend - q; \
1635 if (l > m) \
1636 (p) = makestrspace(l, q); \
1637} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001638#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001639#define STACKSTRNUL(p) do { \
1640 if ((p) == sstrend) \
1641 (p) = growstackstr(); \
1642 *(p) = '\0'; \
1643} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001644#define STUNPUTC(p) (--(p))
1645#define STTOPC(p) ((p)[-1])
1646#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001647
1648#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001649#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650#define stackstrend() ((void *)sstrend)
1651
1652
1653/* ============ String helpers */
1654
1655/*
1656 * prefix -- see if pfx is a prefix of string.
1657 */
1658static char *
1659prefix(const char *string, const char *pfx)
1660{
1661 while (*pfx) {
1662 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001663 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001664 }
1665 return (char *) string;
1666}
1667
1668/*
1669 * Check for a valid number. This should be elsewhere.
1670 */
1671static int
1672is_number(const char *p)
1673{
1674 do {
1675 if (!isdigit(*p))
1676 return 0;
1677 } while (*++p != '\0');
1678 return 1;
1679}
1680
1681/*
1682 * Convert a string of digits to an integer, printing an error message on
1683 * failure.
1684 */
1685static int
1686number(const char *s)
1687{
1688 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001689 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001690 return atoi(s);
1691}
1692
1693/*
1694 * Produce a possibly single quoted string suitable as input to the shell.
1695 * The return string is allocated on the stack.
1696 */
1697static char *
1698single_quote(const char *s)
1699{
1700 char *p;
1701
1702 STARTSTACKSTR(p);
1703
1704 do {
1705 char *q;
1706 size_t len;
1707
1708 len = strchrnul(s, '\'') - s;
1709
1710 q = p = makestrspace(len + 3, p);
1711
1712 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001713 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001714 *q++ = '\'';
1715 s += len;
1716
1717 STADJUST(q - p, p);
1718
Denys Vlasenkocd716832009-11-28 22:14:02 +01001719 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001720 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001721 len = 0;
1722 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001723
1724 q = p = makestrspace(len + 3, p);
1725
1726 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001727 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001728 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001729
1730 STADJUST(q - p, p);
1731 } while (*s);
1732
Denys Vlasenkocd716832009-11-28 22:14:02 +01001733 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001734
1735 return stackblock();
1736}
1737
1738
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001739/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740
1741static char **argptr; /* argument list for builtin commands */
1742static char *optionarg; /* set by nextopt (like getopt) */
1743static char *optptr; /* used by nextopt */
1744
1745/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001746 * XXX - should get rid of. Have all builtins use getopt(3).
1747 * The library getopt must have the BSD extension static variable
1748 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001749 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001750 * Standard option processing (a la getopt) for builtin routines.
1751 * The only argument that is passed to nextopt is the option string;
1752 * the other arguments are unnecessary. It returns the character,
1753 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001754 */
1755static int
1756nextopt(const char *optstring)
1757{
1758 char *p;
1759 const char *q;
1760 char c;
1761
1762 p = optptr;
1763 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001764 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001766 if (p == NULL)
1767 return '\0';
1768 if (*p != '-')
1769 return '\0';
1770 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001771 return '\0';
1772 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001773 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001775 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001777 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001778 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001779 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001780 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001781 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782 if (*++q == ':')
1783 q++;
1784 }
1785 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001786 if (*p == '\0') {
1787 p = *argptr++;
1788 if (p == NULL)
1789 ash_msg_and_raise_error("no arg for -%c option", c);
1790 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001791 optionarg = p;
1792 p = NULL;
1793 }
1794 optptr = p;
1795 return c;
1796}
1797
1798
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001799/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001800
Denis Vlasenko01631112007-12-16 17:20:38 +00001801/*
1802 * The parsefile structure pointed to by the global variable parsefile
1803 * contains information about the current file being read.
1804 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001805struct shparam {
1806 int nparam; /* # of positional parameters (without $0) */
1807#if ENABLE_ASH_GETOPTS
1808 int optind; /* next parameter to be processed by getopts */
1809 int optoff; /* used by getopts */
1810#endif
1811 unsigned char malloced; /* if parameter list dynamically allocated */
1812 char **p; /* parameter list */
1813};
1814
1815/*
1816 * Free the list of positional parameters.
1817 */
1818static void
1819freeparam(volatile struct shparam *param)
1820{
Denis Vlasenko01631112007-12-16 17:20:38 +00001821 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001822 char **ap, **ap1;
1823 ap = ap1 = param->p;
1824 while (*ap)
1825 free(*ap++);
1826 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001827 }
1828}
1829
1830#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001831static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001832#endif
1833
1834struct var {
1835 struct var *next; /* next entry in hash list */
1836 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001837 const char *var_text; /* name=value */
1838 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001839 /* the variable gets set/unset */
1840};
1841
1842struct localvar {
1843 struct localvar *next; /* next local variable in list */
1844 struct var *vp; /* the variable that was made local */
1845 int flags; /* saved flags */
1846 const char *text; /* saved text */
1847};
1848
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849/* flags */
1850#define VEXPORT 0x01 /* variable is exported */
1851#define VREADONLY 0x02 /* variable cannot be modified */
1852#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1853#define VTEXTFIXED 0x08 /* text is statically allocated */
1854#define VSTACK 0x10 /* text is allocated on the stack */
1855#define VUNSET 0x20 /* the variable is not set */
1856#define VNOFUNC 0x40 /* don't call the callback function */
1857#define VNOSET 0x80 /* do not set variable - just readonly test */
1858#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001859#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001860# define VDYNAMIC 0x200 /* dynamic variable */
1861#else
1862# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001863#endif
1864
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001865
Denis Vlasenko01631112007-12-16 17:20:38 +00001866/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001867#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001868static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001869change_lc_all(const char *value)
1870{
1871 if (value && *value != '\0')
1872 setlocale(LC_ALL, value);
1873}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001874static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001875change_lc_ctype(const char *value)
1876{
1877 if (value && *value != '\0')
1878 setlocale(LC_CTYPE, value);
1879}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001880#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001881#if ENABLE_ASH_MAIL
1882static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001883static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001884#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001885static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001886#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001887static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001888#endif
1889
Denis Vlasenko01631112007-12-16 17:20:38 +00001890static const struct {
1891 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001892 const char *var_text;
1893 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001894} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001895 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001896#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001897 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1898 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001899#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001900 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1901 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1902 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1903 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001904#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001905 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001906#endif
1907#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001908 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001909#endif
1910#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001911 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1912 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001913#endif
1914#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001915 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001916#endif
1917};
1918
Denis Vlasenko0b769642008-07-24 07:54:57 +00001919struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001920
1921struct globals_var {
1922 struct shparam shellparam; /* $@ current positional parameters */
1923 struct redirtab *redirlist;
1924 int g_nullredirs;
1925 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1926 struct var *vartab[VTABSIZE];
1927 struct var varinit[ARRAY_SIZE(varinit_data)];
1928};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001929extern struct globals_var *const ash_ptr_to_globals_var;
1930#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001931#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001932//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001933#define g_nullredirs (G_var.g_nullredirs )
1934#define preverrout_fd (G_var.preverrout_fd)
1935#define vartab (G_var.vartab )
1936#define varinit (G_var.varinit )
1937#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001938 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001939 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1940 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001941 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001942 varinit[i].flags = varinit_data[i].flags; \
1943 varinit[i].var_text = varinit_data[i].var_text; \
1944 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001945 } \
1946} while (0)
1947
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001948#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001949#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001950# define vmail (&vifs)[1]
1951# define vmpath (&vmail)[1]
1952# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001953#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001954# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001955#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001956#define vps1 (&vpath)[1]
1957#define vps2 (&vps1)[1]
1958#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001959#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001960# define voptind (&vps4)[1]
1961# if ENABLE_ASH_RANDOM_SUPPORT
1962# define vrandom (&voptind)[1]
1963# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001964#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001965# if ENABLE_ASH_RANDOM_SUPPORT
1966# define vrandom (&vps4)[1]
1967# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001968#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001969
1970/*
1971 * The following macros access the values of the above variables.
1972 * They have to skip over the name. They return the null string
1973 * for unset variables.
1974 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001975#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001976#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001977#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001978# define mailval() (vmail.var_text + 5)
1979# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001980# define mpathset() ((vmpath.flags & VUNSET) == 0)
1981#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001982#define pathval() (vpath.var_text + 5)
1983#define ps1val() (vps1.var_text + 4)
1984#define ps2val() (vps2.var_text + 4)
1985#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001986#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001987# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001988#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001989
Denis Vlasenko01631112007-12-16 17:20:38 +00001990#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001991static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001992getoptsreset(const char *value)
1993{
1994 shellparam.optind = number(value);
1995 shellparam.optoff = -1;
1996}
1997#endif
1998
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02001999/* math.h has these, otherwise define our private copies */
2000#if !ENABLE_SH_MATH_SUPPORT
2001#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2002#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002003/*
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002004 * Return the pointer to the first char which is not part of a legal variable name
2005 * (a letter or underscore followed by letters, underscores, and digits).
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002006 */
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002007static const char*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002008endofname(const char *name)
2009{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002010 if (!is_name(*name))
2011 return name;
2012 while (*++name) {
2013 if (!is_in_name(*name))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002014 break;
2015 }
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002016 return name;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002017}
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002018#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002019
2020/*
2021 * Compares two strings up to the first = or '\0'. The first
2022 * string must be terminated by '='; the second may be terminated by
2023 * either '=' or '\0'.
2024 */
2025static int
2026varcmp(const char *p, const char *q)
2027{
2028 int c, d;
2029
2030 while ((c = *p) == (d = *q)) {
2031 if (!c || c == '=')
2032 goto out;
2033 p++;
2034 q++;
2035 }
2036 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002037 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002038 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002039 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002040 out:
2041 return c - d;
2042}
2043
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002044/*
2045 * Find the appropriate entry in the hash table from the name.
2046 */
2047static struct var **
2048hashvar(const char *p)
2049{
2050 unsigned hashval;
2051
2052 hashval = ((unsigned char) *p) << 4;
2053 while (*p && *p != '=')
2054 hashval += (unsigned char) *p++;
2055 return &vartab[hashval % VTABSIZE];
2056}
2057
2058static int
2059vpcmp(const void *a, const void *b)
2060{
2061 return varcmp(*(const char **)a, *(const char **)b);
2062}
2063
2064/*
2065 * This routine initializes the builtin variables.
2066 */
2067static void
2068initvar(void)
2069{
2070 struct var *vp;
2071 struct var *end;
2072 struct var **vpp;
2073
2074 /*
2075 * PS1 depends on uid
2076 */
2077#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002078 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002079#else
2080 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002081 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002082#endif
2083 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002084 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002085 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002086 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002087 vp->next = *vpp;
2088 *vpp = vp;
2089 } while (++vp < end);
2090}
2091
2092static struct var **
2093findvar(struct var **vpp, const char *name)
2094{
2095 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002096 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002097 break;
2098 }
2099 }
2100 return vpp;
2101}
2102
2103/*
2104 * Find the value of a variable. Returns NULL if not set.
2105 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01002106static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002107lookupvar(const char *name)
2108{
2109 struct var *v;
2110
2111 v = *findvar(hashvar(name), name);
2112 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002113#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002114 /*
2115 * Dynamic variables are implemented roughly the same way they are
2116 * in bash. Namely, they're "special" so long as they aren't unset.
2117 * As soon as they're unset, they're no longer dynamic, and dynamic
2118 * lookup will no longer happen at that point. -- PFM.
2119 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002120 if (v->flags & VDYNAMIC)
2121 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002122#endif
2123 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002124 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002125 }
2126 return NULL;
2127}
2128
2129/*
2130 * Search the environment of a builtin command.
2131 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002132static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002133bltinlookup(const char *name)
2134{
2135 struct strlist *sp;
2136
2137 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002138 if (varcmp(sp->text, name) == 0)
2139 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002140 }
2141 return lookupvar(name);
2142}
2143
2144/*
2145 * Same as setvar except that the variable and value are passed in
2146 * the first argument as name=value. Since the first argument will
2147 * be actually stored in the table, it should not be a string that
2148 * will go away.
2149 * Called with interrupts off.
2150 */
2151static void
2152setvareq(char *s, int flags)
2153{
2154 struct var *vp, **vpp;
2155
2156 vpp = hashvar(s);
2157 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2158 vp = *findvar(vpp, s);
2159 if (vp) {
2160 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2161 const char *n;
2162
2163 if (flags & VNOSAVE)
2164 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002165 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002166 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2167 }
2168
2169 if (flags & VNOSET)
2170 return;
2171
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002172 if (vp->var_func && !(flags & VNOFUNC))
2173 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002174
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002175 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2176 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002177
2178 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2179 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002180 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002181 if (flags & VNOSET)
2182 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002183 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002184 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002185 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002186 *vpp = vp;
2187 }
2188 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2189 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002190 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002191 vp->flags = flags;
2192}
2193
2194/*
2195 * Set the value of a variable. The flags argument is ored with the
2196 * flags of the variable. If val is NULL, the variable is unset.
2197 */
2198static void
2199setvar(const char *name, const char *val, int flags)
2200{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002201 const char *q;
2202 char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002203 char *nameeq;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002204 size_t namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002205 size_t vallen;
2206
2207 q = endofname(name);
2208 p = strchrnul(q, '=');
2209 namelen = p - name;
2210 if (!namelen || p != q)
2211 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2212 vallen = 0;
2213 if (val == NULL) {
2214 flags |= VUNSET;
2215 } else {
2216 vallen = strlen(val);
2217 }
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002218
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002219 INT_OFF;
2220 nameeq = ckmalloc(namelen + vallen + 2);
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002221 p = memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002222 if (val) {
2223 *p++ = '=';
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002224 p = memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002225 }
2226 *p = '\0';
2227 setvareq(nameeq, flags | VNOSAVE);
2228 INT_ON;
2229}
2230
Denys Vlasenko03dad222010-01-12 23:29:57 +01002231static void FAST_FUNC
2232setvar2(const char *name, const char *val)
2233{
2234 setvar(name, val, 0);
2235}
2236
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002237#if ENABLE_ASH_GETOPTS
2238/*
2239 * Safe version of setvar, returns 1 on success 0 on failure.
2240 */
2241static int
2242setvarsafe(const char *name, const char *val, int flags)
2243{
2244 int err;
2245 volatile int saveint;
2246 struct jmploc *volatile savehandler = exception_handler;
2247 struct jmploc jmploc;
2248
2249 SAVE_INT(saveint);
2250 if (setjmp(jmploc.loc))
2251 err = 1;
2252 else {
2253 exception_handler = &jmploc;
2254 setvar(name, val, flags);
2255 err = 0;
2256 }
2257 exception_handler = savehandler;
2258 RESTORE_INT(saveint);
2259 return err;
2260}
2261#endif
2262
2263/*
2264 * Unset the specified variable.
2265 */
2266static int
2267unsetvar(const char *s)
2268{
2269 struct var **vpp;
2270 struct var *vp;
2271 int retval;
2272
2273 vpp = findvar(hashvar(s), s);
2274 vp = *vpp;
2275 retval = 2;
2276 if (vp) {
2277 int flags = vp->flags;
2278
2279 retval = 1;
2280 if (flags & VREADONLY)
2281 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002282#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002283 vp->flags &= ~VDYNAMIC;
2284#endif
2285 if (flags & VUNSET)
2286 goto ok;
2287 if ((flags & VSTRFIXED) == 0) {
2288 INT_OFF;
2289 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002290 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002291 *vpp = vp->next;
2292 free(vp);
2293 INT_ON;
2294 } else {
2295 setvar(s, 0, 0);
2296 vp->flags &= ~VEXPORT;
2297 }
2298 ok:
2299 retval = 0;
2300 }
2301 out:
2302 return retval;
2303}
2304
2305/*
2306 * Process a linked list of variable assignments.
2307 */
2308static void
2309listsetvar(struct strlist *list_set_var, int flags)
2310{
2311 struct strlist *lp = list_set_var;
2312
2313 if (!lp)
2314 return;
2315 INT_OFF;
2316 do {
2317 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002318 lp = lp->next;
2319 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002320 INT_ON;
2321}
2322
2323/*
2324 * Generate a list of variables satisfying the given conditions.
2325 */
2326static char **
2327listvars(int on, int off, char ***end)
2328{
2329 struct var **vpp;
2330 struct var *vp;
2331 char **ep;
2332 int mask;
2333
2334 STARTSTACKSTR(ep);
2335 vpp = vartab;
2336 mask = on | off;
2337 do {
2338 for (vp = *vpp; vp; vp = vp->next) {
2339 if ((vp->flags & mask) == on) {
2340 if (ep == stackstrend())
2341 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002342 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002343 }
2344 }
2345 } while (++vpp < vartab + VTABSIZE);
2346 if (ep == stackstrend())
2347 ep = growstackstr();
2348 if (end)
2349 *end = ep;
2350 *ep++ = NULL;
2351 return grabstackstr(ep);
2352}
2353
2354
2355/* ============ Path search helper
2356 *
2357 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002358 * of the path before the first call; path_advance will update
2359 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002360 * the possible path expansions in sequence. If an option (indicated by
2361 * a percent sign) appears in the path entry then the global variable
2362 * pathopt will be set to point to it; otherwise pathopt will be set to
2363 * NULL.
2364 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002365static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002366
2367static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002368path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002369{
2370 const char *p;
2371 char *q;
2372 const char *start;
2373 size_t len;
2374
2375 if (*path == NULL)
2376 return NULL;
2377 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002378 for (p = start; *p && *p != ':' && *p != '%'; p++)
2379 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002380 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2381 while (stackblocksize() < len)
2382 growstackblock();
2383 q = stackblock();
2384 if (p != start) {
2385 memcpy(q, start, p - start);
2386 q += p - start;
2387 *q++ = '/';
2388 }
2389 strcpy(q, name);
2390 pathopt = NULL;
2391 if (*p == '%') {
2392 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002393 while (*p && *p != ':')
2394 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002395 }
2396 if (*p == ':')
2397 *path = p + 1;
2398 else
2399 *path = NULL;
2400 return stalloc(len);
2401}
2402
2403
2404/* ============ Prompt */
2405
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002406static smallint doprompt; /* if set, prompt the user */
2407static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002408
2409#if ENABLE_FEATURE_EDITING
2410static line_input_t *line_input_state;
2411static const char *cmdedit_prompt;
2412static void
2413putprompt(const char *s)
2414{
2415 if (ENABLE_ASH_EXPAND_PRMT) {
2416 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002417 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002418 return;
2419 }
2420 cmdedit_prompt = s;
2421}
2422#else
2423static void
2424putprompt(const char *s)
2425{
2426 out2str(s);
2427}
2428#endif
2429
2430#if ENABLE_ASH_EXPAND_PRMT
2431/* expandstr() needs parsing machinery, so it is far away ahead... */
2432static const char *expandstr(const char *ps);
2433#else
2434#define expandstr(s) s
2435#endif
2436
2437static void
Denys Vlasenko958581a2010-09-12 15:04:27 +02002438setprompt_if(smallint do_set, int whichprompt)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002439{
2440 const char *prompt;
Denys Vlasenko958581a2010-09-12 15:04:27 +02002441 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2442
2443 if (!do_set)
2444 return;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002445
2446 needprompt = 0;
2447
2448 switch (whichprompt) {
2449 case 1:
2450 prompt = ps1val();
2451 break;
2452 case 2:
2453 prompt = ps2val();
2454 break;
2455 default: /* 0 */
2456 prompt = nullstr;
2457 }
2458#if ENABLE_ASH_EXPAND_PRMT
2459 setstackmark(&smark);
2460 stalloc(stackblocksize());
2461#endif
2462 putprompt(expandstr(prompt));
2463#if ENABLE_ASH_EXPAND_PRMT
2464 popstackmark(&smark);
2465#endif
2466}
2467
2468
2469/* ============ The cd and pwd commands */
2470
2471#define CD_PHYSICAL 1
2472#define CD_PRINT 2
2473
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002474static int
2475cdopt(void)
2476{
2477 int flags = 0;
2478 int i, j;
2479
2480 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002481 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002482 if (i != j) {
2483 flags ^= CD_PHYSICAL;
2484 j = i;
2485 }
2486 }
2487
2488 return flags;
2489}
2490
2491/*
2492 * Update curdir (the name of the current directory) in response to a
2493 * cd command.
2494 */
2495static const char *
2496updatepwd(const char *dir)
2497{
2498 char *new;
2499 char *p;
2500 char *cdcomppath;
2501 const char *lim;
2502
2503 cdcomppath = ststrdup(dir);
2504 STARTSTACKSTR(new);
2505 if (*dir != '/') {
2506 if (curdir == nullstr)
2507 return 0;
2508 new = stack_putstr(curdir, new);
2509 }
2510 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002511 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002512 if (*dir != '/') {
2513 if (new[-1] != '/')
2514 USTPUTC('/', new);
2515 if (new > lim && *lim == '/')
2516 lim++;
2517 } else {
2518 USTPUTC('/', new);
2519 cdcomppath++;
2520 if (dir[1] == '/' && dir[2] != '/') {
2521 USTPUTC('/', new);
2522 cdcomppath++;
2523 lim++;
2524 }
2525 }
2526 p = strtok(cdcomppath, "/");
2527 while (p) {
2528 switch (*p) {
2529 case '.':
2530 if (p[1] == '.' && p[2] == '\0') {
2531 while (new > lim) {
2532 STUNPUTC(new);
2533 if (new[-1] == '/')
2534 break;
2535 }
2536 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002537 }
2538 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002539 break;
2540 /* fall through */
2541 default:
2542 new = stack_putstr(p, new);
2543 USTPUTC('/', new);
2544 }
2545 p = strtok(0, "/");
2546 }
2547 if (new > lim)
2548 STUNPUTC(new);
2549 *new = 0;
2550 return stackblock();
2551}
2552
2553/*
2554 * Find out what the current directory is. If we already know the current
2555 * directory, this routine returns immediately.
2556 */
2557static char *
2558getpwd(void)
2559{
Denis Vlasenko01631112007-12-16 17:20:38 +00002560 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002561 return dir ? dir : nullstr;
2562}
2563
2564static void
2565setpwd(const char *val, int setold)
2566{
2567 char *oldcur, *dir;
2568
2569 oldcur = dir = curdir;
2570
2571 if (setold) {
2572 setvar("OLDPWD", oldcur, VEXPORT);
2573 }
2574 INT_OFF;
2575 if (physdir != nullstr) {
2576 if (physdir != oldcur)
2577 free(physdir);
2578 physdir = nullstr;
2579 }
2580 if (oldcur == val || !val) {
2581 char *s = getpwd();
2582 physdir = s;
2583 if (!val)
2584 dir = s;
2585 } else
2586 dir = ckstrdup(val);
2587 if (oldcur != dir && oldcur != nullstr) {
2588 free(oldcur);
2589 }
2590 curdir = dir;
2591 INT_ON;
2592 setvar("PWD", dir, VEXPORT);
2593}
2594
2595static void hashcd(void);
2596
2597/*
2598 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2599 * know that the current directory has changed.
2600 */
2601static int
2602docd(const char *dest, int flags)
2603{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002604 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002605 int err;
2606
2607 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2608
2609 INT_OFF;
2610 if (!(flags & CD_PHYSICAL)) {
2611 dir = updatepwd(dest);
2612 if (dir)
2613 dest = dir;
2614 }
2615 err = chdir(dest);
2616 if (err)
2617 goto out;
2618 setpwd(dir, 1);
2619 hashcd();
2620 out:
2621 INT_ON;
2622 return err;
2623}
2624
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002625static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002626cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002627{
2628 const char *dest;
2629 const char *path;
2630 const char *p;
2631 char c;
2632 struct stat statb;
2633 int flags;
2634
2635 flags = cdopt();
2636 dest = *argptr;
2637 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002638 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002639 else if (LONE_DASH(dest)) {
2640 dest = bltinlookup("OLDPWD");
2641 flags |= CD_PRINT;
2642 }
2643 if (!dest)
2644 dest = nullstr;
2645 if (*dest == '/')
2646 goto step7;
2647 if (*dest == '.') {
2648 c = dest[1];
2649 dotdot:
2650 switch (c) {
2651 case '\0':
2652 case '/':
2653 goto step6;
2654 case '.':
2655 c = dest[2];
2656 if (c != '.')
2657 goto dotdot;
2658 }
2659 }
2660 if (!*dest)
2661 dest = ".";
2662 path = bltinlookup("CDPATH");
2663 if (!path) {
2664 step6:
2665 step7:
2666 p = dest;
2667 goto docd;
2668 }
2669 do {
2670 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002671 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002672 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2673 if (c && c != ':')
2674 flags |= CD_PRINT;
2675 docd:
2676 if (!docd(p, flags))
2677 goto out;
2678 break;
2679 }
2680 } while (path);
2681 ash_msg_and_raise_error("can't cd to %s", dest);
2682 /* NOTREACHED */
2683 out:
2684 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002685 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002686 return 0;
2687}
2688
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002689static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002690pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002691{
2692 int flags;
2693 const char *dir = curdir;
2694
2695 flags = cdopt();
2696 if (flags) {
2697 if (physdir == nullstr)
2698 setpwd(dir, 0);
2699 dir = physdir;
2700 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002701 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002702 return 0;
2703}
2704
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002705
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002706/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002707
Denis Vlasenko834dee72008-10-07 09:18:30 +00002708
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002709#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002710
Eric Andersenc470f442003-07-28 09:56:35 +00002711/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002712#define CWORD 0 /* character is nothing special */
2713#define CNL 1 /* newline character */
2714#define CBACK 2 /* a backslash character */
2715#define CSQUOTE 3 /* single quote */
2716#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002717#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002718#define CBQUOTE 6 /* backwards single quote */
2719#define CVAR 7 /* a dollar sign */
2720#define CENDVAR 8 /* a '}' character */
2721#define CLP 9 /* a left paren in arithmetic */
2722#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002723#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002724#define CCTL 12 /* like CWORD, except it must be escaped */
2725#define CSPCL 13 /* these terminate a word */
2726#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002727
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002728#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002729#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002730# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002731#endif
2732
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002733#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002734
Mike Frysinger98c52642009-04-02 10:02:37 +00002735#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002736# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002737#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002738# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002739#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002740static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002741#if ENABLE_ASH_ALIAS
2742 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2743#endif
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2745 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2746 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2747 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2748 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2749 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2750 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2751 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2752 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2753 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2754 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002755#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002756 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2757 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2758 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2759#endif
2760#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002761};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002762/* Constants below must match table above */
2763enum {
2764#if ENABLE_ASH_ALIAS
2765 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2766#endif
2767 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2768 CNL_CNL_CNL_CNL , /* 2 */
2769 CWORD_CCTL_CCTL_CWORD , /* 3 */
2770 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2771 CVAR_CVAR_CWORD_CVAR , /* 5 */
2772 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2773 CSPCL_CWORD_CWORD_CLP , /* 7 */
2774 CSPCL_CWORD_CWORD_CRP , /* 8 */
2775 CBACK_CBACK_CCTL_CBACK , /* 9 */
2776 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2777 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2778 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2779 CWORD_CWORD_CWORD_CWORD , /* 13 */
2780 CCTL_CCTL_CCTL_CCTL , /* 14 */
2781};
Eric Andersen2870d962001-07-02 17:27:21 +00002782
Denys Vlasenkocd716832009-11-28 22:14:02 +01002783/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2784 * caller must ensure proper cast on it if c is *char_ptr!
2785 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002786/* Values for syntax param */
2787#define BASESYNTAX 0 /* not in quotes */
2788#define DQSYNTAX 1 /* in double quotes */
2789#define SQSYNTAX 2 /* in single quotes */
2790#define ARISYNTAX 3 /* in arithmetic */
2791#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002792
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002793#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002794
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002795static int
2796SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002797{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002798 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002799# if ENABLE_ASH_ALIAS
2800 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002801 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2802 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2803 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2804 11, 3 /* "}~" */
2805 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002806# else
2807 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002808 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2809 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2810 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2811 10, 2 /* "}~" */
2812 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002813# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002814 const char *s;
2815 int indx;
2816
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002817 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002818 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002819# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002820 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002821 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002822 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002823# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002824 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002825 /* Cast is purely for paranoia here,
2826 * just in case someone passed signed char to us */
2827 if ((unsigned char)c >= CTL_FIRST
2828 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002829 ) {
2830 return CCTL;
2831 }
2832 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002833 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002834 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002835 indx = syntax_index_table[s - spec_symbls];
2836 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002837 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002838}
2839
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002840#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002841
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002842static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002843 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002844 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2855 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2878 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2879 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2881 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2883 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2884 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2885 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2886 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2889 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2891 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2892 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2904 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2907 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2937 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2941 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2969 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2970 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2972 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2974 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2975 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2976 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2977 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2978 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2979 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2980 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2981 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003100 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01003101# if ENABLE_ASH_ALIAS
3102 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3103# endif
Eric Andersen2870d962001-07-02 17:27:21 +00003104};
3105
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003106# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003107
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01003108#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003109
Eric Andersen2870d962001-07-02 17:27:21 +00003110
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003111/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003112
Denis Vlasenko131ae172007-02-18 13:00:19 +00003113#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003114
3115#define ALIASINUSE 1
3116#define ALIASDEAD 2
3117
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003118struct alias {
3119 struct alias *next;
3120 char *name;
3121 char *val;
3122 int flag;
3123};
3124
Denis Vlasenko01631112007-12-16 17:20:38 +00003125
3126static struct alias **atab; // [ATABSIZE];
3127#define INIT_G_alias() do { \
3128 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3129} while (0)
3130
Eric Andersen2870d962001-07-02 17:27:21 +00003131
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003132static struct alias **
3133__lookupalias(const char *name) {
3134 unsigned int hashval;
3135 struct alias **app;
3136 const char *p;
3137 unsigned int ch;
3138
3139 p = name;
3140
3141 ch = (unsigned char)*p;
3142 hashval = ch << 4;
3143 while (ch) {
3144 hashval += ch;
3145 ch = (unsigned char)*++p;
3146 }
3147 app = &atab[hashval % ATABSIZE];
3148
3149 for (; *app; app = &(*app)->next) {
3150 if (strcmp(name, (*app)->name) == 0) {
3151 break;
3152 }
3153 }
3154
3155 return app;
3156}
3157
3158static struct alias *
3159lookupalias(const char *name, int check)
3160{
3161 struct alias *ap = *__lookupalias(name);
3162
3163 if (check && ap && (ap->flag & ALIASINUSE))
3164 return NULL;
3165 return ap;
3166}
3167
3168static struct alias *
3169freealias(struct alias *ap)
3170{
3171 struct alias *next;
3172
3173 if (ap->flag & ALIASINUSE) {
3174 ap->flag |= ALIASDEAD;
3175 return ap;
3176 }
3177
3178 next = ap->next;
3179 free(ap->name);
3180 free(ap->val);
3181 free(ap);
3182 return next;
3183}
Eric Andersencb57d552001-06-28 07:25:16 +00003184
Eric Andersenc470f442003-07-28 09:56:35 +00003185static void
3186setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003187{
3188 struct alias *ap, **app;
3189
3190 app = __lookupalias(name);
3191 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003192 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003193 if (ap) {
3194 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003195 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003196 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003197 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003198 ap->flag &= ~ALIASDEAD;
3199 } else {
3200 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003201 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003202 ap->name = ckstrdup(name);
3203 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003204 /*ap->flag = 0; - ckzalloc did it */
3205 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003206 *app = ap;
3207 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003208 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003209}
3210
Eric Andersenc470f442003-07-28 09:56:35 +00003211static int
3212unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003213{
Eric Andersencb57d552001-06-28 07:25:16 +00003214 struct alias **app;
3215
3216 app = __lookupalias(name);
3217
3218 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003219 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003220 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003221 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003222 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003223 }
3224
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003225 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003226}
3227
Eric Andersenc470f442003-07-28 09:56:35 +00003228static void
3229rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003230{
Eric Andersencb57d552001-06-28 07:25:16 +00003231 struct alias *ap, **app;
3232 int i;
3233
Denis Vlasenkob012b102007-02-19 22:43:01 +00003234 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003235 for (i = 0; i < ATABSIZE; i++) {
3236 app = &atab[i];
3237 for (ap = *app; ap; ap = *app) {
3238 *app = freealias(*app);
3239 if (ap == *app) {
3240 app = &ap->next;
3241 }
3242 }
3243 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003244 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003245}
3246
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003247static void
3248printalias(const struct alias *ap)
3249{
3250 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3251}
3252
Eric Andersencb57d552001-06-28 07:25:16 +00003253/*
3254 * TODO - sort output
3255 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003256static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003257aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003258{
3259 char *n, *v;
3260 int ret = 0;
3261 struct alias *ap;
3262
Denis Vlasenko68404f12008-03-17 09:00:54 +00003263 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003264 int i;
3265
Denis Vlasenko68404f12008-03-17 09:00:54 +00003266 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003267 for (ap = atab[i]; ap; ap = ap->next) {
3268 printalias(ap);
3269 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003270 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003271 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003272 }
3273 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003274 v = strchr(n+1, '=');
3275 if (v == NULL) { /* n+1: funny ksh stuff */
3276 ap = *__lookupalias(n);
3277 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003278 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003279 ret = 1;
3280 } else
3281 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003282 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003283 *v++ = '\0';
3284 setalias(n, v);
3285 }
3286 }
3287
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003288 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003289}
3290
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003291static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003292unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003293{
3294 int i;
3295
3296 while ((i = nextopt("a")) != '\0') {
3297 if (i == 'a') {
3298 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003299 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003300 }
3301 }
3302 for (i = 0; *argptr; argptr++) {
3303 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003304 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003305 i = 1;
3306 }
3307 }
3308
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003309 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003310}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003311
Denis Vlasenko131ae172007-02-18 13:00:19 +00003312#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003313
Eric Andersenc470f442003-07-28 09:56:35 +00003314
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003315/* ============ jobs.c */
3316
3317/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003318#define FORK_FG 0
3319#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003320#define FORK_NOJOB 2
3321
3322/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003323#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3324#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3325#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003326
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327/*
3328 * A job structure contains information about a job. A job is either a
3329 * single process or a set of processes contained in a pipeline. In the
3330 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3331 * array of pids.
3332 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003333struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003334 pid_t ps_pid; /* process id */
3335 int ps_status; /* last process status from wait() */
3336 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003337};
3338
3339struct job {
3340 struct procstat ps0; /* status of process */
3341 struct procstat *ps; /* status or processes when more than one */
3342#if JOBS
3343 int stopstatus; /* status of a stopped job */
3344#endif
3345 uint32_t
3346 nprocs: 16, /* number of processes */
3347 state: 8,
3348#define JOBRUNNING 0 /* at least one proc running */
3349#define JOBSTOPPED 1 /* all procs are stopped */
3350#define JOBDONE 2 /* all procs are completed */
3351#if JOBS
3352 sigint: 1, /* job was killed by SIGINT */
3353 jobctl: 1, /* job running under job control */
3354#endif
3355 waited: 1, /* true if this entry has been waited for */
3356 used: 1, /* true if this entry is in used */
3357 changed: 1; /* true if status has changed */
3358 struct job *prev_job; /* previous job */
3359};
3360
Denis Vlasenko68404f12008-03-17 09:00:54 +00003361static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362static int forkshell(struct job *, union node *, int);
3363static int waitforjob(struct job *);
3364
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003365#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003366enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003367#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003369static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003370static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003371#endif
3372
3373/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003374 * Ignore a signal.
3375 */
3376static void
3377ignoresig(int signo)
3378{
3379 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3380 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3381 /* No, need to do it */
3382 signal(signo, SIG_IGN);
3383 }
3384 sigmode[signo - 1] = S_HARD_IGN;
3385}
3386
3387/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003388 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003389 */
3390static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003391signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003392{
3393 gotsig[signo - 1] = 1;
3394
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003395 if (signo == SIGINT && !trap[SIGINT]) {
3396 if (!suppress_int) {
3397 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003398 raise_interrupt(); /* does not return */
3399 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003400 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003401 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003402 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003403 }
3404}
3405
3406/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003407 * Set the signal handler for the specified signal. The routine figures
3408 * out what it should be set to.
3409 */
3410static void
3411setsignal(int signo)
3412{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003413 char *t;
3414 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003415 struct sigaction act;
3416
3417 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003418 new_act = S_DFL;
3419 if (t != NULL) { /* trap for this sig is set */
3420 new_act = S_CATCH;
3421 if (t[0] == '\0') /* trap is "": ignore this sig */
3422 new_act = S_IGN;
3423 }
3424
3425 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003426 switch (signo) {
3427 case SIGINT:
3428 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003429 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430 break;
3431 case SIGQUIT:
3432#if DEBUG
3433 if (debug)
3434 break;
3435#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003436 /* man bash:
3437 * "In all cases, bash ignores SIGQUIT. Non-builtin
3438 * commands run by bash have signal handlers
3439 * set to the values inherited by the shell
3440 * from its parent". */
3441 new_act = S_IGN;
3442 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003443 case SIGTERM:
3444 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003445 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003446 break;
3447#if JOBS
3448 case SIGTSTP:
3449 case SIGTTOU:
3450 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003451 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003452 break;
3453#endif
3454 }
3455 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003456//TODO: if !rootshell, we reset SIGQUIT to DFL,
3457//whereas we have to restore it to what shell got on entry
3458//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003459
3460 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003461 cur_act = *t;
3462 if (cur_act == 0) {
3463 /* current setting is not yet known */
3464 if (sigaction(signo, NULL, &act)) {
3465 /* pretend it worked; maybe we should give a warning,
3466 * but other shells don't. We don't alter sigmode,
3467 * so we retry every time.
3468 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003469 return;
3470 }
3471 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003472 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003473 if (mflag
3474 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3475 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003476 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003477 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003478 }
3479 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003480 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003481 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003482
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003483 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003484 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003485 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003486 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003487 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3488 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003489 break;
3490 case S_IGN:
3491 act.sa_handler = SIG_IGN;
3492 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003493 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003494 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003495
3496 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003497}
3498
3499/* mode flags for set_curjob */
3500#define CUR_DELETE 2
3501#define CUR_RUNNING 1
3502#define CUR_STOPPED 0
3503
3504/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003505#define DOWAIT_NONBLOCK WNOHANG
3506#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003507
3508#if JOBS
3509/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003510static int initialpgrp; //references:2
3511static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003512#endif
3513/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003514static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003515/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003516static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003517/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003518static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003519/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003520static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003521
3522static void
3523set_curjob(struct job *jp, unsigned mode)
3524{
3525 struct job *jp1;
3526 struct job **jpp, **curp;
3527
3528 /* first remove from list */
3529 jpp = curp = &curjob;
3530 do {
3531 jp1 = *jpp;
3532 if (jp1 == jp)
3533 break;
3534 jpp = &jp1->prev_job;
3535 } while (1);
3536 *jpp = jp1->prev_job;
3537
3538 /* Then re-insert in correct position */
3539 jpp = curp;
3540 switch (mode) {
3541 default:
3542#if DEBUG
3543 abort();
3544#endif
3545 case CUR_DELETE:
3546 /* job being deleted */
3547 break;
3548 case CUR_RUNNING:
3549 /* newly created job or backgrounded job,
3550 put after all stopped jobs. */
3551 do {
3552 jp1 = *jpp;
3553#if JOBS
3554 if (!jp1 || jp1->state != JOBSTOPPED)
3555#endif
3556 break;
3557 jpp = &jp1->prev_job;
3558 } while (1);
3559 /* FALLTHROUGH */
3560#if JOBS
3561 case CUR_STOPPED:
3562#endif
3563 /* newly stopped job - becomes curjob */
3564 jp->prev_job = *jpp;
3565 *jpp = jp;
3566 break;
3567 }
3568}
3569
3570#if JOBS || DEBUG
3571static int
3572jobno(const struct job *jp)
3573{
3574 return jp - jobtab + 1;
3575}
3576#endif
3577
3578/*
3579 * Convert a job name to a job structure.
3580 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003581#if !JOBS
3582#define getjob(name, getctl) getjob(name)
3583#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003584static struct job *
3585getjob(const char *name, int getctl)
3586{
3587 struct job *jp;
3588 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003589 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003590 unsigned num;
3591 int c;
3592 const char *p;
3593 char *(*match)(const char *, const char *);
3594
3595 jp = curjob;
3596 p = name;
3597 if (!p)
3598 goto currentjob;
3599
3600 if (*p != '%')
3601 goto err;
3602
3603 c = *++p;
3604 if (!c)
3605 goto currentjob;
3606
3607 if (!p[1]) {
3608 if (c == '+' || c == '%') {
3609 currentjob:
3610 err_msg = "No current job";
3611 goto check;
3612 }
3613 if (c == '-') {
3614 if (jp)
3615 jp = jp->prev_job;
3616 err_msg = "No previous job";
3617 check:
3618 if (!jp)
3619 goto err;
3620 goto gotit;
3621 }
3622 }
3623
3624 if (is_number(p)) {
3625 num = atoi(p);
3626 if (num < njobs) {
3627 jp = jobtab + num - 1;
3628 if (jp->used)
3629 goto gotit;
3630 goto err;
3631 }
3632 }
3633
3634 match = prefix;
3635 if (*p == '?') {
3636 match = strstr;
3637 p++;
3638 }
3639
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003640 found = NULL;
3641 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003642 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003643 if (found)
3644 goto err;
3645 found = jp;
3646 err_msg = "%s: ambiguous";
3647 }
3648 jp = jp->prev_job;
3649 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003650 if (!found)
3651 goto err;
3652 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653
3654 gotit:
3655#if JOBS
3656 err_msg = "job %s not created under job control";
3657 if (getctl && jp->jobctl == 0)
3658 goto err;
3659#endif
3660 return jp;
3661 err:
3662 ash_msg_and_raise_error(err_msg, name);
3663}
3664
3665/*
3666 * Mark a job structure as unused.
3667 */
3668static void
3669freejob(struct job *jp)
3670{
3671 struct procstat *ps;
3672 int i;
3673
3674 INT_OFF;
3675 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003676 if (ps->ps_cmd != nullstr)
3677 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678 }
3679 if (jp->ps != &jp->ps0)
3680 free(jp->ps);
3681 jp->used = 0;
3682 set_curjob(jp, CUR_DELETE);
3683 INT_ON;
3684}
3685
3686#if JOBS
3687static void
3688xtcsetpgrp(int fd, pid_t pgrp)
3689{
3690 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003691 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003692}
3693
3694/*
3695 * Turn job control on and off.
3696 *
3697 * Note: This code assumes that the third arg to ioctl is a character
3698 * pointer, which is true on Berkeley systems but not System V. Since
3699 * System V doesn't have job control yet, this isn't a problem now.
3700 *
3701 * Called with interrupts off.
3702 */
3703static void
3704setjobctl(int on)
3705{
3706 int fd;
3707 int pgrp;
3708
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003709 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003710 return;
3711 if (on) {
3712 int ofd;
3713 ofd = fd = open(_PATH_TTY, O_RDWR);
3714 if (fd < 0) {
3715 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3716 * That sometimes helps to acquire controlling tty.
3717 * Obviously, a workaround for bugs when someone
3718 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003719 fd = 2;
3720 while (!isatty(fd))
3721 if (--fd < 0)
3722 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003723 }
3724 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003725 if (ofd >= 0)
3726 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003727 if (fd < 0)
3728 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003729 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003730 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003731 do { /* while we are in the background */
3732 pgrp = tcgetpgrp(fd);
3733 if (pgrp < 0) {
3734 out:
3735 ash_msg("can't access tty; job control turned off");
3736 mflag = on = 0;
3737 goto close;
3738 }
3739 if (pgrp == getpgrp())
3740 break;
3741 killpg(0, SIGTTIN);
3742 } while (1);
3743 initialpgrp = pgrp;
3744
3745 setsignal(SIGTSTP);
3746 setsignal(SIGTTOU);
3747 setsignal(SIGTTIN);
3748 pgrp = rootpid;
3749 setpgid(0, pgrp);
3750 xtcsetpgrp(fd, pgrp);
3751 } else {
3752 /* turning job control off */
3753 fd = ttyfd;
3754 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003755 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003756 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003757 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003758 setpgid(0, pgrp);
3759 setsignal(SIGTSTP);
3760 setsignal(SIGTTOU);
3761 setsignal(SIGTTIN);
3762 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003763 if (fd >= 0)
3764 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003765 fd = -1;
3766 }
3767 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003768 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003769}
3770
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003771static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003772killcmd(int argc, char **argv)
3773{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003774 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003775 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003776 do {
3777 if (argv[i][0] == '%') {
3778 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003779 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003780 /* Enough space for ' -NNN<nul>' */
3781 argv[i] = alloca(sizeof(int)*3 + 3);
3782 /* kill_main has matching code to expect
3783 * leading space. Needed to not confuse
3784 * negative pids with "kill -SIGNAL_NO" syntax */
3785 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003786 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003787 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003788 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003789 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003790}
3791
3792static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003793showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003794{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003795 struct procstat *ps;
3796 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003797
Denys Vlasenko285ad152009-12-04 23:02:27 +01003798 psend = jp->ps + jp->nprocs;
3799 for (ps = jp->ps + 1; ps < psend; ps++)
3800 printf(" | %s", ps->ps_cmd);
3801 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003802 flush_stdout_stderr();
3803}
3804
3805
3806static int
3807restartjob(struct job *jp, int mode)
3808{
3809 struct procstat *ps;
3810 int i;
3811 int status;
3812 pid_t pgid;
3813
3814 INT_OFF;
3815 if (jp->state == JOBDONE)
3816 goto out;
3817 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003819 if (mode == FORK_FG)
3820 xtcsetpgrp(ttyfd, pgid);
3821 killpg(pgid, SIGCONT);
3822 ps = jp->ps;
3823 i = jp->nprocs;
3824 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003825 if (WIFSTOPPED(ps->ps_status)) {
3826 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003827 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003828 ps++;
3829 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003830 out:
3831 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3832 INT_ON;
3833 return status;
3834}
3835
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003836static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003837fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003838{
3839 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003840 int mode;
3841 int retval;
3842
3843 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3844 nextopt(nullstr);
3845 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003846 do {
3847 jp = getjob(*argv, 1);
3848 if (mode == FORK_BG) {
3849 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003850 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003851 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003852 out1str(jp->ps[0].ps_cmd);
3853 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003854 retval = restartjob(jp, mode);
3855 } while (*argv && *++argv);
3856 return retval;
3857}
3858#endif
3859
3860static int
3861sprint_status(char *s, int status, int sigonly)
3862{
3863 int col;
3864 int st;
3865
3866 col = 0;
3867 if (!WIFEXITED(status)) {
3868#if JOBS
3869 if (WIFSTOPPED(status))
3870 st = WSTOPSIG(status);
3871 else
3872#endif
3873 st = WTERMSIG(status);
3874 if (sigonly) {
3875 if (st == SIGINT || st == SIGPIPE)
3876 goto out;
3877#if JOBS
3878 if (WIFSTOPPED(status))
3879 goto out;
3880#endif
3881 }
3882 st &= 0x7f;
3883 col = fmtstr(s, 32, strsignal(st));
3884 if (WCOREDUMP(status)) {
3885 col += fmtstr(s + col, 16, " (core dumped)");
3886 }
3887 } else if (!sigonly) {
3888 st = WEXITSTATUS(status);
3889 if (st)
3890 col = fmtstr(s, 16, "Done(%d)", st);
3891 else
3892 col = fmtstr(s, 16, "Done");
3893 }
3894 out:
3895 return col;
3896}
3897
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003899dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003900{
3901 int pid;
3902 int status;
3903 struct job *jp;
3904 struct job *thisjob;
3905 int state;
3906
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003907 TRACE(("dowait(0x%x) called\n", wait_flags));
3908
3909 /* Do a wait system call. If job control is compiled in, we accept
3910 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3911 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003912 if (doing_jobctl)
3913 wait_flags |= WUNTRACED;
3914 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003915 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3916 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003917 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003918 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003919
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920 INT_OFF;
3921 thisjob = NULL;
3922 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003923 struct procstat *ps;
3924 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925 if (jp->state == JOBDONE)
3926 continue;
3927 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003928 ps = jp->ps;
3929 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003931 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003932 TRACE(("Job %d: changing status of proc %d "
3933 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003934 jobno(jp), pid, ps->ps_status, status));
3935 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 thisjob = jp;
3937 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003938 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003939 state = JOBRUNNING;
3940#if JOBS
3941 if (state == JOBRUNNING)
3942 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003943 if (WIFSTOPPED(ps->ps_status)) {
3944 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003945 state = JOBSTOPPED;
3946 }
3947#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003948 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003949 if (thisjob)
3950 goto gotjob;
3951 }
3952#if JOBS
3953 if (!WIFSTOPPED(status))
3954#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003955 jobless--;
3956 goto out;
3957
3958 gotjob:
3959 if (state != JOBRUNNING) {
3960 thisjob->changed = 1;
3961
3962 if (thisjob->state != state) {
3963 TRACE(("Job %d: changing state from %d to %d\n",
3964 jobno(thisjob), thisjob->state, state));
3965 thisjob->state = state;
3966#if JOBS
3967 if (state == JOBSTOPPED) {
3968 set_curjob(thisjob, CUR_STOPPED);
3969 }
3970#endif
3971 }
3972 }
3973
3974 out:
3975 INT_ON;
3976
3977 if (thisjob && thisjob == job) {
3978 char s[48 + 1];
3979 int len;
3980
3981 len = sprint_status(s, status, 1);
3982 if (len) {
3983 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003984 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003985 out2str(s);
3986 }
3987 }
3988 return pid;
3989}
3990
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003991static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003992blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003993{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003994 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003995 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003996 raise_exception(EXSIG);
3997 return pid;
3998}
3999
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004000#if JOBS
4001static void
4002showjob(FILE *out, struct job *jp, int mode)
4003{
4004 struct procstat *ps;
4005 struct procstat *psend;
4006 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004007 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008 char s[80];
4009
4010 ps = jp->ps;
4011
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004012 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004013 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01004014 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004015 return;
4016 }
4017
4018 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004019 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004020
4021 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004022 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004023 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004024 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004025
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004026 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004027 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004028
4029 psend = ps + jp->nprocs;
4030
4031 if (jp->state == JOBRUNNING) {
4032 strcpy(s + col, "Running");
4033 col += sizeof("Running") - 1;
4034 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01004035 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004036 if (jp->state == JOBSTOPPED)
4037 status = jp->stopstatus;
4038 col += sprint_status(s + col, status, 0);
4039 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004040 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004042 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4043 * or prints several "PID | <cmdN>" lines,
4044 * depending on SHOW_PIDS bit.
4045 * We do not print status of individual processes
4046 * between PID and <cmdN>. bash does it, but not very well:
4047 * first line shows overall job status, not process status,
4048 * making it impossible to know 1st process status.
4049 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004050 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004051 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004052 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004053 s[0] = '\0';
4054 col = 33;
4055 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004056 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004057 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01004058 fprintf(out, "%s%*c%s%s",
4059 s,
4060 33 - col >= 0 ? 33 - col : 0, ' ',
4061 ps == jp->ps ? "" : "| ",
4062 ps->ps_cmd
4063 );
4064 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004065 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066
4067 jp->changed = 0;
4068
4069 if (jp->state == JOBDONE) {
4070 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4071 freejob(jp);
4072 }
4073}
4074
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004075/*
4076 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4077 * statuses have changed since the last call to showjobs.
4078 */
4079static void
4080showjobs(FILE *out, int mode)
4081{
4082 struct job *jp;
4083
Denys Vlasenko883cea42009-07-11 15:31:59 +02004084 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004085
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004086 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004087 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004088 continue;
4089
4090 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004091 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004092 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004093 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004094 }
4095}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004096
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004097static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004098jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004099{
4100 int mode, m;
4101
4102 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004103 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004104 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004105 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004106 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004107 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004108 }
4109
4110 argv = argptr;
4111 if (*argv) {
4112 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004113 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004114 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004115 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004116 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004117 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004118
4119 return 0;
4120}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121#endif /* JOBS */
4122
Michael Abbott359da5e2009-12-04 23:03:29 +01004123/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124static int
4125getstatus(struct job *job)
4126{
4127 int status;
4128 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004129 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004130
Michael Abbott359da5e2009-12-04 23:03:29 +01004131 /* Fetch last member's status */
4132 ps = job->ps + job->nprocs - 1;
4133 status = ps->ps_status;
4134 if (pipefail) {
4135 /* "set -o pipefail" mode: use last _nonzero_ status */
4136 while (status == 0 && --ps >= job->ps)
4137 status = ps->ps_status;
4138 }
4139
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004140 retval = WEXITSTATUS(status);
4141 if (!WIFEXITED(status)) {
4142#if JOBS
4143 retval = WSTOPSIG(status);
4144 if (!WIFSTOPPED(status))
4145#endif
4146 {
4147 /* XXX: limits number of signals */
4148 retval = WTERMSIG(status);
4149#if JOBS
4150 if (retval == SIGINT)
4151 job->sigint = 1;
4152#endif
4153 }
4154 retval += 128;
4155 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004156 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004157 jobno(job), job->nprocs, status, retval));
4158 return retval;
4159}
4160
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004161static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004162waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004163{
4164 struct job *job;
4165 int retval;
4166 struct job *jp;
4167
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004168 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004169 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004170
4171 nextopt(nullstr);
4172 retval = 0;
4173
4174 argv = argptr;
4175 if (!*argv) {
4176 /* wait for all jobs */
4177 for (;;) {
4178 jp = curjob;
4179 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004180 if (!jp) /* no running procs */
4181 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004182 if (jp->state == JOBRUNNING)
4183 break;
4184 jp->waited = 1;
4185 jp = jp->prev_job;
4186 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004187 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004188 /* man bash:
4189 * "When bash is waiting for an asynchronous command via
4190 * the wait builtin, the reception of a signal for which a trap
4191 * has been set will cause the wait builtin to return immediately
4192 * with an exit status greater than 128, immediately after which
4193 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004194 *
4195 * blocking_wait_with_raise_on_sig raises signal handlers
4196 * if it gets no pid (pid < 0). However,
4197 * if child sends us a signal *and immediately exits*,
4198 * blocking_wait_with_raise_on_sig gets pid > 0
4199 * and does not handle pending_sig. Check this case: */
4200 if (pending_sig)
4201 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004202 }
4203 }
4204
4205 retval = 127;
4206 do {
4207 if (**argv != '%') {
4208 pid_t pid = number(*argv);
4209 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004210 while (1) {
4211 if (!job)
4212 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004213 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 break;
4215 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004216 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 } else
4218 job = getjob(*argv, 0);
4219 /* loop until process terminated or stopped */
4220 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004221 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004222 job->waited = 1;
4223 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004224 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004225 } while (*++argv);
4226
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004227 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004228 return retval;
4229}
4230
4231static struct job *
4232growjobtab(void)
4233{
4234 size_t len;
4235 ptrdiff_t offset;
4236 struct job *jp, *jq;
4237
4238 len = njobs * sizeof(*jp);
4239 jq = jobtab;
4240 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4241
4242 offset = (char *)jp - (char *)jq;
4243 if (offset) {
4244 /* Relocate pointers */
4245 size_t l = len;
4246
4247 jq = (struct job *)((char *)jq + l);
4248 while (l) {
4249 l -= sizeof(*jp);
4250 jq--;
4251#define joff(p) ((struct job *)((char *)(p) + l))
4252#define jmove(p) (p) = (void *)((char *)(p) + offset)
4253 if (joff(jp)->ps == &jq->ps0)
4254 jmove(joff(jp)->ps);
4255 if (joff(jp)->prev_job)
4256 jmove(joff(jp)->prev_job);
4257 }
4258 if (curjob)
4259 jmove(curjob);
4260#undef joff
4261#undef jmove
4262 }
4263
4264 njobs += 4;
4265 jobtab = jp;
4266 jp = (struct job *)((char *)jp + len);
4267 jq = jp + 3;
4268 do {
4269 jq->used = 0;
4270 } while (--jq >= jp);
4271 return jp;
4272}
4273
4274/*
4275 * Return a new job structure.
4276 * Called with interrupts off.
4277 */
4278static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004279makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004280{
4281 int i;
4282 struct job *jp;
4283
4284 for (i = njobs, jp = jobtab; ; jp++) {
4285 if (--i < 0) {
4286 jp = growjobtab();
4287 break;
4288 }
4289 if (jp->used == 0)
4290 break;
4291 if (jp->state != JOBDONE || !jp->waited)
4292 continue;
4293#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004294 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004295 continue;
4296#endif
4297 freejob(jp);
4298 break;
4299 }
4300 memset(jp, 0, sizeof(*jp));
4301#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004302 /* jp->jobctl is a bitfield.
4303 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004304 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004305 jp->jobctl = 1;
4306#endif
4307 jp->prev_job = curjob;
4308 curjob = jp;
4309 jp->used = 1;
4310 jp->ps = &jp->ps0;
4311 if (nprocs > 1) {
4312 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4313 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004314 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004315 jobno(jp)));
4316 return jp;
4317}
4318
4319#if JOBS
4320/*
4321 * Return a string identifying a command (to be printed by the
4322 * jobs command).
4323 */
4324static char *cmdnextc;
4325
4326static void
4327cmdputs(const char *s)
4328{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004329 static const char vstype[VSTYPE + 1][3] = {
4330 "", "}", "-", "+", "?", "=",
4331 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004332 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004333 };
4334
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004335 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004336 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004337 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004338 unsigned char c;
4339 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004340 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004341
Denys Vlasenko46a14772009-12-10 21:27:13 +01004342 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004343 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4344 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004345 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004346 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004347 switch (c) {
4348 case CTLESC:
4349 c = *p++;
4350 break;
4351 case CTLVAR:
4352 subtype = *p++;
4353 if ((subtype & VSTYPE) == VSLENGTH)
4354 str = "${#";
4355 else
4356 str = "${";
4357 if (!(subtype & VSQUOTE) == !(quoted & 1))
4358 goto dostr;
4359 quoted ^= 1;
4360 c = '"';
4361 break;
4362 case CTLENDVAR:
4363 str = "\"}" + !(quoted & 1);
4364 quoted >>= 1;
4365 subtype = 0;
4366 goto dostr;
4367 case CTLBACKQ:
4368 str = "$(...)";
4369 goto dostr;
4370 case CTLBACKQ+CTLQUOTE:
4371 str = "\"$(...)\"";
4372 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004373#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004374 case CTLARI:
4375 str = "$((";
4376 goto dostr;
4377 case CTLENDARI:
4378 str = "))";
4379 goto dostr;
4380#endif
4381 case CTLQUOTEMARK:
4382 quoted ^= 1;
4383 c = '"';
4384 break;
4385 case '=':
4386 if (subtype == 0)
4387 break;
4388 if ((subtype & VSTYPE) != VSNORMAL)
4389 quoted <<= 1;
4390 str = vstype[subtype & VSTYPE];
4391 if (subtype & VSNUL)
4392 c = ':';
4393 else
4394 goto checkstr;
4395 break;
4396 case '\'':
4397 case '\\':
4398 case '"':
4399 case '$':
4400 /* These can only happen inside quotes */
4401 cc[0] = c;
4402 str = cc;
4403 c = '\\';
4404 break;
4405 default:
4406 break;
4407 }
4408 USTPUTC(c, nextc);
4409 checkstr:
4410 if (!str)
4411 continue;
4412 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004413 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004414 USTPUTC(c, nextc);
4415 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004416 } /* while *p++ not NUL */
4417
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004418 if (quoted & 1) {
4419 USTPUTC('"', nextc);
4420 }
4421 *nextc = 0;
4422 cmdnextc = nextc;
4423}
4424
4425/* cmdtxt() and cmdlist() call each other */
4426static void cmdtxt(union node *n);
4427
4428static void
4429cmdlist(union node *np, int sep)
4430{
4431 for (; np; np = np->narg.next) {
4432 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004433 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004434 cmdtxt(np);
4435 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004436 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004437 }
4438}
4439
4440static void
4441cmdtxt(union node *n)
4442{
4443 union node *np;
4444 struct nodelist *lp;
4445 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004446
4447 if (!n)
4448 return;
4449 switch (n->type) {
4450 default:
4451#if DEBUG
4452 abort();
4453#endif
4454 case NPIPE:
4455 lp = n->npipe.cmdlist;
4456 for (;;) {
4457 cmdtxt(lp->n);
4458 lp = lp->next;
4459 if (!lp)
4460 break;
4461 cmdputs(" | ");
4462 }
4463 break;
4464 case NSEMI:
4465 p = "; ";
4466 goto binop;
4467 case NAND:
4468 p = " && ";
4469 goto binop;
4470 case NOR:
4471 p = " || ";
4472 binop:
4473 cmdtxt(n->nbinary.ch1);
4474 cmdputs(p);
4475 n = n->nbinary.ch2;
4476 goto donode;
4477 case NREDIR:
4478 case NBACKGND:
4479 n = n->nredir.n;
4480 goto donode;
4481 case NNOT:
4482 cmdputs("!");
4483 n = n->nnot.com;
4484 donode:
4485 cmdtxt(n);
4486 break;
4487 case NIF:
4488 cmdputs("if ");
4489 cmdtxt(n->nif.test);
4490 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004491 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004492 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004493 cmdputs("; else ");
4494 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004495 } else {
4496 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004497 }
4498 p = "; fi";
4499 goto dotail;
4500 case NSUBSHELL:
4501 cmdputs("(");
4502 n = n->nredir.n;
4503 p = ")";
4504 goto dotail;
4505 case NWHILE:
4506 p = "while ";
4507 goto until;
4508 case NUNTIL:
4509 p = "until ";
4510 until:
4511 cmdputs(p);
4512 cmdtxt(n->nbinary.ch1);
4513 n = n->nbinary.ch2;
4514 p = "; done";
4515 dodo:
4516 cmdputs("; do ");
4517 dotail:
4518 cmdtxt(n);
4519 goto dotail2;
4520 case NFOR:
4521 cmdputs("for ");
4522 cmdputs(n->nfor.var);
4523 cmdputs(" in ");
4524 cmdlist(n->nfor.args, 1);
4525 n = n->nfor.body;
4526 p = "; done";
4527 goto dodo;
4528 case NDEFUN:
4529 cmdputs(n->narg.text);
4530 p = "() { ... }";
4531 goto dotail2;
4532 case NCMD:
4533 cmdlist(n->ncmd.args, 1);
4534 cmdlist(n->ncmd.redirect, 0);
4535 break;
4536 case NARG:
4537 p = n->narg.text;
4538 dotail2:
4539 cmdputs(p);
4540 break;
4541 case NHERE:
4542 case NXHERE:
4543 p = "<<...";
4544 goto dotail2;
4545 case NCASE:
4546 cmdputs("case ");
4547 cmdputs(n->ncase.expr->narg.text);
4548 cmdputs(" in ");
4549 for (np = n->ncase.cases; np; np = np->nclist.next) {
4550 cmdtxt(np->nclist.pattern);
4551 cmdputs(") ");
4552 cmdtxt(np->nclist.body);
4553 cmdputs(";; ");
4554 }
4555 p = "esac";
4556 goto dotail2;
4557 case NTO:
4558 p = ">";
4559 goto redir;
4560 case NCLOBBER:
4561 p = ">|";
4562 goto redir;
4563 case NAPPEND:
4564 p = ">>";
4565 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004566#if ENABLE_ASH_BASH_COMPAT
4567 case NTO2:
4568#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004569 case NTOFD:
4570 p = ">&";
4571 goto redir;
4572 case NFROM:
4573 p = "<";
4574 goto redir;
4575 case NFROMFD:
4576 p = "<&";
4577 goto redir;
4578 case NFROMTO:
4579 p = "<>";
4580 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004581 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004582 cmdputs(p);
4583 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004584 cmdputs(utoa(n->ndup.dupfd));
4585 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004586 }
4587 n = n->nfile.fname;
4588 goto donode;
4589 }
4590}
4591
4592static char *
4593commandtext(union node *n)
4594{
4595 char *name;
4596
4597 STARTSTACKSTR(cmdnextc);
4598 cmdtxt(n);
4599 name = stackblock();
4600 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4601 name, cmdnextc, cmdnextc));
4602 return ckstrdup(name);
4603}
4604#endif /* JOBS */
4605
4606/*
4607 * Fork off a subshell. If we are doing job control, give the subshell its
4608 * own process group. Jp is a job structure that the job is to be added to.
4609 * N is the command that will be evaluated by the child. Both jp and n may
4610 * be NULL. The mode parameter can be one of the following:
4611 * FORK_FG - Fork off a foreground process.
4612 * FORK_BG - Fork off a background process.
4613 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4614 * process group even if job control is on.
4615 *
4616 * When job control is turned off, background processes have their standard
4617 * input redirected to /dev/null (except for the second and later processes
4618 * in a pipeline).
4619 *
4620 * Called with interrupts off.
4621 */
4622/*
4623 * Clear traps on a fork.
4624 */
4625static void
4626clear_traps(void)
4627{
4628 char **tp;
4629
4630 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004631 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004632 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004633 if (trap_ptr == trap)
4634 free(*tp);
4635 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004636 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004637 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004638 setsignal(tp - trap);
4639 INT_ON;
4640 }
4641 }
Alexander Shishkinccb97712010-07-25 13:07:39 +02004642 may_have_traps = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004643}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004644
4645/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004646static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004647
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004648/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004649static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004650forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004651{
4652 int oldlvl;
4653
4654 TRACE(("Child shell %d\n", getpid()));
4655 oldlvl = shlvl;
4656 shlvl++;
4657
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004658 /* man bash: "Non-builtin commands run by bash have signal handlers
4659 * set to the values inherited by the shell from its parent".
4660 * Do we do it correctly? */
4661
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004662 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004663
4664 if (mode == FORK_NOJOB /* is it `xxx` ? */
4665 && n && n->type == NCMD /* is it single cmd? */
4666 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004667 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004668 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4669 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4670 ) {
4671 TRACE(("Trap hack\n"));
4672 /* Awful hack for `trap` or $(trap).
4673 *
4674 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4675 * contains an example where "trap" is executed in a subshell:
4676 *
4677 * save_traps=$(trap)
4678 * ...
4679 * eval "$save_traps"
4680 *
4681 * Standard does not say that "trap" in subshell shall print
4682 * parent shell's traps. It only says that its output
4683 * must have suitable form, but then, in the above example
4684 * (which is not supposed to be normative), it implies that.
4685 *
4686 * bash (and probably other shell) does implement it
4687 * (traps are reset to defaults, but "trap" still shows them),
4688 * but as a result, "trap" logic is hopelessly messed up:
4689 *
4690 * # trap
4691 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4692 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4693 * # true | trap <--- trap is in subshell - no output (ditto)
4694 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4695 * trap -- 'echo Ho' SIGWINCH
4696 * # echo `(trap)` <--- in subshell in subshell - output
4697 * trap -- 'echo Ho' SIGWINCH
4698 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4699 * trap -- 'echo Ho' SIGWINCH
4700 *
4701 * The rules when to forget and when to not forget traps
4702 * get really complex and nonsensical.
4703 *
4704 * Our solution: ONLY bare $(trap) or `trap` is special.
4705 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004706 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004707 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004708 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004709 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004710 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004711#if JOBS
4712 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004713 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004714 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4715 pid_t pgrp;
4716
4717 if (jp->nprocs == 0)
4718 pgrp = getpid();
4719 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004720 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004721 /* this can fail because we are doing it in the parent also */
4722 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004723 if (mode == FORK_FG)
4724 xtcsetpgrp(ttyfd, pgrp);
4725 setsignal(SIGTSTP);
4726 setsignal(SIGTTOU);
4727 } else
4728#endif
4729 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004730 /* man bash: "When job control is not in effect,
4731 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004732 ignoresig(SIGINT);
4733 ignoresig(SIGQUIT);
4734 if (jp->nprocs == 0) {
4735 close(0);
4736 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004737 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004738 }
4739 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004740 if (!oldlvl) {
4741 if (iflag) { /* why if iflag only? */
4742 setsignal(SIGINT);
4743 setsignal(SIGTERM);
4744 }
4745 /* man bash:
4746 * "In all cases, bash ignores SIGQUIT. Non-builtin
4747 * commands run by bash have signal handlers
4748 * set to the values inherited by the shell
4749 * from its parent".
4750 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004751 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004752 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004753#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004754 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004755 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004756 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004757 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004758 /* "jobs": we do not want to clear job list for it,
4759 * instead we remove only _its_ own_ job from job list.
4760 * This makes "jobs .... | cat" more useful.
4761 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004762 freejob(curjob);
4763 return;
4764 }
4765#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004766 for (jp = curjob; jp; jp = jp->prev_job)
4767 freejob(jp);
4768 jobless = 0;
4769}
4770
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004771/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004772#if !JOBS
4773#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4774#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004775static void
4776forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4777{
4778 TRACE(("In parent shell: child = %d\n", pid));
4779 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004780 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4781 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004782 jobless++;
4783 return;
4784 }
4785#if JOBS
4786 if (mode != FORK_NOJOB && jp->jobctl) {
4787 int pgrp;
4788
4789 if (jp->nprocs == 0)
4790 pgrp = pid;
4791 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004792 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004793 /* This can fail because we are doing it in the child also */
4794 setpgid(pid, pgrp);
4795 }
4796#endif
4797 if (mode == FORK_BG) {
4798 backgndpid = pid; /* set $! */
4799 set_curjob(jp, CUR_RUNNING);
4800 }
4801 if (jp) {
4802 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004803 ps->ps_pid = pid;
4804 ps->ps_status = -1;
4805 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004806#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004807 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004808 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004809#endif
4810 }
4811}
4812
4813static int
4814forkshell(struct job *jp, union node *n, int mode)
4815{
4816 int pid;
4817
4818 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4819 pid = fork();
4820 if (pid < 0) {
4821 TRACE(("Fork failed, errno=%d", errno));
4822 if (jp)
4823 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004824 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004825 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004826 if (pid == 0) {
4827 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004828 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004829 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004830 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004831 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004832 return pid;
4833}
4834
4835/*
4836 * Wait for job to finish.
4837 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004838 * Under job control we have the problem that while a child process
4839 * is running interrupts generated by the user are sent to the child
4840 * but not to the shell. This means that an infinite loop started by
4841 * an interactive user may be hard to kill. With job control turned off,
4842 * an interactive user may place an interactive program inside a loop.
4843 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004844 * these interrupts to also abort the loop. The approach we take here
4845 * is to have the shell ignore interrupt signals while waiting for a
4846 * foreground process to terminate, and then send itself an interrupt
4847 * signal if the child process was terminated by an interrupt signal.
4848 * Unfortunately, some programs want to do a bit of cleanup and then
4849 * exit on interrupt; unless these processes terminate themselves by
4850 * sending a signal to themselves (instead of calling exit) they will
4851 * confuse this approach.
4852 *
4853 * Called with interrupts off.
4854 */
4855static int
4856waitforjob(struct job *jp)
4857{
4858 int st;
4859
4860 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004861
4862 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004863 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004864 /* In non-interactive shells, we _can_ get
4865 * a keyboard signal here and be EINTRed,
4866 * but we just loop back, waiting for command to complete.
4867 *
4868 * man bash:
4869 * "If bash is waiting for a command to complete and receives
4870 * a signal for which a trap has been set, the trap
4871 * will not be executed until the command completes."
4872 *
4873 * Reality is that even if trap is not set, bash
4874 * will not act on the signal until command completes.
4875 * Try this. sleep5intoff.c:
4876 * #include <signal.h>
4877 * #include <unistd.h>
4878 * int main() {
4879 * sigset_t set;
4880 * sigemptyset(&set);
4881 * sigaddset(&set, SIGINT);
4882 * sigaddset(&set, SIGQUIT);
4883 * sigprocmask(SIG_BLOCK, &set, NULL);
4884 * sleep(5);
4885 * return 0;
4886 * }
4887 * $ bash -c './sleep5intoff; echo hi'
4888 * ^C^C^C^C <--- pressing ^C once a second
4889 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004890 * $ bash -c './sleep5intoff; echo hi'
4891 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4892 * $ _
4893 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004894 dowait(DOWAIT_BLOCK, jp);
4895 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004896 INT_ON;
4897
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004898 st = getstatus(jp);
4899#if JOBS
4900 if (jp->jobctl) {
4901 xtcsetpgrp(ttyfd, rootpid);
4902 /*
4903 * This is truly gross.
4904 * If we're doing job control, then we did a TIOCSPGRP which
4905 * caused us (the shell) to no longer be in the controlling
4906 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4907 * intuit from the subprocess exit status whether a SIGINT
4908 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4909 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004910 if (jp->sigint) /* TODO: do the same with all signals */
4911 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004912 }
4913 if (jp->state == JOBDONE)
4914#endif
4915 freejob(jp);
4916 return st;
4917}
4918
4919/*
4920 * return 1 if there are stopped jobs, otherwise 0
4921 */
4922static int
4923stoppedjobs(void)
4924{
4925 struct job *jp;
4926 int retval;
4927
4928 retval = 0;
4929 if (job_warning)
4930 goto out;
4931 jp = curjob;
4932 if (jp && jp->state == JOBSTOPPED) {
4933 out2str("You have stopped jobs.\n");
4934 job_warning = 2;
4935 retval++;
4936 }
4937 out:
4938 return retval;
4939}
4940
4941
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004942/* ============ redir.c
4943 *
4944 * Code for dealing with input/output redirection.
4945 */
4946
4947#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004948#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004949
4950/*
4951 * Open a file in noclobber mode.
4952 * The code was copied from bash.
4953 */
4954static int
4955noclobberopen(const char *fname)
4956{
4957 int r, fd;
4958 struct stat finfo, finfo2;
4959
4960 /*
4961 * If the file exists and is a regular file, return an error
4962 * immediately.
4963 */
4964 r = stat(fname, &finfo);
4965 if (r == 0 && S_ISREG(finfo.st_mode)) {
4966 errno = EEXIST;
4967 return -1;
4968 }
4969
4970 /*
4971 * If the file was not present (r != 0), make sure we open it
4972 * exclusively so that if it is created before we open it, our open
4973 * will fail. Make sure that we do not truncate an existing file.
4974 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4975 * file was not a regular file, we leave O_EXCL off.
4976 */
4977 if (r != 0)
4978 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4979 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4980
4981 /* If the open failed, return the file descriptor right away. */
4982 if (fd < 0)
4983 return fd;
4984
4985 /*
4986 * OK, the open succeeded, but the file may have been changed from a
4987 * non-regular file to a regular file between the stat and the open.
4988 * We are assuming that the O_EXCL open handles the case where FILENAME
4989 * did not exist and is symlinked to an existing file between the stat
4990 * and open.
4991 */
4992
4993 /*
4994 * If we can open it and fstat the file descriptor, and neither check
4995 * revealed that it was a regular file, and the file has not been
4996 * replaced, return the file descriptor.
4997 */
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02004998 if (fstat(fd, &finfo2) == 0
4999 && !S_ISREG(finfo2.st_mode)
5000 && finfo.st_dev == finfo2.st_dev
5001 && finfo.st_ino == finfo2.st_ino
5002 ) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003 return fd;
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02005004 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005005
5006 /* The file has been replaced. badness. */
5007 close(fd);
5008 errno = EEXIST;
5009 return -1;
5010}
5011
5012/*
5013 * Handle here documents. Normally we fork off a process to write the
5014 * data to a pipe. If the document is short, we can stuff the data in
5015 * the pipe without forking.
5016 */
5017/* openhere needs this forward reference */
5018static void expandhere(union node *arg, int fd);
5019static int
5020openhere(union node *redir)
5021{
5022 int pip[2];
5023 size_t len = 0;
5024
5025 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005026 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005027 if (redir->type == NHERE) {
5028 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005029 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005030 full_write(pip[1], redir->nhere.doc->narg.text, len);
5031 goto out;
5032 }
5033 }
5034 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005035 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005036 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00005037 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5038 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5039 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5040 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005041 signal(SIGPIPE, SIG_DFL);
5042 if (redir->type == NHERE)
5043 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00005044 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005045 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00005046 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005047 }
5048 out:
5049 close(pip[1]);
5050 return pip[0];
5051}
5052
5053static int
5054openredirect(union node *redir)
5055{
5056 char *fname;
5057 int f;
5058
5059 switch (redir->nfile.type) {
5060 case NFROM:
5061 fname = redir->nfile.expfname;
5062 f = open(fname, O_RDONLY);
5063 if (f < 0)
5064 goto eopen;
5065 break;
5066 case NFROMTO:
5067 fname = redir->nfile.expfname;
Andreas Bühmannda75f442010-06-24 04:32:37 +02005068 f = open(fname, O_RDWR|O_CREAT, 0666);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005069 if (f < 0)
5070 goto ecreate;
5071 break;
5072 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00005073#if ENABLE_ASH_BASH_COMPAT
5074 case NTO2:
5075#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005076 /* Take care of noclobber mode. */
5077 if (Cflag) {
5078 fname = redir->nfile.expfname;
5079 f = noclobberopen(fname);
5080 if (f < 0)
5081 goto ecreate;
5082 break;
5083 }
5084 /* FALLTHROUGH */
5085 case NCLOBBER:
5086 fname = redir->nfile.expfname;
5087 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5088 if (f < 0)
5089 goto ecreate;
5090 break;
5091 case NAPPEND:
5092 fname = redir->nfile.expfname;
5093 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5094 if (f < 0)
5095 goto ecreate;
5096 break;
5097 default:
5098#if DEBUG
5099 abort();
5100#endif
5101 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005102/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00005103// case NTOFD:
5104// case NFROMFD:
5105// f = -1;
5106// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 case NHERE:
5108 case NXHERE:
5109 f = openhere(redir);
5110 break;
5111 }
5112
5113 return f;
5114 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005115 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005116 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005117 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005118}
5119
5120/*
5121 * Copy a file descriptor to be >= to. Returns -1
5122 * if the source file descriptor is closed, EMPTY if there are no unused
5123 * file descriptors left.
5124 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005125/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5126 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005127enum {
5128 COPYFD_EXACT = (int)~(INT_MAX),
5129 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5130};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005131static int
5132copyfd(int from, int to)
5133{
5134 int newfd;
5135
Denis Vlasenko5a867312008-07-24 19:46:38 +00005136 if (to & COPYFD_EXACT) {
5137 to &= ~COPYFD_EXACT;
5138 /*if (from != to)*/
5139 newfd = dup2(from, to);
5140 } else {
5141 newfd = fcntl(from, F_DUPFD, to);
5142 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005143 if (newfd < 0) {
5144 if (errno == EMFILE)
5145 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005146 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005147 ash_msg_and_raise_error("%d: %m", from);
5148 }
5149 return newfd;
5150}
5151
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005152/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005153struct two_fd_t {
5154 int orig, copy;
5155};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005156struct redirtab {
5157 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005158 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005159 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005160 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005161};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005162#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005163
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005164static int need_to_remember(struct redirtab *rp, int fd)
5165{
5166 int i;
5167
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005168 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005169 return 0;
5170
5171 for (i = 0; i < rp->pair_count; i++) {
5172 if (rp->two_fd[i].orig == fd) {
5173 /* already remembered */
5174 return 0;
5175 }
5176 }
5177 return 1;
5178}
5179
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005180/* "hidden" fd is a fd used to read scripts, or a copy of such */
5181static int is_hidden_fd(struct redirtab *rp, int fd)
5182{
5183 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005184 struct parsefile *pf;
5185
5186 if (fd == -1)
5187 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005188 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005189 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005190 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005191 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005192 * $ ash # running ash interactively
5193 * $ . ./script.sh
5194 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005195 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005196 * it's still ok to use it: "read" builtin uses it,
5197 * why should we cripple "exec" builtin?
5198 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005199 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005200 return 1;
5201 }
5202 pf = pf->prev;
5203 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005204
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005205 if (!rp)
5206 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005207 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005208 fd |= COPYFD_RESTORE;
5209 for (i = 0; i < rp->pair_count; i++) {
5210 if (rp->two_fd[i].copy == fd) {
5211 return 1;
5212 }
5213 }
5214 return 0;
5215}
5216
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005217/*
5218 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5219 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005220 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005221 */
5222/* flags passed to redirect */
5223#define REDIR_PUSH 01 /* save previous values of file descriptors */
5224#define REDIR_SAVEFD2 03 /* set preverrout */
5225static void
5226redirect(union node *redir, int flags)
5227{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005228 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005229 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005230 int i;
5231 int fd;
5232 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005233 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005234
Denis Vlasenko01631112007-12-16 17:20:38 +00005235 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005236 if (!redir) {
5237 return;
5238 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005239
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005240 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005241 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 INT_OFF;
5243 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005244 union node *tmp = redir;
5245 do {
5246 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005247#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005248 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005249 sv_pos++;
5250#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005251 tmp = tmp->nfile.next;
5252 } while (tmp);
5253 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005254 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005255 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005256 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005257 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005258 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005259 while (sv_pos > 0) {
5260 sv_pos--;
5261 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5262 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005263 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005264
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005265 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005266 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005267 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005268 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005269 right_fd = redir->ndup.dupfd;
5270 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005271 /* redirect from/to same file descriptor? */
5272 if (right_fd == fd)
5273 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005274 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005275 if (is_hidden_fd(sv, right_fd)) {
5276 errno = EBADF; /* as if it is closed */
5277 ash_msg_and_raise_error("%d: %m", right_fd);
5278 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005279 newfd = -1;
5280 } else {
5281 newfd = openredirect(redir); /* always >= 0 */
5282 if (fd == newfd) {
5283 /* Descriptor wasn't open before redirect.
5284 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005285 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005286 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005287 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005288 continue;
5289 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005290 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005291#if ENABLE_ASH_BASH_COMPAT
5292 redirect_more:
5293#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005294 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005295 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005296 /* Careful to not accidentally "save"
5297 * to the same fd as right side fd in N>&M */
5298 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5299 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005300/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5301 * are closed in popredir() in the child, preventing them from leaking
5302 * into child. (popredir() also cleans up the mess in case of failures)
5303 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005304 if (i == -1) {
5305 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005306 if (i != EBADF) {
5307 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005308 if (newfd >= 0)
5309 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005310 errno = i;
5311 ash_msg_and_raise_error("%d: %m", fd);
5312 /* NOTREACHED */
5313 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005314 /* EBADF: it is not open - good, remember to close it */
5315 remember_to_close:
5316 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005317 } else { /* fd is open, save its copy */
5318 /* "exec fd>&-" should not close fds
5319 * which point to script file(s).
5320 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005321 if (is_hidden_fd(sv, fd))
5322 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005323 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005324 if (fd == 2)
5325 copied_fd2 = i;
5326 sv->two_fd[sv_pos].orig = fd;
5327 sv->two_fd[sv_pos].copy = i;
5328 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005329 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005330 if (newfd < 0) {
5331 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005332 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005333 /* Don't want to trigger debugging */
5334 if (fd != -1)
5335 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005336 } else {
5337 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005338 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005339 } else if (fd != newfd) { /* move newfd to fd */
5340 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005341#if ENABLE_ASH_BASH_COMPAT
5342 if (!(redir->nfile.type == NTO2 && fd == 2))
5343#endif
5344 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005345 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005346#if ENABLE_ASH_BASH_COMPAT
5347 if (redir->nfile.type == NTO2 && fd == 1) {
5348 /* We already redirected it to fd 1, now copy it to 2 */
5349 newfd = 1;
5350 fd = 2;
5351 goto redirect_more;
5352 }
5353#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005354 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005355
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005356 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005357 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5358 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005359}
5360
5361/*
5362 * Undo the effects of the last redirection.
5363 */
5364static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005365popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005366{
5367 struct redirtab *rp;
5368 int i;
5369
Denis Vlasenko01631112007-12-16 17:20:38 +00005370 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005371 return;
5372 INT_OFF;
5373 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005374 for (i = 0; i < rp->pair_count; i++) {
5375 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005376 int copy = rp->two_fd[i].copy;
5377 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005378 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005379 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005380 continue;
5381 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005382 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005383 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005384 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005385 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005386 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005387 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005388 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005389 }
5390 }
5391 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005392 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005393 free(rp);
5394 INT_ON;
5395}
5396
5397/*
5398 * Undo all redirections. Called on error or interrupt.
5399 */
5400
5401/*
5402 * Discard all saved file descriptors.
5403 */
5404static void
5405clearredir(int drop)
5406{
5407 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005408 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005409 if (!redirlist)
5410 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005411 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005412 }
5413}
5414
5415static int
5416redirectsafe(union node *redir, int flags)
5417{
5418 int err;
5419 volatile int saveint;
5420 struct jmploc *volatile savehandler = exception_handler;
5421 struct jmploc jmploc;
5422
5423 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005424 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5425 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005426 if (!err) {
5427 exception_handler = &jmploc;
5428 redirect(redir, flags);
5429 }
5430 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005431 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005432 longjmp(exception_handler->loc, 1);
5433 RESTORE_INT(saveint);
5434 return err;
5435}
5436
5437
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005438/* ============ Routines to expand arguments to commands
5439 *
5440 * We have to deal with backquotes, shell variables, and file metacharacters.
5441 */
5442
Mike Frysinger98c52642009-04-02 10:02:37 +00005443#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005444static arith_t
5445ash_arith(const char *s)
5446{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005447 arith_state_t math_state;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005448 arith_t result;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005449
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005450 math_state.lookupvar = lookupvar;
5451 math_state.setvar = setvar2;
5452 //math_state.endofname = endofname;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005453
5454 INT_OFF;
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005455 result = arith(&math_state, s);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005456 if (math_state.errmsg)
5457 ash_msg_and_raise_error(math_state.errmsg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005458 INT_ON;
5459
5460 return result;
5461}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005462#endif
5463
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464/*
5465 * expandarg flags
5466 */
5467#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5468#define EXP_TILDE 0x2 /* do normal tilde expansion */
5469#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5470#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5471#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5472#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5473#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5474#define EXP_WORD 0x80 /* expand word in parameter expansion */
5475#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5476/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005477 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005478 */
5479#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5480#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5481#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5482#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5483#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5484
5485/*
5486 * Structure specifying which parts of the string should be searched
5487 * for IFS characters.
5488 */
5489struct ifsregion {
5490 struct ifsregion *next; /* next region in list */
5491 int begoff; /* offset of start of region */
5492 int endoff; /* offset of end of region */
5493 int nulonly; /* search for nul bytes only */
5494};
5495
5496struct arglist {
5497 struct strlist *list;
5498 struct strlist **lastp;
5499};
5500
5501/* output of current string */
5502static char *expdest;
5503/* list of back quote expressions */
5504static struct nodelist *argbackq;
5505/* first struct in list of ifs regions */
5506static struct ifsregion ifsfirst;
5507/* last struct in list */
5508static struct ifsregion *ifslastp;
5509/* holds expanded arg list */
5510static struct arglist exparg;
5511
5512/*
5513 * Our own itoa().
5514 */
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005515#if !ENABLE_SH_MATH_SUPPORT
5516/* cvtnum() is used even if math support is off (to prepare $? values and such) */
5517typedef long arith_t;
5518# define ARITH_FMT "%ld"
5519#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005520static int
5521cvtnum(arith_t num)
5522{
5523 int len;
5524
5525 expdest = makestrspace(32, expdest);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005526 len = fmtstr(expdest, 32, ARITH_FMT, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005527 STADJUST(len, expdest);
5528 return len;
5529}
5530
5531static size_t
5532esclen(const char *start, const char *p)
5533{
5534 size_t esc = 0;
5535
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005536 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005537 esc++;
5538 }
5539 return esc;
5540}
5541
5542/*
5543 * Remove any CTLESC characters from a string.
5544 */
5545static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005546rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005547{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005548 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005549
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005550 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005551 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005552 unsigned protect_against_glob;
5553 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005554
5555 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005556 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005557 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005558
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005559 q = p;
5560 r = str;
5561 if (flag & RMESCAPE_ALLOC) {
5562 size_t len = p - str;
5563 size_t fulllen = len + strlen(p) + 1;
5564
5565 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005566 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005567 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005568 /* p and str may be invalidated by makestrspace */
5569 str = (char *)stackblock() + strloc;
5570 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005571 } else if (flag & RMESCAPE_HEAP) {
5572 r = ckmalloc(fulllen);
5573 } else {
5574 r = stalloc(fulllen);
5575 }
5576 q = r;
5577 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005578 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005579 }
5580 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005581
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005582 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5583 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005584 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005585 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005586 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005587// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5588// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5589// Note: both inquotes and protect_against_glob only affect whether
5590// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005591 inquotes = ~inquotes;
5592 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005593 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005594 continue;
5595 }
5596 if (*p == '\\') {
5597 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005598 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005599 goto copy;
5600 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005601 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005602 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005603 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005604 *q++ = '\\';
5605 }
5606 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005607 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005608 copy:
5609 *q++ = *p++;
5610 }
5611 *q = '\0';
5612 if (flag & RMESCAPE_GROW) {
5613 expdest = r;
5614 STADJUST(q - r + 1, expdest);
5615 }
5616 return r;
5617}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005618#define pmatch(a, b) !fnmatch((a), (b), 0)
5619
5620/*
5621 * Prepare a pattern for a expmeta (internal glob(3)) call.
5622 *
5623 * Returns an stalloced string.
5624 */
5625static char *
5626preglob(const char *pattern, int quoted, int flag)
5627{
5628 flag |= RMESCAPE_GLOB;
5629 if (quoted) {
5630 flag |= RMESCAPE_QUOTED;
5631 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005632 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005633}
5634
5635/*
5636 * Put a string on the stack.
5637 */
5638static void
5639memtodest(const char *p, size_t len, int syntax, int quotes)
5640{
5641 char *q = expdest;
5642
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005643 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005644
5645 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005646 unsigned char c = *p++;
5647 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005648 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005649 if (quotes) {
5650 int n = SIT(c, syntax);
5651 if (n == CCTL || n == CBACK)
5652 USTPUTC(CTLESC, q);
5653 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005654 USTPUTC(c, q);
5655 }
5656
5657 expdest = q;
5658}
5659
5660static void
5661strtodest(const char *p, int syntax, int quotes)
5662{
5663 memtodest(p, strlen(p), syntax, quotes);
5664}
5665
5666/*
5667 * Record the fact that we have to scan this region of the
5668 * string for IFS characters.
5669 */
5670static void
5671recordregion(int start, int end, int nulonly)
5672{
5673 struct ifsregion *ifsp;
5674
5675 if (ifslastp == NULL) {
5676 ifsp = &ifsfirst;
5677 } else {
5678 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005679 ifsp = ckzalloc(sizeof(*ifsp));
5680 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005681 ifslastp->next = ifsp;
5682 INT_ON;
5683 }
5684 ifslastp = ifsp;
5685 ifslastp->begoff = start;
5686 ifslastp->endoff = end;
5687 ifslastp->nulonly = nulonly;
5688}
5689
5690static void
5691removerecordregions(int endoff)
5692{
5693 if (ifslastp == NULL)
5694 return;
5695
5696 if (ifsfirst.endoff > endoff) {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005697 while (ifsfirst.next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005698 struct ifsregion *ifsp;
5699 INT_OFF;
5700 ifsp = ifsfirst.next->next;
5701 free(ifsfirst.next);
5702 ifsfirst.next = ifsp;
5703 INT_ON;
5704 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005705 if (ifsfirst.begoff > endoff) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005706 ifslastp = NULL;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005707 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005708 ifslastp = &ifsfirst;
5709 ifsfirst.endoff = endoff;
5710 }
5711 return;
5712 }
5713
5714 ifslastp = &ifsfirst;
5715 while (ifslastp->next && ifslastp->next->begoff < endoff)
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005716 ifslastp = ifslastp->next;
5717 while (ifslastp->next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005718 struct ifsregion *ifsp;
5719 INT_OFF;
5720 ifsp = ifslastp->next->next;
5721 free(ifslastp->next);
5722 ifslastp->next = ifsp;
5723 INT_ON;
5724 }
5725 if (ifslastp->endoff > endoff)
5726 ifslastp->endoff = endoff;
5727}
5728
5729static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005730exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005731{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005732 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005733 char *name;
5734 struct passwd *pw;
5735 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005736 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005737 int startloc;
5738
5739 name = p + 1;
5740
5741 while ((c = *++p) != '\0') {
5742 switch (c) {
5743 case CTLESC:
5744 return startp;
5745 case CTLQUOTEMARK:
5746 return startp;
5747 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005748 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005749 goto done;
5750 break;
5751 case '/':
5752 case CTLENDVAR:
5753 goto done;
5754 }
5755 }
5756 done:
5757 *p = '\0';
5758 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005759 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005760 } else {
5761 pw = getpwnam(name);
5762 if (pw == NULL)
5763 goto lose;
5764 home = pw->pw_dir;
5765 }
5766 if (!home || !*home)
5767 goto lose;
5768 *p = c;
5769 startloc = expdest - (char *)stackblock();
5770 strtodest(home, SQSYNTAX, quotes);
5771 recordregion(startloc, expdest - (char *)stackblock(), 0);
5772 return p;
5773 lose:
5774 *p = c;
5775 return startp;
5776}
5777
5778/*
5779 * Execute a command inside back quotes. If it's a builtin command, we
5780 * want to save its output in a block obtained from malloc. Otherwise
5781 * we fork off a subprocess and get the output of the command via a pipe.
5782 * Should be called with interrupts off.
5783 */
5784struct backcmd { /* result of evalbackcmd */
5785 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005786 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005787 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005788 struct job *jp; /* job structure for command */
5789};
5790
5791/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005792static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005793#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005794static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005795
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005796static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005797evalbackcmd(union node *n, struct backcmd *result)
5798{
5799 int saveherefd;
5800
5801 result->fd = -1;
5802 result->buf = NULL;
5803 result->nleft = 0;
5804 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005805 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005806 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005807
5808 saveherefd = herefd;
5809 herefd = -1;
5810
5811 {
5812 int pip[2];
5813 struct job *jp;
5814
5815 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005816 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005817 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005818 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5819 FORCE_INT_ON;
5820 close(pip[0]);
5821 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005822 /*close(1);*/
5823 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005824 close(pip[1]);
5825 }
5826 eflag = 0;
5827 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5828 /* NOTREACHED */
5829 }
5830 close(pip[1]);
5831 result->fd = pip[0];
5832 result->jp = jp;
5833 }
5834 herefd = saveherefd;
5835 out:
5836 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5837 result->fd, result->buf, result->nleft, result->jp));
5838}
5839
5840/*
5841 * Expand stuff in backwards quotes.
5842 */
5843static void
5844expbackq(union node *cmd, int quoted, int quotes)
5845{
5846 struct backcmd in;
5847 int i;
5848 char buf[128];
5849 char *p;
5850 char *dest;
5851 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005852 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005853 struct stackmark smark;
5854
5855 INT_OFF;
5856 setstackmark(&smark);
5857 dest = expdest;
5858 startloc = dest - (char *)stackblock();
5859 grabstackstr(dest);
5860 evalbackcmd(cmd, &in);
5861 popstackmark(&smark);
5862
5863 p = in.buf;
5864 i = in.nleft;
5865 if (i == 0)
5866 goto read;
5867 for (;;) {
5868 memtodest(p, i, syntax, quotes);
5869 read:
5870 if (in.fd < 0)
5871 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005872 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005873 TRACE(("expbackq: read returns %d\n", i));
5874 if (i <= 0)
5875 break;
5876 p = buf;
5877 }
5878
Denis Vlasenko60818682007-09-28 22:07:23 +00005879 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 if (in.fd >= 0) {
5881 close(in.fd);
5882 back_exitstatus = waitforjob(in.jp);
5883 }
5884 INT_ON;
5885
5886 /* Eat all trailing newlines */
5887 dest = expdest;
5888 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5889 STUNPUTC(dest);
5890 expdest = dest;
5891
5892 if (quoted == 0)
5893 recordregion(startloc, dest - (char *)stackblock(), 0);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005894 TRACE(("evalbackq: size:%d:'%.*s'\n",
5895 (int)((dest - (char *)stackblock()) - startloc),
5896 (int)((dest - (char *)stackblock()) - startloc),
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897 stackblock() + startloc));
5898}
5899
Mike Frysinger98c52642009-04-02 10:02:37 +00005900#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901/*
5902 * Expand arithmetic expression. Backup to start of expression,
5903 * evaluate, place result in (backed up) result, adjust string position.
5904 */
5905static void
5906expari(int quotes)
5907{
5908 char *p, *start;
5909 int begoff;
5910 int flag;
5911 int len;
5912
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005913 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005914
5915 /*
5916 * This routine is slightly over-complicated for
5917 * efficiency. Next we scan backwards looking for the
5918 * start of arithmetic.
5919 */
5920 start = stackblock();
5921 p = expdest - 1;
5922 *p = '\0';
5923 p--;
5924 do {
5925 int esc;
5926
Denys Vlasenkocd716832009-11-28 22:14:02 +01005927 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005928 p--;
5929#if DEBUG
5930 if (p < start) {
5931 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5932 }
5933#endif
5934 }
5935
5936 esc = esclen(start, p);
5937 if (!(esc % 2)) {
5938 break;
5939 }
5940
5941 p -= esc + 1;
5942 } while (1);
5943
5944 begoff = p - start;
5945
5946 removerecordregions(begoff);
5947
5948 flag = p[1];
5949
5950 expdest = p;
5951
5952 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005953 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005954
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005955 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005956
5957 if (flag != '"')
5958 recordregion(begoff, begoff + len, 0);
5959}
5960#endif
5961
5962/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005963static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005964
5965/*
5966 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5967 * characters to allow for further processing. Otherwise treat
5968 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005969 *
5970 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5971 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5972 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 */
5974static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005975argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005976{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005977 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005978 '=',
5979 ':',
5980 CTLQUOTEMARK,
5981 CTLENDVAR,
5982 CTLESC,
5983 CTLVAR,
5984 CTLBACKQ,
5985 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005986#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005987 CTLENDARI,
5988#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005989 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005990 };
5991 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005992 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5993 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005994 int inquotes;
5995 size_t length;
5996 int startloc;
5997
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005998 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005999 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006000 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006001 reject++;
6002 }
6003 inquotes = 0;
6004 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006005 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006006 char *q;
6007
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006008 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006009 tilde:
6010 q = p;
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006011 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006012 q++;
6013 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006014 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006015 }
6016 start:
6017 startloc = expdest - (char *)stackblock();
6018 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006019 unsigned char c;
6020
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006021 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006022 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006023 if (c) {
6024 if (!(c & 0x80)
Denys Vlasenko958581a2010-09-12 15:04:27 +02006025 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006026 ) {
6027 /* c == '=' || c == ':' || c == CTLENDARI */
6028 length++;
6029 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006030 }
6031 if (length > 0) {
6032 int newloc;
6033 expdest = stack_nputstr(p, length, expdest);
6034 newloc = expdest - (char *)stackblock();
6035 if (breakall && !inquotes && newloc > startloc) {
6036 recordregion(startloc, newloc, 0);
6037 }
6038 startloc = newloc;
6039 }
6040 p += length + 1;
6041 length = 0;
6042
6043 switch (c) {
6044 case '\0':
6045 goto breakloop;
6046 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006047 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006048 p--;
6049 continue;
6050 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006051 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006052 reject++;
6053 /* fall through */
6054 case ':':
6055 /*
6056 * sort of a hack - expand tildes in variable
6057 * assignments (after the first '=' and after ':'s).
6058 */
6059 if (*--p == '~') {
6060 goto tilde;
6061 }
6062 continue;
6063 }
6064
6065 switch (c) {
6066 case CTLENDVAR: /* ??? */
6067 goto breakloop;
6068 case CTLQUOTEMARK:
6069 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006070 if (!inquotes
6071 && memcmp(p, dolatstr, 4) == 0
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006072 && ( p[4] == (char)CTLQUOTEMARK
6073 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006074 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006075 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006076 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006077 goto start;
6078 }
6079 inquotes = !inquotes;
6080 addquote:
6081 if (quotes) {
6082 p--;
6083 length++;
6084 startloc++;
6085 }
6086 break;
6087 case CTLESC:
6088 startloc++;
6089 length++;
6090 goto addquote;
6091 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006092 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006093 goto start;
6094 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006095 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006096 case CTLBACKQ|CTLQUOTE:
6097 expbackq(argbackq->n, c, quotes);
6098 argbackq = argbackq->next;
6099 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00006100#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006101 case CTLENDARI:
6102 p--;
6103 expari(quotes);
6104 goto start;
6105#endif
6106 }
6107 }
Denys Vlasenko958581a2010-09-12 15:04:27 +02006108 breakloop: ;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006109}
6110
6111static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006112scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6113 char *pattern, int quotes, int zero)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006114{
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006115 char *loc, *loc2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006116 char c;
6117
6118 loc = startp;
6119 loc2 = rmesc;
6120 do {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006121 int match;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006122 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006123
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006124 c = *loc2;
6125 if (zero) {
6126 *loc2 = '\0';
6127 s = rmesc;
6128 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006129 match = pmatch(pattern, s);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006130
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006131 *loc2 = c;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006132 if (match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006133 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006134 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006135 loc++;
6136 loc++;
6137 loc2++;
6138 } while (c);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006139 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006140}
6141
6142static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006143scanright(char *startp, char *rmesc, char *rmescend,
6144 char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006146#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6147 int try2optimize = match_at_start;
6148#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149 int esc = 0;
6150 char *loc;
6151 char *loc2;
6152
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006153 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6154 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6155 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6156 * Logic:
6157 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6158 * and on each iteration they go back two/one char until they reach the beginning.
6159 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6160 */
6161 /* TODO: document in what other circumstances we are called. */
6162
6163 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006164 int match;
6165 char c = *loc2;
6166 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006167 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006168 *loc2 = '\0';
6169 s = rmesc;
6170 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006171 match = pmatch(pattern, s);
6172 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006173 *loc2 = c;
6174 if (match)
6175 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006176#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6177 if (try2optimize) {
6178 /* Maybe we can optimize this:
6179 * if pattern ends with unescaped *, we can avoid checking
6180 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6181 * it wont match truncated "raw_value_of_" strings too.
6182 */
6183 unsigned plen = strlen(pattern);
6184 /* Does it end with "*"? */
6185 if (plen != 0 && pattern[--plen] == '*') {
6186 /* "xxxx*" is not escaped */
6187 /* "xxx\*" is escaped */
6188 /* "xx\\*" is not escaped */
6189 /* "x\\\*" is escaped */
6190 int slashes = 0;
6191 while (plen != 0 && pattern[--plen] == '\\')
6192 slashes++;
6193 if (!(slashes & 1))
6194 break; /* ends with unescaped "*" */
6195 }
6196 try2optimize = 0;
6197 }
6198#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006199 loc--;
6200 if (quotes) {
6201 if (--esc < 0) {
6202 esc = esclen(startp, loc);
6203 }
6204 if (esc % 2) {
6205 esc--;
6206 loc--;
6207 }
6208 }
6209 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006210 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006211}
6212
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006213static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006214static void
6215varunset(const char *end, const char *var, const char *umsg, int varflags)
6216{
6217 const char *msg;
6218 const char *tail;
6219
6220 tail = nullstr;
6221 msg = "parameter not set";
6222 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006223 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006224 if (varflags & VSNUL)
6225 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006226 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006227 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006228 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006229 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006230 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006231}
6232
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006233#if ENABLE_ASH_BASH_COMPAT
6234static char *
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006235parse_sub_pattern(char *arg, int varflags)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006236{
6237 char *idx, *repl = NULL;
6238 unsigned char c;
6239
Denys Vlasenko16149002010-08-06 22:06:21 +02006240 //char *org_arg = arg;
Denys Vlasenko33bbb272010-08-07 22:24:36 +02006241 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
Denis Vlasenko2659c632008-06-14 06:04:59 +00006242 idx = arg;
6243 while (1) {
6244 c = *arg;
6245 if (!c)
6246 break;
6247 if (c == '/') {
6248 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006249 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006250 repl = idx + 1;
6251 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006252 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006253 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006254 *idx++ = c;
Denis Vlasenko2659c632008-06-14 06:04:59 +00006255 arg++;
Denys Vlasenko33bbb272010-08-07 22:24:36 +02006256 /*
6257 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6258 * The result is a_\_z_c (not a\_\_z_c)!
6259 *
6260 * Enable debug prints in this function and you'll see:
6261 * ash: arg:'\\b/_\\_z_' varflags:d
6262 * ash: pattern:'\\b' repl:'_\_z_'
6263 * That is, \\b is interpreted as \\b, but \\_ as \_!
6264 * IOW: search pattern and replace string treat backslashes
6265 * differently! That is the reason why we check repl below:
6266 */
6267 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6268 arg++; /* skip both '\', not just first one */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006269 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006270 *idx = c; /* NUL */
Denys Vlasenko16149002010-08-06 22:06:21 +02006271 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272
6273 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006274}
6275#endif /* ENABLE_ASH_BASH_COMPAT */
6276
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006277static const char *
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006278subevalvar(char *p, char *varname, int strloc, int subtype,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006279 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006280{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006281 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006282 char *startp;
6283 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006284 char *rmesc, *rmescend;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006285 char *str;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006286 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006287 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006288 int saveherefd = herefd;
6289 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006290 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006291 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006292
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006293 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6294 // p, varname, strloc, subtype, startloc, varflags, quotes);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006295
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006296 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006297 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6298 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006299 STPUTC('\0', expdest);
6300 herefd = saveherefd;
6301 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006302 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006303
6304 switch (subtype) {
6305 case VSASSIGN:
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006306 setvar(varname, startp, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006307 amount = startp - expdest;
6308 STADJUST(amount, expdest);
6309 return startp;
6310
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006311 case VSQUESTION:
6312 varunset(p, varname, startp, varflags);
6313 /* NOTREACHED */
6314
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006315#if ENABLE_ASH_BASH_COMPAT
6316 case VSSUBSTR:
6317 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006318 /* Read POS in ${var:POS:LEN} */
6319 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006320 len = str - startp - 1;
6321
6322 /* *loc != '\0', guaranteed by parser */
6323 if (quotes) {
6324 char *ptr;
6325
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006326 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006327 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006328 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006329 len--;
6330 ptr++;
6331 }
6332 }
6333 }
6334 orig_len = len;
6335
6336 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006337 /* ${var::LEN} */
6338 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006339 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006340 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006341 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006342 while (*loc && *loc != ':') {
6343 /* TODO?
6344 * bash complains on: var=qwe; echo ${var:1a:123}
6345 if (!isdigit(*loc))
6346 ash_msg_and_raise_error(msg_illnum, str);
6347 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006348 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006349 }
6350 if (*loc++ == ':') {
6351 len = number(loc);
6352 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006353 }
6354 if (pos >= orig_len) {
6355 pos = 0;
6356 len = 0;
6357 }
6358 if (len > (orig_len - pos))
6359 len = orig_len - pos;
6360
6361 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006362 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006363 str++;
6364 }
6365 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006366 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006367 *loc++ = *str++;
6368 *loc++ = *str++;
6369 }
6370 *loc = '\0';
6371 amount = loc - expdest;
6372 STADJUST(amount, expdest);
6373 return loc;
6374#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006375 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006376
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006377 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006378
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006379 /* We'll comeback here if we grow the stack while handling
6380 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6381 * stack will need rebasing, and we'll need to remove our work
6382 * areas each time
6383 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006384 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006385
6386 amount = expdest - ((char *)stackblock() + resetloc);
6387 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006388 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006389
6390 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006391 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006392 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006393 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006394 if (rmesc != startp) {
6395 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006396 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006397 }
6398 }
6399 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006400 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006401 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006402 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006403
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006404#if ENABLE_ASH_BASH_COMPAT
6405 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006406 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006407
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006408 if (!repl) {
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006409 repl = parse_sub_pattern(str, varflags);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006410 //bb_error_msg("repl:'%s'", repl);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006411 if (!repl)
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006412 repl = nullstr;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006413 }
6414
6415 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006416 if (str[0] == '\0')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006417 return NULL;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006418
6419 len = 0;
6420 idx = startp;
6421 end = str - 1;
6422 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006423 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006424 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006425 //bb_error_msg("scanright('%s'):'%s'", str, loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006426 if (!loc) {
6427 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006428 char *restart_detect = stackblock();
6429 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006430 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006431 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006432 idx++;
6433 len++;
6434 STPUTC(*idx, expdest);
6435 }
6436 if (stackblock() != restart_detect)
6437 goto restart;
6438 idx++;
6439 len++;
6440 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006441 /* continue; - prone to quadratic behavior, smarter code: */
6442 if (idx >= end)
6443 break;
6444 if (str[0] == '*') {
6445 /* Pattern is "*foo". If "*foo" does not match "long_string",
6446 * it would never match "ong_string" etc, no point in trying.
6447 */
6448 goto skip_matching;
6449 }
6450 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006451 }
6452
6453 if (subtype == VSREPLACEALL) {
6454 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006455 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006456 idx++;
6457 idx++;
6458 rmesc++;
6459 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006460 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006461 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006462 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006463
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006464 //bb_error_msg("repl:'%s'", repl);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006465 for (loc = (char*)repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006466 char *restart_detect = stackblock();
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006467 if (quotes && *loc == '\\') {
6468 STPUTC(CTLESC, expdest);
6469 len++;
6470 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006471 STPUTC(*loc, expdest);
6472 if (stackblock() != restart_detect)
6473 goto restart;
6474 len++;
6475 }
6476
6477 if (subtype == VSREPLACE) {
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006478 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006479 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006480 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006481 STPUTC(*idx, expdest);
6482 if (stackblock() != restart_detect)
6483 goto restart;
6484 len++;
6485 idx++;
6486 }
6487 break;
6488 }
6489 }
6490
6491 /* We've put the replaced text into a buffer at workloc, now
6492 * move it to the right place and adjust the stack.
6493 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006494 STPUTC('\0', expdest);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006495 startp = (char *)stackblock() + startloc;
6496 memmove(startp, (char *)stackblock() + workloc, len + 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006497 //bb_error_msg("startp:'%s'", startp);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006498 amount = expdest - (startp + len);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006499 STADJUST(-amount, expdest);
6500 return startp;
6501 }
6502#endif /* ENABLE_ASH_BASH_COMPAT */
6503
6504 subtype -= VSTRIMRIGHT;
6505#if DEBUG
6506 if (subtype < 0 || subtype > 7)
6507 abort();
6508#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006509 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006510 zero = subtype >> 1;
6511 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6512 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6513
6514 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6515 if (loc) {
6516 if (zero) {
6517 memmove(startp, loc, str - loc);
6518 loc = startp + (str - loc) - 1;
6519 }
6520 *loc = '\0';
6521 amount = loc - expdest;
6522 STADJUST(amount, expdest);
6523 }
6524 return loc;
6525}
6526
6527/*
6528 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006529 * name parameter (examples):
6530 * ash -c 'echo $1' name:'1='
6531 * ash -c 'echo $qwe' name:'qwe='
6532 * ash -c 'echo $$' name:'$='
6533 * ash -c 'echo ${$}' name:'$='
6534 * ash -c 'echo ${$##q}' name:'$=q'
6535 * ash -c 'echo ${#$}' name:'$='
6536 * note: examples with bad shell syntax:
6537 * ash -c 'echo ${#$1}' name:'$=1'
6538 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006539 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006540static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006541varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006542{
Mike Frysinger98c52642009-04-02 10:02:37 +00006543 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006544 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006545 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 int sepq = 0;
6547 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006548 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006549 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006550 int quoted = varflags & VSQUOTE;
6551 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006552
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006553 switch (*name) {
6554 case '$':
6555 num = rootpid;
6556 goto numvar;
6557 case '?':
6558 num = exitstatus;
6559 goto numvar;
6560 case '#':
6561 num = shellparam.nparam;
6562 goto numvar;
6563 case '!':
6564 num = backgndpid;
6565 if (num == 0)
6566 return -1;
6567 numvar:
6568 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006569 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006570 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006571 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006572 for (i = NOPTS - 1; i >= 0; i--) {
6573 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006574 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006575 len++;
6576 }
6577 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006578 check_1char_name:
6579#if 0
6580 /* handles cases similar to ${#$1} */
6581 if (name[2] != '\0')
6582 raise_error_syntax("bad substitution");
6583#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006584 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006585 case '@': {
6586 char **ap;
6587 int sep;
6588
6589 if (quoted && (flags & EXP_FULL)) {
6590 /* note: this is not meant as PEOF value */
6591 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006592 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006593 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594 /* fall through */
6595 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006596 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006597 i = SIT(sep, syntax);
6598 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006599 sepq = 1;
6600 param:
6601 ap = shellparam.p;
6602 if (!ap)
6603 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006604 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006605 size_t partlen;
6606
6607 partlen = strlen(p);
6608 len += partlen;
6609
6610 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6611 memtodest(p, partlen, syntax, quotes);
6612
6613 if (*ap && sep) {
6614 char *q;
6615
6616 len++;
6617 if (subtype == VSPLUS || subtype == VSLENGTH) {
6618 continue;
6619 }
6620 q = expdest;
6621 if (sepq)
6622 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006623 /* note: may put NUL despite sep != 0
6624 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006625 STPUTC(sep, q);
6626 expdest = q;
6627 }
6628 }
6629 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006630 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006631 case '0':
6632 case '1':
6633 case '2':
6634 case '3':
6635 case '4':
6636 case '5':
6637 case '6':
6638 case '7':
6639 case '8':
6640 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006641 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006642 if (num < 0 || num > shellparam.nparam)
6643 return -1;
6644 p = num ? shellparam.p[num - 1] : arg0;
6645 goto value;
6646 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006647 /* NB: name has form "VAR=..." */
6648
6649 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6650 * which should be considered before we check variables. */
6651 if (var_str_list) {
6652 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6653 p = NULL;
6654 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006655 char *str, *eq;
6656 str = var_str_list->text;
6657 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006658 if (!eq) /* stop at first non-assignment */
6659 break;
6660 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006661 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006662 && strncmp(str, name, name_len) == 0
6663 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006664 p = eq;
6665 /* goto value; - WRONG! */
6666 /* think "A=1 A=2 B=$A" */
6667 }
6668 var_str_list = var_str_list->next;
6669 } while (var_str_list);
6670 if (p)
6671 goto value;
6672 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006673 p = lookupvar(name);
6674 value:
6675 if (!p)
6676 return -1;
6677
6678 len = strlen(p);
6679 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6680 memtodest(p, len, syntax, quotes);
6681 return len;
6682 }
6683
6684 if (subtype == VSPLUS || subtype == VSLENGTH)
6685 STADJUST(-len, expdest);
6686 return len;
6687}
6688
6689/*
6690 * Expand a variable, and return a pointer to the next character in the
6691 * input string.
6692 */
6693static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006694evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006695{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006696 char varflags;
6697 char subtype;
6698 char quoted;
6699 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006700 char *var;
6701 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006702 int startloc;
6703 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006704
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006705 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006706 subtype = varflags & VSTYPE;
6707 quoted = varflags & VSQUOTE;
6708 var = p;
6709 easy = (!quoted || (*var == '@' && shellparam.nparam));
6710 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006711 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006712
6713 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006714 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006715 if (varflags & VSNUL)
6716 varlen--;
6717
6718 if (subtype == VSPLUS) {
6719 varlen = -1 - varlen;
6720 goto vsplus;
6721 }
6722
6723 if (subtype == VSMINUS) {
6724 vsplus:
6725 if (varlen < 0) {
6726 argstr(
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006727 p,
6728 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006729 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006730 );
6731 goto end;
6732 }
6733 if (easy)
6734 goto record;
6735 goto end;
6736 }
6737
6738 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6739 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006740 if (subevalvar(p, var, /* strloc: */ 0,
6741 subtype, startloc, varflags,
6742 /* quotes: */ 0,
6743 var_str_list)
6744 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006745 varflags &= ~VSNUL;
6746 /*
6747 * Remove any recorded regions beyond
6748 * start of variable
6749 */
6750 removerecordregions(startloc);
6751 goto again;
6752 }
6753 goto end;
6754 }
6755 if (easy)
6756 goto record;
6757 goto end;
6758 }
6759
6760 if (varlen < 0 && uflag)
6761 varunset(p, var, 0, 0);
6762
6763 if (subtype == VSLENGTH) {
6764 cvtnum(varlen > 0 ? varlen : 0);
6765 goto record;
6766 }
6767
6768 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006769 if (easy)
6770 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006771 goto end;
6772 }
6773
6774#if DEBUG
6775 switch (subtype) {
6776 case VSTRIMLEFT:
6777 case VSTRIMLEFTMAX:
6778 case VSTRIMRIGHT:
6779 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006780#if ENABLE_ASH_BASH_COMPAT
6781 case VSSUBSTR:
6782 case VSREPLACE:
6783 case VSREPLACEALL:
6784#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006785 break;
6786 default:
6787 abort();
6788 }
6789#endif
6790
6791 if (varlen >= 0) {
6792 /*
6793 * Terminate the string and start recording the pattern
6794 * right after it
6795 */
6796 STPUTC('\0', expdest);
6797 patloc = expdest - (char *)stackblock();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006798 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006799 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006800//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006801 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006802 var_str_list)
6803 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006804 int amount = expdest - (
6805 (char *)stackblock() + patloc - 1
6806 );
6807 STADJUST(-amount, expdest);
6808 }
6809 /* Remove any recorded regions beyond start of variable */
6810 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006811 record:
6812 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006813 }
6814
6815 end:
6816 if (subtype != VSNORMAL) { /* skip to end of alternative */
6817 int nesting = 1;
6818 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006819 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006820 if (c == CTLESC)
6821 p++;
6822 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6823 if (varlen >= 0)
6824 argbackq = argbackq->next;
6825 } else if (c == CTLVAR) {
6826 if ((*p++ & VSTYPE) != VSNORMAL)
6827 nesting++;
6828 } else if (c == CTLENDVAR) {
6829 if (--nesting == 0)
6830 break;
6831 }
6832 }
6833 }
6834 return p;
6835}
6836
6837/*
6838 * Break the argument string into pieces based upon IFS and add the
6839 * strings to the argument list. The regions of the string to be
6840 * searched for IFS characters have been stored by recordregion.
6841 */
6842static void
6843ifsbreakup(char *string, struct arglist *arglist)
6844{
6845 struct ifsregion *ifsp;
6846 struct strlist *sp;
6847 char *start;
6848 char *p;
6849 char *q;
6850 const char *ifs, *realifs;
6851 int ifsspc;
6852 int nulonly;
6853
6854 start = string;
6855 if (ifslastp != NULL) {
6856 ifsspc = 0;
6857 nulonly = 0;
6858 realifs = ifsset() ? ifsval() : defifs;
6859 ifsp = &ifsfirst;
6860 do {
6861 p = string + ifsp->begoff;
6862 nulonly = ifsp->nulonly;
6863 ifs = nulonly ? nullstr : realifs;
6864 ifsspc = 0;
6865 while (p < string + ifsp->endoff) {
6866 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006867 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006868 p++;
6869 if (!strchr(ifs, *p)) {
6870 p++;
6871 continue;
6872 }
6873 if (!nulonly)
6874 ifsspc = (strchr(defifs, *p) != NULL);
6875 /* Ignore IFS whitespace at start */
6876 if (q == start && ifsspc) {
6877 p++;
6878 start = p;
6879 continue;
6880 }
6881 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006882 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006883 sp->text = start;
6884 *arglist->lastp = sp;
6885 arglist->lastp = &sp->next;
6886 p++;
6887 if (!nulonly) {
6888 for (;;) {
6889 if (p >= string + ifsp->endoff) {
6890 break;
6891 }
6892 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006893 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006894 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006895 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006896 p = q;
6897 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006898 }
6899 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006900 if (ifsspc) {
6901 p++;
6902 ifsspc = 0;
6903 } else {
6904 p = q;
6905 break;
6906 }
6907 } else
6908 p++;
6909 }
6910 }
6911 start = p;
6912 } /* while */
6913 ifsp = ifsp->next;
6914 } while (ifsp != NULL);
6915 if (nulonly)
6916 goto add;
6917 }
6918
6919 if (!*start)
6920 return;
6921
6922 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006923 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006924 sp->text = start;
6925 *arglist->lastp = sp;
6926 arglist->lastp = &sp->next;
6927}
6928
6929static void
6930ifsfree(void)
6931{
6932 struct ifsregion *p;
6933
6934 INT_OFF;
6935 p = ifsfirst.next;
6936 do {
6937 struct ifsregion *ifsp;
6938 ifsp = p->next;
6939 free(p);
6940 p = ifsp;
6941 } while (p);
6942 ifslastp = NULL;
6943 ifsfirst.next = NULL;
6944 INT_ON;
6945}
6946
6947/*
6948 * Add a file name to the list.
6949 */
6950static void
6951addfname(const char *name)
6952{
6953 struct strlist *sp;
6954
Denis Vlasenko597906c2008-02-20 16:38:54 +00006955 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006956 sp->text = ststrdup(name);
6957 *exparg.lastp = sp;
6958 exparg.lastp = &sp->next;
6959}
6960
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006961/*
6962 * Do metacharacter (i.e. *, ?, [...]) expansion.
6963 */
6964static void
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006965expmeta(char *expdir, char *enddir, char *name)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006966{
6967 char *p;
6968 const char *cp;
6969 char *start;
6970 char *endname;
6971 int metaflag;
6972 struct stat statb;
6973 DIR *dirp;
6974 struct dirent *dp;
6975 int atend;
6976 int matchdot;
6977
6978 metaflag = 0;
6979 start = name;
6980 for (p = name; *p; p++) {
6981 if (*p == '*' || *p == '?')
6982 metaflag = 1;
6983 else if (*p == '[') {
6984 char *q = p + 1;
6985 if (*q == '!')
6986 q++;
6987 for (;;) {
6988 if (*q == '\\')
6989 q++;
6990 if (*q == '/' || *q == '\0')
6991 break;
6992 if (*++q == ']') {
6993 metaflag = 1;
6994 break;
6995 }
6996 }
6997 } else if (*p == '\\')
6998 p++;
6999 else if (*p == '/') {
7000 if (metaflag)
7001 goto out;
7002 start = p + 1;
7003 }
7004 }
7005 out:
7006 if (metaflag == 0) { /* we've reached the end of the file name */
7007 if (enddir != expdir)
7008 metaflag++;
7009 p = name;
7010 do {
7011 if (*p == '\\')
7012 p++;
7013 *enddir++ = *p;
7014 } while (*p++);
7015 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7016 addfname(expdir);
7017 return;
7018 }
7019 endname = p;
7020 if (name < start) {
7021 p = name;
7022 do {
7023 if (*p == '\\')
7024 p++;
7025 *enddir++ = *p++;
7026 } while (p < start);
7027 }
7028 if (enddir == expdir) {
7029 cp = ".";
7030 } else if (enddir == expdir + 1 && *expdir == '/') {
7031 cp = "/";
7032 } else {
7033 cp = expdir;
7034 enddir[-1] = '\0';
7035 }
7036 dirp = opendir(cp);
7037 if (dirp == NULL)
7038 return;
7039 if (enddir != expdir)
7040 enddir[-1] = '/';
7041 if (*endname == 0) {
7042 atend = 1;
7043 } else {
7044 atend = 0;
7045 *endname++ = '\0';
7046 }
7047 matchdot = 0;
7048 p = start;
7049 if (*p == '\\')
7050 p++;
7051 if (*p == '.')
7052 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007053 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007054 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007055 continue;
7056 if (pmatch(start, dp->d_name)) {
7057 if (atend) {
7058 strcpy(enddir, dp->d_name);
7059 addfname(expdir);
7060 } else {
7061 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7062 continue;
7063 p[-1] = '/';
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007064 expmeta(expdir, p, endname);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007065 }
7066 }
7067 }
7068 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007069 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007070 endname[-1] = '/';
7071}
7072
7073static struct strlist *
7074msort(struct strlist *list, int len)
7075{
7076 struct strlist *p, *q = NULL;
7077 struct strlist **lpp;
7078 int half;
7079 int n;
7080
7081 if (len <= 1)
7082 return list;
7083 half = len >> 1;
7084 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007085 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007086 q = p;
7087 p = p->next;
7088 }
7089 q->next = NULL; /* terminate first half of list */
7090 q = msort(list, half); /* sort first half of list */
7091 p = msort(p, len - half); /* sort second half */
7092 lpp = &list;
7093 for (;;) {
7094#if ENABLE_LOCALE_SUPPORT
7095 if (strcoll(p->text, q->text) < 0)
7096#else
7097 if (strcmp(p->text, q->text) < 0)
7098#endif
7099 {
7100 *lpp = p;
7101 lpp = &p->next;
7102 p = *lpp;
7103 if (p == NULL) {
7104 *lpp = q;
7105 break;
7106 }
7107 } else {
7108 *lpp = q;
7109 lpp = &q->next;
7110 q = *lpp;
7111 if (q == NULL) {
7112 *lpp = p;
7113 break;
7114 }
7115 }
7116 }
7117 return list;
7118}
7119
7120/*
7121 * Sort the results of file name expansion. It calculates the number of
7122 * strings to sort and then calls msort (short for merge sort) to do the
7123 * work.
7124 */
7125static struct strlist *
7126expsort(struct strlist *str)
7127{
7128 int len;
7129 struct strlist *sp;
7130
7131 len = 0;
7132 for (sp = str; sp; sp = sp->next)
7133 len++;
7134 return msort(str, len);
7135}
7136
7137static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007138expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007139{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007140 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007141 '*', '?', '[', 0
7142 };
7143 /* TODO - EXP_REDIR */
7144
7145 while (str) {
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007146 char *expdir;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007147 struct strlist **savelastp;
7148 struct strlist *sp;
7149 char *p;
7150
7151 if (fflag)
7152 goto nometa;
7153 if (!strpbrk(str->text, metachars))
7154 goto nometa;
7155 savelastp = exparg.lastp;
7156
7157 INT_OFF;
7158 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7159 {
7160 int i = strlen(str->text);
7161 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7162 }
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007163 expmeta(expdir, expdir, p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007164 free(expdir);
7165 if (p != str->text)
7166 free(p);
7167 INT_ON;
7168 if (exparg.lastp == savelastp) {
7169 /*
7170 * no matches
7171 */
7172 nometa:
7173 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007174 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007175 exparg.lastp = &str->next;
7176 } else {
7177 *exparg.lastp = NULL;
7178 *savelastp = sp = expsort(*savelastp);
7179 while (sp->next != NULL)
7180 sp = sp->next;
7181 exparg.lastp = &sp->next;
7182 }
7183 str = str->next;
7184 }
7185}
7186
7187/*
7188 * Perform variable substitution and command substitution on an argument,
7189 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7190 * perform splitting and file name expansion. When arglist is NULL, perform
7191 * here document expansion.
7192 */
7193static void
7194expandarg(union node *arg, struct arglist *arglist, int flag)
7195{
7196 struct strlist *sp;
7197 char *p;
7198
7199 argbackq = arg->narg.backquote;
7200 STARTSTACKSTR(expdest);
7201 ifsfirst.next = NULL;
7202 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007203 argstr(arg->narg.text, flag,
7204 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007205 p = _STPUTC('\0', expdest);
7206 expdest = p - 1;
7207 if (arglist == NULL) {
7208 return; /* here document expanded */
7209 }
7210 p = grabstackstr(p);
7211 exparg.lastp = &exparg.list;
7212 /*
7213 * TODO - EXP_REDIR
7214 */
7215 if (flag & EXP_FULL) {
7216 ifsbreakup(p, &exparg);
7217 *exparg.lastp = NULL;
7218 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007219 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007220 } else {
7221 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007222 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007223 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007224 sp->text = p;
7225 *exparg.lastp = sp;
7226 exparg.lastp = &sp->next;
7227 }
7228 if (ifsfirst.next)
7229 ifsfree();
7230 *exparg.lastp = NULL;
7231 if (exparg.list) {
7232 *arglist->lastp = exparg.list;
7233 arglist->lastp = exparg.lastp;
7234 }
7235}
7236
7237/*
7238 * Expand shell variables and backquotes inside a here document.
7239 */
7240static void
7241expandhere(union node *arg, int fd)
7242{
7243 herefd = fd;
7244 expandarg(arg, (struct arglist *)NULL, 0);
7245 full_write(fd, stackblock(), expdest - (char *)stackblock());
7246}
7247
7248/*
7249 * Returns true if the pattern matches the string.
7250 */
7251static int
7252patmatch(char *pattern, const char *string)
7253{
7254 return pmatch(preglob(pattern, 0, 0), string);
7255}
7256
7257/*
7258 * See if a pattern matches in a case statement.
7259 */
7260static int
7261casematch(union node *pattern, char *val)
7262{
7263 struct stackmark smark;
7264 int result;
7265
7266 setstackmark(&smark);
7267 argbackq = pattern->narg.backquote;
7268 STARTSTACKSTR(expdest);
7269 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007270 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7271 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007272 STACKSTRNUL(expdest);
7273 result = patmatch(stackblock(), val);
7274 popstackmark(&smark);
7275 return result;
7276}
7277
7278
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007279/* ============ find_command */
7280
7281struct builtincmd {
7282 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007283 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007284 /* unsigned flags; */
7285};
7286#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007287/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007288 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007289#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007290#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007291
7292struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007293 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007294 union param {
7295 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007296 /* index >= 0 for commands without path (slashes) */
7297 /* (TODO: what exactly does the value mean? PATH position?) */
7298 /* index == -1 for commands with slashes */
7299 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007300 const struct builtincmd *cmd;
7301 struct funcnode *func;
7302 } u;
7303};
7304/* values of cmdtype */
7305#define CMDUNKNOWN -1 /* no entry in table for command */
7306#define CMDNORMAL 0 /* command is an executable program */
7307#define CMDFUNCTION 1 /* command is a shell function */
7308#define CMDBUILTIN 2 /* command is a shell builtin */
7309
7310/* action to find_command() */
7311#define DO_ERR 0x01 /* prints errors */
7312#define DO_ABS 0x02 /* checks absolute paths */
7313#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7314#define DO_ALTPATH 0x08 /* using alternate path */
7315#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7316
7317static void find_command(char *, struct cmdentry *, int, const char *);
7318
7319
7320/* ============ Hashing commands */
7321
7322/*
7323 * When commands are first encountered, they are entered in a hash table.
7324 * This ensures that a full path search will not have to be done for them
7325 * on each invocation.
7326 *
7327 * We should investigate converting to a linear search, even though that
7328 * would make the command name "hash" a misnomer.
7329 */
7330
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007331struct tblentry {
7332 struct tblentry *next; /* next entry in hash chain */
7333 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007334 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007335 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007336 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007337};
7338
Denis Vlasenko01631112007-12-16 17:20:38 +00007339static struct tblentry **cmdtable;
7340#define INIT_G_cmdtable() do { \
7341 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7342} while (0)
7343
7344static int builtinloc = -1; /* index in path of %builtin, or -1 */
7345
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007346
7347static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007348tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007349{
7350 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007351
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007352#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007353 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007354 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007355 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007356 while (*envp)
7357 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007358 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007359 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007360 /* re-exec ourselves with the new arguments */
7361 execve(bb_busybox_exec_path, argv, envp);
7362 /* If they called chroot or otherwise made the binary no longer
7363 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007364 }
7365#endif
7366
7367 repeat:
7368#ifdef SYSV
7369 do {
7370 execve(cmd, argv, envp);
7371 } while (errno == EINTR);
7372#else
7373 execve(cmd, argv, envp);
7374#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007375 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007376 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007377 return;
7378 }
7379 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007380 char **ap;
7381 char **new;
7382
7383 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007384 continue;
7385 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007386 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007387 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007388 ap += 2;
7389 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007390 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007391 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007392 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007393 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007394 goto repeat;
7395 }
7396}
7397
7398/*
7399 * Exec a program. Never returns. If you change this routine, you may
7400 * have to change the find_command routine as well.
7401 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007402static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007403static void
7404shellexec(char **argv, const char *path, int idx)
7405{
7406 char *cmdname;
7407 int e;
7408 char **envp;
7409 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007410#if ENABLE_FEATURE_SH_STANDALONE
7411 int applet_no = -1;
7412#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007413
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007414 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007415 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007416 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007417#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007418 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007419#endif
7420 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007421 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007422 e = errno;
7423 } else {
7424 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007425 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007426 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007427 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007428 if (errno != ENOENT && errno != ENOTDIR)
7429 e = errno;
7430 }
7431 stunalloc(cmdname);
7432 }
7433 }
7434
7435 /* Map to POSIX errors */
7436 switch (e) {
7437 case EACCES:
7438 exerrno = 126;
7439 break;
7440 case ENOENT:
7441 exerrno = 127;
7442 break;
7443 default:
7444 exerrno = 2;
7445 break;
7446 }
7447 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007448 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7449 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007450 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7451 /* NOTREACHED */
7452}
7453
7454static void
7455printentry(struct tblentry *cmdp)
7456{
7457 int idx;
7458 const char *path;
7459 char *name;
7460
7461 idx = cmdp->param.index;
7462 path = pathval();
7463 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007464 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007465 stunalloc(name);
7466 } while (--idx >= 0);
7467 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7468}
7469
7470/*
7471 * Clear out command entries. The argument specifies the first entry in
7472 * PATH which has changed.
7473 */
7474static void
7475clearcmdentry(int firstchange)
7476{
7477 struct tblentry **tblp;
7478 struct tblentry **pp;
7479 struct tblentry *cmdp;
7480
7481 INT_OFF;
7482 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7483 pp = tblp;
7484 while ((cmdp = *pp) != NULL) {
7485 if ((cmdp->cmdtype == CMDNORMAL &&
7486 cmdp->param.index >= firstchange)
7487 || (cmdp->cmdtype == CMDBUILTIN &&
7488 builtinloc >= firstchange)
7489 ) {
7490 *pp = cmdp->next;
7491 free(cmdp);
7492 } else {
7493 pp = &cmdp->next;
7494 }
7495 }
7496 }
7497 INT_ON;
7498}
7499
7500/*
7501 * Locate a command in the command hash table. If "add" is nonzero,
7502 * add the command to the table if it is not already present. The
7503 * variable "lastcmdentry" is set to point to the address of the link
7504 * pointing to the entry, so that delete_cmd_entry can delete the
7505 * entry.
7506 *
7507 * Interrupts must be off if called with add != 0.
7508 */
7509static struct tblentry **lastcmdentry;
7510
7511static struct tblentry *
7512cmdlookup(const char *name, int add)
7513{
7514 unsigned int hashval;
7515 const char *p;
7516 struct tblentry *cmdp;
7517 struct tblentry **pp;
7518
7519 p = name;
7520 hashval = (unsigned char)*p << 4;
7521 while (*p)
7522 hashval += (unsigned char)*p++;
7523 hashval &= 0x7FFF;
7524 pp = &cmdtable[hashval % CMDTABLESIZE];
7525 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7526 if (strcmp(cmdp->cmdname, name) == 0)
7527 break;
7528 pp = &cmdp->next;
7529 }
7530 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007531 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7532 + strlen(name)
7533 /* + 1 - already done because
7534 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007535 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007536 cmdp->cmdtype = CMDUNKNOWN;
7537 strcpy(cmdp->cmdname, name);
7538 }
7539 lastcmdentry = pp;
7540 return cmdp;
7541}
7542
7543/*
7544 * Delete the command entry returned on the last lookup.
7545 */
7546static void
7547delete_cmd_entry(void)
7548{
7549 struct tblentry *cmdp;
7550
7551 INT_OFF;
7552 cmdp = *lastcmdentry;
7553 *lastcmdentry = cmdp->next;
7554 if (cmdp->cmdtype == CMDFUNCTION)
7555 freefunc(cmdp->param.func);
7556 free(cmdp);
7557 INT_ON;
7558}
7559
7560/*
7561 * Add a new command entry, replacing any existing command entry for
7562 * the same name - except special builtins.
7563 */
7564static void
7565addcmdentry(char *name, struct cmdentry *entry)
7566{
7567 struct tblentry *cmdp;
7568
7569 cmdp = cmdlookup(name, 1);
7570 if (cmdp->cmdtype == CMDFUNCTION) {
7571 freefunc(cmdp->param.func);
7572 }
7573 cmdp->cmdtype = entry->cmdtype;
7574 cmdp->param = entry->u;
7575 cmdp->rehash = 0;
7576}
7577
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007578static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007579hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007580{
7581 struct tblentry **pp;
7582 struct tblentry *cmdp;
7583 int c;
7584 struct cmdentry entry;
7585 char *name;
7586
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007587 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007588 clearcmdentry(0);
7589 return 0;
7590 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007591
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007592 if (*argptr == NULL) {
7593 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7594 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7595 if (cmdp->cmdtype == CMDNORMAL)
7596 printentry(cmdp);
7597 }
7598 }
7599 return 0;
7600 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007601
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007602 c = 0;
7603 while ((name = *argptr) != NULL) {
7604 cmdp = cmdlookup(name, 0);
7605 if (cmdp != NULL
7606 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007607 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7608 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007609 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007610 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007611 find_command(name, &entry, DO_ERR, pathval());
7612 if (entry.cmdtype == CMDUNKNOWN)
7613 c = 1;
7614 argptr++;
7615 }
7616 return c;
7617}
7618
7619/*
7620 * Called when a cd is done. Marks all commands so the next time they
7621 * are executed they will be rehashed.
7622 */
7623static void
7624hashcd(void)
7625{
7626 struct tblentry **pp;
7627 struct tblentry *cmdp;
7628
7629 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7630 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007631 if (cmdp->cmdtype == CMDNORMAL
7632 || (cmdp->cmdtype == CMDBUILTIN
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02007633 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007634 && builtinloc > 0)
7635 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007636 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007637 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007638 }
7639 }
7640}
7641
7642/*
7643 * Fix command hash table when PATH changed.
7644 * Called before PATH is changed. The argument is the new value of PATH;
7645 * pathval() still returns the old value at this point.
7646 * Called with interrupts off.
7647 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007648static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007649changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007651 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007652 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007653 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007654 int idx_bltin;
7655
7656 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657 firstchange = 9999; /* assume no change */
7658 idx = 0;
7659 idx_bltin = -1;
7660 for (;;) {
7661 if (*old != *new) {
7662 firstchange = idx;
7663 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007664 || (*old == ':' && *new == '\0')
7665 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007666 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007667 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007668 old = new; /* ignore subsequent differences */
7669 }
7670 if (*new == '\0')
7671 break;
7672 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7673 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007674 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007675 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007676 new++;
7677 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007678 }
7679 if (builtinloc < 0 && idx_bltin >= 0)
7680 builtinloc = idx_bltin; /* zap builtins */
7681 if (builtinloc >= 0 && idx_bltin < 0)
7682 firstchange = 0;
7683 clearcmdentry(firstchange);
7684 builtinloc = idx_bltin;
7685}
7686
7687#define TEOF 0
7688#define TNL 1
7689#define TREDIR 2
7690#define TWORD 3
7691#define TSEMI 4
7692#define TBACKGND 5
7693#define TAND 6
7694#define TOR 7
7695#define TPIPE 8
7696#define TLP 9
7697#define TRP 10
7698#define TENDCASE 11
7699#define TENDBQUOTE 12
7700#define TNOT 13
7701#define TCASE 14
7702#define TDO 15
7703#define TDONE 16
7704#define TELIF 17
7705#define TELSE 18
7706#define TESAC 19
7707#define TFI 20
7708#define TFOR 21
7709#define TIF 22
7710#define TIN 23
7711#define TTHEN 24
7712#define TUNTIL 25
7713#define TWHILE 26
7714#define TBEGIN 27
7715#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007716typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007717
7718/* first char is indicating which tokens mark the end of a list */
7719static const char *const tokname_array[] = {
7720 "\1end of file",
7721 "\0newline",
7722 "\0redirection",
7723 "\0word",
7724 "\0;",
7725 "\0&",
7726 "\0&&",
7727 "\0||",
7728 "\0|",
7729 "\0(",
7730 "\1)",
7731 "\1;;",
7732 "\1`",
7733#define KWDOFFSET 13
7734 /* the following are keywords */
7735 "\0!",
7736 "\0case",
7737 "\1do",
7738 "\1done",
7739 "\1elif",
7740 "\1else",
7741 "\1esac",
7742 "\1fi",
7743 "\0for",
7744 "\0if",
7745 "\0in",
7746 "\1then",
7747 "\0until",
7748 "\0while",
7749 "\0{",
7750 "\1}",
7751};
7752
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007753/* Wrapper around strcmp for qsort/bsearch/... */
7754static int
7755pstrcmp(const void *a, const void *b)
7756{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007757 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007758}
7759
7760static const char *const *
7761findkwd(const char *s)
7762{
7763 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007764 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7765 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007766}
7767
7768/*
7769 * Locate and print what a word is...
7770 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007771static int
7772describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007773{
7774 struct cmdentry entry;
7775 struct tblentry *cmdp;
7776#if ENABLE_ASH_ALIAS
7777 const struct alias *ap;
7778#endif
7779 const char *path = pathval();
7780
7781 if (describe_command_verbose) {
7782 out1str(command);
7783 }
7784
7785 /* First look at the keywords */
7786 if (findkwd(command)) {
7787 out1str(describe_command_verbose ? " is a shell keyword" : command);
7788 goto out;
7789 }
7790
7791#if ENABLE_ASH_ALIAS
7792 /* Then look at the aliases */
7793 ap = lookupalias(command, 0);
7794 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007795 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007796 out1str("alias ");
7797 printalias(ap);
7798 return 0;
7799 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007800 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007801 goto out;
7802 }
7803#endif
7804 /* Then check if it is a tracked alias */
7805 cmdp = cmdlookup(command, 0);
7806 if (cmdp != NULL) {
7807 entry.cmdtype = cmdp->cmdtype;
7808 entry.u = cmdp->param;
7809 } else {
7810 /* Finally use brute force */
7811 find_command(command, &entry, DO_ABS, path);
7812 }
7813
7814 switch (entry.cmdtype) {
7815 case CMDNORMAL: {
7816 int j = entry.u.index;
7817 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007818 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007819 p = command;
7820 } else {
7821 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007822 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007823 stunalloc(p);
7824 } while (--j >= 0);
7825 }
7826 if (describe_command_verbose) {
7827 out1fmt(" is%s %s",
7828 (cmdp ? " a tracked alias for" : nullstr), p
7829 );
7830 } else {
7831 out1str(p);
7832 }
7833 break;
7834 }
7835
7836 case CMDFUNCTION:
7837 if (describe_command_verbose) {
7838 out1str(" is a shell function");
7839 } else {
7840 out1str(command);
7841 }
7842 break;
7843
7844 case CMDBUILTIN:
7845 if (describe_command_verbose) {
7846 out1fmt(" is a %sshell builtin",
7847 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7848 "special " : nullstr
7849 );
7850 } else {
7851 out1str(command);
7852 }
7853 break;
7854
7855 default:
7856 if (describe_command_verbose) {
7857 out1str(": not found\n");
7858 }
7859 return 127;
7860 }
7861 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007862 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007863 return 0;
7864}
7865
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007866static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007867typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007868{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007869 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007870 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007871 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007872
Denis Vlasenko46846e22007-05-20 13:08:31 +00007873 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007874 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007875 i++;
7876 verbose = 0;
7877 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007878 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007879 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007880 }
7881 return err;
7882}
7883
7884#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007885static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007886commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007887{
7888 int c;
7889 enum {
7890 VERIFY_BRIEF = 1,
7891 VERIFY_VERBOSE = 2,
7892 } verify = 0;
7893
7894 while ((c = nextopt("pvV")) != '\0')
7895 if (c == 'V')
7896 verify |= VERIFY_VERBOSE;
7897 else if (c == 'v')
7898 verify |= VERIFY_BRIEF;
7899#if DEBUG
7900 else if (c != 'p')
7901 abort();
7902#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007903 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7904 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007905 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007906 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007907
7908 return 0;
7909}
7910#endif
7911
7912
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007913/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007914
Denis Vlasenko340299a2008-11-21 10:36:36 +00007915static int funcblocksize; /* size of structures in function */
7916static int funcstringsize; /* size of strings in node */
7917static void *funcblock; /* block to allocate function from */
7918static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007919
Eric Andersencb57d552001-06-28 07:25:16 +00007920/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007921#define EV_EXIT 01 /* exit after evaluating tree */
7922#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007923#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007924
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007925static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007926 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7927 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7928 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7929 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7930 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7931 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7932 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7933 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7934 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7935 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7936 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7937 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7938 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7939 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7940 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7941 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7942 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007943#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007944 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007945#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007946 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7947 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7948 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7949 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7950 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7951 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7952 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7953 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7954 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007955};
7956
7957static void calcsize(union node *n);
7958
7959static void
7960sizenodelist(struct nodelist *lp)
7961{
7962 while (lp) {
7963 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7964 calcsize(lp->n);
7965 lp = lp->next;
7966 }
7967}
7968
7969static void
7970calcsize(union node *n)
7971{
7972 if (n == NULL)
7973 return;
7974 funcblocksize += nodesize[n->type];
7975 switch (n->type) {
7976 case NCMD:
7977 calcsize(n->ncmd.redirect);
7978 calcsize(n->ncmd.args);
7979 calcsize(n->ncmd.assign);
7980 break;
7981 case NPIPE:
7982 sizenodelist(n->npipe.cmdlist);
7983 break;
7984 case NREDIR:
7985 case NBACKGND:
7986 case NSUBSHELL:
7987 calcsize(n->nredir.redirect);
7988 calcsize(n->nredir.n);
7989 break;
7990 case NAND:
7991 case NOR:
7992 case NSEMI:
7993 case NWHILE:
7994 case NUNTIL:
7995 calcsize(n->nbinary.ch2);
7996 calcsize(n->nbinary.ch1);
7997 break;
7998 case NIF:
7999 calcsize(n->nif.elsepart);
8000 calcsize(n->nif.ifpart);
8001 calcsize(n->nif.test);
8002 break;
8003 case NFOR:
8004 funcstringsize += strlen(n->nfor.var) + 1;
8005 calcsize(n->nfor.body);
8006 calcsize(n->nfor.args);
8007 break;
8008 case NCASE:
8009 calcsize(n->ncase.cases);
8010 calcsize(n->ncase.expr);
8011 break;
8012 case NCLIST:
8013 calcsize(n->nclist.body);
8014 calcsize(n->nclist.pattern);
8015 calcsize(n->nclist.next);
8016 break;
8017 case NDEFUN:
8018 case NARG:
8019 sizenodelist(n->narg.backquote);
8020 funcstringsize += strlen(n->narg.text) + 1;
8021 calcsize(n->narg.next);
8022 break;
8023 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008024#if ENABLE_ASH_BASH_COMPAT
8025 case NTO2:
8026#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008027 case NCLOBBER:
8028 case NFROM:
8029 case NFROMTO:
8030 case NAPPEND:
8031 calcsize(n->nfile.fname);
8032 calcsize(n->nfile.next);
8033 break;
8034 case NTOFD:
8035 case NFROMFD:
8036 calcsize(n->ndup.vname);
8037 calcsize(n->ndup.next);
8038 break;
8039 case NHERE:
8040 case NXHERE:
8041 calcsize(n->nhere.doc);
8042 calcsize(n->nhere.next);
8043 break;
8044 case NNOT:
8045 calcsize(n->nnot.com);
8046 break;
8047 };
8048}
8049
8050static char *
8051nodeckstrdup(char *s)
8052{
8053 char *rtn = funcstring;
8054
8055 strcpy(funcstring, s);
8056 funcstring += strlen(s) + 1;
8057 return rtn;
8058}
8059
8060static union node *copynode(union node *);
8061
8062static struct nodelist *
8063copynodelist(struct nodelist *lp)
8064{
8065 struct nodelist *start;
8066 struct nodelist **lpp;
8067
8068 lpp = &start;
8069 while (lp) {
8070 *lpp = funcblock;
8071 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8072 (*lpp)->n = copynode(lp->n);
8073 lp = lp->next;
8074 lpp = &(*lpp)->next;
8075 }
8076 *lpp = NULL;
8077 return start;
8078}
8079
8080static union node *
8081copynode(union node *n)
8082{
8083 union node *new;
8084
8085 if (n == NULL)
8086 return NULL;
8087 new = funcblock;
8088 funcblock = (char *) funcblock + nodesize[n->type];
8089
8090 switch (n->type) {
8091 case NCMD:
8092 new->ncmd.redirect = copynode(n->ncmd.redirect);
8093 new->ncmd.args = copynode(n->ncmd.args);
8094 new->ncmd.assign = copynode(n->ncmd.assign);
8095 break;
8096 case NPIPE:
8097 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008098 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008099 break;
8100 case NREDIR:
8101 case NBACKGND:
8102 case NSUBSHELL:
8103 new->nredir.redirect = copynode(n->nredir.redirect);
8104 new->nredir.n = copynode(n->nredir.n);
8105 break;
8106 case NAND:
8107 case NOR:
8108 case NSEMI:
8109 case NWHILE:
8110 case NUNTIL:
8111 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8112 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8113 break;
8114 case NIF:
8115 new->nif.elsepart = copynode(n->nif.elsepart);
8116 new->nif.ifpart = copynode(n->nif.ifpart);
8117 new->nif.test = copynode(n->nif.test);
8118 break;
8119 case NFOR:
8120 new->nfor.var = nodeckstrdup(n->nfor.var);
8121 new->nfor.body = copynode(n->nfor.body);
8122 new->nfor.args = copynode(n->nfor.args);
8123 break;
8124 case NCASE:
8125 new->ncase.cases = copynode(n->ncase.cases);
8126 new->ncase.expr = copynode(n->ncase.expr);
8127 break;
8128 case NCLIST:
8129 new->nclist.body = copynode(n->nclist.body);
8130 new->nclist.pattern = copynode(n->nclist.pattern);
8131 new->nclist.next = copynode(n->nclist.next);
8132 break;
8133 case NDEFUN:
8134 case NARG:
8135 new->narg.backquote = copynodelist(n->narg.backquote);
8136 new->narg.text = nodeckstrdup(n->narg.text);
8137 new->narg.next = copynode(n->narg.next);
8138 break;
8139 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008140#if ENABLE_ASH_BASH_COMPAT
8141 case NTO2:
8142#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008143 case NCLOBBER:
8144 case NFROM:
8145 case NFROMTO:
8146 case NAPPEND:
8147 new->nfile.fname = copynode(n->nfile.fname);
8148 new->nfile.fd = n->nfile.fd;
8149 new->nfile.next = copynode(n->nfile.next);
8150 break;
8151 case NTOFD:
8152 case NFROMFD:
8153 new->ndup.vname = copynode(n->ndup.vname);
8154 new->ndup.dupfd = n->ndup.dupfd;
8155 new->ndup.fd = n->ndup.fd;
8156 new->ndup.next = copynode(n->ndup.next);
8157 break;
8158 case NHERE:
8159 case NXHERE:
8160 new->nhere.doc = copynode(n->nhere.doc);
8161 new->nhere.fd = n->nhere.fd;
8162 new->nhere.next = copynode(n->nhere.next);
8163 break;
8164 case NNOT:
8165 new->nnot.com = copynode(n->nnot.com);
8166 break;
8167 };
8168 new->type = n->type;
8169 return new;
8170}
8171
8172/*
8173 * Make a copy of a parse tree.
8174 */
8175static struct funcnode *
8176copyfunc(union node *n)
8177{
8178 struct funcnode *f;
8179 size_t blocksize;
8180
8181 funcblocksize = offsetof(struct funcnode, n);
8182 funcstringsize = 0;
8183 calcsize(n);
8184 blocksize = funcblocksize;
8185 f = ckmalloc(blocksize + funcstringsize);
8186 funcblock = (char *) f + offsetof(struct funcnode, n);
8187 funcstring = (char *) f + blocksize;
8188 copynode(n);
8189 f->count = 0;
8190 return f;
8191}
8192
8193/*
8194 * Define a shell function.
8195 */
8196static void
8197defun(char *name, union node *func)
8198{
8199 struct cmdentry entry;
8200
8201 INT_OFF;
8202 entry.cmdtype = CMDFUNCTION;
8203 entry.u.func = copyfunc(func);
8204 addcmdentry(name, &entry);
8205 INT_ON;
8206}
8207
Denis Vlasenko4b875702009-03-19 13:30:04 +00008208/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008209#define SKIPBREAK (1 << 0)
8210#define SKIPCONT (1 << 1)
8211#define SKIPFUNC (1 << 2)
8212#define SKIPFILE (1 << 3)
8213#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008214static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008215static int skipcount; /* number of levels to skip */
8216static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008217static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008218
Denis Vlasenko4b875702009-03-19 13:30:04 +00008219/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008220static int evalstring(char *s, int mask);
8221
Denis Vlasenko4b875702009-03-19 13:30:04 +00008222/* Called to execute a trap.
8223 * Single callsite - at the end of evaltree().
Denys Vlasenkob563f622010-09-25 17:15:13 +02008224 * If we return non-zero, evaltree raises EXEXIT exception.
Denis Vlasenko4b875702009-03-19 13:30:04 +00008225 *
8226 * Perhaps we should avoid entering new trap handlers
8227 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008228 */
8229static int
8230dotrap(void)
8231{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008232 uint8_t *g;
8233 int sig;
8234 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008235
8236 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008237 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008238 xbarrier();
8239
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008240 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008241 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8242 int want_exexit;
8243 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008244
Denis Vlasenko4b875702009-03-19 13:30:04 +00008245 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008246 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008247 t = trap[sig];
8248 /* non-trapped SIGINT is handled separately by raise_interrupt,
8249 * don't upset it by resetting gotsig[SIGINT-1] */
8250 if (sig == SIGINT && !t)
8251 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008252
8253 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008254 *g = 0;
8255 if (!t)
8256 continue;
8257 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008258 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008259 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008260 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008261 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008262 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008263 }
8264
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008265 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008266 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008267}
8268
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008269/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008270static void evalloop(union node *, int);
8271static void evalfor(union node *, int);
8272static void evalcase(union node *, int);
8273static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008274static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008275static void evalpipe(union node *, int);
8276static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008277static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008278static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008279
Eric Andersen62483552001-07-10 06:09:16 +00008280/*
Eric Andersenc470f442003-07-28 09:56:35 +00008281 * Evaluate a parse tree. The value is left in the global variable
8282 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008283 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008284static void
Eric Andersenc470f442003-07-28 09:56:35 +00008285evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008286{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008287 struct jmploc *volatile savehandler = exception_handler;
8288 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008289 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008290 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008291 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008292 int int_level;
8293
8294 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008295
Eric Andersenc470f442003-07-28 09:56:35 +00008296 if (n == NULL) {
8297 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008298 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008299 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008300 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008301
8302 exception_handler = &jmploc;
8303 {
8304 int err = setjmp(jmploc.loc);
8305 if (err) {
8306 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008307 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008308 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8309 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008310 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008311 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008312 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008313 TRACE(("exception %d in evaltree, propagating err=%d\n",
8314 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008315 exception_handler = savehandler;
8316 longjmp(exception_handler->loc, err);
8317 }
8318 }
8319
Eric Andersenc470f442003-07-28 09:56:35 +00008320 switch (n->type) {
8321 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008322#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008323 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008324 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008325 break;
8326#endif
8327 case NNOT:
8328 evaltree(n->nnot.com, EV_TESTED);
8329 status = !exitstatus;
8330 goto setstatus;
8331 case NREDIR:
8332 expredir(n->nredir.redirect);
8333 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8334 if (!status) {
8335 evaltree(n->nredir.n, flags & EV_TESTED);
8336 status = exitstatus;
8337 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008338 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008339 goto setstatus;
8340 case NCMD:
8341 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008342 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008343 if (eflag && !(flags & EV_TESTED))
8344 checkexit = ~0;
8345 goto calleval;
8346 case NFOR:
8347 evalfn = evalfor;
8348 goto calleval;
8349 case NWHILE:
8350 case NUNTIL:
8351 evalfn = evalloop;
8352 goto calleval;
8353 case NSUBSHELL:
8354 case NBACKGND:
8355 evalfn = evalsubshell;
8356 goto calleval;
8357 case NPIPE:
8358 evalfn = evalpipe;
8359 goto checkexit;
8360 case NCASE:
8361 evalfn = evalcase;
8362 goto calleval;
8363 case NAND:
8364 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008365 case NSEMI: {
8366
Eric Andersenc470f442003-07-28 09:56:35 +00008367#if NAND + 1 != NOR
8368#error NAND + 1 != NOR
8369#endif
8370#if NOR + 1 != NSEMI
8371#error NOR + 1 != NSEMI
8372#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008373 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008374 evaltree(
8375 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008376 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008377 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008378 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008379 break;
8380 if (!evalskip) {
8381 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008382 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008383 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008384 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008385 evalfn(n, flags);
8386 break;
8387 }
8388 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008389 }
Eric Andersenc470f442003-07-28 09:56:35 +00008390 case NIF:
8391 evaltree(n->nif.test, EV_TESTED);
8392 if (evalskip)
8393 break;
8394 if (exitstatus == 0) {
8395 n = n->nif.ifpart;
8396 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008397 }
8398 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008399 n = n->nif.elsepart;
8400 goto evaln;
8401 }
8402 goto success;
8403 case NDEFUN:
8404 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008405 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008406 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008407 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008408 exitstatus = status;
8409 break;
8410 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008411
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008412 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008413 exception_handler = savehandler;
Denys Vlasenkob563f622010-09-25 17:15:13 +02008414
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008415 out1:
Denys Vlasenkob563f622010-09-25 17:15:13 +02008416 /* Order of checks below is important:
8417 * signal handlers trigger before exit caused by "set -e".
8418 */
8419 if (pending_sig && dotrap())
8420 goto exexit;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008421 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008422 evalskip |= SKIPEVAL;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008423
8424 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008425 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008426 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008427 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008428
8429 RESTORE_INT(int_level);
8430 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008431}
8432
Eric Andersenc470f442003-07-28 09:56:35 +00008433#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8434static
8435#endif
8436void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8437
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008438static void
Eric Andersenc470f442003-07-28 09:56:35 +00008439evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008440{
8441 int status;
8442
8443 loopnest++;
8444 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008445 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008446 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008447 int i;
8448
Eric Andersencb57d552001-06-28 07:25:16 +00008449 evaltree(n->nbinary.ch1, EV_TESTED);
8450 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008451 skipping:
8452 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008453 evalskip = 0;
8454 continue;
8455 }
8456 if (evalskip == SKIPBREAK && --skipcount <= 0)
8457 evalskip = 0;
8458 break;
8459 }
Eric Andersenc470f442003-07-28 09:56:35 +00008460 i = exitstatus;
8461 if (n->type != NWHILE)
8462 i = !i;
8463 if (i != 0)
8464 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008465 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008466 status = exitstatus;
8467 if (evalskip)
8468 goto skipping;
8469 }
8470 loopnest--;
8471 exitstatus = status;
8472}
8473
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008474static void
Eric Andersenc470f442003-07-28 09:56:35 +00008475evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008476{
8477 struct arglist arglist;
8478 union node *argp;
8479 struct strlist *sp;
8480 struct stackmark smark;
8481
8482 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008483 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008484 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008485 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008486 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008487 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008488 if (evalskip)
8489 goto out;
8490 }
8491 *arglist.lastp = NULL;
8492
8493 exitstatus = 0;
8494 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008495 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008496 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008497 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008498 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008499 if (evalskip) {
8500 if (evalskip == SKIPCONT && --skipcount <= 0) {
8501 evalskip = 0;
8502 continue;
8503 }
8504 if (evalskip == SKIPBREAK && --skipcount <= 0)
8505 evalskip = 0;
8506 break;
8507 }
8508 }
8509 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008510 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008511 popstackmark(&smark);
8512}
8513
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008514static void
Eric Andersenc470f442003-07-28 09:56:35 +00008515evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008516{
8517 union node *cp;
8518 union node *patp;
8519 struct arglist arglist;
8520 struct stackmark smark;
8521
8522 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008523 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008524 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008525 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008526 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008527 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8528 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008529 if (casematch(patp, arglist.list->text)) {
8530 if (evalskip == 0) {
8531 evaltree(cp->nclist.body, flags);
8532 }
8533 goto out;
8534 }
8535 }
8536 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008537 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008538 popstackmark(&smark);
8539}
8540
Eric Andersenc470f442003-07-28 09:56:35 +00008541/*
8542 * Kick off a subshell to evaluate a tree.
8543 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008544static void
Eric Andersenc470f442003-07-28 09:56:35 +00008545evalsubshell(union node *n, int flags)
8546{
8547 struct job *jp;
8548 int backgnd = (n->type == NBACKGND);
8549 int status;
8550
8551 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008552 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008553 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008554 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008555 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008556 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008557 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008558 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008559 flags |= EV_EXIT;
8560 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008561 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008562 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008563 redirect(n->nredir.redirect, 0);
8564 evaltreenr(n->nredir.n, flags);
8565 /* never returns */
8566 }
8567 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008568 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008569 status = waitforjob(jp);
8570 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008571 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008572}
8573
Eric Andersenc470f442003-07-28 09:56:35 +00008574/*
8575 * Compute the names of the files in a redirection list.
8576 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008577static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008578static void
8579expredir(union node *n)
8580{
8581 union node *redir;
8582
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008583 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008584 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008585
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008586 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008587 fn.lastp = &fn.list;
8588 switch (redir->type) {
8589 case NFROMTO:
8590 case NFROM:
8591 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008592#if ENABLE_ASH_BASH_COMPAT
8593 case NTO2:
8594#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008595 case NCLOBBER:
8596 case NAPPEND:
8597 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008598#if ENABLE_ASH_BASH_COMPAT
8599 store_expfname:
8600#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008601 redir->nfile.expfname = fn.list->text;
8602 break;
8603 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008604 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008605 if (redir->ndup.vname) {
8606 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008607 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008608 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008609#if ENABLE_ASH_BASH_COMPAT
8610//FIXME: we used expandarg with different args!
8611 if (!isdigit_str9(fn.list->text)) {
8612 /* >&file, not >&fd */
8613 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8614 ash_msg_and_raise_error("redir error");
8615 redir->type = NTO2;
8616 goto store_expfname;
8617 }
8618#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008619 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008620 }
8621 break;
8622 }
8623 }
8624}
8625
Eric Andersencb57d552001-06-28 07:25:16 +00008626/*
Eric Andersencb57d552001-06-28 07:25:16 +00008627 * Evaluate a pipeline. All the processes in the pipeline are children
8628 * of the process creating the pipeline. (This differs from some versions
8629 * of the shell, which make the last process in a pipeline the parent
8630 * of all the rest.)
8631 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008632static void
Eric Andersenc470f442003-07-28 09:56:35 +00008633evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008634{
8635 struct job *jp;
8636 struct nodelist *lp;
8637 int pipelen;
8638 int prevfd;
8639 int pip[2];
8640
Eric Andersenc470f442003-07-28 09:56:35 +00008641 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008642 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008643 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008644 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008645 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008646 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008647 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008648 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008649 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008650 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008651 pip[1] = -1;
8652 if (lp->next) {
8653 if (pipe(pip) < 0) {
8654 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008655 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008656 }
8657 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008658 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008659 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008660 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008661 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008662 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008663 if (prevfd > 0) {
8664 dup2(prevfd, 0);
8665 close(prevfd);
8666 }
8667 if (pip[1] > 1) {
8668 dup2(pip[1], 1);
8669 close(pip[1]);
8670 }
Eric Andersenc470f442003-07-28 09:56:35 +00008671 evaltreenr(lp->n, flags);
8672 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008673 }
8674 if (prevfd >= 0)
8675 close(prevfd);
8676 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008677 /* Don't want to trigger debugging */
8678 if (pip[1] != -1)
8679 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008680 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008681 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008682 exitstatus = waitforjob(jp);
8683 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008684 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008685 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008686}
8687
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008688/*
8689 * Controls whether the shell is interactive or not.
8690 */
8691static void
8692setinteractive(int on)
8693{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008694 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008695
8696 if (++on == is_interactive)
8697 return;
8698 is_interactive = on;
8699 setsignal(SIGINT);
8700 setsignal(SIGQUIT);
8701 setsignal(SIGTERM);
8702#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8703 if (is_interactive > 1) {
8704 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008705 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008706
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008707 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008708 /* note: ash and hush share this string */
8709 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008710 "Enter 'help' for a list of built-in commands."
8711 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008712 bb_banner,
8713 "built-in shell (ash)"
8714 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008715 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008716 }
8717 }
8718#endif
8719}
8720
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008721static void
8722optschanged(void)
8723{
8724#if DEBUG
8725 opentrace();
8726#endif
8727 setinteractive(iflag);
8728 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008729#if ENABLE_FEATURE_EDITING_VI
8730 if (viflag)
8731 line_input_state->flags |= VI_MODE;
8732 else
8733 line_input_state->flags &= ~VI_MODE;
8734#else
8735 viflag = 0; /* forcibly keep the option off */
8736#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008737}
8738
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008739static struct localvar *localvars;
8740
8741/*
8742 * Called after a function returns.
8743 * Interrupts must be off.
8744 */
8745static void
8746poplocalvars(void)
8747{
8748 struct localvar *lvp;
8749 struct var *vp;
8750
8751 while ((lvp = localvars) != NULL) {
8752 localvars = lvp->next;
8753 vp = lvp->vp;
Denys Vlasenkob563f622010-09-25 17:15:13 +02008754 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008755 if (vp == NULL) { /* $- saved */
8756 memcpy(optlist, lvp->text, sizeof(optlist));
8757 free((char*)lvp->text);
8758 optschanged();
8759 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008760 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008761 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008762 if (vp->var_func)
8763 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008764 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008765 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008766 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008767 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008768 }
8769 free(lvp);
8770 }
8771}
8772
8773static int
8774evalfun(struct funcnode *func, int argc, char **argv, int flags)
8775{
8776 volatile struct shparam saveparam;
8777 struct localvar *volatile savelocalvars;
8778 struct jmploc *volatile savehandler;
8779 struct jmploc jmploc;
8780 int e;
8781
8782 saveparam = shellparam;
8783 savelocalvars = localvars;
8784 e = setjmp(jmploc.loc);
8785 if (e) {
8786 goto funcdone;
8787 }
8788 INT_OFF;
8789 savehandler = exception_handler;
8790 exception_handler = &jmploc;
8791 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008792 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008793 func->count++;
8794 funcnest++;
8795 INT_ON;
8796 shellparam.nparam = argc - 1;
8797 shellparam.p = argv + 1;
8798#if ENABLE_ASH_GETOPTS
8799 shellparam.optind = 1;
8800 shellparam.optoff = -1;
8801#endif
8802 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008803 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008804 INT_OFF;
8805 funcnest--;
8806 freefunc(func);
8807 poplocalvars();
8808 localvars = savelocalvars;
8809 freeparam(&shellparam);
8810 shellparam = saveparam;
8811 exception_handler = savehandler;
8812 INT_ON;
8813 evalskip &= ~SKIPFUNC;
8814 return e;
8815}
8816
Denis Vlasenko131ae172007-02-18 13:00:19 +00008817#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008818static char **
8819parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008820{
8821 char *cp, c;
8822
8823 for (;;) {
8824 cp = *++argv;
8825 if (!cp)
8826 return 0;
8827 if (*cp++ != '-')
8828 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008829 c = *cp++;
8830 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008831 break;
8832 if (c == '-' && !*cp) {
8833 argv++;
8834 break;
8835 }
8836 do {
8837 switch (c) {
8838 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008839 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008840 break;
8841 default:
8842 /* run 'typecmd' for other options */
8843 return 0;
8844 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008845 c = *cp++;
8846 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008847 }
8848 return argv;
8849}
8850#endif
8851
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008852/*
8853 * Make a variable a local variable. When a variable is made local, it's
8854 * value and flags are saved in a localvar structure. The saved values
8855 * will be restored when the shell function returns. We handle the name
8856 * "-" as a special case.
8857 */
8858static void
8859mklocal(char *name)
8860{
8861 struct localvar *lvp;
8862 struct var **vpp;
8863 struct var *vp;
8864
8865 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008866 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008867 if (LONE_DASH(name)) {
8868 char *p;
8869 p = ckmalloc(sizeof(optlist));
8870 lvp->text = memcpy(p, optlist, sizeof(optlist));
8871 vp = NULL;
8872 } else {
8873 char *eq;
8874
8875 vpp = hashvar(name);
8876 vp = *findvar(vpp, name);
8877 eq = strchr(name, '=');
8878 if (vp == NULL) {
8879 if (eq)
8880 setvareq(name, VSTRFIXED);
8881 else
8882 setvar(name, NULL, VSTRFIXED);
8883 vp = *vpp; /* the new variable */
8884 lvp->flags = VUNSET;
8885 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008886 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008887 lvp->flags = vp->flags;
8888 vp->flags |= VSTRFIXED|VTEXTFIXED;
8889 if (eq)
8890 setvareq(name, 0);
8891 }
8892 }
8893 lvp->vp = vp;
8894 lvp->next = localvars;
8895 localvars = lvp;
8896 INT_ON;
8897}
8898
8899/*
8900 * The "local" command.
8901 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008902static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008903localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008904{
8905 char *name;
8906
8907 argv = argptr;
8908 while ((name = *argv++) != NULL) {
8909 mklocal(name);
8910 }
8911 return 0;
8912}
8913
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008914static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008915falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008916{
8917 return 1;
8918}
8919
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008920static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008921truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008922{
8923 return 0;
8924}
8925
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008926static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008927execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008928{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008929 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008930 iflag = 0; /* exit on error */
8931 mflag = 0;
8932 optschanged();
8933 shellexec(argv + 1, pathval(), 0);
8934 }
8935 return 0;
8936}
8937
8938/*
8939 * The return command.
8940 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008941static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008942returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008943{
8944 /*
8945 * If called outside a function, do what ksh does;
8946 * skip the rest of the file.
8947 */
8948 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8949 return argv[1] ? number(argv[1]) : exitstatus;
8950}
8951
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008952/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008953static int breakcmd(int, char **) FAST_FUNC;
8954static int dotcmd(int, char **) FAST_FUNC;
8955static int evalcmd(int, char **) FAST_FUNC;
8956static int exitcmd(int, char **) FAST_FUNC;
8957static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008958#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008959static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008960#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008961#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008962static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008963#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008964#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008965static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008966#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008967static int readcmd(int, char **) FAST_FUNC;
8968static int setcmd(int, char **) FAST_FUNC;
8969static int shiftcmd(int, char **) FAST_FUNC;
8970static int timescmd(int, char **) FAST_FUNC;
8971static int trapcmd(int, char **) FAST_FUNC;
8972static int umaskcmd(int, char **) FAST_FUNC;
8973static int unsetcmd(int, char **) FAST_FUNC;
8974static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008975
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008976#define BUILTIN_NOSPEC "0"
8977#define BUILTIN_SPECIAL "1"
8978#define BUILTIN_REGULAR "2"
8979#define BUILTIN_SPEC_REG "3"
8980#define BUILTIN_ASSIGN "4"
8981#define BUILTIN_SPEC_ASSG "5"
8982#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008983#define BUILTIN_SPEC_REG_ASSG "7"
8984
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008985/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008986#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008987static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008988#endif
8989#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008990static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008991#endif
8992#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008993static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008994#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008995
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008996/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008997static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008998 { BUILTIN_SPEC_REG "." , dotcmd },
8999 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009000#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009001 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00009002#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009003 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009004#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00009005#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009006#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009007 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009008#endif
9009#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009010 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009011#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009012 { BUILTIN_SPEC_REG "break" , breakcmd },
9013 { BUILTIN_REGULAR "cd" , cdcmd },
9014 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009015#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009016 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009017#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009018 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009019#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009020 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009021#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009022 { BUILTIN_SPEC_REG "eval" , evalcmd },
9023 { BUILTIN_SPEC_REG "exec" , execcmd },
9024 { BUILTIN_SPEC_REG "exit" , exitcmd },
9025 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9026 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009027#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009028 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009029#endif
9030#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009031 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009032#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009033 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009034#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009035 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009036#endif
9037#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009038 { BUILTIN_REGULAR "jobs" , jobscmd },
9039 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009040#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00009041#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009042 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009043#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009044 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009045#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009046 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009047#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009048 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9049 { BUILTIN_REGULAR "read" , readcmd },
9050 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9051 { BUILTIN_SPEC_REG "return" , returncmd },
9052 { BUILTIN_SPEC_REG "set" , setcmd },
9053 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009054#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009055 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009056#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009057#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009058 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009059#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009060 { BUILTIN_SPEC_REG "times" , timescmd },
9061 { BUILTIN_SPEC_REG "trap" , trapcmd },
9062 { BUILTIN_REGULAR "true" , truecmd },
9063 { BUILTIN_NOSPEC "type" , typecmd },
9064 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9065 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009066#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009067 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009068#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009069 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9070 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009071};
9072
Denis Vlasenko80591b02008-03-25 07:49:43 +00009073/* Should match the above table! */
9074#define COMMANDCMD (builtintab + \
9075 2 + \
9076 1 * ENABLE_ASH_BUILTIN_TEST + \
9077 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9078 1 * ENABLE_ASH_ALIAS + \
9079 1 * ENABLE_ASH_JOB_CONTROL + \
9080 3)
9081#define EXECCMD (builtintab + \
9082 2 + \
9083 1 * ENABLE_ASH_BUILTIN_TEST + \
9084 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9085 1 * ENABLE_ASH_ALIAS + \
9086 1 * ENABLE_ASH_JOB_CONTROL + \
9087 3 + \
9088 1 * ENABLE_ASH_CMDCMD + \
9089 1 + \
9090 ENABLE_ASH_BUILTIN_ECHO + \
9091 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009092
9093/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009094 * Search the table of builtin commands.
9095 */
9096static struct builtincmd *
9097find_builtin(const char *name)
9098{
9099 struct builtincmd *bp;
9100
9101 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00009102 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009103 pstrcmp
9104 );
9105 return bp;
9106}
9107
9108/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009109 * Execute a simple command.
9110 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009111static int
9112isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009113{
9114 const char *q = endofname(p);
9115 if (p == q)
9116 return 0;
9117 return *q == '=';
9118}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009119static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009120bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009121{
9122 /* Preserve exitstatus of a previous possible redirection
9123 * as POSIX mandates */
9124 return back_exitstatus;
9125}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009126static void
Eric Andersenc470f442003-07-28 09:56:35 +00009127evalcommand(union node *cmd, int flags)
9128{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009129 static const struct builtincmd null_bltin = {
9130 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009131 };
Eric Andersenc470f442003-07-28 09:56:35 +00009132 struct stackmark smark;
9133 union node *argp;
9134 struct arglist arglist;
9135 struct arglist varlist;
9136 char **argv;
9137 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009138 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009139 struct cmdentry cmdentry;
9140 struct job *jp;
9141 char *lastarg;
9142 const char *path;
9143 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009144 int status;
9145 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009146 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009147 smallint cmd_is_exec;
9148 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009149
9150 /* First expand the arguments. */
9151 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9152 setstackmark(&smark);
9153 back_exitstatus = 0;
9154
9155 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009156 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009157 varlist.lastp = &varlist.list;
9158 *varlist.lastp = NULL;
9159 arglist.lastp = &arglist.list;
9160 *arglist.lastp = NULL;
9161
9162 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009163 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009164 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9165 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9166 }
9167
Eric Andersenc470f442003-07-28 09:56:35 +00009168 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9169 struct strlist **spp;
9170
9171 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009172 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009173 expandarg(argp, &arglist, EXP_VARTILDE);
9174 else
9175 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9176
Eric Andersenc470f442003-07-28 09:56:35 +00009177 for (sp = *spp; sp; sp = sp->next)
9178 argc++;
9179 }
9180
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009181 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009182 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009183 TRACE(("evalcommand arg: %s\n", sp->text));
9184 *nargv++ = sp->text;
9185 }
9186 *nargv = NULL;
9187
9188 lastarg = NULL;
9189 if (iflag && funcnest == 0 && argc > 0)
9190 lastarg = nargv[-1];
9191
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009192 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009193 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009194 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009195
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009196 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009197 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9198 struct strlist **spp;
9199 char *p;
9200
9201 spp = varlist.lastp;
9202 expandarg(argp, &varlist, EXP_VARTILDE);
9203
9204 /*
9205 * Modify the command lookup path, if a PATH= assignment
9206 * is present
9207 */
9208 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009209 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009210 path = p;
9211 }
9212
9213 /* Print the command if xflag is set. */
9214 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009215 int n;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009216 const char *p = " %s" + 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009217
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009218 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009219 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009220 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009221 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009222 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009223 sp = sp->next;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009224 p = " %s";
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009225 }
9226 sp = arglist.list;
9227 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009228 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009229 }
9230
9231 cmd_is_exec = 0;
9232 spclbltin = -1;
9233
9234 /* Now locate the command. */
9235 if (argc) {
9236 const char *oldpath;
9237 int cmd_flag = DO_ERR;
9238
9239 path += 5;
9240 oldpath = path;
9241 for (;;) {
9242 find_command(argv[0], &cmdentry, cmd_flag, path);
9243 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009244 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009245 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009246 goto bail;
9247 }
9248
9249 /* implement bltin and command here */
9250 if (cmdentry.cmdtype != CMDBUILTIN)
9251 break;
9252 if (spclbltin < 0)
9253 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9254 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009255 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009256#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009257 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009258 path = oldpath;
9259 nargv = parse_command_args(argv, &path);
9260 if (!nargv)
9261 break;
9262 argc -= nargv - argv;
9263 argv = nargv;
9264 cmd_flag |= DO_NOFUNC;
9265 } else
9266#endif
9267 break;
9268 }
9269 }
9270
9271 if (status) {
9272 /* We have a redirection error. */
9273 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009274 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009275 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009276 exitstatus = status;
9277 goto out;
9278 }
9279
9280 /* Execute the command. */
9281 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009282 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009283
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009284#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009285/* (1) BUG: if variables are set, we need to fork, or save/restore them
9286 * around run_nofork_applet() call.
9287 * (2) Should this check also be done in forkshell()?
9288 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9289 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009290 /* find_command() encodes applet_no as (-2 - applet_no) */
9291 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009292 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009293 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009294 /* run <applet>_main() */
9295 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009296 break;
9297 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009298#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009299 /* Can we avoid forking off? For example, very last command
9300 * in a script or a subshell does not need forking,
9301 * we can just exec it.
9302 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009303 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009304 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009305 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009306 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009307 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009308 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009309 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009310 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009311 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009312 break;
9313 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009314 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009315 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009316 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009317 }
9318 listsetvar(varlist.list, VEXPORT|VSTACK);
9319 shellexec(argv, path, cmdentry.u.index);
9320 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009321 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009322 case CMDBUILTIN:
9323 cmdenviron = varlist.list;
9324 if (cmdenviron) {
9325 struct strlist *list = cmdenviron;
9326 int i = VNOSET;
9327 if (spclbltin > 0 || argc == 0) {
9328 i = 0;
9329 if (cmd_is_exec && argc > 1)
9330 i = VEXPORT;
9331 }
9332 listsetvar(list, i);
9333 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009334 /* Tight loop with builtins only:
9335 * "while kill -0 $child; do true; done"
9336 * will never exit even if $child died, unless we do this
9337 * to reap the zombie and make kill detect that it's gone: */
9338 dowait(DOWAIT_NONBLOCK, NULL);
9339
Eric Andersenc470f442003-07-28 09:56:35 +00009340 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9341 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009342 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009343 if (i == EXEXIT)
9344 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009345 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009346 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009347 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009348 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009349 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009350 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009351 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009352 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009353 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009354 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009355 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009356 }
9357 break;
9358
9359 case CMDFUNCTION:
9360 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009361 /* See above for the rationale */
9362 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009363 if (evalfun(cmdentry.u.func, argc, argv, flags))
9364 goto raise;
9365 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009366
9367 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009368
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009369 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009370 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009371 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009372 /* dsl: I think this is intended to be used to support
9373 * '_' in 'vi' command mode during line editing...
9374 * However I implemented that within libedit itself.
9375 */
9376 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009377 }
Eric Andersenc470f442003-07-28 09:56:35 +00009378 popstackmark(&smark);
9379}
9380
9381static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009382evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9383{
Eric Andersenc470f442003-07-28 09:56:35 +00009384 char *volatile savecmdname;
9385 struct jmploc *volatile savehandler;
9386 struct jmploc jmploc;
9387 int i;
9388
9389 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009390 i = setjmp(jmploc.loc);
9391 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009392 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009393 savehandler = exception_handler;
9394 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009395 commandname = argv[0];
9396 argptr = argv + 1;
9397 optptr = NULL; /* initialize nextopt */
9398 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009399 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009400 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009401 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009402 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009403 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009404 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009405
9406 return i;
9407}
9408
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009409static int
9410goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009411{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02009412 return endofname(p)[0] == '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009413}
9414
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009415
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009416/*
9417 * Search for a command. This is called before we fork so that the
9418 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009419 * the child. The check for "goodname" is an overly conservative
9420 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009421 */
Eric Andersenc470f442003-07-28 09:56:35 +00009422static void
9423prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009424{
9425 struct cmdentry entry;
9426
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009427 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9428 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009429}
9430
Eric Andersencb57d552001-06-28 07:25:16 +00009431
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009432/* ============ Builtin commands
9433 *
9434 * Builtin commands whose functions are closely tied to evaluation
9435 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009436 */
9437
9438/*
Eric Andersencb57d552001-06-28 07:25:16 +00009439 * Handle break and continue commands. Break, continue, and return are
9440 * all handled by setting the evalskip flag. The evaluation routines
9441 * above all check this flag, and if it is set they start skipping
9442 * commands rather than executing them. The variable skipcount is
9443 * the number of loops to break/continue, or the number of function
9444 * levels to return. (The latter is always 1.) It should probably
9445 * be an error to break out of more loops than exist, but it isn't
9446 * in the standard shell so we don't make it one here.
9447 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009448static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009449breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009450{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009451 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009452
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009453 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009454 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009455 if (n > loopnest)
9456 n = loopnest;
9457 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009458 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009459 skipcount = n;
9460 }
9461 return 0;
9462}
9463
Eric Andersenc470f442003-07-28 09:56:35 +00009464
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009465/* ============ input.c
9466 *
Eric Andersen90898442003-08-06 11:20:52 +00009467 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009468 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009469
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009470enum {
9471 INPUT_PUSH_FILE = 1,
9472 INPUT_NOFILE_OK = 2,
9473};
Eric Andersencb57d552001-06-28 07:25:16 +00009474
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009475static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009476/* values of checkkwd variable */
9477#define CHKALIAS 0x1
9478#define CHKKWD 0x2
9479#define CHKNL 0x4
9480
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009481/*
9482 * Push a string back onto the input at this current parsefile level.
9483 * We handle aliases this way.
9484 */
9485#if !ENABLE_ASH_ALIAS
9486#define pushstring(s, ap) pushstring(s)
9487#endif
9488static void
9489pushstring(char *s, struct alias *ap)
9490{
9491 struct strpush *sp;
9492 int len;
9493
9494 len = strlen(s);
9495 INT_OFF;
9496 if (g_parsefile->strpush) {
9497 sp = ckzalloc(sizeof(*sp));
9498 sp->prev = g_parsefile->strpush;
9499 } else {
9500 sp = &(g_parsefile->basestrpush);
9501 }
9502 g_parsefile->strpush = sp;
9503 sp->prev_string = g_parsefile->next_to_pgetc;
9504 sp->prev_left_in_line = g_parsefile->left_in_line;
9505#if ENABLE_ASH_ALIAS
9506 sp->ap = ap;
9507 if (ap) {
9508 ap->flag |= ALIASINUSE;
9509 sp->string = s;
9510 }
9511#endif
9512 g_parsefile->next_to_pgetc = s;
9513 g_parsefile->left_in_line = len;
9514 INT_ON;
9515}
9516
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009517static void
9518popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009519{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009520 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009521
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009522 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009523#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009524 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009525 if (g_parsefile->next_to_pgetc[-1] == ' '
9526 || g_parsefile->next_to_pgetc[-1] == '\t'
9527 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009528 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009529 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009530 if (sp->string != sp->ap->val) {
9531 free(sp->string);
9532 }
9533 sp->ap->flag &= ~ALIASINUSE;
9534 if (sp->ap->flag & ALIASDEAD) {
9535 unalias(sp->ap->name);
9536 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009537 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009538#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009539 g_parsefile->next_to_pgetc = sp->prev_string;
9540 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009541 g_parsefile->strpush = sp->prev;
9542 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009543 free(sp);
9544 INT_ON;
9545}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009546
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009547//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9548//it peeks whether it is &>, and then pushes back both chars.
9549//This function needs to save last *next_to_pgetc to buf[0]
9550//to make two pungetc() reliable. Currently,
9551// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009552static int
9553preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009554{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009555 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009556 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009557
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009558 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009559#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009560 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009561 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9562 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009563 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009564#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009565 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009566#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009567 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009568 if (nr == 0) {
9569 /* Ctrl+C pressed */
9570 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009571 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009572 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009573 raise(SIGINT);
9574 return 1;
9575 }
Eric Andersenc470f442003-07-28 09:56:35 +00009576 goto retry;
9577 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009578 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009579 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009580 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009581 }
Eric Andersencb57d552001-06-28 07:25:16 +00009582 }
9583#else
Denys Vlasenko161bb8f2010-06-06 05:07:11 +02009584 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009585#endif
9586
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009587#if 0
9588/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009589 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009590 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009591 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009592 if (flags >= 0 && (flags & O_NONBLOCK)) {
9593 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009594 if (fcntl(0, F_SETFL, flags) >= 0) {
9595 out2str("sh: turning off NDELAY mode\n");
9596 goto retry;
9597 }
9598 }
9599 }
9600 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009601#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009602 return nr;
9603}
9604
9605/*
9606 * Refill the input buffer and return the next input character:
9607 *
9608 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009609 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9610 * or we are reading from a string so we can't refill the buffer,
9611 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009612 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009613 * 4) Process input up to the next newline, deleting nul characters.
9614 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009615//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9616#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009617static int
Eric Andersenc470f442003-07-28 09:56:35 +00009618preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009619{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009620 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009621 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009622
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009623 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009624#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009625 if (g_parsefile->left_in_line == -1
9626 && g_parsefile->strpush->ap
9627 && g_parsefile->next_to_pgetc[-1] != ' '
9628 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009629 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009630 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009631 return PEOA;
9632 }
Eric Andersen2870d962001-07-02 17:27:21 +00009633#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009634 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009635 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009636 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9637 g_parsefile->left_in_line,
9638 g_parsefile->next_to_pgetc,
9639 g_parsefile->next_to_pgetc);
9640 if (--g_parsefile->left_in_line >= 0)
9641 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009642 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009643 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009644 * "pgetc" needs refilling.
9645 */
9646
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009647 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009648 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009649 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009650 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009651 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009652 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009653 /* even in failure keep left_in_line and next_to_pgetc
9654 * in lock step, for correct multi-layer pungetc.
9655 * left_in_line was decremented before preadbuffer(),
9656 * must inc next_to_pgetc: */
9657 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009658 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009659 }
Eric Andersencb57d552001-06-28 07:25:16 +00009660
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009661 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009662 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009663 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009664 again:
9665 more = preadfd();
9666 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009667 /* don't try reading again */
9668 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009669 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009670 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009671 return PEOF;
9672 }
9673 }
9674
Denis Vlasenko727752d2008-11-28 03:41:47 +00009675 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009676 * Set g_parsefile->left_in_line
9677 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009678 * NUL chars are deleted.
9679 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009680 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009681 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009682 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009683
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009684 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009685
Denis Vlasenko727752d2008-11-28 03:41:47 +00009686 c = *q;
9687 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009688 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009689 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009690 q++;
9691 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009692 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009693 break;
9694 }
Eric Andersencb57d552001-06-28 07:25:16 +00009695 }
9696
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009697 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009698 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9699 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009700 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009701 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009702 }
9703 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009704 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009705
Eric Andersencb57d552001-06-28 07:25:16 +00009706 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009707 char save = *q;
9708 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009709 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009710 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009711 }
9712
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009713 pgetc_debug("preadbuffer at %d:%p'%s'",
9714 g_parsefile->left_in_line,
9715 g_parsefile->next_to_pgetc,
9716 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009717 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009718}
9719
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009720#define pgetc_as_macro() \
9721 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009722 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009723 : preadbuffer() \
9724 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009725
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009726static int
9727pgetc(void)
9728{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009729 pgetc_debug("pgetc_fast at %d:%p'%s'",
9730 g_parsefile->left_in_line,
9731 g_parsefile->next_to_pgetc,
9732 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009733 return pgetc_as_macro();
9734}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009735
9736#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009737# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009738#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009739# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009740#endif
9741
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009742#if ENABLE_ASH_ALIAS
9743static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009744pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009745{
9746 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009747 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009748 pgetc_debug("pgetc_fast at %d:%p'%s'",
9749 g_parsefile->left_in_line,
9750 g_parsefile->next_to_pgetc,
9751 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009752 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009753 } while (c == PEOA);
9754 return c;
9755}
9756#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009757# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009758#endif
9759
9760/*
9761 * Read a line from the script.
9762 */
9763static char *
9764pfgets(char *line, int len)
9765{
9766 char *p = line;
9767 int nleft = len;
9768 int c;
9769
9770 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009771 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009772 if (c == PEOF) {
9773 if (p == line)
9774 return NULL;
9775 break;
9776 }
9777 *p++ = c;
9778 if (c == '\n')
9779 break;
9780 }
9781 *p = '\0';
9782 return line;
9783}
9784
Eric Andersenc470f442003-07-28 09:56:35 +00009785/*
9786 * Undo the last call to pgetc. Only one character may be pushed back.
9787 * PEOF may be pushed back.
9788 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009789static void
Eric Andersenc470f442003-07-28 09:56:35 +00009790pungetc(void)
9791{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009792 g_parsefile->left_in_line++;
9793 g_parsefile->next_to_pgetc--;
9794 pgetc_debug("pushed back to %d:%p'%s'",
9795 g_parsefile->left_in_line,
9796 g_parsefile->next_to_pgetc,
9797 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009798}
9799
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009800/*
9801 * To handle the "." command, a stack of input files is used. Pushfile
9802 * adds a new entry to the stack and popfile restores the previous level.
9803 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009804static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009805pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009806{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009807 struct parsefile *pf;
9808
Denis Vlasenko597906c2008-02-20 16:38:54 +00009809 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009810 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009811 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009812 /*pf->strpush = NULL; - ckzalloc did it */
9813 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009814 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009815}
9816
9817static void
9818popfile(void)
9819{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009820 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009821
Denis Vlasenkob012b102007-02-19 22:43:01 +00009822 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009823 if (pf->pf_fd >= 0)
9824 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009825 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009826 while (pf->strpush)
9827 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009828 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009829 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009830 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009831}
9832
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009833/*
9834 * Return to top level.
9835 */
9836static void
9837popallfiles(void)
9838{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009839 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009840 popfile();
9841}
9842
9843/*
9844 * Close the file(s) that the shell is reading commands from. Called
9845 * after a fork is done.
9846 */
9847static void
9848closescript(void)
9849{
9850 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009851 if (g_parsefile->pf_fd > 0) {
9852 close(g_parsefile->pf_fd);
9853 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009854 }
9855}
9856
9857/*
9858 * Like setinputfile, but takes an open file descriptor. Call this with
9859 * interrupts off.
9860 */
9861static void
9862setinputfd(int fd, int push)
9863{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009864 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009865 if (push) {
9866 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009867 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009868 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009869 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009870 if (g_parsefile->buf == NULL)
9871 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009872 g_parsefile->left_in_buffer = 0;
9873 g_parsefile->left_in_line = 0;
9874 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009875}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009876
Eric Andersenc470f442003-07-28 09:56:35 +00009877/*
9878 * Set the input to take input from a file. If push is set, push the
9879 * old input onto the stack first.
9880 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009881static int
9882setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009883{
9884 int fd;
9885 int fd2;
9886
Denis Vlasenkob012b102007-02-19 22:43:01 +00009887 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009888 fd = open(fname, O_RDONLY);
9889 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009890 if (flags & INPUT_NOFILE_OK)
9891 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009892 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009893 }
Eric Andersenc470f442003-07-28 09:56:35 +00009894 if (fd < 10) {
9895 fd2 = copyfd(fd, 10);
9896 close(fd);
9897 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009898 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009899 fd = fd2;
9900 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009901 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009902 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009903 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009904 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009905}
9906
Eric Andersencb57d552001-06-28 07:25:16 +00009907/*
9908 * Like setinputfile, but takes input from a string.
9909 */
Eric Andersenc470f442003-07-28 09:56:35 +00009910static void
9911setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009912{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009913 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009914 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009915 g_parsefile->next_to_pgetc = string;
9916 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009917 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009918 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009919 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009920}
9921
9922
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009923/* ============ mail.c
9924 *
9925 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009926 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009927
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009928#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009929
Eric Andersencb57d552001-06-28 07:25:16 +00009930#define MAXMBOXES 10
9931
Eric Andersenc470f442003-07-28 09:56:35 +00009932/* times of mailboxes */
9933static time_t mailtime[MAXMBOXES];
9934/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009935static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009936
Eric Andersencb57d552001-06-28 07:25:16 +00009937/*
Eric Andersenc470f442003-07-28 09:56:35 +00009938 * Print appropriate message(s) if mail has arrived.
9939 * If mail_var_path_changed is set,
9940 * then the value of MAIL has mail_var_path_changed,
9941 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009942 */
Eric Andersenc470f442003-07-28 09:56:35 +00009943static void
9944chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009945{
Eric Andersencb57d552001-06-28 07:25:16 +00009946 const char *mpath;
9947 char *p;
9948 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009949 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009950 struct stackmark smark;
9951 struct stat statb;
9952
Eric Andersencb57d552001-06-28 07:25:16 +00009953 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009954 mpath = mpathset() ? mpathval() : mailval();
9955 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009956 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009957 if (p == NULL)
9958 break;
9959 if (*p == '\0')
9960 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009961 for (q = p; *q; q++)
9962 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009963#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009964 if (q[-1] != '/')
9965 abort();
9966#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009967 q[-1] = '\0'; /* delete trailing '/' */
9968 if (stat(p, &statb) < 0) {
9969 *mtp = 0;
9970 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009971 }
Eric Andersenc470f442003-07-28 09:56:35 +00009972 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9973 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009974 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009975 pathopt ? pathopt : "you have mail"
9976 );
9977 }
9978 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009979 }
Eric Andersenc470f442003-07-28 09:56:35 +00009980 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009981 popstackmark(&smark);
9982}
Eric Andersencb57d552001-06-28 07:25:16 +00009983
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009984static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009985changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009986{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009987 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009988}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009989
Denis Vlasenko131ae172007-02-18 13:00:19 +00009990#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009991
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009992
9993/* ============ ??? */
9994
Eric Andersencb57d552001-06-28 07:25:16 +00009995/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009996 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009997 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009998static void
9999setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010000{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010001 char **newparam;
10002 char **ap;
10003 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +000010004
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010005 for (nparam = 0; argv[nparam]; nparam++)
10006 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010007 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10008 while (*argv) {
10009 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +000010010 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010011 *ap = NULL;
10012 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +000010013 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010014 shellparam.nparam = nparam;
10015 shellparam.p = newparam;
10016#if ENABLE_ASH_GETOPTS
10017 shellparam.optind = 1;
10018 shellparam.optoff = -1;
10019#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010020}
10021
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010022/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010023 * Process shell options. The global variable argptr contains a pointer
10024 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010025 *
10026 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10027 * For a non-interactive shell, an error condition encountered
10028 * by a special built-in ... shall cause the shell to write a diagnostic message
10029 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +000010030 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010031 * ...
10032 * Utility syntax error (option or operand error) Shall exit
10033 * ...
10034 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10035 * we see that bash does not do that (set "finishes" with error code 1 instead,
10036 * and shell continues), and people rely on this behavior!
10037 * Testcase:
10038 * set -o barfoo 2>/dev/null
10039 * echo $?
10040 *
10041 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010042 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010043static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010044plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +000010045{
10046 int i;
10047
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010048 if (name) {
10049 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010050 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000010051 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010052 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010053 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010054 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010055 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010056 return 1;
Eric Andersen62483552001-07-10 06:09:16 +000010057 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010058 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010059 if (val) {
10060 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10061 } else {
10062 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10063 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010064 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010065 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010066}
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010067static void
10068setoption(int flag, int val)
10069{
10070 int i;
10071
10072 for (i = 0; i < NOPTS; i++) {
10073 if (optletters(i) == flag) {
10074 optlist[i] = val;
10075 return;
10076 }
10077 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010078 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010079 /* NOTREACHED */
10080}
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010081static int
Eric Andersenc470f442003-07-28 09:56:35 +000010082options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +000010083{
10084 char *p;
10085 int val;
10086 int c;
10087
10088 if (cmdline)
10089 minusc = NULL;
10090 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010091 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010092 if (c != '-' && c != '+')
10093 break;
10094 argptr++;
10095 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010096 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +000010097 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010098 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +000010099 if (!cmdline) {
10100 /* "-" means turn off -x and -v */
10101 if (p[0] == '\0')
10102 xflag = vflag = 0;
10103 /* "--" means reset params */
10104 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +000010105 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010106 }
Eric Andersenc470f442003-07-28 09:56:35 +000010107 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010108 }
Eric Andersencb57d552001-06-28 07:25:16 +000010109 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010110 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010111 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010112 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010113 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010114 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010115 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010116 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010117 /* it already printed err message */
10118 return 1; /* error */
10119 }
Eric Andersencb57d552001-06-28 07:25:16 +000010120 if (*argptr)
10121 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010122 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10123 isloginsh = 1;
10124 /* bash does not accept +-login, we also won't */
10125 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010126 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010127 isloginsh = 1;
10128 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010129 } else {
10130 setoption(c, val);
10131 }
10132 }
10133 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010134 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010135}
10136
Eric Andersencb57d552001-06-28 07:25:16 +000010137/*
Eric Andersencb57d552001-06-28 07:25:16 +000010138 * The shift builtin command.
10139 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010140static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010141shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010142{
10143 int n;
10144 char **ap1, **ap2;
10145
10146 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010147 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010148 n = number(argv[1]);
10149 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010150 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010151 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010152 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010153 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010154 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010155 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010156 }
10157 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010158 while ((*ap2++ = *ap1++) != NULL)
10159 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010160#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010161 shellparam.optind = 1;
10162 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010163#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010164 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010165 return 0;
10166}
10167
Eric Andersencb57d552001-06-28 07:25:16 +000010168/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010169 * POSIX requires that 'set' (but not export or readonly) output the
10170 * variables in lexicographic order - by the locale's collating order (sigh).
10171 * Maybe we could keep them in an ordered balanced binary tree
10172 * instead of hashed lists.
10173 * For now just roll 'em through qsort for printing...
10174 */
10175static int
10176showvars(const char *sep_prefix, int on, int off)
10177{
10178 const char *sep;
10179 char **ep, **epend;
10180
10181 ep = listvars(on, off, &epend);
10182 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10183
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010184 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010185
10186 for (; ep < epend; ep++) {
10187 const char *p;
10188 const char *q;
10189
10190 p = strchrnul(*ep, '=');
10191 q = nullstr;
10192 if (*p)
10193 q = single_quote(++p);
10194 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10195 }
10196 return 0;
10197}
10198
10199/*
Eric Andersencb57d552001-06-28 07:25:16 +000010200 * The set command builtin.
10201 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010202static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010203setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010204{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010205 int retval;
10206
Denis Vlasenko68404f12008-03-17 09:00:54 +000010207 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010208 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010209 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010210 retval = 1;
10211 if (!options(0)) { /* if no parse error... */
10212 retval = 0;
10213 optschanged();
10214 if (*argptr != NULL) {
10215 setparam(argptr);
10216 }
Eric Andersencb57d552001-06-28 07:25:16 +000010217 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010218 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010219 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010220}
10221
Denis Vlasenko131ae172007-02-18 13:00:19 +000010222#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010223static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010224change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010225{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010226 uint32_t t;
10227
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010228 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010229 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010230 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010231 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010232 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010233 vrandom.flags &= ~VNOFUNC;
10234 } else {
10235 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010236 t = strtoul(value, NULL, 10);
10237 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010238 }
Eric Andersenef02f822004-03-11 13:34:24 +000010239}
Eric Andersen16767e22004-03-16 05:14:10 +000010240#endif
10241
Denis Vlasenko131ae172007-02-18 13:00:19 +000010242#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010243static int
Eric Andersenc470f442003-07-28 09:56:35 +000010244getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010245{
10246 char *p, *q;
10247 char c = '?';
10248 int done = 0;
10249 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010250 char s[12];
10251 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010252
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010253 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010254 return 1;
10255 optnext = optfirst + *param_optind - 1;
10256
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010257 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010258 p = NULL;
10259 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010260 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010261 if (p == NULL || *p == '\0') {
10262 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010263 p = *optnext;
10264 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010265 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010266 p = NULL;
10267 done = 1;
10268 goto out;
10269 }
10270 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010271 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010272 goto atend;
10273 }
10274
10275 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010276 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010277 if (*q == '\0') {
10278 if (optstr[0] == ':') {
10279 s[0] = c;
10280 s[1] = '\0';
10281 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010282 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010283 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010284 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010285 }
10286 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010287 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010288 }
10289 if (*++q == ':')
10290 q++;
10291 }
10292
10293 if (*++q == ':') {
10294 if (*p == '\0' && (p = *optnext) == NULL) {
10295 if (optstr[0] == ':') {
10296 s[0] = c;
10297 s[1] = '\0';
10298 err |= setvarsafe("OPTARG", s, 0);
10299 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010300 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010301 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010302 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010303 c = '?';
10304 }
Eric Andersenc470f442003-07-28 09:56:35 +000010305 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010306 }
10307
10308 if (p == *optnext)
10309 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010310 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010311 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010312 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010313 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010314 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010315 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010316 *param_optind = optnext - optfirst + 1;
10317 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010318 err |= setvarsafe("OPTIND", s, VNOFUNC);
10319 s[0] = c;
10320 s[1] = '\0';
10321 err |= setvarsafe(optvar, s, 0);
10322 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010323 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010324 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010325 flush_stdout_stderr();
10326 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010327 }
10328 return done;
10329}
Eric Andersenc470f442003-07-28 09:56:35 +000010330
10331/*
10332 * The getopts builtin. Shellparam.optnext points to the next argument
10333 * to be processed. Shellparam.optptr points to the next character to
10334 * be processed in the current argument. If shellparam.optnext is NULL,
10335 * then it's the first time getopts has been called.
10336 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010337static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010338getoptscmd(int argc, char **argv)
10339{
10340 char **optbase;
10341
10342 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010343 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010344 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010345 optbase = shellparam.p;
10346 if (shellparam.optind > shellparam.nparam + 1) {
10347 shellparam.optind = 1;
10348 shellparam.optoff = -1;
10349 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010350 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010351 optbase = &argv[3];
10352 if (shellparam.optind > argc - 2) {
10353 shellparam.optind = 1;
10354 shellparam.optoff = -1;
10355 }
10356 }
10357
10358 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010359 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010360}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010361#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010362
Eric Andersencb57d552001-06-28 07:25:16 +000010363
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010364/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010365
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010366struct heredoc {
10367 struct heredoc *next; /* next here document in list */
10368 union node *here; /* redirection node */
10369 char *eofmark; /* string indicating end of input */
10370 smallint striptabs; /* if set, strip leading tabs */
10371};
10372
10373static smallint tokpushback; /* last token pushed back */
10374static smallint parsebackquote; /* nonzero if we are inside backquotes */
10375static smallint quoteflag; /* set if (part of) last token was quoted */
10376static token_id_t lasttoken; /* last token read (integer id Txxx) */
10377static struct heredoc *heredoclist; /* list of here documents to read */
10378static char *wordtext; /* text of last word returned by readtoken */
10379static struct nodelist *backquotelist;
10380static union node *redirnode;
10381static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010382
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010383static const char *
10384tokname(char *buf, int tok)
10385{
10386 if (tok < TSEMI)
10387 return tokname_array[tok] + 1;
10388 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10389 return buf;
10390}
10391
10392/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010393 * Called when an unexpected token is read during the parse. The argument
10394 * is the token that is expected, or -1 if more than one type of token can
10395 * occur at this point.
10396 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010397static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010398static void
10399raise_error_unexpected_syntax(int token)
10400{
10401 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010402 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010403 int l;
10404
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010405 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010406 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010407 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010408 raise_error_syntax(msg);
10409 /* NOTREACHED */
10410}
Eric Andersencb57d552001-06-28 07:25:16 +000010411
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010412#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010413
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414/* parsing is heavily cross-recursive, need these forward decls */
10415static union node *andor(void);
10416static union node *pipeline(void);
10417static union node *parse_command(void);
10418static void parseheredoc(void);
10419static char peektoken(void);
10420static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010421
Eric Andersenc470f442003-07-28 09:56:35 +000010422static union node *
10423list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010424{
10425 union node *n1, *n2, *n3;
10426 int tok;
10427
Eric Andersenc470f442003-07-28 09:56:35 +000010428 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10429 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010430 return NULL;
10431 n1 = NULL;
10432 for (;;) {
10433 n2 = andor();
10434 tok = readtoken();
10435 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010436 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010437 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010438 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010439 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010440 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010441 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010442 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010443 n2 = n3;
10444 }
10445 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010446 }
10447 }
10448 if (n1 == NULL) {
10449 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010450 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010451 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010452 n3->type = NSEMI;
10453 n3->nbinary.ch1 = n1;
10454 n3->nbinary.ch2 = n2;
10455 n1 = n3;
10456 }
10457 switch (tok) {
10458 case TBACKGND:
10459 case TSEMI:
10460 tok = readtoken();
10461 /* fall through */
10462 case TNL:
10463 if (tok == TNL) {
10464 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010465 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010466 return n1;
10467 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010468 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010469 }
Eric Andersenc470f442003-07-28 09:56:35 +000010470 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010471 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010472 return n1;
10473 break;
10474 case TEOF:
10475 if (heredoclist)
10476 parseheredoc();
10477 else
Eric Andersenc470f442003-07-28 09:56:35 +000010478 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010479 return n1;
10480 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010481 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010482 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010483 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010484 return n1;
10485 }
10486 }
10487}
10488
Eric Andersenc470f442003-07-28 09:56:35 +000010489static union node *
10490andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010491{
Eric Andersencb57d552001-06-28 07:25:16 +000010492 union node *n1, *n2, *n3;
10493 int t;
10494
Eric Andersencb57d552001-06-28 07:25:16 +000010495 n1 = pipeline();
10496 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010497 t = readtoken();
10498 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010499 t = NAND;
10500 } else if (t == TOR) {
10501 t = NOR;
10502 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010503 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010504 return n1;
10505 }
Eric Andersenc470f442003-07-28 09:56:35 +000010506 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010507 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010508 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010509 n3->type = t;
10510 n3->nbinary.ch1 = n1;
10511 n3->nbinary.ch2 = n2;
10512 n1 = n3;
10513 }
10514}
10515
Eric Andersenc470f442003-07-28 09:56:35 +000010516static union node *
10517pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010518{
Eric Andersencb57d552001-06-28 07:25:16 +000010519 union node *n1, *n2, *pipenode;
10520 struct nodelist *lp, *prev;
10521 int negate;
10522
10523 negate = 0;
10524 TRACE(("pipeline: entered\n"));
10525 if (readtoken() == TNOT) {
10526 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010527 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010528 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010529 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010530 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010531 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010532 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010533 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010534 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010535 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010536 pipenode->npipe.cmdlist = lp;
10537 lp->n = n1;
10538 do {
10539 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010540 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010541 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010542 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010543 prev->next = lp;
10544 } while (readtoken() == TPIPE);
10545 lp->next = NULL;
10546 n1 = pipenode;
10547 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010548 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010549 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010550 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010551 n2->type = NNOT;
10552 n2->nnot.com = n1;
10553 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010554 }
10555 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010556}
10557
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010558static union node *
10559makename(void)
10560{
10561 union node *n;
10562
Denis Vlasenko597906c2008-02-20 16:38:54 +000010563 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010564 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010565 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010566 n->narg.text = wordtext;
10567 n->narg.backquote = backquotelist;
10568 return n;
10569}
10570
10571static void
10572fixredir(union node *n, const char *text, int err)
10573{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010574 int fd;
10575
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010576 TRACE(("Fix redir %s %d\n", text, err));
10577 if (!err)
10578 n->ndup.vname = NULL;
10579
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010580 fd = bb_strtou(text, NULL, 10);
10581 if (!errno && fd >= 0)
10582 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010583 else if (LONE_DASH(text))
10584 n->ndup.dupfd = -1;
10585 else {
10586 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010587 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010588 n->ndup.vname = makename();
10589 }
10590}
10591
10592/*
10593 * Returns true if the text contains nothing to expand (no dollar signs
10594 * or backquotes).
10595 */
10596static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010597noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010598{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010599 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010600
Denys Vlasenkocd716832009-11-28 22:14:02 +010010601 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010602 if (c == CTLQUOTEMARK)
10603 continue;
10604 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010605 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010606 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010607 return 0;
10608 }
10609 return 1;
10610}
10611
10612static void
10613parsefname(void)
10614{
10615 union node *n = redirnode;
10616
10617 if (readtoken() != TWORD)
10618 raise_error_unexpected_syntax(-1);
10619 if (n->type == NHERE) {
10620 struct heredoc *here = heredoc;
10621 struct heredoc *p;
10622 int i;
10623
10624 if (quoteflag == 0)
10625 n->type = NXHERE;
10626 TRACE(("Here document %d\n", n->type));
10627 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010628 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010629 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010630 here->eofmark = wordtext;
10631 here->next = NULL;
10632 if (heredoclist == NULL)
10633 heredoclist = here;
10634 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010635 for (p = heredoclist; p->next; p = p->next)
10636 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010637 p->next = here;
10638 }
10639 } else if (n->type == NTOFD || n->type == NFROMFD) {
10640 fixredir(n, wordtext, 0);
10641 } else {
10642 n->nfile.fname = makename();
10643 }
10644}
Eric Andersencb57d552001-06-28 07:25:16 +000010645
Eric Andersenc470f442003-07-28 09:56:35 +000010646static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010647simplecmd(void)
10648{
10649 union node *args, **app;
10650 union node *n = NULL;
10651 union node *vars, **vpp;
10652 union node **rpp, *redir;
10653 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010654#if ENABLE_ASH_BASH_COMPAT
10655 smallint double_brackets_flag = 0;
10656#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010657
10658 args = NULL;
10659 app = &args;
10660 vars = NULL;
10661 vpp = &vars;
10662 redir = NULL;
10663 rpp = &redir;
10664
10665 savecheckkwd = CHKALIAS;
10666 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010667 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010668 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010669 t = readtoken();
10670 switch (t) {
10671#if ENABLE_ASH_BASH_COMPAT
10672 case TAND: /* "&&" */
10673 case TOR: /* "||" */
10674 if (!double_brackets_flag) {
10675 tokpushback = 1;
10676 goto out;
10677 }
10678 wordtext = (char *) (t == TAND ? "-a" : "-o");
10679#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010680 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010681 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010682 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010683 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010684 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010685#if ENABLE_ASH_BASH_COMPAT
10686 if (strcmp("[[", wordtext) == 0)
10687 double_brackets_flag = 1;
10688 else if (strcmp("]]", wordtext) == 0)
10689 double_brackets_flag = 0;
10690#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010691 n->narg.backquote = backquotelist;
10692 if (savecheckkwd && isassignment(wordtext)) {
10693 *vpp = n;
10694 vpp = &n->narg.next;
10695 } else {
10696 *app = n;
10697 app = &n->narg.next;
10698 savecheckkwd = 0;
10699 }
10700 break;
10701 case TREDIR:
10702 *rpp = n = redirnode;
10703 rpp = &n->nfile.next;
10704 parsefname(); /* read name of redirection file */
10705 break;
10706 case TLP:
10707 if (args && app == &args->narg.next
10708 && !vars && !redir
10709 ) {
10710 struct builtincmd *bcmd;
10711 const char *name;
10712
10713 /* We have a function */
10714 if (readtoken() != TRP)
10715 raise_error_unexpected_syntax(TRP);
10716 name = n->narg.text;
10717 if (!goodname(name)
10718 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10719 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010720 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010721 }
10722 n->type = NDEFUN;
10723 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10724 n->narg.next = parse_command();
10725 return n;
10726 }
10727 /* fall through */
10728 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010729 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010730 goto out;
10731 }
10732 }
10733 out:
10734 *app = NULL;
10735 *vpp = NULL;
10736 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010737 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010738 n->type = NCMD;
10739 n->ncmd.args = args;
10740 n->ncmd.assign = vars;
10741 n->ncmd.redirect = redir;
10742 return n;
10743}
10744
10745static union node *
10746parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010747{
Eric Andersencb57d552001-06-28 07:25:16 +000010748 union node *n1, *n2;
10749 union node *ap, **app;
10750 union node *cp, **cpp;
10751 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010752 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010753 int t;
10754
10755 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010756 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010757
Eric Andersencb57d552001-06-28 07:25:16 +000010758 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010759 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010760 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010761 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010762 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010763 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010764 n1->type = NIF;
10765 n1->nif.test = list(0);
10766 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010767 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010768 n1->nif.ifpart = list(0);
10769 n2 = n1;
10770 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010771 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010772 n2 = n2->nif.elsepart;
10773 n2->type = NIF;
10774 n2->nif.test = list(0);
10775 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010776 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010777 n2->nif.ifpart = list(0);
10778 }
10779 if (lasttoken == TELSE)
10780 n2->nif.elsepart = list(0);
10781 else {
10782 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010783 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010784 }
Eric Andersenc470f442003-07-28 09:56:35 +000010785 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010786 break;
10787 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010788 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010789 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010790 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010791 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010792 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010793 got = readtoken();
10794 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010795 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010796 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010797 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010798 }
10799 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010800 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010801 break;
10802 }
10803 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010804 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010805 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010806 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010807 n1->type = NFOR;
10808 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010809 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010810 if (readtoken() == TIN) {
10811 app = &ap;
10812 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010813 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010814 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010815 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010816 n2->narg.text = wordtext;
10817 n2->narg.backquote = backquotelist;
10818 *app = n2;
10819 app = &n2->narg.next;
10820 }
10821 *app = NULL;
10822 n1->nfor.args = ap;
10823 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010824 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010825 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010826 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010827 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010828 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010829 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010830 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010831 n1->nfor.args = n2;
10832 /*
10833 * Newline or semicolon here is optional (but note
10834 * that the original Bourne shell only allowed NL).
10835 */
10836 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010837 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010838 }
Eric Andersenc470f442003-07-28 09:56:35 +000010839 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010840 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010841 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010842 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010843 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010844 break;
10845 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010846 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010847 n1->type = NCASE;
10848 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010849 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010850 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010851 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010852 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010853 n2->narg.text = wordtext;
10854 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010855 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010856 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010857 } while (readtoken() == TNL);
10858 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010859 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010860 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010861 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010862 checkkwd = CHKNL | CHKKWD;
10863 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010864 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010865 if (lasttoken == TLP)
10866 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010867 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010868 cp->type = NCLIST;
10869 app = &cp->nclist.pattern;
10870 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010871 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010872 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010873 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010874 ap->narg.text = wordtext;
10875 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010876 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010877 break;
10878 app = &ap->narg.next;
10879 readtoken();
10880 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010881 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010882 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010883 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010884 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010885
Eric Andersenc470f442003-07-28 09:56:35 +000010886 cpp = &cp->nclist.next;
10887
10888 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010889 t = readtoken();
10890 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010891 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010892 raise_error_unexpected_syntax(TENDCASE);
10893 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010894 }
Eric Andersenc470f442003-07-28 09:56:35 +000010895 }
Eric Andersencb57d552001-06-28 07:25:16 +000010896 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010897 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010898 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010899 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010900 n1->type = NSUBSHELL;
10901 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010902 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010903 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010904 break;
10905 case TBEGIN:
10906 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010907 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010908 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010909 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010910 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010911 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010912 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010913 }
10914
Eric Andersenc470f442003-07-28 09:56:35 +000010915 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010916 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010917
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010918 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010919 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010920 checkkwd = CHKKWD | CHKALIAS;
10921 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010922 while (readtoken() == TREDIR) {
10923 *rpp = n2 = redirnode;
10924 rpp = &n2->nfile.next;
10925 parsefname();
10926 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010927 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010928 *rpp = NULL;
10929 if (redir) {
10930 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010931 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010932 n2->type = NREDIR;
10933 n2->nredir.n = n1;
10934 n1 = n2;
10935 }
10936 n1->nredir.redirect = redir;
10937 }
Eric Andersencb57d552001-06-28 07:25:16 +000010938 return n1;
10939}
10940
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010941#if ENABLE_ASH_BASH_COMPAT
10942static int decode_dollar_squote(void)
10943{
10944 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10945 int c, cnt;
10946 char *p;
10947 char buf[4];
10948
10949 c = pgetc();
10950 p = strchr(C_escapes, c);
10951 if (p) {
10952 buf[0] = c;
10953 p = buf;
10954 cnt = 3;
10955 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10956 do {
10957 c = pgetc();
10958 *++p = c;
10959 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10960 pungetc();
10961 } else if (c == 'x') { /* \xHH */
10962 do {
10963 c = pgetc();
10964 *++p = c;
10965 } while (isxdigit(c) && --cnt);
10966 pungetc();
10967 if (cnt == 3) { /* \x but next char is "bad" */
10968 c = 'x';
10969 goto unrecognized;
10970 }
10971 } else { /* simple seq like \\ or \t */
10972 p++;
10973 }
10974 *p = '\0';
10975 p = buf;
10976 c = bb_process_escape_sequence((void*)&p);
10977 } else { /* unrecognized "\z": print both chars unless ' or " */
10978 if (c != '\'' && c != '"') {
10979 unrecognized:
10980 c |= 0x100; /* "please encode \, then me" */
10981 }
10982 }
10983 return c;
10984}
10985#endif
10986
Eric Andersencb57d552001-06-28 07:25:16 +000010987/*
10988 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10989 * is not NULL, read a here document. In the latter case, eofmark is the
10990 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010991 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010992 * is the first character of the input token or document.
10993 *
10994 * Because C does not have internal subroutines, I have simulated them
10995 * using goto's to implement the subroutine linkage. The following macros
10996 * will run code that appears at the end of readtoken1.
10997 */
Eric Andersen2870d962001-07-02 17:27:21 +000010998#define CHECKEND() {goto checkend; checkend_return:;}
10999#define PARSEREDIR() {goto parseredir; parseredir_return:;}
11000#define PARSESUB() {goto parsesub; parsesub_return:;}
11001#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11002#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11003#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000011004static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010011005readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000011006{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011007 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010011008 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000011009 char *out;
11010 int len;
11011 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011012 struct nodelist *bqlist;
11013 smallint quotef;
11014 smallint dblquote;
11015 smallint oldstyle;
11016 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000011017#if ENABLE_ASH_EXPAND_PRMT
11018 smallint pssyntax; /* we are expanding a prompt string */
11019#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011020 int varnest; /* levels of variables expansion */
11021 int arinest; /* levels of arithmetic expansion */
11022 int parenlevel; /* levels of parens in arithmetic */
11023 int dqvarnest; /* levels of variables expansion within double quotes */
11024
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011025 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011026
Eric Andersencb57d552001-06-28 07:25:16 +000011027#if __GNUC__
11028 /* Avoid longjmp clobbering */
11029 (void) &out;
11030 (void) &quotef;
11031 (void) &dblquote;
11032 (void) &varnest;
11033 (void) &arinest;
11034 (void) &parenlevel;
11035 (void) &dqvarnest;
11036 (void) &oldstyle;
11037 (void) &prevsyntax;
11038 (void) &syntax;
11039#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011040 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000011041 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011042 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011043 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000011044#if ENABLE_ASH_EXPAND_PRMT
11045 pssyntax = (syntax == PSSYNTAX);
11046 if (pssyntax)
11047 syntax = DQSYNTAX;
11048#endif
11049 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011050 varnest = 0;
11051 arinest = 0;
11052 parenlevel = 0;
11053 dqvarnest = 0;
11054
11055 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011056 loop:
11057 /* For each line, until end of word */
Denys Vlasenko958581a2010-09-12 15:04:27 +020011058 CHECKEND(); /* set c to PEOF if at end of here document */
11059 for (;;) { /* until end of line or end of word */
11060 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11061 switch (SIT(c, syntax)) {
11062 case CNL: /* '\n' */
11063 if (syntax == BASESYNTAX)
11064 goto endword; /* exit outer loop */
11065 USTPUTC(c, out);
11066 g_parsefile->linno++;
11067 setprompt_if(doprompt, 2);
11068 c = pgetc();
11069 goto loop; /* continue outer loop */
11070 case CWORD:
11071 USTPUTC(c, out);
11072 break;
11073 case CCTL:
11074 if (eofmark == NULL || dblquote)
11075 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011076#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko958581a2010-09-12 15:04:27 +020011077 if (c == '\\' && bash_dollar_squote) {
11078 c = decode_dollar_squote();
11079 if (c & 0x100) {
11080 USTPUTC('\\', out);
11081 c = (unsigned char)c;
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011082 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011083 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011084#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011085 USTPUTC(c, out);
11086 break;
11087 case CBACK: /* backslash */
11088 c = pgetc_without_PEOA();
11089 if (c == PEOF) {
11090 USTPUTC(CTLESC, out);
11091 USTPUTC('\\', out);
11092 pungetc();
11093 } else if (c == '\n') {
11094 setprompt_if(doprompt, 2);
11095 } else {
11096#if ENABLE_ASH_EXPAND_PRMT
11097 if (c == '$' && pssyntax) {
Eric Andersenc470f442003-07-28 09:56:35 +000011098 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011099 USTPUTC('\\', out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011100 }
Denis Vlasenko46a53062007-09-24 18:30:02 +000011101#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011102 /* Backslash is retained if we are in "str" and next char isn't special */
11103 if (dblquote
11104 && c != '\\'
11105 && c != '`'
11106 && c != '$'
11107 && (c != '"' || eofmark != NULL)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011108 ) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011109 USTPUTC(CTLESC, out);
11110 USTPUTC('\\', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011111 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011112 if (SIT(c, SQSYNTAX) == CCTL)
11113 USTPUTC(CTLESC, out);
Denys Vlasenko0ff78a02010-08-30 15:20:07 +020011114 USTPUTC(c, out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011115 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011116 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011117 break;
11118 case CSQUOTE:
11119 syntax = SQSYNTAX;
11120 quotemark:
11121 if (eofmark == NULL) {
11122 USTPUTC(CTLQUOTEMARK, out);
11123 }
11124 break;
11125 case CDQUOTE:
11126 syntax = DQSYNTAX;
11127 dblquote = 1;
11128 goto quotemark;
11129 case CENDQUOTE:
11130 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11131 if (eofmark != NULL && arinest == 0
11132 && varnest == 0
11133 ) {
11134 USTPUTC(c, out);
11135 } else {
11136 if (dqvarnest == 0) {
11137 syntax = BASESYNTAX;
11138 dblquote = 0;
11139 }
11140 quotef = 1;
11141 goto quotemark;
11142 }
11143 break;
11144 case CVAR: /* '$' */
11145 PARSESUB(); /* parse substitution */
11146 break;
11147 case CENDVAR: /* '}' */
11148 if (varnest > 0) {
11149 varnest--;
11150 if (dqvarnest > 0) {
11151 dqvarnest--;
11152 }
11153 c = CTLENDVAR;
11154 }
11155 USTPUTC(c, out);
11156 break;
11157#if ENABLE_SH_MATH_SUPPORT
11158 case CLP: /* '(' in arithmetic */
11159 parenlevel++;
11160 USTPUTC(c, out);
11161 break;
11162 case CRP: /* ')' in arithmetic */
11163 if (parenlevel > 0) {
11164 parenlevel--;
11165 } else {
11166 if (pgetc() == ')') {
11167 if (--arinest == 0) {
11168 syntax = prevsyntax;
11169 dblquote = (syntax == DQSYNTAX);
11170 c = CTLENDARI;
11171 }
11172 } else {
11173 /*
11174 * unbalanced parens
11175 * (don't 2nd guess - no error)
11176 */
11177 pungetc();
11178 }
11179 }
11180 USTPUTC(c, out);
11181 break;
11182#endif
11183 case CBQUOTE: /* '`' */
11184 PARSEBACKQOLD();
11185 break;
11186 case CENDFILE:
11187 goto endword; /* exit outer loop */
11188 case CIGN:
11189 break;
11190 default:
11191 if (varnest == 0) {
11192#if ENABLE_ASH_BASH_COMPAT
11193 if (c == '&') {
11194 if (pgetc() == '>')
11195 c = 0x100 + '>'; /* flag &> */
11196 pungetc();
11197 }
11198#endif
11199 goto endword; /* exit outer loop */
11200 }
11201 IF_ASH_ALIAS(if (c != PEOA))
11202 USTPUTC(c, out);
11203 }
11204 c = pgetc_fast();
11205 } /* for (;;) */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011206 endword:
Denys Vlasenko958581a2010-09-12 15:04:27 +020011207
Mike Frysinger98c52642009-04-02 10:02:37 +000011208#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011209 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011210 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011211#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011212 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011213 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011214 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011215 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011216 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011217 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011218 }
11219 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011220 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011221 out = stackblock();
11222 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011223 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011224 && quotef == 0
11225 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011226 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011227 PARSEREDIR(); /* passed as params: out, c */
11228 lasttoken = TREDIR;
11229 return lasttoken;
11230 }
11231 /* else: non-number X seen, interpret it
11232 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011233 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011234 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011235 }
11236 quoteflag = quotef;
11237 backquotelist = bqlist;
11238 grabstackblock(len);
11239 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011240 lasttoken = TWORD;
11241 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011242/* end of readtoken routine */
11243
Eric Andersencb57d552001-06-28 07:25:16 +000011244/*
11245 * Check to see whether we are at the end of the here document. When this
11246 * is called, c is set to the first character of the next input line. If
11247 * we are at the end of the here document, this routine sets the c to PEOF.
11248 */
Eric Andersenc470f442003-07-28 09:56:35 +000011249checkend: {
11250 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011251#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011252 if (c == PEOA)
11253 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011254#endif
11255 if (striptabs) {
11256 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011257 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011258 }
Eric Andersenc470f442003-07-28 09:56:35 +000011259 }
11260 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011261 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011262 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011263
Eric Andersenc470f442003-07-28 09:56:35 +000011264 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011265 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11266 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011267 if (*p == '\n' && *q == '\0') {
11268 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011269 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011270 needprompt = doprompt;
11271 } else {
11272 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011273 }
11274 }
11275 }
11276 }
Eric Andersenc470f442003-07-28 09:56:35 +000011277 goto checkend_return;
11278}
Eric Andersencb57d552001-06-28 07:25:16 +000011279
Eric Andersencb57d552001-06-28 07:25:16 +000011280/*
11281 * Parse a redirection operator. The variable "out" points to a string
11282 * specifying the fd to be redirected. The variable "c" contains the
11283 * first character of the redirection operator.
11284 */
Eric Andersenc470f442003-07-28 09:56:35 +000011285parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011286 /* out is already checked to be a valid number or "" */
11287 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011288 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011289
Denis Vlasenko597906c2008-02-20 16:38:54 +000011290 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011291 if (c == '>') {
11292 np->nfile.fd = 1;
11293 c = pgetc();
11294 if (c == '>')
11295 np->type = NAPPEND;
11296 else if (c == '|')
11297 np->type = NCLOBBER;
11298 else if (c == '&')
11299 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011300 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011301 else {
11302 np->type = NTO;
11303 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011304 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011305 }
11306#if ENABLE_ASH_BASH_COMPAT
11307 else if (c == 0x100 + '>') { /* this flags &> redirection */
11308 np->nfile.fd = 1;
11309 pgetc(); /* this is '>', no need to check */
11310 np->type = NTO2;
11311 }
11312#endif
11313 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011314 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011315 c = pgetc();
11316 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011317 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011318 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011319 np = stzalloc(sizeof(struct nhere));
11320 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011321 }
11322 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011323 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011324 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011325 c = pgetc();
11326 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011327 heredoc->striptabs = 1;
11328 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011329 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011330 pungetc();
11331 }
11332 break;
11333
11334 case '&':
11335 np->type = NFROMFD;
11336 break;
11337
11338 case '>':
11339 np->type = NFROMTO;
11340 break;
11341
11342 default:
11343 np->type = NFROM;
11344 pungetc();
11345 break;
11346 }
Eric Andersencb57d552001-06-28 07:25:16 +000011347 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011348 if (fd >= 0)
11349 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011350 redirnode = np;
11351 goto parseredir_return;
11352}
Eric Andersencb57d552001-06-28 07:25:16 +000011353
Eric Andersencb57d552001-06-28 07:25:16 +000011354/*
11355 * Parse a substitution. At this point, we have read the dollar sign
11356 * and nothing else.
11357 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011358
11359/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11360 * (assuming ascii char codes, as the original implementation did) */
11361#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011362 (((unsigned)(c) - 33 < 32) \
11363 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011364parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011365 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011366 int typeloc;
11367 int flags;
Eric Andersencb57d552001-06-28 07:25:16 +000011368
Eric Andersenc470f442003-07-28 09:56:35 +000011369 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011370 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011371 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011372 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011373#if ENABLE_ASH_BASH_COMPAT
11374 if (c == '\'')
11375 bash_dollar_squote = 1;
11376 else
11377#endif
11378 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011379 pungetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011380 } else if (c == '(') {
11381 /* $(command) or $((arith)) */
Eric Andersenc470f442003-07-28 09:56:35 +000011382 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011383#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011384 PARSEARITH();
11385#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011386 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011387#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011388 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011389 pungetc();
11390 PARSEBACKQNEW();
11391 }
11392 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011393 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
Eric Andersenc470f442003-07-28 09:56:35 +000011394 USTPUTC(CTLVAR, out);
11395 typeloc = out - (char *)stackblock();
11396 USTPUTC(VSNORMAL, out);
11397 subtype = VSNORMAL;
11398 if (c == '{') {
11399 c = pgetc();
11400 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011401 c = pgetc();
11402 if (c == '}')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011403 c = '#'; /* ${#} - same as $# */
Eric Andersenc470f442003-07-28 09:56:35 +000011404 else
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011405 subtype = VSLENGTH; /* ${#VAR} */
11406 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011407 subtype = 0;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011408 }
Eric Andersenc470f442003-07-28 09:56:35 +000011409 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011410 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011411 /* $[{[#]]NAME[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011412 do {
11413 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011414 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011415 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011416 } else if (isdigit(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011417 /* $[{[#]]NUM[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011418 do {
11419 STPUTC(c, out);
11420 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011421 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011422 } else if (is_special(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011423 /* $[{[#]]<specialchar>[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011424 USTPUTC(c, out);
11425 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011426 } else {
11427 badsub:
11428 raise_error_syntax("bad substitution");
11429 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011430 if (c != '}' && subtype == VSLENGTH) {
11431 /* ${#VAR didn't end with } */
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011432 goto badsub;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011433 }
Eric Andersencb57d552001-06-28 07:25:16 +000011434
Eric Andersenc470f442003-07-28 09:56:35 +000011435 STPUTC('=', out);
11436 flags = 0;
11437 if (subtype == 0) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011438 /* ${VAR...} but not $VAR or ${#VAR} */
11439 /* c == first char after VAR */
Eric Andersenc470f442003-07-28 09:56:35 +000011440 switch (c) {
11441 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011442 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011443#if ENABLE_ASH_BASH_COMPAT
11444 if (c == ':' || c == '$' || isdigit(c)) {
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011445//TODO: support more general format ${v:EXPR:EXPR},
11446// where EXPR follows $(()) rules
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011447 subtype = VSSUBSTR;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011448 pungetc();
11449 break; /* "goto do_pungetc" is bigger (!) */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011450 }
11451#endif
11452 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011453 /*FALLTHROUGH*/
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011454 default: {
11455 static const char types[] ALIGN1 = "}-+?=";
11456 const char *p = strchr(types, c);
Eric Andersenc470f442003-07-28 09:56:35 +000011457 if (p == NULL)
11458 goto badsub;
11459 subtype = p - types + VSNORMAL;
11460 break;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011461 }
Eric Andersenc470f442003-07-28 09:56:35 +000011462 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011463 case '#': {
11464 int cc = c;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011465 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011466 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011467 if (c != cc)
11468 goto do_pungetc;
11469 subtype++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011470 break;
11471 }
11472#if ENABLE_ASH_BASH_COMPAT
11473 case '/':
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011474 /* ${v/[/]pattern/repl} */
11475//TODO: encode pattern and repl separately.
11476// Currently ${v/$var_with_slash/repl} is horribly broken
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011477 subtype = VSREPLACE;
11478 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011479 if (c != '/')
11480 goto do_pungetc;
11481 subtype++; /* VSREPLACEALL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011482 break;
11483#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011484 }
Eric Andersenc470f442003-07-28 09:56:35 +000011485 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011486 do_pungetc:
Eric Andersenc470f442003-07-28 09:56:35 +000011487 pungetc();
11488 }
11489 if (dblquote || arinest)
11490 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011491 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011492 if (subtype != VSNORMAL) {
11493 varnest++;
11494 if (dblquote || arinest) {
11495 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011496 }
11497 }
11498 }
Eric Andersenc470f442003-07-28 09:56:35 +000011499 goto parsesub_return;
11500}
Eric Andersencb57d552001-06-28 07:25:16 +000011501
Eric Andersencb57d552001-06-28 07:25:16 +000011502/*
11503 * Called to parse command substitutions. Newstyle is set if the command
11504 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11505 * list of commands (passed by reference), and savelen is the number of
11506 * characters on the top of the stack which must be preserved.
11507 */
Eric Andersenc470f442003-07-28 09:56:35 +000011508parsebackq: {
11509 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011510 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011511 union node *n;
11512 char *volatile str;
11513 struct jmploc jmploc;
11514 struct jmploc *volatile savehandler;
11515 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011516 smallint saveprompt = 0;
11517
Eric Andersencb57d552001-06-28 07:25:16 +000011518#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011519 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011520#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011521 savepbq = parsebackquote;
11522 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011523 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011524 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011525 exception_handler = savehandler;
11526 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011527 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011528 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011529 str = NULL;
11530 savelen = out - (char *)stackblock();
11531 if (savelen > 0) {
11532 str = ckmalloc(savelen);
11533 memcpy(str, stackblock(), savelen);
11534 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011535 savehandler = exception_handler;
11536 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011537 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011538 if (oldstyle) {
11539 /* We must read until the closing backquote, giving special
11540 treatment to some slashes, and then push the string and
11541 reread it as input, interpreting it normally. */
11542 char *pout;
Eric Andersenc470f442003-07-28 09:56:35 +000011543 size_t psavelen;
11544 char *pstr;
11545
Eric Andersenc470f442003-07-28 09:56:35 +000011546 STARTSTACKSTR(pout);
11547 for (;;) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011548 int pc;
11549
11550 setprompt_if(needprompt, 2);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011551 pc = pgetc();
11552 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011553 case '`':
11554 goto done;
11555
11556 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011557 pc = pgetc();
11558 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011559 g_parsefile->linno++;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011560 setprompt_if(doprompt, 2);
Eric Andersenc470f442003-07-28 09:56:35 +000011561 /*
11562 * If eating a newline, avoid putting
11563 * the newline into the new character
11564 * stream (via the STPUTC after the
11565 * switch).
11566 */
11567 continue;
11568 }
11569 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011570 && (!dblquote || pc != '"')
11571 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011572 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011573 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011574 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011575 break;
11576 }
11577 /* fall through */
11578
11579 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011580 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011581 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011582 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011583
11584 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011585 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011586 needprompt = doprompt;
11587 break;
11588
11589 default:
11590 break;
11591 }
11592 STPUTC(pc, pout);
11593 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011594 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011595 STPUTC('\0', pout);
11596 psavelen = pout - (char *)stackblock();
11597 if (psavelen > 0) {
11598 pstr = grabstackstr(pout);
11599 setinputstring(pstr);
11600 }
11601 }
11602 nlpp = &bqlist;
11603 while (*nlpp)
11604 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011605 *nlpp = stzalloc(sizeof(**nlpp));
11606 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011607 parsebackquote = oldstyle;
11608
11609 if (oldstyle) {
11610 saveprompt = doprompt;
11611 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011612 }
11613
Eric Andersenc470f442003-07-28 09:56:35 +000011614 n = list(2);
11615
11616 if (oldstyle)
11617 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011618 else if (readtoken() != TRP)
11619 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011620
11621 (*nlpp)->n = n;
11622 if (oldstyle) {
11623 /*
11624 * Start reading from old file again, ignoring any pushed back
11625 * tokens left from the backquote parsing
11626 */
11627 popfile();
11628 tokpushback = 0;
11629 }
11630 while (stackblocksize() <= savelen)
11631 growstackblock();
11632 STARTSTACKSTR(out);
11633 if (str) {
11634 memcpy(out, str, savelen);
11635 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011636 INT_OFF;
11637 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011638 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011639 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011640 }
11641 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011642 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011643 if (arinest || dblquote)
11644 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11645 else
11646 USTPUTC(CTLBACKQ, out);
11647 if (oldstyle)
11648 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011649 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011650}
11651
Mike Frysinger98c52642009-04-02 10:02:37 +000011652#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011653/*
11654 * Parse an arithmetic expansion (indicate start of one and set state)
11655 */
Eric Andersenc470f442003-07-28 09:56:35 +000011656parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011657 if (++arinest == 1) {
11658 prevsyntax = syntax;
11659 syntax = ARISYNTAX;
11660 USTPUTC(CTLARI, out);
11661 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011662 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011663 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011664 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011665 } else {
11666 /*
11667 * we collapse embedded arithmetic expansion to
11668 * parenthesis, which should be equivalent
11669 */
11670 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011671 }
Eric Andersenc470f442003-07-28 09:56:35 +000011672 goto parsearith_return;
11673}
11674#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011675
Eric Andersenc470f442003-07-28 09:56:35 +000011676} /* end of readtoken */
11677
Eric Andersencb57d552001-06-28 07:25:16 +000011678/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011679 * Read the next input token.
11680 * If the token is a word, we set backquotelist to the list of cmds in
11681 * backquotes. We set quoteflag to true if any part of the word was
11682 * quoted.
11683 * If the token is TREDIR, then we set redirnode to a structure containing
11684 * the redirection.
11685 * In all cases, the variable startlinno is set to the number of the line
11686 * on which the token starts.
11687 *
11688 * [Change comment: here documents and internal procedures]
11689 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11690 * word parsing code into a separate routine. In this case, readtoken
11691 * doesn't need to have any internal procedures, but parseword does.
11692 * We could also make parseoperator in essence the main routine, and
11693 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011694 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011695#define NEW_xxreadtoken
11696#ifdef NEW_xxreadtoken
11697/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011698static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011699 '\n', '(', ')', /* singles */
11700 '&', '|', ';', /* doubles */
11701 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011702};
Eric Andersencb57d552001-06-28 07:25:16 +000011703
Denis Vlasenko834dee72008-10-07 09:18:30 +000011704#define xxreadtoken_singles 3
11705#define xxreadtoken_doubles 3
11706
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011707static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011708 TNL, TLP, TRP, /* only single occurrence allowed */
11709 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11710 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011711 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011712};
11713
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011714static int
11715xxreadtoken(void)
11716{
11717 int c;
11718
11719 if (tokpushback) {
11720 tokpushback = 0;
11721 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011722 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011723 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011724 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011725 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011726 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011727 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011728 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011729
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011730 if (c == '#') {
11731 while ((c = pgetc()) != '\n' && c != PEOF)
11732 continue;
11733 pungetc();
11734 } else if (c == '\\') {
11735 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011736 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011737 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011738 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011739 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011740 setprompt_if(doprompt, 2);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011741 } else {
11742 const char *p;
11743
11744 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11745 if (c != PEOF) {
11746 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011747 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011748 needprompt = doprompt;
11749 }
11750
11751 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011752 if (p == NULL)
11753 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011754
Denis Vlasenko834dee72008-10-07 09:18:30 +000011755 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11756 int cc = pgetc();
11757 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011758 p += xxreadtoken_doubles + 1;
11759 } else {
11760 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011761#if ENABLE_ASH_BASH_COMPAT
11762 if (c == '&' && cc == '>') /* &> */
11763 break; /* return readtoken1(...) */
11764#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011765 }
11766 }
11767 }
11768 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11769 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011770 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011771 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011772
11773 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011774}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011775#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011776#define RETURN(token) return lasttoken = token
11777static int
11778xxreadtoken(void)
11779{
11780 int c;
11781
11782 if (tokpushback) {
11783 tokpushback = 0;
11784 return lasttoken;
11785 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011786 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011787 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011788 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011789 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011790 switch (c) {
11791 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011792 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011793 continue;
11794 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011795 while ((c = pgetc()) != '\n' && c != PEOF)
11796 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011797 pungetc();
11798 continue;
11799 case '\\':
11800 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011801 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011802 setprompt_if(doprompt, 2);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011803 continue;
11804 }
11805 pungetc();
11806 goto breakloop;
11807 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011808 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011809 needprompt = doprompt;
11810 RETURN(TNL);
11811 case PEOF:
11812 RETURN(TEOF);
11813 case '&':
11814 if (pgetc() == '&')
11815 RETURN(TAND);
11816 pungetc();
11817 RETURN(TBACKGND);
11818 case '|':
11819 if (pgetc() == '|')
11820 RETURN(TOR);
11821 pungetc();
11822 RETURN(TPIPE);
11823 case ';':
11824 if (pgetc() == ';')
11825 RETURN(TENDCASE);
11826 pungetc();
11827 RETURN(TSEMI);
11828 case '(':
11829 RETURN(TLP);
11830 case ')':
11831 RETURN(TRP);
11832 default:
11833 goto breakloop;
11834 }
11835 }
11836 breakloop:
11837 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11838#undef RETURN
11839}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011840#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011841
11842static int
11843readtoken(void)
11844{
11845 int t;
11846#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011847 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011848#endif
11849
11850#if ENABLE_ASH_ALIAS
11851 top:
11852#endif
11853
11854 t = xxreadtoken();
11855
11856 /*
11857 * eat newlines
11858 */
11859 if (checkkwd & CHKNL) {
11860 while (t == TNL) {
11861 parseheredoc();
11862 t = xxreadtoken();
11863 }
11864 }
11865
11866 if (t != TWORD || quoteflag) {
11867 goto out;
11868 }
11869
11870 /*
11871 * check for keywords
11872 */
11873 if (checkkwd & CHKKWD) {
11874 const char *const *pp;
11875
11876 pp = findkwd(wordtext);
11877 if (pp) {
11878 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011879 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011880 goto out;
11881 }
11882 }
11883
11884 if (checkkwd & CHKALIAS) {
11885#if ENABLE_ASH_ALIAS
11886 struct alias *ap;
11887 ap = lookupalias(wordtext, 1);
11888 if (ap != NULL) {
11889 if (*ap->val) {
11890 pushstring(ap->val, ap);
11891 }
11892 goto top;
11893 }
11894#endif
11895 }
11896 out:
11897 checkkwd = 0;
11898#if DEBUG
11899 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011900 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011901 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011902 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011903#endif
11904 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011905}
11906
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011907static char
11908peektoken(void)
11909{
11910 int t;
11911
11912 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011913 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011914 return tokname_array[t][0];
11915}
Eric Andersencb57d552001-06-28 07:25:16 +000011916
11917/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011918 * Read and parse a command. Returns NODE_EOF on end of file.
11919 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011920 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011921static union node *
11922parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011923{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011924 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011925
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011926 tokpushback = 0;
11927 doprompt = interact;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011928 setprompt_if(doprompt, doprompt);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011929 needprompt = 0;
11930 t = readtoken();
11931 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011932 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011933 if (t == TNL)
11934 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011935 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011936 return list(1);
11937}
11938
11939/*
11940 * Input any here documents.
11941 */
11942static void
11943parseheredoc(void)
11944{
11945 struct heredoc *here;
11946 union node *n;
11947
11948 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011949 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011950
11951 while (here) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011952 setprompt_if(needprompt, 2);
11953 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011954 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011955 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011956 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011957 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011958 n->narg.text = wordtext;
11959 n->narg.backquote = backquotelist;
11960 here->here->nhere.doc = n;
11961 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011962 }
Eric Andersencb57d552001-06-28 07:25:16 +000011963}
11964
11965
11966/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011967 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011968 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011969#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011970static const char *
11971expandstr(const char *ps)
11972{
11973 union node n;
11974
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011975 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11976 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011977 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011978 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011979 popfile();
11980
11981 n.narg.type = NARG;
11982 n.narg.next = NULL;
11983 n.narg.text = wordtext;
11984 n.narg.backquote = backquotelist;
11985
11986 expandarg(&n, NULL, 0);
11987 return stackblock();
11988}
11989#endif
11990
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011991/*
11992 * Execute a command or commands contained in a string.
11993 */
11994static int
11995evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011996{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011997 union node *n;
11998 struct stackmark smark;
11999 int skip;
12000
12001 setinputstring(s);
12002 setstackmark(&smark);
12003
12004 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012005 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012006 evaltree(n, 0);
12007 popstackmark(&smark);
12008 skip = evalskip;
12009 if (skip)
12010 break;
12011 }
12012 popfile();
12013
12014 skip &= mask;
12015 evalskip = skip;
12016 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000012017}
12018
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012019/*
12020 * The eval command.
12021 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012022static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012023evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012024{
12025 char *p;
12026 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012027
Denis Vlasenko68404f12008-03-17 09:00:54 +000012028 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012029 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012030 argv += 2;
12031 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012032 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012033 for (;;) {
12034 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012035 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012036 if (p == NULL)
12037 break;
12038 STPUTC(' ', concat);
12039 }
12040 STPUTC('\0', concat);
12041 p = grabstackstr(concat);
12042 }
12043 evalstring(p, ~SKIPEVAL);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012044 }
12045 return exitstatus;
12046}
12047
12048/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010012049 * Read and execute commands.
12050 * "Top" is nonzero for the top level command loop;
12051 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012052 */
12053static int
12054cmdloop(int top)
12055{
12056 union node *n;
12057 struct stackmark smark;
12058 int inter;
12059 int numeof = 0;
12060
12061 TRACE(("cmdloop(%d) called\n", top));
12062 for (;;) {
12063 int skip;
12064
12065 setstackmark(&smark);
12066#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000012067 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012068 showjobs(stderr, SHOW_CHANGED);
12069#endif
12070 inter = 0;
12071 if (iflag && top) {
12072 inter++;
12073#if ENABLE_ASH_MAIL
12074 chkmail();
12075#endif
12076 }
12077 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020012078#if DEBUG
12079 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020012080 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000012081#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012082 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012083 if (!top || numeof >= 50)
12084 break;
12085 if (!stoppedjobs()) {
12086 if (!Iflag)
12087 break;
12088 out2str("\nUse \"exit\" to leave shell.\n");
12089 }
12090 numeof++;
12091 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000012092 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12093 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012094 numeof = 0;
12095 evaltree(n, 0);
12096 }
12097 popstackmark(&smark);
12098 skip = evalskip;
12099
12100 if (skip) {
12101 evalskip = 0;
12102 return skip & SKIPEVAL;
12103 }
12104 }
12105 return 0;
12106}
12107
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012108/*
12109 * Take commands from a file. To be compatible we should do a path
12110 * search for the file, which is necessary to find sub-commands.
12111 */
12112static char *
12113find_dot_file(char *name)
12114{
12115 char *fullname;
12116 const char *path = pathval();
12117 struct stat statb;
12118
12119 /* don't try this for absolute or relative paths */
12120 if (strchr(name, '/'))
12121 return name;
12122
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012123 /* IIRC standards do not say whether . is to be searched.
12124 * And it is even smaller this way, making it unconditional for now:
12125 */
12126 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12127 fullname = name;
12128 goto try_cur_dir;
12129 }
12130
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012131 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012132 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012133 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12134 /*
12135 * Don't bother freeing here, since it will
12136 * be freed by the caller.
12137 */
12138 return fullname;
12139 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012140 if (fullname != name)
12141 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012142 }
12143
12144 /* not found in the PATH */
12145 ash_msg_and_raise_error("%s: not found", name);
12146 /* NOTREACHED */
12147}
12148
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012149static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012150dotcmd(int argc, char **argv)
12151{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012152 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012153 struct strlist *sp;
12154 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012155
12156 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012157 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012158
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012159 if (!argv[1]) {
12160 /* bash says: "bash: .: filename argument required" */
12161 return 2; /* bash compat */
12162 }
12163
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012164 /* "false; . empty_file; echo $?" should print 0, not 1: */
12165 exitstatus = 0;
12166
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012167 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012168
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012169 argv += 2;
12170 argc -= 2;
12171 if (argc) { /* argc > 0, argv[0] != NULL */
12172 saveparam = shellparam;
12173 shellparam.malloced = 0;
12174 shellparam.nparam = argc;
12175 shellparam.p = argv;
12176 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012177
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012178 setinputfile(fullname, INPUT_PUSH_FILE);
12179 commandname = fullname;
12180 cmdloop(0);
12181 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012182
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012183 if (argc) {
12184 freeparam(&shellparam);
12185 shellparam = saveparam;
12186 };
12187
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012188 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012189}
12190
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012191static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012192exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012193{
12194 if (stoppedjobs())
12195 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012196 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012197 exitstatus = number(argv[1]);
12198 raise_exception(EXEXIT);
12199 /* NOTREACHED */
12200}
12201
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012202/*
12203 * Read a file containing shell functions.
12204 */
12205static void
12206readcmdfile(char *name)
12207{
12208 setinputfile(name, INPUT_PUSH_FILE);
12209 cmdloop(0);
12210 popfile();
12211}
12212
12213
Denis Vlasenkocc571512007-02-23 21:10:35 +000012214/* ============ find_command inplementation */
12215
12216/*
12217 * Resolve a command name. If you change this routine, you may have to
12218 * change the shellexec routine as well.
12219 */
12220static void
12221find_command(char *name, struct cmdentry *entry, int act, const char *path)
12222{
12223 struct tblentry *cmdp;
12224 int idx;
12225 int prev;
12226 char *fullname;
12227 struct stat statb;
12228 int e;
12229 int updatetbl;
12230 struct builtincmd *bcmd;
12231
12232 /* If name contains a slash, don't use PATH or hash table */
12233 if (strchr(name, '/') != NULL) {
12234 entry->u.index = -1;
12235 if (act & DO_ABS) {
12236 while (stat(name, &statb) < 0) {
12237#ifdef SYSV
12238 if (errno == EINTR)
12239 continue;
12240#endif
12241 entry->cmdtype = CMDUNKNOWN;
12242 return;
12243 }
12244 }
12245 entry->cmdtype = CMDNORMAL;
12246 return;
12247 }
12248
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012249/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012250
12251 updatetbl = (path == pathval());
12252 if (!updatetbl) {
12253 act |= DO_ALTPATH;
12254 if (strstr(path, "%builtin") != NULL)
12255 act |= DO_ALTBLTIN;
12256 }
12257
12258 /* If name is in the table, check answer will be ok */
12259 cmdp = cmdlookup(name, 0);
12260 if (cmdp != NULL) {
12261 int bit;
12262
12263 switch (cmdp->cmdtype) {
12264 default:
12265#if DEBUG
12266 abort();
12267#endif
12268 case CMDNORMAL:
12269 bit = DO_ALTPATH;
12270 break;
12271 case CMDFUNCTION:
12272 bit = DO_NOFUNC;
12273 break;
12274 case CMDBUILTIN:
12275 bit = DO_ALTBLTIN;
12276 break;
12277 }
12278 if (act & bit) {
12279 updatetbl = 0;
12280 cmdp = NULL;
12281 } else if (cmdp->rehash == 0)
12282 /* if not invalidated by cd, we're done */
12283 goto success;
12284 }
12285
12286 /* If %builtin not in path, check for builtin next */
12287 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012288 if (bcmd) {
12289 if (IS_BUILTIN_REGULAR(bcmd))
12290 goto builtin_success;
12291 if (act & DO_ALTPATH) {
12292 if (!(act & DO_ALTBLTIN))
12293 goto builtin_success;
12294 } else if (builtinloc <= 0) {
12295 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012296 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012297 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012298
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012299#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012300 {
12301 int applet_no = find_applet_by_name(name);
12302 if (applet_no >= 0) {
12303 entry->cmdtype = CMDNORMAL;
12304 entry->u.index = -2 - applet_no;
12305 return;
12306 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012307 }
12308#endif
12309
Denis Vlasenkocc571512007-02-23 21:10:35 +000012310 /* We have to search path. */
12311 prev = -1; /* where to start */
12312 if (cmdp && cmdp->rehash) { /* doing a rehash */
12313 if (cmdp->cmdtype == CMDBUILTIN)
12314 prev = builtinloc;
12315 else
12316 prev = cmdp->param.index;
12317 }
12318
12319 e = ENOENT;
12320 idx = -1;
12321 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012322 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012323 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012324 /* NB: code below will still use fullname
12325 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012326 idx++;
12327 if (pathopt) {
12328 if (prefix(pathopt, "builtin")) {
12329 if (bcmd)
12330 goto builtin_success;
12331 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012332 }
12333 if ((act & DO_NOFUNC)
12334 || !prefix(pathopt, "func")
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +020012335 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012336 continue;
12337 }
12338 }
12339 /* if rehash, don't redo absolute path names */
12340 if (fullname[0] == '/' && idx <= prev) {
12341 if (idx < prev)
12342 continue;
12343 TRACE(("searchexec \"%s\": no change\n", name));
12344 goto success;
12345 }
12346 while (stat(fullname, &statb) < 0) {
12347#ifdef SYSV
12348 if (errno == EINTR)
12349 continue;
12350#endif
12351 if (errno != ENOENT && errno != ENOTDIR)
12352 e = errno;
12353 goto loop;
12354 }
12355 e = EACCES; /* if we fail, this will be the error */
12356 if (!S_ISREG(statb.st_mode))
12357 continue;
12358 if (pathopt) { /* this is a %func directory */
12359 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012360 /* NB: stalloc will return space pointed by fullname
12361 * (because we don't have any intervening allocations
12362 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012363 readcmdfile(fullname);
12364 cmdp = cmdlookup(name, 0);
12365 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12366 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12367 stunalloc(fullname);
12368 goto success;
12369 }
12370 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12371 if (!updatetbl) {
12372 entry->cmdtype = CMDNORMAL;
12373 entry->u.index = idx;
12374 return;
12375 }
12376 INT_OFF;
12377 cmdp = cmdlookup(name, 1);
12378 cmdp->cmdtype = CMDNORMAL;
12379 cmdp->param.index = idx;
12380 INT_ON;
12381 goto success;
12382 }
12383
12384 /* We failed. If there was an entry for this command, delete it */
12385 if (cmdp && updatetbl)
12386 delete_cmd_entry();
12387 if (act & DO_ERR)
12388 ash_msg("%s: %s", name, errmsg(e, "not found"));
12389 entry->cmdtype = CMDUNKNOWN;
12390 return;
12391
12392 builtin_success:
12393 if (!updatetbl) {
12394 entry->cmdtype = CMDBUILTIN;
12395 entry->u.cmd = bcmd;
12396 return;
12397 }
12398 INT_OFF;
12399 cmdp = cmdlookup(name, 1);
12400 cmdp->cmdtype = CMDBUILTIN;
12401 cmdp->param.cmd = bcmd;
12402 INT_ON;
12403 success:
12404 cmdp->rehash = 0;
12405 entry->cmdtype = cmdp->cmdtype;
12406 entry->u = cmdp->param;
12407}
12408
12409
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012410/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012411
Eric Andersencb57d552001-06-28 07:25:16 +000012412/*
Eric Andersencb57d552001-06-28 07:25:16 +000012413 * The trap builtin.
12414 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012415static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012416trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012417{
12418 char *action;
12419 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012420 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012421
Eric Andersenc470f442003-07-28 09:56:35 +000012422 nextopt(nullstr);
12423 ap = argptr;
12424 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012425 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012426 char *tr = trap_ptr[signo];
12427 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012428 /* note: bash adds "SIG", but only if invoked
12429 * as "bash". If called as "sh", or if set -o posix,
12430 * then it prints short signal names.
12431 * We are printing short names: */
12432 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012433 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012434 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012435 /* trap_ptr != trap only if we are in special-cased `trap` code.
12436 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012437 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012438 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012439 }
12440 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012441 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012442 if (trap_ptr != trap) {
12443 free(trap_ptr);
12444 trap_ptr = trap;
12445 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012446 */
Eric Andersencb57d552001-06-28 07:25:16 +000012447 return 0;
12448 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012449
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012450 action = NULL;
12451 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012452 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012453 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012454 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012455 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012456 if (signo < 0) {
12457 /* Mimic bash message exactly */
12458 ash_msg("%s: invalid signal specification", *ap);
12459 exitcode = 1;
12460 goto next;
12461 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012462 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012463 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012464 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012465 action = NULL;
12466 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012467 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012468 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012469 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012470 if (action)
12471 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012472 trap[signo] = action;
12473 if (signo != 0)
12474 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012475 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012476 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012477 ap++;
12478 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012479 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012480}
12481
Eric Andersenc470f442003-07-28 09:56:35 +000012482
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012483/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012484
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012485#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012486/*
12487 * Lists available builtins
12488 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012489static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012490helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012491{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012492 unsigned col;
12493 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012494
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012495 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012496 "Built-in commands:\n"
12497 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012498 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012499 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012500 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012501 if (col > 60) {
12502 out1fmt("\n");
12503 col = 0;
12504 }
12505 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012506#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012507 {
12508 const char *a = applet_names;
12509 while (*a) {
12510 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12511 if (col > 60) {
12512 out1fmt("\n");
12513 col = 0;
12514 }
12515 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012516 }
12517 }
12518#endif
12519 out1fmt("\n\n");
12520 return EXIT_SUCCESS;
12521}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012522#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012523
Eric Andersencb57d552001-06-28 07:25:16 +000012524/*
Eric Andersencb57d552001-06-28 07:25:16 +000012525 * The export and readonly commands.
12526 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012527static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012528exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012529{
12530 struct var *vp;
12531 char *name;
12532 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012533 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012534 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012535
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012536 if (nextopt("p") != 'p') {
12537 aptr = argptr;
12538 name = *aptr;
12539 if (name) {
12540 do {
12541 p = strchr(name, '=');
12542 if (p != NULL) {
12543 p++;
12544 } else {
12545 vp = *findvar(hashvar(name), name);
12546 if (vp) {
12547 vp->flags |= flag;
12548 continue;
12549 }
Eric Andersencb57d552001-06-28 07:25:16 +000012550 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012551 setvar(name, p, flag);
12552 } while ((name = *++aptr) != NULL);
12553 return 0;
12554 }
Eric Andersencb57d552001-06-28 07:25:16 +000012555 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012556 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012557 return 0;
12558}
12559
Eric Andersencb57d552001-06-28 07:25:16 +000012560/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012561 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012562 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012563static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012564unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012565{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012566 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012567
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012568 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012569 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012570 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012571}
12572
Eric Andersencb57d552001-06-28 07:25:16 +000012573/*
Eric Andersencb57d552001-06-28 07:25:16 +000012574 * The unset builtin command. We unset the function before we unset the
12575 * variable to allow a function to be unset when there is a readonly variable
12576 * with the same name.
12577 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012578static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012579unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012580{
12581 char **ap;
12582 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012583 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012584 int ret = 0;
12585
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012586 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012587 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012588 }
Eric Andersencb57d552001-06-28 07:25:16 +000012589
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012590 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012591 if (flag != 'f') {
12592 i = unsetvar(*ap);
12593 ret |= i;
12594 if (!(i & 2))
12595 continue;
12596 }
12597 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012598 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012599 }
Eric Andersenc470f442003-07-28 09:56:35 +000012600 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012601}
12602
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012603static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012604 ' ', offsetof(struct tms, tms_utime),
12605 '\n', offsetof(struct tms, tms_stime),
12606 ' ', offsetof(struct tms, tms_cutime),
12607 '\n', offsetof(struct tms, tms_cstime),
12608 0
12609};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012610static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012611timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012612{
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012613 unsigned long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012614 const unsigned char *p;
12615 struct tms buf;
12616
12617 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012618 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012619
12620 p = timescmd_str;
12621 do {
12622 t = *(clock_t *)(((char *) &buf) + p[1]);
12623 s = t / clk_tck;
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012624 t = t % clk_tck;
12625 out1fmt("%lum%lu.%03lus%c",
12626 s / 60, s % 60,
12627 (t * 1000) / clk_tck,
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012628 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012629 p += 2;
12630 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012631
Eric Andersencb57d552001-06-28 07:25:16 +000012632 return 0;
12633}
12634
Mike Frysinger98c52642009-04-02 10:02:37 +000012635#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012636/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012637 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012638 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012639 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012640 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012641 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012642static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012643letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012644{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012645 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012646
Denis Vlasenko68404f12008-03-17 09:00:54 +000012647 argv++;
12648 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012649 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012650 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012651 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012652 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012653
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012654 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012655}
Eric Andersenc470f442003-07-28 09:56:35 +000012656#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012657
Eric Andersenc470f442003-07-28 09:56:35 +000012658/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012659 * The read builtin. Options:
12660 * -r Do not interpret '\' specially
12661 * -s Turn off echo (tty only)
12662 * -n NCHARS Read NCHARS max
12663 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12664 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12665 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012666 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012667 * TODO: bash also has:
12668 * -a ARRAY Read into array[0],[1],etc
12669 * -d DELIM End on DELIM char, not newline
12670 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012671 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012672static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012673readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012674{
Denys Vlasenko73067272010-01-12 22:11:24 +010012675 char *opt_n = NULL;
12676 char *opt_p = NULL;
12677 char *opt_t = NULL;
12678 char *opt_u = NULL;
12679 int read_flags = 0;
12680 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012681 int i;
12682
Denys Vlasenko73067272010-01-12 22:11:24 +010012683 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012684 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012685 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012686 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012687 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012688 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012689 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012690 break;
12691 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012692 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012693 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012694 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012695 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012696 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012697 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012698 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012699 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012700 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012701 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012702 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012703 default:
12704 break;
12705 }
Eric Andersenc470f442003-07-28 09:56:35 +000012706 }
Paul Fox02eb9342005-09-07 16:56:02 +000012707
Denys Vlasenko03dad222010-01-12 23:29:57 +010012708 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012709 argptr,
12710 bltinlookup("IFS"), /* can be NULL */
12711 read_flags,
12712 opt_n,
12713 opt_p,
12714 opt_t,
12715 opt_u
12716 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012717
Denys Vlasenko73067272010-01-12 22:11:24 +010012718 if ((uintptr_t)r > 1)
12719 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012720
Denys Vlasenko73067272010-01-12 22:11:24 +010012721 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012722}
12723
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012724static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012725umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012726{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012727 static const char permuser[3] ALIGN1 = "ugo";
12728 static const char permmode[3] ALIGN1 = "rwx";
12729 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012730 S_IRUSR, S_IWUSR, S_IXUSR,
12731 S_IRGRP, S_IWGRP, S_IXGRP,
12732 S_IROTH, S_IWOTH, S_IXOTH
12733 };
12734
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012735 /* TODO: use bb_parse_mode() instead */
12736
Eric Andersenc470f442003-07-28 09:56:35 +000012737 char *ap;
12738 mode_t mask;
12739 int i;
12740 int symbolic_mode = 0;
12741
12742 while (nextopt("S") != '\0') {
12743 symbolic_mode = 1;
12744 }
12745
Denis Vlasenkob012b102007-02-19 22:43:01 +000012746 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012747 mask = umask(0);
12748 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012749 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012750
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012751 ap = *argptr;
12752 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012753 if (symbolic_mode) {
12754 char buf[18];
12755 char *p = buf;
12756
12757 for (i = 0; i < 3; i++) {
12758 int j;
12759
12760 *p++ = permuser[i];
12761 *p++ = '=';
12762 for (j = 0; j < 3; j++) {
12763 if ((mask & permmask[3 * i + j]) == 0) {
12764 *p++ = permmode[j];
12765 }
12766 }
12767 *p++ = ',';
12768 }
12769 *--p = 0;
12770 puts(buf);
12771 } else {
12772 out1fmt("%.4o\n", mask);
12773 }
12774 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012775 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012776 mask = 0;
12777 do {
12778 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012779 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012780 mask = (mask << 3) + (*ap - '0');
12781 } while (*++ap != '\0');
12782 umask(mask);
12783 } else {
12784 mask = ~mask & 0777;
12785 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012786 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012787 }
12788 umask(~mask & 0777);
12789 }
12790 }
12791 return 0;
12792}
12793
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012794static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012795ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012796{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012797 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012798}
12799
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012800/* ============ main() and helpers */
12801
12802/*
12803 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012804 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012805static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012806static void
12807exitshell(void)
12808{
12809 struct jmploc loc;
12810 char *p;
12811 int status;
12812
12813 status = exitstatus;
12814 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12815 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012816 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012817/* dash bug: it just does _exit(exitstatus) here
12818 * but we have to do setjobctl(0) first!
12819 * (bug is still not fixed in dash-0.5.3 - if you run dash
12820 * under Midnight Commander, on exit from dash MC is backgrounded) */
12821 status = exitstatus;
12822 goto out;
12823 }
12824 exception_handler = &loc;
12825 p = trap[0];
12826 if (p) {
12827 trap[0] = NULL;
12828 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012829 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012830 }
12831 flush_stdout_stderr();
12832 out:
12833 setjobctl(0);
12834 _exit(status);
12835 /* NOTREACHED */
12836}
12837
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012838static void
12839init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012840{
12841 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012842 /* we will never free this */
12843 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012844
12845 /* from trap.c: */
12846 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012847 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12848 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12849 */
Denys Vlasenkocacb2cd2010-10-05 00:13:02 +020012850 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012851
12852 /* from var.c: */
12853 {
12854 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012855 const char *p;
12856 struct stat st1, st2;
12857
12858 initvar();
12859 for (envp = environ; envp && *envp; envp++) {
12860 if (strchr(*envp, '=')) {
12861 setvareq(*envp, VEXPORT|VTEXTFIXED);
12862 }
12863 }
12864
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012865 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012866
12867 p = lookupvar("PWD");
12868 if (p)
12869 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12870 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12871 p = '\0';
12872 setpwd(p, 0);
12873 }
12874}
12875
12876/*
12877 * Process the shell command line arguments.
12878 */
12879static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012880procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012881{
12882 int i;
12883 const char *xminusc;
12884 char **xargv;
12885
12886 xargv = argv;
12887 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012888 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012889 xargv++;
12890 for (i = 0; i < NOPTS; i++)
12891 optlist[i] = 2;
12892 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012893 if (options(1)) {
12894 /* it already printed err message */
12895 raise_exception(EXERROR);
12896 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012897 xargv = argptr;
12898 xminusc = minusc;
12899 if (*xargv == NULL) {
12900 if (xminusc)
12901 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12902 sflag = 1;
12903 }
12904 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12905 iflag = 1;
12906 if (mflag == 2)
12907 mflag = iflag;
12908 for (i = 0; i < NOPTS; i++)
12909 if (optlist[i] == 2)
12910 optlist[i] = 0;
12911#if DEBUG == 2
12912 debug = 1;
12913#endif
12914 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12915 if (xminusc) {
12916 minusc = *xargv++;
12917 if (*xargv)
12918 goto setarg0;
12919 } else if (!sflag) {
12920 setinputfile(*xargv, 0);
12921 setarg0:
12922 arg0 = *xargv++;
12923 commandname = arg0;
12924 }
12925
12926 shellparam.p = xargv;
12927#if ENABLE_ASH_GETOPTS
12928 shellparam.optind = 1;
12929 shellparam.optoff = -1;
12930#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012931 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012932 while (*xargv) {
12933 shellparam.nparam++;
12934 xargv++;
12935 }
12936 optschanged();
12937}
12938
12939/*
12940 * Read /etc/profile or .profile.
12941 */
12942static void
12943read_profile(const char *name)
12944{
12945 int skip;
12946
12947 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12948 return;
12949 skip = cmdloop(0);
12950 popfile();
12951 if (skip)
12952 exitshell();
12953}
12954
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012955/*
12956 * This routine is called when an error or an interrupt occurs in an
12957 * interactive shell and control is returned to the main command loop.
12958 */
12959static void
12960reset(void)
12961{
12962 /* from eval.c: */
12963 evalskip = 0;
12964 loopnest = 0;
12965 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012966 g_parsefile->left_in_buffer = 0;
12967 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012968 popallfiles();
12969 /* from parser.c: */
12970 tokpushback = 0;
12971 checkkwd = 0;
12972 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012973 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012974}
12975
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012976#if PROFILE
12977static short profile_buf[16384];
12978extern int etext();
12979#endif
12980
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012981/*
12982 * Main routine. We initialize things, parse the arguments, execute
12983 * profiles if we're a login shell, and then call cmdloop to execute
12984 * commands. The setjmp call sets up the location to jump to when an
12985 * exception occurs. When an exception occurs the variable "state"
12986 * is used to figure out how far we had gotten.
12987 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012988int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012989int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012990{
Mike Frysinger98c52642009-04-02 10:02:37 +000012991 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012992 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012993 struct jmploc jmploc;
12994 struct stackmark smark;
12995
Denis Vlasenko01631112007-12-16 17:20:38 +000012996 /* Initialize global data */
12997 INIT_G_misc();
12998 INIT_G_memstack();
12999 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013000#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013001 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013002#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013003 INIT_G_cmdtable();
13004
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013005#if PROFILE
13006 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13007#endif
13008
13009#if ENABLE_FEATURE_EDITING
13010 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13011#endif
13012 state = 0;
13013 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013014 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013015 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013016
13017 reset();
13018
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013019 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013020 if (e == EXERROR)
13021 exitstatus = 2;
13022 s = state;
Denys Vlasenkob563f622010-09-25 17:15:13 +020013023 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013024 exitshell();
Denys Vlasenkob563f622010-09-25 17:15:13 +020013025 }
13026 if (e == EXINT) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013027 outcslow('\n', stderr);
Denys Vlasenkob563f622010-09-25 17:15:13 +020013028 }
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013029
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013030 popstackmark(&smark);
13031 FORCE_INT_ON; /* enable interrupts */
13032 if (s == 1)
13033 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013034 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013035 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013036 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013037 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013038 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013039 }
13040 exception_handler = &jmploc;
13041#if DEBUG
13042 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013043 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013044 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013045#endif
13046 rootpid = getpid();
13047
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013048 init();
13049 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013050 procargs(argv);
13051
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013052#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13053 if (iflag) {
13054 const char *hp = lookupvar("HISTFILE");
13055
13056 if (hp == NULL) {
13057 hp = lookupvar("HOME");
13058 if (hp != NULL) {
13059 char *defhp = concat_path_file(hp, ".ash_history");
13060 setvar("HISTFILE", defhp, 0);
13061 free(defhp);
13062 }
13063 }
13064 }
13065#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013066 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013067 isloginsh = 1;
13068 if (isloginsh) {
13069 state = 1;
13070 read_profile("/etc/profile");
13071 state1:
13072 state = 2;
13073 read_profile(".profile");
13074 }
13075 state2:
13076 state = 3;
13077 if (
13078#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013079 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013080#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013081 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013082 ) {
13083 shinit = lookupvar("ENV");
13084 if (shinit != NULL && *shinit != '\0') {
13085 read_profile(shinit);
13086 }
13087 }
13088 state3:
13089 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013090 if (minusc) {
13091 /* evalstring pushes parsefile stack.
13092 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013093 * is one of stacked source fds.
13094 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020013095 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020013096 // ^^ not necessary since now we special-case fd 0
13097 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013098 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013099 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013100
13101 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013102#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013103 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013104 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013105 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013106 line_input_state->hist_file = hp;
13107 }
13108#endif
13109 state4: /* XXX ??? - why isn't this before the "if" statement */
13110 cmdloop(1);
13111 }
13112#if PROFILE
13113 monitor(0);
13114#endif
13115#ifdef GPROF
13116 {
13117 extern void _mcleanup(void);
13118 _mcleanup();
13119 }
13120#endif
Denys Vlasenkob563f622010-09-25 17:15:13 +020013121 TRACE(("End of main reached\n"));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013122 exitshell();
13123 /* NOTREACHED */
13124}
13125
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013126
Eric Andersendf82f612001-06-28 07:46:40 +000013127/*-
13128 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013129 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013130 *
13131 * This code is derived from software contributed to Berkeley by
13132 * Kenneth Almquist.
13133 *
13134 * Redistribution and use in source and binary forms, with or without
13135 * modification, are permitted provided that the following conditions
13136 * are met:
13137 * 1. Redistributions of source code must retain the above copyright
13138 * notice, this list of conditions and the following disclaimer.
13139 * 2. Redistributions in binary form must reproduce the above copyright
13140 * notice, this list of conditions and the following disclaimer in the
13141 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013142 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013143 * may be used to endorse or promote products derived from this software
13144 * without specific prior written permission.
13145 *
13146 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13147 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13148 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13149 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13150 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13151 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13152 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13153 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13154 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13155 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13156 * SUCH DAMAGE.
13157 */