blob: 42c91257ed6cd65895407789bbe66712c6749113 [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 *
Denys Vlasenkof451b2c2012-06-09 02:06:57 +020026 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
Eric Andersenc470f442003-07-28 09:56:35 +000029 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000030#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000031/* Tweak debug output verbosity here */
32#define DEBUG_TIME 0
33#define DEBUG_PID 1
34#define DEBUG_SIG 1
35
Eric Andersenc470f442003-07-28 09:56:35 +000036#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000038#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000039
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 Vlasenko3fa97af2014-04-15 11:43:29 +020044#include <sys/utsname.h> /* for setting $HOSTNAME */
Denys Vlasenko73067272010-01-12 22:11:24 +010045
Denys Vlasenko20704f02011-03-23 17:59:27 +010046#include "busybox.h" /* for applet_names */
47#include "unicode.h"
48
Denys Vlasenko73067272010-01-12 22:11:24 +010049#include "shell_common.h"
Denys Vlasenko26777aa2010-11-22 23:49:10 +010050#if ENABLE_SH_MATH_SUPPORT
51# include "math.h"
52#endif
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020053#if ENABLE_ASH_RANDOM_SUPPORT
54# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020055#else
56# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020057#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000058
Denys Vlasenko1fcbff22010-06-26 02:40:08 +020059#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +010060#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000061/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020062# undef CONFIG_FEATURE_SH_STANDALONE
63# undef ENABLE_FEATURE_SH_STANDALONE
64# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010065# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020066# define ENABLE_FEATURE_SH_STANDALONE 0
67# define IF_FEATURE_SH_STANDALONE(...)
68# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000069#endif
70
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000071#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000072# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#endif
74
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010075#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000076# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000077#endif
78
Denys Vlasenko771f1992010-07-16 14:31:34 +020079//config:config ASH
80//config: bool "ash"
81//config: default y
82//config: depends on !NOMMU
83//config: help
84//config: Tha 'ash' shell adds about 60k in the default configuration and is
85//config: the most complete and most pedantically correct shell included with
86//config: busybox. This shell is actually a derivative of the Debian 'dash'
87//config: shell (by Herbert Xu), which was created by porting the 'ash' shell
88//config: (written by Kenneth Almquist) from NetBSD.
89//config:
90//config:config ASH_BASH_COMPAT
91//config: bool "bash-compatible extensions"
92//config: default y
93//config: depends on ASH
94//config: help
95//config: Enable bash-compatible extensions.
96//config:
Denys Vlasenko046341e2011-02-04 17:53:59 +010097//config:config ASH_IDLE_TIMEOUT
98//config: bool "Idle timeout variable"
99//config: default n
100//config: depends on ASH
101//config: help
Denys Vlasenko66c5b122011-02-08 05:07:02 +0100102//config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
Denys Vlasenko046341e2011-02-04 17:53:59 +0100103//config:
Denys Vlasenko771f1992010-07-16 14:31:34 +0200104//config:config ASH_JOB_CONTROL
105//config: bool "Job control"
106//config: default y
107//config: depends on ASH
108//config: help
109//config: Enable job control in the ash shell.
110//config:
111//config:config ASH_ALIAS
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100112//config: bool "Alias support"
Denys Vlasenko771f1992010-07-16 14:31:34 +0200113//config: default y
114//config: depends on ASH
115//config: help
116//config: Enable alias support in the ash shell.
117//config:
118//config:config ASH_GETOPTS
119//config: bool "Builtin getopt to parse positional parameters"
120//config: default y
121//config: depends on ASH
122//config: help
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100123//config: Enable support for getopts builtin in ash.
Denys Vlasenko771f1992010-07-16 14:31:34 +0200124//config:
125//config:config ASH_BUILTIN_ECHO
126//config: bool "Builtin version of 'echo'"
127//config: default y
128//config: depends on ASH
129//config: help
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100130//config: Enable support for echo builtin in ash.
Denys Vlasenko771f1992010-07-16 14:31:34 +0200131//config:
132//config:config ASH_BUILTIN_PRINTF
133//config: bool "Builtin version of 'printf'"
134//config: default y
135//config: depends on ASH
136//config: help
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100137//config: Enable support for printf builtin in ash.
Denys Vlasenko771f1992010-07-16 14:31:34 +0200138//config:
139//config:config ASH_BUILTIN_TEST
140//config: bool "Builtin version of 'test'"
141//config: default y
142//config: depends on ASH
143//config: help
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100144//config: Enable support for test builtin in ash.
Denys Vlasenko771f1992010-07-16 14:31:34 +0200145//config:
Denys Vlasenko2ec34962014-09-08 16:52:39 +0200146//config:config ASH_HELP
147//config: bool "help builtin"
148//config: default y
149//config: depends on ASH
150//config: help
151//config: Enable help builtin in ash.
152//config:
Denys Vlasenko771f1992010-07-16 14:31:34 +0200153//config:config ASH_CMDCMD
154//config: bool "'command' command to override shell builtins"
155//config: default y
156//config: depends on ASH
157//config: help
158//config: Enable support for the ash 'command' builtin, which allows
159//config: you to run the specified command with the specified arguments,
160//config: even when there is an ash builtin command with the same name.
161//config:
162//config:config ASH_MAIL
163//config: bool "Check for new mail on interactive shells"
164//config: default n
165//config: depends on ASH
166//config: help
Denys Vlasenko8c52f802011-02-04 17:36:21 +0100167//config: Enable "check for new mail" function in the ash shell.
Denys Vlasenko771f1992010-07-16 14:31:34 +0200168//config:
169//config:config ASH_OPTIMIZE_FOR_SIZE
170//config: bool "Optimize for size instead of speed"
171//config: default y
172//config: depends on ASH
173//config: help
174//config: Compile ash for reduced size at the price of speed.
175//config:
176//config:config ASH_RANDOM_SUPPORT
177//config: bool "Pseudorandom generator and $RANDOM variable"
178//config: default y
179//config: depends on ASH
180//config: help
181//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
182//config: Each read of "$RANDOM" will generate a new pseudorandom value.
183//config: You can reset the generator by using a specified start value.
184//config: After "unset RANDOM" the generator will switch off and this
185//config: variable will no longer have special treatment.
186//config:
187//config:config ASH_EXPAND_PRMT
188//config: bool "Expand prompt string"
189//config: default y
190//config: depends on ASH
191//config: help
192//config: "PS#" may contain volatile content, such as backquote commands.
193//config: This option recreates the prompt string from the environment
194//config: variable each time it is displayed.
Denys Vlasenko51ca7762010-07-16 17:16:40 +0200195//config:
Denys Vlasenko771f1992010-07-16 14:31:34 +0200196
Denys Vlasenko20704f02011-03-23 17:59:27 +0100197//applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
198//applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
199//applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
200
201//kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
202//kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
203
Denis Vlasenkob012b102007-02-19 22:43:01 +0000204
Denis Vlasenko01631112007-12-16 17:20:38 +0000205/* ============ Hash table sizes. Configurable. */
206
207#define VTABSIZE 39
208#define ATABSIZE 39
209#define CMDTABLESIZE 31 /* should be prime */
210
211
Denis Vlasenkob012b102007-02-19 22:43:01 +0000212/* ============ Shell options */
213
214static const char *const optletters_optnames[] = {
215 "e" "errexit",
216 "f" "noglob",
217 "I" "ignoreeof",
218 "i" "interactive",
219 "m" "monitor",
220 "n" "noexec",
221 "s" "stdin",
222 "x" "xtrace",
223 "v" "verbose",
224 "C" "noclobber",
225 "a" "allexport",
226 "b" "notify",
227 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100228 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100229#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100230 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100231#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000232#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000233 ,"\0" "nolog"
234 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000235#endif
236};
237
Denys Vlasenko285ad152009-12-04 23:02:27 +0100238#define optletters(n) optletters_optnames[n][0]
239#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000240
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000241enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000242
Eric Andersenc470f442003-07-28 09:56:35 +0000243
Denis Vlasenkob012b102007-02-19 22:43:01 +0000244/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000245
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200246#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000247
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000248/*
Eric Andersenc470f442003-07-28 09:56:35 +0000249 * We enclose jmp_buf in a structure so that we can declare pointers to
250 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000251 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000252 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000253 * exception handlers, the user should save the value of handler on entry
254 * to an inner scope, set handler to point to a jmploc structure for the
255 * inner scope, and restore handler on exit from the scope.
256 */
Eric Andersenc470f442003-07-28 09:56:35 +0000257struct jmploc {
258 jmp_buf loc;
259};
Denis Vlasenko01631112007-12-16 17:20:38 +0000260
261struct globals_misc {
262 /* pid of main shell */
263 int rootpid;
264 /* shell level: 0 for the main shell, 1 for its children, and so on */
265 int shlvl;
266#define rootshell (!shlvl)
267 char *minusc; /* argument to -c option */
268
269 char *curdir; // = nullstr; /* current working directory */
270 char *physdir; // = nullstr; /* physical working directory */
271
272 char *arg0; /* value of $0 */
273
274 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000275
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200276 volatile int suppress_int; /* counter */
277 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000278 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200279 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000280 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000281 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000282#define EXINT 0 /* SIGINT received */
283#define EXERROR 1 /* a generic error */
284#define EXSHELLPROC 2 /* execute a shell procedure */
285#define EXEXEC 3 /* command execution failed */
286#define EXEXIT 4 /* exit the shell */
287#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000288
Denis Vlasenko01631112007-12-16 17:20:38 +0000289 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000290 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000291
292 char optlist[NOPTS];
293#define eflag optlist[0]
294#define fflag optlist[1]
295#define Iflag optlist[2]
296#define iflag optlist[3]
297#define mflag optlist[4]
298#define nflag optlist[5]
299#define sflag optlist[6]
300#define xflag optlist[7]
301#define vflag optlist[8]
302#define Cflag optlist[9]
303#define aflag optlist[10]
304#define bflag optlist[11]
305#define uflag optlist[12]
306#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100307#if ENABLE_ASH_BASH_COMPAT
308# define pipefail optlist[14]
309#else
310# define pipefail 0
311#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000312#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100313# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
314# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000315#endif
316
317 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000318 /*
319 * Sigmode records the current value of the signal handlers for the various
320 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000321 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000322 */
323 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000324#define S_DFL 1 /* default signal handling (SIG_DFL) */
325#define S_CATCH 2 /* signal is caught */
326#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000327#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000328
Denis Vlasenko01631112007-12-16 17:20:38 +0000329 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000330 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200331 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000332 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200333 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000334
335 /* Rarely referenced stuff */
336#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200337 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000338#endif
339 pid_t backgndpid; /* pid of last background process */
340 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000341};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000342extern struct globals_misc *const ash_ptr_to_globals_misc;
343#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000344#define rootpid (G_misc.rootpid )
345#define shlvl (G_misc.shlvl )
346#define minusc (G_misc.minusc )
347#define curdir (G_misc.curdir )
348#define physdir (G_misc.physdir )
349#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000350#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000351#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200352#define suppress_int (G_misc.suppress_int )
353#define pending_int (G_misc.pending_int )
354#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000355#define isloginsh (G_misc.isloginsh )
356#define nullstr (G_misc.nullstr )
357#define optlist (G_misc.optlist )
358#define sigmode (G_misc.sigmode )
359#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200360#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000361#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200362#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200363#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000364#define backgndpid (G_misc.backgndpid )
365#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000366#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000367 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
368 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000369 curdir = nullstr; \
370 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200371 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000372} while (0)
373
374
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000375/* ============ DEBUG */
376#if DEBUG
377static void trace_printf(const char *fmt, ...);
378static void trace_vprintf(const char *fmt, va_list va);
379# define TRACE(param) trace_printf param
380# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000381# define close(fd) do { \
382 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000383 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200384 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000385 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000386} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000387#else
388# define TRACE(param)
389# define TRACEV(param)
390#endif
391
392
Denis Vlasenko559691a2008-10-05 18:39:31 +0000393/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000394#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
395
Denys Vlasenko1961aea2013-02-26 00:36:53 +0100396#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
397#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
398
Denis Vlasenko559691a2008-10-05 18:39:31 +0000399static int isdigit_str9(const char *str)
400{
401 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
402 while (--maxlen && isdigit(*str))
403 str++;
404 return (*str == '\0');
405}
Denis Vlasenko01631112007-12-16 17:20:38 +0000406
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200407static const char *var_end(const char *var)
408{
409 while (*var)
410 if (*var++ == '=')
411 break;
412 return var;
413}
414
Denis Vlasenko559691a2008-10-05 18:39:31 +0000415
416/* ============ Interrupts / exceptions */
Denys Vlasenko66c5b122011-02-08 05:07:02 +0100417
418static void exitshell(void) NORETURN;
419
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000420/*
Eric Andersen2870d962001-07-02 17:27:21 +0000421 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000422 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000423 * much more efficient and portable. (But hacking the kernel is so much
424 * more fun than worrying about efficiency and portability. :-))
425 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000426#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200427 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000428 xbarrier(); \
429} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000430
431/*
432 * Called to raise an exception. Since C doesn't include exceptions, we
433 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000434 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000435 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000436static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000437static void
438raise_exception(int e)
439{
440#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000441 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000442 abort();
443#endif
444 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000445 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000446 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000447}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000448#if DEBUG
449#define raise_exception(e) do { \
450 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
451 raise_exception(e); \
452} while (0)
453#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000454
455/*
456 * Called from trap.c when a SIGINT is received. (If the user specifies
457 * that SIGINT is to be trapped or ignored using the trap builtin, then
458 * this routine is not called.) Suppressint is nonzero when interrupts
459 * are held using the INT_OFF macro. (The test for iflag is just
460 * defensive programming.)
461 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000462static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000463static void
464raise_interrupt(void)
465{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000466 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000467
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200468 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000469 /* Signal is not automatically unmasked after it is raised,
470 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000471 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200472 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000473
Denis Vlasenko4b875702009-03-19 13:30:04 +0000474 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000475 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
476 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000477 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000478 signal(SIGINT, SIG_DFL);
479 raise(SIGINT);
480 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000481 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000482 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000483 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000484 /* NOTREACHED */
485}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000486#if DEBUG
487#define raise_interrupt() do { \
488 TRACE(("raising interrupt on line %d\n", __LINE__)); \
489 raise_interrupt(); \
490} while (0)
491#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000492
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000493static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000494int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000495{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000496 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200497 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000498 raise_interrupt();
499 }
500}
501#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000502static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000503force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000504{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000505 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200506 suppress_int = 0;
507 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000508 raise_interrupt();
509}
510#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000511
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200512#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000513
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000514#define RESTORE_INT(v) do { \
515 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200516 suppress_int = (v); \
517 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000518 raise_interrupt(); \
519} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000520
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000521
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000522/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000523
Eric Andersenc470f442003-07-28 09:56:35 +0000524static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000525outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000526{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000527 INT_OFF;
528 fputs(p, file);
529 INT_ON;
530}
531
532static void
533flush_stdout_stderr(void)
534{
535 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100536 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000537 INT_ON;
538}
539
540static void
541outcslow(int c, FILE *dest)
542{
543 INT_OFF;
544 putc(c, dest);
545 fflush(dest);
546 INT_ON;
547}
548
549static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
550static int
551out1fmt(const char *fmt, ...)
552{
553 va_list ap;
554 int r;
555
556 INT_OFF;
557 va_start(ap, fmt);
558 r = vprintf(fmt, ap);
559 va_end(ap);
560 INT_ON;
561 return r;
562}
563
564static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
565static int
566fmtstr(char *outbuf, size_t length, const char *fmt, ...)
567{
568 va_list ap;
569 int ret;
570
571 va_start(ap, fmt);
572 INT_OFF;
573 ret = vsnprintf(outbuf, length, fmt, ap);
574 va_end(ap);
575 INT_ON;
576 return ret;
577}
578
579static void
580out1str(const char *p)
581{
582 outstr(p, stdout);
583}
584
585static void
586out2str(const char *p)
587{
588 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100589 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000590}
591
592
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000593/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000594
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000595/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100596#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200597#define CTLESC ((unsigned char)'\201') /* escape next character */
598#define CTLVAR ((unsigned char)'\202') /* variable defn */
599#define CTLENDVAR ((unsigned char)'\203')
600#define CTLBACKQ ((unsigned char)'\204')
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200601#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
602#define CTLENDARI ((unsigned char)'\207')
603#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100604#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000605
606/* variable substitution byte (follows CTLVAR) */
607#define VSTYPE 0x0f /* type of variable substitution */
608#define VSNUL 0x10 /* colon--treat the empty string as unset */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000609
610/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000611#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
612#define VSMINUS 0x2 /* ${var-text} */
613#define VSPLUS 0x3 /* ${var+text} */
614#define VSQUESTION 0x4 /* ${var?message} */
615#define VSASSIGN 0x5 /* ${var=text} */
616#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
617#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
618#define VSTRIMLEFT 0x8 /* ${var#pattern} */
619#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
620#define VSLENGTH 0xa /* ${#var} */
621#if ENABLE_ASH_BASH_COMPAT
622#define VSSUBSTR 0xc /* ${var:position:length} */
623#define VSREPLACE 0xd /* ${var/pattern/replacement} */
624#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
625#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000626
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000627static const char dolatstr[] ALIGN1 = {
Ron Yorston549deab2015-05-18 09:57:51 +0200628 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000629};
Ron Yorston549deab2015-05-18 09:57:51 +0200630#define DOLATSTRLEN 6
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000631
Denis Vlasenko559691a2008-10-05 18:39:31 +0000632#define NCMD 0
633#define NPIPE 1
634#define NREDIR 2
635#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000636#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000637#define NAND 5
638#define NOR 6
639#define NSEMI 7
640#define NIF 8
641#define NWHILE 9
642#define NUNTIL 10
643#define NFOR 11
644#define NCASE 12
645#define NCLIST 13
646#define NDEFUN 14
647#define NARG 15
648#define NTO 16
649#if ENABLE_ASH_BASH_COMPAT
650#define NTO2 17
651#endif
652#define NCLOBBER 18
653#define NFROM 19
654#define NFROMTO 20
655#define NAPPEND 21
656#define NTOFD 22
657#define NFROMFD 23
658#define NHERE 24
659#define NXHERE 25
660#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000661#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000662
663union node;
664
665struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000666 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000667 union node *assign;
668 union node *args;
669 union node *redirect;
670};
671
672struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000673 smallint type;
674 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000675 struct nodelist *cmdlist;
676};
677
678struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000679 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000680 union node *n;
681 union node *redirect;
682};
683
684struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000685 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000686 union node *ch1;
687 union node *ch2;
688};
689
690struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000691 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000692 union node *test;
693 union node *ifpart;
694 union node *elsepart;
695};
696
697struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000698 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000699 union node *args;
700 union node *body;
701 char *var;
702};
703
704struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000705 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000706 union node *expr;
707 union node *cases;
708};
709
710struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000711 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000712 union node *next;
713 union node *pattern;
714 union node *body;
715};
716
717struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000718 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000719 union node *next;
720 char *text;
721 struct nodelist *backquote;
722};
723
Denis Vlasenko559691a2008-10-05 18:39:31 +0000724/* nfile and ndup layout must match!
725 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
726 * that it is actually NTO2 (>&file), and change its type.
727 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000728struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000729 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000730 union node *next;
731 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000732 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000733 union node *fname;
734 char *expfname;
735};
736
737struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000738 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000739 union node *next;
740 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000741 int dupfd;
742 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000743 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000744};
745
746struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000747 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000748 union node *next;
749 int fd;
750 union node *doc;
751};
752
753struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000754 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000755 union node *com;
756};
757
758union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000759 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000760 struct ncmd ncmd;
761 struct npipe npipe;
762 struct nredir nredir;
763 struct nbinary nbinary;
764 struct nif nif;
765 struct nfor nfor;
766 struct ncase ncase;
767 struct nclist nclist;
768 struct narg narg;
769 struct nfile nfile;
770 struct ndup ndup;
771 struct nhere nhere;
772 struct nnot nnot;
773};
774
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200775/*
776 * NODE_EOF is returned by parsecmd when it encounters an end of file.
777 * It must be distinct from NULL.
778 */
779#define NODE_EOF ((union node *) -1L)
780
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000781struct nodelist {
782 struct nodelist *next;
783 union node *n;
784};
785
786struct funcnode {
787 int count;
788 union node n;
789};
790
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000791/*
792 * Free a parse tree.
793 */
794static void
795freefunc(struct funcnode *f)
796{
797 if (f && --f->count < 0)
798 free(f);
799}
800
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000801
802/* ============ Debugging output */
803
804#if DEBUG
805
806static FILE *tracefile;
807
808static void
809trace_printf(const char *fmt, ...)
810{
811 va_list va;
812
813 if (debug != 1)
814 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000815 if (DEBUG_TIME)
816 fprintf(tracefile, "%u ", (int) time(NULL));
817 if (DEBUG_PID)
818 fprintf(tracefile, "[%u] ", (int) getpid());
819 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200820 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000821 va_start(va, fmt);
822 vfprintf(tracefile, fmt, va);
823 va_end(va);
824}
825
826static void
827trace_vprintf(const char *fmt, va_list va)
828{
829 if (debug != 1)
830 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000831 if (DEBUG_TIME)
832 fprintf(tracefile, "%u ", (int) time(NULL));
833 if (DEBUG_PID)
834 fprintf(tracefile, "[%u] ", (int) getpid());
835 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200836 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837 vfprintf(tracefile, fmt, va);
838}
839
840static void
841trace_puts(const char *s)
842{
843 if (debug != 1)
844 return;
845 fputs(s, tracefile);
846}
847
848static void
849trace_puts_quoted(char *s)
850{
851 char *p;
852 char c;
853
854 if (debug != 1)
855 return;
856 putc('"', tracefile);
857 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100858 switch ((unsigned char)*p) {
859 case '\n': c = 'n'; goto backslash;
860 case '\t': c = 't'; goto backslash;
861 case '\r': c = 'r'; goto backslash;
862 case '\"': c = '\"'; goto backslash;
863 case '\\': c = '\\'; goto backslash;
864 case CTLESC: c = 'e'; goto backslash;
865 case CTLVAR: c = 'v'; goto backslash;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100866 case CTLBACKQ: c = 'q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000867 backslash:
868 putc('\\', tracefile);
869 putc(c, tracefile);
870 break;
871 default:
872 if (*p >= ' ' && *p <= '~')
873 putc(*p, tracefile);
874 else {
875 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100876 putc((*p >> 6) & 03, tracefile);
877 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000878 putc(*p & 07, tracefile);
879 }
880 break;
881 }
882 }
883 putc('"', tracefile);
884}
885
886static void
887trace_puts_args(char **ap)
888{
889 if (debug != 1)
890 return;
891 if (!*ap)
892 return;
893 while (1) {
894 trace_puts_quoted(*ap);
895 if (!*++ap) {
896 putc('\n', tracefile);
897 break;
898 }
899 putc(' ', tracefile);
900 }
901}
902
903static void
904opentrace(void)
905{
906 char s[100];
907#ifdef O_APPEND
908 int flags;
909#endif
910
911 if (debug != 1) {
912 if (tracefile)
913 fflush(tracefile);
914 /* leave open because libedit might be using it */
915 return;
916 }
917 strcpy(s, "./trace");
918 if (tracefile) {
919 if (!freopen(s, "a", tracefile)) {
920 fprintf(stderr, "Can't re-open %s\n", s);
921 debug = 0;
922 return;
923 }
924 } else {
925 tracefile = fopen(s, "a");
926 if (tracefile == NULL) {
927 fprintf(stderr, "Can't open %s\n", s);
928 debug = 0;
929 return;
930 }
931 }
932#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000933 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000934 if (flags >= 0)
935 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
936#endif
937 setlinebuf(tracefile);
938 fputs("\nTracing started.\n", tracefile);
939}
940
941static void
942indent(int amount, char *pfx, FILE *fp)
943{
944 int i;
945
946 for (i = 0; i < amount; i++) {
947 if (pfx && i == amount - 1)
948 fputs(pfx, fp);
949 putc('\t', fp);
950 }
951}
952
953/* little circular references here... */
954static void shtree(union node *n, int ind, char *pfx, FILE *fp);
955
956static void
957sharg(union node *arg, FILE *fp)
958{
959 char *p;
960 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100961 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000962
963 if (arg->type != NARG) {
964 out1fmt("<node type %d>\n", arg->type);
965 abort();
966 }
967 bqlist = arg->narg.backquote;
968 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100969 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000970 case CTLESC:
Dan Fandrich77d48722010-09-07 23:38:28 -0700971 p++;
972 putc(*p, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000973 break;
974 case CTLVAR:
975 putc('$', fp);
976 putc('{', fp);
977 subtype = *++p;
978 if (subtype == VSLENGTH)
979 putc('#', fp);
980
Dan Fandrich77d48722010-09-07 23:38:28 -0700981 while (*p != '=') {
982 putc(*p, fp);
983 p++;
984 }
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000985
986 if (subtype & VSNUL)
987 putc(':', fp);
988
989 switch (subtype & VSTYPE) {
990 case VSNORMAL:
991 putc('}', fp);
992 break;
993 case VSMINUS:
994 putc('-', fp);
995 break;
996 case VSPLUS:
997 putc('+', fp);
998 break;
999 case VSQUESTION:
1000 putc('?', fp);
1001 break;
1002 case VSASSIGN:
1003 putc('=', fp);
1004 break;
1005 case VSTRIMLEFT:
1006 putc('#', fp);
1007 break;
1008 case VSTRIMLEFTMAX:
1009 putc('#', fp);
1010 putc('#', fp);
1011 break;
1012 case VSTRIMRIGHT:
1013 putc('%', fp);
1014 break;
1015 case VSTRIMRIGHTMAX:
1016 putc('%', fp);
1017 putc('%', fp);
1018 break;
1019 case VSLENGTH:
1020 break;
1021 default:
1022 out1fmt("<subtype %d>", subtype);
1023 }
1024 break;
1025 case CTLENDVAR:
1026 putc('}', fp);
1027 break;
1028 case CTLBACKQ:
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001029 putc('$', fp);
1030 putc('(', fp);
1031 shtree(bqlist->n, -1, NULL, fp);
1032 putc(')', fp);
1033 break;
1034 default:
1035 putc(*p, fp);
1036 break;
1037 }
1038 }
1039}
1040
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02001041static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001042shcmd(union node *cmd, FILE *fp)
1043{
1044 union node *np;
1045 int first;
1046 const char *s;
1047 int dftfd;
1048
1049 first = 1;
1050 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001051 if (!first)
1052 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001053 sharg(np, fp);
1054 first = 0;
1055 }
1056 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001057 if (!first)
1058 putc(' ', fp);
1059 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001060 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001061 case NTO: s = ">>"+1; dftfd = 1; break;
1062 case NCLOBBER: s = ">|"; dftfd = 1; break;
1063 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001064#if ENABLE_ASH_BASH_COMPAT
1065 case NTO2:
1066#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001067 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001068 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001069 case NFROMFD: s = "<&"; break;
1070 case NFROMTO: s = "<>"; break;
1071 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001072 }
1073 if (np->nfile.fd != dftfd)
1074 fprintf(fp, "%d", np->nfile.fd);
1075 fputs(s, fp);
1076 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1077 fprintf(fp, "%d", np->ndup.dupfd);
1078 } else {
1079 sharg(np->nfile.fname, fp);
1080 }
1081 first = 0;
1082 }
1083}
1084
1085static void
1086shtree(union node *n, int ind, char *pfx, FILE *fp)
1087{
1088 struct nodelist *lp;
1089 const char *s;
1090
1091 if (n == NULL)
1092 return;
1093
1094 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +02001095
1096 if (n == NODE_EOF) {
1097 fputs("<EOF>", fp);
1098 return;
1099 }
1100
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001101 switch (n->type) {
1102 case NSEMI:
1103 s = "; ";
1104 goto binop;
1105 case NAND:
1106 s = " && ";
1107 goto binop;
1108 case NOR:
1109 s = " || ";
1110 binop:
1111 shtree(n->nbinary.ch1, ind, NULL, fp);
1112 /* if (ind < 0) */
1113 fputs(s, fp);
1114 shtree(n->nbinary.ch2, ind, NULL, fp);
1115 break;
1116 case NCMD:
1117 shcmd(n, fp);
1118 if (ind >= 0)
1119 putc('\n', fp);
1120 break;
1121 case NPIPE:
1122 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02001123 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001124 if (lp->next)
1125 fputs(" | ", fp);
1126 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00001127 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001128 fputs(" &", fp);
1129 if (ind >= 0)
1130 putc('\n', fp);
1131 break;
1132 default:
1133 fprintf(fp, "<node type %d>", n->type);
1134 if (ind >= 0)
1135 putc('\n', fp);
1136 break;
1137 }
1138}
1139
1140static void
1141showtree(union node *n)
1142{
1143 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001144 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001145}
1146
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001147#endif /* DEBUG */
1148
1149
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001150/* ============ Parser data */
1151
1152/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001153 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1154 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001155struct strlist {
1156 struct strlist *next;
1157 char *text;
1158};
1159
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001160struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001161
Denis Vlasenkob012b102007-02-19 22:43:01 +00001162struct strpush {
1163 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001164 char *prev_string;
1165 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001166#if ENABLE_ASH_ALIAS
1167 struct alias *ap; /* if push was associated with an alias */
1168#endif
1169 char *string; /* remember the string since it may change */
1170};
1171
1172struct parsefile {
1173 struct parsefile *prev; /* preceding file on stack */
1174 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001175 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001176 int left_in_line; /* number of chars left in this line */
1177 int left_in_buffer; /* number of chars left in this buffer past the line */
1178 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001179 char *buf; /* input buffer */
1180 struct strpush *strpush; /* for pushing strings at this level */
1181 struct strpush basestrpush; /* so pushing one is fast */
1182};
1183
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001184static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001185static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001186static int startlinno; /* line # where last token started */
1187static char *commandname; /* currently executing command */
1188static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001189static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001190
1191
1192/* ============ Message printing */
1193
1194static void
1195ash_vmsg(const char *msg, va_list ap)
1196{
1197 fprintf(stderr, "%s: ", arg0);
1198 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001199 if (strcmp(arg0, commandname))
1200 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001201 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001202 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001203 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001204 vfprintf(stderr, msg, ap);
1205 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001206}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001207
1208/*
1209 * Exverror is called to raise the error exception. If the second argument
1210 * is not NULL then error prints an error message using printf style
1211 * formatting. It then raises the error exception.
1212 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001213static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001214static void
1215ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001216{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001217#if DEBUG
1218 if (msg) {
1219 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1220 TRACEV((msg, ap));
1221 TRACE(("\") pid=%d\n", getpid()));
1222 } else
1223 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1224 if (msg)
1225#endif
1226 ash_vmsg(msg, ap);
1227
1228 flush_stdout_stderr();
1229 raise_exception(cond);
1230 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001231}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001232
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001233static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001234static void
1235ash_msg_and_raise_error(const char *msg, ...)
1236{
1237 va_list ap;
1238
1239 va_start(ap, msg);
1240 ash_vmsg_and_raise(EXERROR, msg, ap);
1241 /* NOTREACHED */
1242 va_end(ap);
1243}
1244
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001245static void raise_error_syntax(const char *) NORETURN;
1246static void
1247raise_error_syntax(const char *msg)
1248{
1249 ash_msg_and_raise_error("syntax error: %s", msg);
1250 /* NOTREACHED */
1251}
1252
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001253static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001254static void
1255ash_msg_and_raise(int cond, const char *msg, ...)
1256{
1257 va_list ap;
1258
1259 va_start(ap, msg);
1260 ash_vmsg_and_raise(cond, msg, ap);
1261 /* NOTREACHED */
1262 va_end(ap);
1263}
1264
1265/*
1266 * error/warning routines for external builtins
1267 */
1268static void
1269ash_msg(const char *fmt, ...)
1270{
1271 va_list ap;
1272
1273 va_start(ap, fmt);
1274 ash_vmsg(fmt, ap);
1275 va_end(ap);
1276}
1277
1278/*
1279 * Return a string describing an error. The returned string may be a
1280 * pointer to a static buffer that will be overwritten on the next call.
1281 * Action describes the operation that got the error.
1282 */
1283static const char *
1284errmsg(int e, const char *em)
1285{
1286 if (e == ENOENT || e == ENOTDIR) {
1287 return em;
1288 }
1289 return strerror(e);
1290}
1291
1292
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001293/* ============ Memory allocation */
1294
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001295#if 0
1296/* I consider these wrappers nearly useless:
1297 * ok, they return you to nearest exception handler, but
1298 * how much memory do you leak in the process, making
1299 * memory starvation worse?
1300 */
1301static void *
1302ckrealloc(void * p, size_t nbytes)
1303{
1304 p = realloc(p, nbytes);
1305 if (!p)
1306 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1307 return p;
1308}
1309
1310static void *
1311ckmalloc(size_t nbytes)
1312{
1313 return ckrealloc(NULL, nbytes);
1314}
1315
1316static void *
1317ckzalloc(size_t nbytes)
1318{
1319 return memset(ckmalloc(nbytes), 0, nbytes);
1320}
1321
1322static char *
1323ckstrdup(const char *s)
1324{
1325 char *p = strdup(s);
1326 if (!p)
1327 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1328 return p;
1329}
1330#else
1331/* Using bbox equivalents. They exit if out of memory */
1332# define ckrealloc xrealloc
1333# define ckmalloc xmalloc
1334# define ckzalloc xzalloc
1335# define ckstrdup xstrdup
1336#endif
1337
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338/*
1339 * It appears that grabstackstr() will barf with such alignments
1340 * because stalloc() will return a string allocated in a new stackblock.
1341 */
1342#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1343enum {
1344 /* Most machines require the value returned from malloc to be aligned
1345 * in some way. The following macro will get this right
1346 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001347 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001348 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001349 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350};
1351
1352struct stack_block {
1353 struct stack_block *prev;
1354 char space[MINSIZE];
1355};
1356
1357struct stackmark {
1358 struct stack_block *stackp;
1359 char *stacknxt;
1360 size_t stacknleft;
1361 struct stackmark *marknext;
1362};
1363
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001364
Denis Vlasenko01631112007-12-16 17:20:38 +00001365struct globals_memstack {
1366 struct stack_block *g_stackp; // = &stackbase;
1367 struct stackmark *markp;
1368 char *g_stacknxt; // = stackbase.space;
1369 char *sstrend; // = stackbase.space + MINSIZE;
1370 size_t g_stacknleft; // = MINSIZE;
1371 int herefd; // = -1;
1372 struct stack_block stackbase;
1373};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001374extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1375#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001376#define g_stackp (G_memstack.g_stackp )
1377#define markp (G_memstack.markp )
1378#define g_stacknxt (G_memstack.g_stacknxt )
1379#define sstrend (G_memstack.sstrend )
1380#define g_stacknleft (G_memstack.g_stacknleft)
1381#define herefd (G_memstack.herefd )
1382#define stackbase (G_memstack.stackbase )
1383#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001384 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1385 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001386 g_stackp = &stackbase; \
1387 g_stacknxt = stackbase.space; \
1388 g_stacknleft = MINSIZE; \
1389 sstrend = stackbase.space + MINSIZE; \
1390 herefd = -1; \
1391} while (0)
1392
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001393
Denis Vlasenko01631112007-12-16 17:20:38 +00001394#define stackblock() ((void *)g_stacknxt)
1395#define stackblocksize() g_stacknleft
1396
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001397/*
1398 * Parse trees for commands are allocated in lifo order, so we use a stack
1399 * to make this more efficient, and also to avoid all sorts of exception
1400 * handling code to handle interrupts in the middle of a parse.
1401 *
1402 * The size 504 was chosen because the Ultrix malloc handles that size
1403 * well.
1404 */
1405static void *
1406stalloc(size_t nbytes)
1407{
1408 char *p;
1409 size_t aligned;
1410
1411 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001412 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001413 size_t len;
1414 size_t blocksize;
1415 struct stack_block *sp;
1416
1417 blocksize = aligned;
1418 if (blocksize < MINSIZE)
1419 blocksize = MINSIZE;
1420 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1421 if (len < blocksize)
1422 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1423 INT_OFF;
1424 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001425 sp->prev = g_stackp;
1426 g_stacknxt = sp->space;
1427 g_stacknleft = blocksize;
1428 sstrend = g_stacknxt + blocksize;
1429 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001430 INT_ON;
1431 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001432 p = g_stacknxt;
1433 g_stacknxt += aligned;
1434 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001435 return p;
1436}
1437
Denis Vlasenko597906c2008-02-20 16:38:54 +00001438static void *
1439stzalloc(size_t nbytes)
1440{
1441 return memset(stalloc(nbytes), 0, nbytes);
1442}
1443
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001444static void
1445stunalloc(void *p)
1446{
1447#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001448 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001449 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001450 abort();
1451 }
1452#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001453 g_stacknleft += g_stacknxt - (char *)p;
1454 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001455}
1456
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001457/*
1458 * Like strdup but works with the ash stack.
1459 */
1460static char *
1461ststrdup(const char *p)
1462{
1463 size_t len = strlen(p) + 1;
1464 return memcpy(stalloc(len), p, len);
1465}
1466
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001467static void
1468setstackmark(struct stackmark *mark)
1469{
Denis Vlasenko01631112007-12-16 17:20:38 +00001470 mark->stackp = g_stackp;
1471 mark->stacknxt = g_stacknxt;
1472 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001473 mark->marknext = markp;
1474 markp = mark;
1475}
1476
1477static void
1478popstackmark(struct stackmark *mark)
1479{
1480 struct stack_block *sp;
1481
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001482 if (!mark->stackp)
1483 return;
1484
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001485 INT_OFF;
1486 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001487 while (g_stackp != mark->stackp) {
1488 sp = g_stackp;
1489 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001490 free(sp);
1491 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001492 g_stacknxt = mark->stacknxt;
1493 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001494 sstrend = mark->stacknxt + mark->stacknleft;
1495 INT_ON;
1496}
1497
1498/*
1499 * When the parser reads in a string, it wants to stick the string on the
1500 * stack and only adjust the stack pointer when it knows how big the
1501 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1502 * of space on top of the stack and stackblocklen returns the length of
1503 * this block. Growstackblock will grow this space by at least one byte,
1504 * possibly moving it (like realloc). Grabstackblock actually allocates the
1505 * part of the block that has been used.
1506 */
1507static void
1508growstackblock(void)
1509{
1510 size_t newlen;
1511
Denis Vlasenko01631112007-12-16 17:20:38 +00001512 newlen = g_stacknleft * 2;
1513 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001514 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1515 if (newlen < 128)
1516 newlen += 128;
1517
Denis Vlasenko01631112007-12-16 17:20:38 +00001518 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001519 struct stack_block *oldstackp;
1520 struct stackmark *xmark;
1521 struct stack_block *sp;
1522 struct stack_block *prevstackp;
1523 size_t grosslen;
1524
1525 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001526 oldstackp = g_stackp;
1527 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001528 prevstackp = sp->prev;
1529 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1530 sp = ckrealloc(sp, grosslen);
1531 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001532 g_stackp = sp;
1533 g_stacknxt = sp->space;
1534 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001535 sstrend = sp->space + newlen;
1536
1537 /*
1538 * Stack marks pointing to the start of the old block
1539 * must be relocated to point to the new block
1540 */
1541 xmark = markp;
1542 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001543 xmark->stackp = g_stackp;
1544 xmark->stacknxt = g_stacknxt;
1545 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001546 xmark = xmark->marknext;
1547 }
1548 INT_ON;
1549 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001550 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001551 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001552 char *p = stalloc(newlen);
1553
1554 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001555 g_stacknxt = memcpy(p, oldspace, oldlen);
1556 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001557 }
1558}
1559
1560static void
1561grabstackblock(size_t len)
1562{
1563 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001564 g_stacknxt += len;
1565 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001566}
1567
1568/*
1569 * The following routines are somewhat easier to use than the above.
1570 * The user declares a variable of type STACKSTR, which may be declared
1571 * to be a register. The macro STARTSTACKSTR initializes things. Then
1572 * the user uses the macro STPUTC to add characters to the string. In
1573 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1574 * grown as necessary. When the user is done, she can just leave the
1575 * string there and refer to it using stackblock(). Or she can allocate
1576 * the space for it using grabstackstr(). If it is necessary to allow
1577 * someone else to use the stack temporarily and then continue to grow
1578 * the string, the user should use grabstack to allocate the space, and
1579 * then call ungrabstr(p) to return to the previous mode of operation.
1580 *
1581 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1582 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1583 * is space for at least one character.
1584 */
1585static void *
1586growstackstr(void)
1587{
1588 size_t len = stackblocksize();
1589 if (herefd >= 0 && len >= 1024) {
1590 full_write(herefd, stackblock(), len);
1591 return stackblock();
1592 }
1593 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001594 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001595}
1596
1597/*
1598 * Called from CHECKSTRSPACE.
1599 */
1600static char *
1601makestrspace(size_t newlen, char *p)
1602{
Denis Vlasenko01631112007-12-16 17:20:38 +00001603 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001604 size_t size = stackblocksize();
1605
1606 for (;;) {
1607 size_t nleft;
1608
1609 size = stackblocksize();
1610 nleft = size - len;
1611 if (nleft >= newlen)
1612 break;
1613 growstackblock();
1614 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001615 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001616}
1617
1618static char *
1619stack_nputstr(const char *s, size_t n, char *p)
1620{
1621 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001622 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001623 return p;
1624}
1625
1626static char *
1627stack_putstr(const char *s, char *p)
1628{
1629 return stack_nputstr(s, strlen(s), p);
1630}
1631
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001632static char *
1633_STPUTC(int c, char *p)
1634{
1635 if (p == sstrend)
1636 p = growstackstr();
1637 *p++ = c;
1638 return p;
1639}
1640
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001641#define STARTSTACKSTR(p) ((p) = stackblock())
1642#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001643#define CHECKSTRSPACE(n, p) do { \
1644 char *q = (p); \
1645 size_t l = (n); \
1646 size_t m = sstrend - q; \
1647 if (l > m) \
1648 (p) = makestrspace(l, q); \
1649} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001650#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001651#define STACKSTRNUL(p) do { \
1652 if ((p) == sstrend) \
1653 (p) = growstackstr(); \
1654 *(p) = '\0'; \
1655} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001656#define STUNPUTC(p) (--(p))
1657#define STTOPC(p) ((p)[-1])
1658#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659
1660#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001661#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001662#define stackstrend() ((void *)sstrend)
1663
1664
1665/* ============ String helpers */
1666
1667/*
1668 * prefix -- see if pfx is a prefix of string.
1669 */
1670static char *
1671prefix(const char *string, const char *pfx)
1672{
1673 while (*pfx) {
1674 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001675 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001676 }
1677 return (char *) string;
1678}
1679
1680/*
1681 * Check for a valid number. This should be elsewhere.
1682 */
1683static int
1684is_number(const char *p)
1685{
1686 do {
1687 if (!isdigit(*p))
1688 return 0;
1689 } while (*++p != '\0');
1690 return 1;
1691}
1692
1693/*
1694 * Convert a string of digits to an integer, printing an error message on
1695 * failure.
1696 */
1697static int
1698number(const char *s)
1699{
1700 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001701 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001702 return atoi(s);
1703}
1704
1705/*
1706 * Produce a possibly single quoted string suitable as input to the shell.
1707 * The return string is allocated on the stack.
1708 */
1709static char *
1710single_quote(const char *s)
1711{
1712 char *p;
1713
1714 STARTSTACKSTR(p);
1715
1716 do {
1717 char *q;
1718 size_t len;
1719
1720 len = strchrnul(s, '\'') - s;
1721
1722 q = p = makestrspace(len + 3, p);
1723
1724 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001725 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726 *q++ = '\'';
1727 s += len;
1728
1729 STADJUST(q - p, p);
1730
Denys Vlasenkocd716832009-11-28 22:14:02 +01001731 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001732 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001733 len = 0;
1734 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001735
1736 q = p = makestrspace(len + 3, p);
1737
1738 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001739 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001741
1742 STADJUST(q - p, p);
1743 } while (*s);
1744
Denys Vlasenkocd716832009-11-28 22:14:02 +01001745 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001746
1747 return stackblock();
1748}
1749
1750
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001751/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001752
1753static char **argptr; /* argument list for builtin commands */
1754static char *optionarg; /* set by nextopt (like getopt) */
1755static char *optptr; /* used by nextopt */
1756
1757/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001758 * XXX - should get rid of. Have all builtins use getopt(3).
1759 * The library getopt must have the BSD extension static variable
1760 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001762 * Standard option processing (a la getopt) for builtin routines.
1763 * The only argument that is passed to nextopt is the option string;
1764 * the other arguments are unnecessary. It returns the character,
1765 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766 */
1767static int
1768nextopt(const char *optstring)
1769{
1770 char *p;
1771 const char *q;
1772 char c;
1773
1774 p = optptr;
1775 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001776 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001778 if (p == NULL)
1779 return '\0';
1780 if (*p != '-')
1781 return '\0';
1782 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783 return '\0';
1784 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001785 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001787 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001788 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001789 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001791 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001793 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794 if (*++q == ':')
1795 q++;
1796 }
1797 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001798 if (*p == '\0') {
1799 p = *argptr++;
1800 if (p == NULL)
1801 ash_msg_and_raise_error("no arg for -%c option", c);
1802 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001803 optionarg = p;
1804 p = NULL;
1805 }
1806 optptr = p;
1807 return c;
1808}
1809
1810
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001811/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001812
Denis Vlasenko01631112007-12-16 17:20:38 +00001813/*
1814 * The parsefile structure pointed to by the global variable parsefile
1815 * contains information about the current file being read.
1816 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001817struct shparam {
1818 int nparam; /* # of positional parameters (without $0) */
1819#if ENABLE_ASH_GETOPTS
1820 int optind; /* next parameter to be processed by getopts */
1821 int optoff; /* used by getopts */
1822#endif
1823 unsigned char malloced; /* if parameter list dynamically allocated */
1824 char **p; /* parameter list */
1825};
1826
1827/*
1828 * Free the list of positional parameters.
1829 */
1830static void
1831freeparam(volatile struct shparam *param)
1832{
Denis Vlasenko01631112007-12-16 17:20:38 +00001833 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001834 char **ap, **ap1;
1835 ap = ap1 = param->p;
1836 while (*ap)
1837 free(*ap++);
1838 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001839 }
1840}
1841
1842#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001843static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001844#endif
1845
1846struct var {
1847 struct var *next; /* next entry in hash list */
1848 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001849 const char *var_text; /* name=value */
1850 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001851 /* the variable gets set/unset */
1852};
1853
1854struct localvar {
1855 struct localvar *next; /* next local variable in list */
1856 struct var *vp; /* the variable that was made local */
1857 int flags; /* saved flags */
1858 const char *text; /* saved text */
1859};
1860
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001861/* flags */
1862#define VEXPORT 0x01 /* variable is exported */
1863#define VREADONLY 0x02 /* variable cannot be modified */
1864#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1865#define VTEXTFIXED 0x08 /* text is statically allocated */
1866#define VSTACK 0x10 /* text is allocated on the stack */
1867#define VUNSET 0x20 /* the variable is not set */
1868#define VNOFUNC 0x40 /* don't call the callback function */
1869#define VNOSET 0x80 /* do not set variable - just readonly test */
1870#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001871#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001872# define VDYNAMIC 0x200 /* dynamic variable */
1873#else
1874# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875#endif
1876
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001877
Denis Vlasenko01631112007-12-16 17:20:38 +00001878/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001879#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001880static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001881change_lc_all(const char *value)
1882{
1883 if (value && *value != '\0')
1884 setlocale(LC_ALL, value);
1885}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001886static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001887change_lc_ctype(const char *value)
1888{
1889 if (value && *value != '\0')
1890 setlocale(LC_CTYPE, value);
1891}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001892#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001893#if ENABLE_ASH_MAIL
1894static void chkmail(void);
Denys Vlasenko8c52f802011-02-04 17:36:21 +01001895static void changemail(const char *var_value) FAST_FUNC;
1896#else
1897# define chkmail() ((void)0)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001898#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001899static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001900#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001901static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001902#endif
1903
Denis Vlasenko01631112007-12-16 17:20:38 +00001904static const struct {
1905 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001906 const char *var_text;
1907 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001908} varinit_data[] = {
Denys Vlasenko566a3132012-07-07 21:40:35 +02001909 /*
1910 * Note: VEXPORT would not work correctly here for NOFORK applets:
1911 * some environment strings may be constant.
1912 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001913 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001914#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001915 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1916 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001917#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001918 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1919 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1920 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1921 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001922#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001923 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001924#endif
1925#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001926 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001927#endif
1928#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001929 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001931#endif
1932#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001933 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001934#endif
1935};
1936
Denis Vlasenko0b769642008-07-24 07:54:57 +00001937struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001938
1939struct globals_var {
1940 struct shparam shellparam; /* $@ current positional parameters */
1941 struct redirtab *redirlist;
1942 int g_nullredirs;
1943 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1944 struct var *vartab[VTABSIZE];
1945 struct var varinit[ARRAY_SIZE(varinit_data)];
1946};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001947extern struct globals_var *const ash_ptr_to_globals_var;
1948#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001949#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001950//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001951#define g_nullredirs (G_var.g_nullredirs )
1952#define preverrout_fd (G_var.preverrout_fd)
1953#define vartab (G_var.vartab )
1954#define varinit (G_var.varinit )
1955#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001956 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001957 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1958 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001959 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001960 varinit[i].flags = varinit_data[i].flags; \
1961 varinit[i].var_text = varinit_data[i].var_text; \
1962 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001963 } \
1964} while (0)
1965
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001966#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001967#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001968# define vmail (&vifs)[1]
1969# define vmpath (&vmail)[1]
1970# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001971#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001972# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001973#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001974#define vps1 (&vpath)[1]
1975#define vps2 (&vps1)[1]
1976#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001977#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001978# define voptind (&vps4)[1]
1979# if ENABLE_ASH_RANDOM_SUPPORT
1980# define vrandom (&voptind)[1]
1981# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001982#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001983# if ENABLE_ASH_RANDOM_SUPPORT
1984# define vrandom (&vps4)[1]
1985# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001986#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001987
1988/*
1989 * The following macros access the values of the above variables.
1990 * They have to skip over the name. They return the null string
1991 * for unset variables.
1992 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001993#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001994#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001995#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001996# define mailval() (vmail.var_text + 5)
1997# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001998# define mpathset() ((vmpath.flags & VUNSET) == 0)
1999#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002000#define pathval() (vpath.var_text + 5)
2001#define ps1val() (vps1.var_text + 4)
2002#define ps2val() (vps2.var_text + 4)
2003#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00002004#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002005# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00002006#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002007
Denis Vlasenko01631112007-12-16 17:20:38 +00002008#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002009static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00002010getoptsreset(const char *value)
2011{
2012 shellparam.optind = number(value);
2013 shellparam.optoff = -1;
2014}
2015#endif
2016
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002017/*
2018 * Compares two strings up to the first = or '\0'. The first
2019 * string must be terminated by '='; the second may be terminated by
2020 * either '=' or '\0'.
2021 */
2022static int
2023varcmp(const char *p, const char *q)
2024{
2025 int c, d;
2026
2027 while ((c = *p) == (d = *q)) {
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02002028 if (c == '\0' || c == '=')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002029 goto out;
2030 p++;
2031 q++;
2032 }
2033 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002034 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002035 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002036 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002037 out:
2038 return c - d;
2039}
2040
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002041/*
2042 * Find the appropriate entry in the hash table from the name.
2043 */
2044static struct var **
2045hashvar(const char *p)
2046{
2047 unsigned hashval;
2048
2049 hashval = ((unsigned char) *p) << 4;
2050 while (*p && *p != '=')
2051 hashval += (unsigned char) *p++;
2052 return &vartab[hashval % VTABSIZE];
2053}
2054
2055static int
2056vpcmp(const void *a, const void *b)
2057{
2058 return varcmp(*(const char **)a, *(const char **)b);
2059}
2060
2061/*
2062 * This routine initializes the builtin variables.
2063 */
2064static void
2065initvar(void)
2066{
2067 struct var *vp;
2068 struct var *end;
2069 struct var **vpp;
2070
2071 /*
2072 * PS1 depends on uid
2073 */
2074#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002075 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002076#else
2077 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002078 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002079#endif
2080 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002081 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002082 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002083 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002084 vp->next = *vpp;
2085 *vpp = vp;
2086 } while (++vp < end);
2087}
2088
2089static struct var **
2090findvar(struct var **vpp, const char *name)
2091{
2092 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002093 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002094 break;
2095 }
2096 }
2097 return vpp;
2098}
2099
2100/*
2101 * Find the value of a variable. Returns NULL if not set.
2102 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01002103static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002104lookupvar(const char *name)
2105{
2106 struct var *v;
2107
2108 v = *findvar(hashvar(name), name);
2109 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002110#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002111 /*
2112 * Dynamic variables are implemented roughly the same way they are
2113 * in bash. Namely, they're "special" so long as they aren't unset.
2114 * As soon as they're unset, they're no longer dynamic, and dynamic
2115 * lookup will no longer happen at that point. -- PFM.
2116 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002117 if (v->flags & VDYNAMIC)
2118 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002119#endif
2120 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002121 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002122 }
2123 return NULL;
2124}
2125
Denys Vlasenkoe9ab07c2014-08-13 18:00:08 +02002126static void reinit_unicode_for_ash(void)
2127{
2128 /* Unicode support should be activated even if LANG is set
2129 * _during_ shell execution, not only if it was set when
2130 * shell was started. Therefore, re-check LANG every time:
2131 */
2132 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2133 || ENABLE_UNICODE_USING_LOCALE
2134 ) {
2135 const char *s = lookupvar("LC_ALL");
2136 if (!s) s = lookupvar("LC_CTYPE");
2137 if (!s) s = lookupvar("LANG");
2138 reinit_unicode(s);
2139 }
2140}
2141
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002142/*
2143 * Search the environment of a builtin command.
2144 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002145static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002146bltinlookup(const char *name)
2147{
2148 struct strlist *sp;
2149
2150 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002151 if (varcmp(sp->text, name) == 0)
2152 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002153 }
2154 return lookupvar(name);
2155}
2156
2157/*
2158 * Same as setvar except that the variable and value are passed in
2159 * the first argument as name=value. Since the first argument will
2160 * be actually stored in the table, it should not be a string that
2161 * will go away.
2162 * Called with interrupts off.
2163 */
2164static void
2165setvareq(char *s, int flags)
2166{
2167 struct var *vp, **vpp;
2168
2169 vpp = hashvar(s);
2170 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2171 vp = *findvar(vpp, s);
2172 if (vp) {
2173 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2174 const char *n;
2175
2176 if (flags & VNOSAVE)
2177 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002178 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002179 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2180 }
2181
2182 if (flags & VNOSET)
2183 return;
2184
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002185 if (vp->var_func && !(flags & VNOFUNC))
2186 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002187
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002188 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2189 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002190
2191 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2192 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002193 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002194 if (flags & VNOSET)
2195 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002196 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002197 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002198 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002199 *vpp = vp;
2200 }
2201 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2202 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002203 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002204 vp->flags = flags;
2205}
2206
2207/*
2208 * Set the value of a variable. The flags argument is ored with the
2209 * flags of the variable. If val is NULL, the variable is unset.
2210 */
2211static void
2212setvar(const char *name, const char *val, int flags)
2213{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002214 const char *q;
2215 char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002216 char *nameeq;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002217 size_t namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002218 size_t vallen;
2219
2220 q = endofname(name);
2221 p = strchrnul(q, '=');
2222 namelen = p - name;
2223 if (!namelen || p != q)
2224 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2225 vallen = 0;
2226 if (val == NULL) {
2227 flags |= VUNSET;
2228 } else {
2229 vallen = strlen(val);
2230 }
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002231
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002232 INT_OFF;
2233 nameeq = ckmalloc(namelen + vallen + 2);
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002234 p = memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002235 if (val) {
2236 *p++ = '=';
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002237 p = memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002238 }
2239 *p = '\0';
2240 setvareq(nameeq, flags | VNOSAVE);
2241 INT_ON;
2242}
2243
Denys Vlasenko03dad222010-01-12 23:29:57 +01002244static void FAST_FUNC
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02002245setvar0(const char *name, const char *val)
Denys Vlasenko03dad222010-01-12 23:29:57 +01002246{
2247 setvar(name, val, 0);
2248}
2249
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002250#if ENABLE_ASH_GETOPTS
2251/*
2252 * Safe version of setvar, returns 1 on success 0 on failure.
2253 */
2254static int
2255setvarsafe(const char *name, const char *val, int flags)
2256{
2257 int err;
2258 volatile int saveint;
2259 struct jmploc *volatile savehandler = exception_handler;
2260 struct jmploc jmploc;
2261
2262 SAVE_INT(saveint);
2263 if (setjmp(jmploc.loc))
2264 err = 1;
2265 else {
2266 exception_handler = &jmploc;
2267 setvar(name, val, flags);
2268 err = 0;
2269 }
2270 exception_handler = savehandler;
2271 RESTORE_INT(saveint);
2272 return err;
2273}
2274#endif
2275
2276/*
2277 * Unset the specified variable.
2278 */
2279static int
2280unsetvar(const char *s)
2281{
2282 struct var **vpp;
2283 struct var *vp;
2284 int retval;
2285
2286 vpp = findvar(hashvar(s), s);
2287 vp = *vpp;
2288 retval = 2;
2289 if (vp) {
2290 int flags = vp->flags;
2291
2292 retval = 1;
2293 if (flags & VREADONLY)
2294 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002295#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002296 vp->flags &= ~VDYNAMIC;
2297#endif
2298 if (flags & VUNSET)
2299 goto ok;
2300 if ((flags & VSTRFIXED) == 0) {
2301 INT_OFF;
2302 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002303 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002304 *vpp = vp->next;
2305 free(vp);
2306 INT_ON;
2307 } else {
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02002308 setvar0(s, NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002309 vp->flags &= ~VEXPORT;
2310 }
2311 ok:
2312 retval = 0;
2313 }
2314 out:
2315 return retval;
2316}
2317
2318/*
2319 * Process a linked list of variable assignments.
2320 */
2321static void
2322listsetvar(struct strlist *list_set_var, int flags)
2323{
2324 struct strlist *lp = list_set_var;
2325
2326 if (!lp)
2327 return;
2328 INT_OFF;
2329 do {
2330 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002331 lp = lp->next;
2332 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002333 INT_ON;
2334}
2335
2336/*
2337 * Generate a list of variables satisfying the given conditions.
2338 */
2339static char **
2340listvars(int on, int off, char ***end)
2341{
2342 struct var **vpp;
2343 struct var *vp;
2344 char **ep;
2345 int mask;
2346
2347 STARTSTACKSTR(ep);
2348 vpp = vartab;
2349 mask = on | off;
2350 do {
2351 for (vp = *vpp; vp; vp = vp->next) {
2352 if ((vp->flags & mask) == on) {
2353 if (ep == stackstrend())
2354 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002355 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002356 }
2357 }
2358 } while (++vpp < vartab + VTABSIZE);
2359 if (ep == stackstrend())
2360 ep = growstackstr();
2361 if (end)
2362 *end = ep;
2363 *ep++ = NULL;
2364 return grabstackstr(ep);
2365}
2366
2367
2368/* ============ Path search helper
2369 *
2370 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002371 * of the path before the first call; path_advance will update
2372 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002373 * the possible path expansions in sequence. If an option (indicated by
2374 * a percent sign) appears in the path entry then the global variable
2375 * pathopt will be set to point to it; otherwise pathopt will be set to
2376 * NULL.
2377 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002378static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002379
2380static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002381path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002382{
2383 const char *p;
2384 char *q;
2385 const char *start;
2386 size_t len;
2387
2388 if (*path == NULL)
2389 return NULL;
2390 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002391 for (p = start; *p && *p != ':' && *p != '%'; p++)
2392 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002393 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2394 while (stackblocksize() < len)
2395 growstackblock();
2396 q = stackblock();
2397 if (p != start) {
2398 memcpy(q, start, p - start);
2399 q += p - start;
2400 *q++ = '/';
2401 }
2402 strcpy(q, name);
2403 pathopt = NULL;
2404 if (*p == '%') {
2405 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002406 while (*p && *p != ':')
2407 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002408 }
2409 if (*p == ':')
2410 *path = p + 1;
2411 else
2412 *path = NULL;
2413 return stalloc(len);
2414}
2415
2416
2417/* ============ Prompt */
2418
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002419static smallint doprompt; /* if set, prompt the user */
2420static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002421
2422#if ENABLE_FEATURE_EDITING
2423static line_input_t *line_input_state;
2424static const char *cmdedit_prompt;
2425static void
2426putprompt(const char *s)
2427{
2428 if (ENABLE_ASH_EXPAND_PRMT) {
2429 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002430 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002431 return;
2432 }
2433 cmdedit_prompt = s;
2434}
2435#else
2436static void
2437putprompt(const char *s)
2438{
2439 out2str(s);
2440}
2441#endif
2442
2443#if ENABLE_ASH_EXPAND_PRMT
2444/* expandstr() needs parsing machinery, so it is far away ahead... */
2445static const char *expandstr(const char *ps);
2446#else
2447#define expandstr(s) s
2448#endif
2449
2450static void
Denys Vlasenko958581a2010-09-12 15:04:27 +02002451setprompt_if(smallint do_set, int whichprompt)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002452{
2453 const char *prompt;
Denys Vlasenko958581a2010-09-12 15:04:27 +02002454 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2455
2456 if (!do_set)
2457 return;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002458
2459 needprompt = 0;
2460
2461 switch (whichprompt) {
2462 case 1:
2463 prompt = ps1val();
2464 break;
2465 case 2:
2466 prompt = ps2val();
2467 break;
2468 default: /* 0 */
2469 prompt = nullstr;
2470 }
2471#if ENABLE_ASH_EXPAND_PRMT
2472 setstackmark(&smark);
2473 stalloc(stackblocksize());
2474#endif
2475 putprompt(expandstr(prompt));
2476#if ENABLE_ASH_EXPAND_PRMT
2477 popstackmark(&smark);
2478#endif
2479}
2480
2481
2482/* ============ The cd and pwd commands */
2483
2484#define CD_PHYSICAL 1
2485#define CD_PRINT 2
2486
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002487static int
2488cdopt(void)
2489{
2490 int flags = 0;
2491 int i, j;
2492
2493 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002494 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002495 if (i != j) {
2496 flags ^= CD_PHYSICAL;
2497 j = i;
2498 }
2499 }
2500
2501 return flags;
2502}
2503
2504/*
2505 * Update curdir (the name of the current directory) in response to a
2506 * cd command.
2507 */
2508static const char *
2509updatepwd(const char *dir)
2510{
2511 char *new;
2512 char *p;
2513 char *cdcomppath;
2514 const char *lim;
2515
2516 cdcomppath = ststrdup(dir);
2517 STARTSTACKSTR(new);
2518 if (*dir != '/') {
2519 if (curdir == nullstr)
2520 return 0;
2521 new = stack_putstr(curdir, new);
2522 }
2523 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002524 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002525 if (*dir != '/') {
2526 if (new[-1] != '/')
2527 USTPUTC('/', new);
2528 if (new > lim && *lim == '/')
2529 lim++;
2530 } else {
2531 USTPUTC('/', new);
2532 cdcomppath++;
2533 if (dir[1] == '/' && dir[2] != '/') {
2534 USTPUTC('/', new);
2535 cdcomppath++;
2536 lim++;
2537 }
2538 }
2539 p = strtok(cdcomppath, "/");
2540 while (p) {
2541 switch (*p) {
2542 case '.':
2543 if (p[1] == '.' && p[2] == '\0') {
2544 while (new > lim) {
2545 STUNPUTC(new);
2546 if (new[-1] == '/')
2547 break;
2548 }
2549 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002550 }
2551 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002552 break;
2553 /* fall through */
2554 default:
2555 new = stack_putstr(p, new);
2556 USTPUTC('/', new);
2557 }
2558 p = strtok(0, "/");
2559 }
2560 if (new > lim)
2561 STUNPUTC(new);
2562 *new = 0;
2563 return stackblock();
2564}
2565
2566/*
2567 * Find out what the current directory is. If we already know the current
2568 * directory, this routine returns immediately.
2569 */
2570static char *
2571getpwd(void)
2572{
Denis Vlasenko01631112007-12-16 17:20:38 +00002573 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002574 return dir ? dir : nullstr;
2575}
2576
2577static void
2578setpwd(const char *val, int setold)
2579{
2580 char *oldcur, *dir;
2581
2582 oldcur = dir = curdir;
2583
2584 if (setold) {
2585 setvar("OLDPWD", oldcur, VEXPORT);
2586 }
2587 INT_OFF;
2588 if (physdir != nullstr) {
2589 if (physdir != oldcur)
2590 free(physdir);
2591 physdir = nullstr;
2592 }
2593 if (oldcur == val || !val) {
2594 char *s = getpwd();
2595 physdir = s;
2596 if (!val)
2597 dir = s;
2598 } else
2599 dir = ckstrdup(val);
2600 if (oldcur != dir && oldcur != nullstr) {
2601 free(oldcur);
2602 }
2603 curdir = dir;
2604 INT_ON;
2605 setvar("PWD", dir, VEXPORT);
2606}
2607
2608static void hashcd(void);
2609
2610/*
2611 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2612 * know that the current directory has changed.
2613 */
2614static int
2615docd(const char *dest, int flags)
2616{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002617 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002618 int err;
2619
2620 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2621
2622 INT_OFF;
2623 if (!(flags & CD_PHYSICAL)) {
2624 dir = updatepwd(dest);
2625 if (dir)
2626 dest = dir;
2627 }
2628 err = chdir(dest);
2629 if (err)
2630 goto out;
2631 setpwd(dir, 1);
2632 hashcd();
2633 out:
2634 INT_ON;
2635 return err;
2636}
2637
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002638static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002639cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002640{
2641 const char *dest;
2642 const char *path;
2643 const char *p;
2644 char c;
2645 struct stat statb;
2646 int flags;
2647
2648 flags = cdopt();
2649 dest = *argptr;
2650 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002651 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002652 else if (LONE_DASH(dest)) {
2653 dest = bltinlookup("OLDPWD");
2654 flags |= CD_PRINT;
2655 }
2656 if (!dest)
2657 dest = nullstr;
2658 if (*dest == '/')
2659 goto step7;
2660 if (*dest == '.') {
2661 c = dest[1];
2662 dotdot:
2663 switch (c) {
2664 case '\0':
2665 case '/':
2666 goto step6;
2667 case '.':
2668 c = dest[2];
2669 if (c != '.')
2670 goto dotdot;
2671 }
2672 }
2673 if (!*dest)
2674 dest = ".";
2675 path = bltinlookup("CDPATH");
2676 if (!path) {
2677 step6:
2678 step7:
2679 p = dest;
2680 goto docd;
2681 }
2682 do {
2683 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002684 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002685 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2686 if (c && c != ':')
2687 flags |= CD_PRINT;
2688 docd:
2689 if (!docd(p, flags))
2690 goto out;
2691 break;
2692 }
2693 } while (path);
2694 ash_msg_and_raise_error("can't cd to %s", dest);
2695 /* NOTREACHED */
2696 out:
2697 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002698 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002699 return 0;
2700}
2701
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002702static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002703pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002704{
2705 int flags;
2706 const char *dir = curdir;
2707
2708 flags = cdopt();
2709 if (flags) {
2710 if (physdir == nullstr)
2711 setpwd(dir, 0);
2712 dir = physdir;
2713 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002714 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002715 return 0;
2716}
2717
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002718
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002719/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002720
Denis Vlasenko834dee72008-10-07 09:18:30 +00002721
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002722#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002723
Eric Andersenc470f442003-07-28 09:56:35 +00002724/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002725#define CWORD 0 /* character is nothing special */
2726#define CNL 1 /* newline character */
2727#define CBACK 2 /* a backslash character */
2728#define CSQUOTE 3 /* single quote */
2729#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002730#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002731#define CBQUOTE 6 /* backwards single quote */
2732#define CVAR 7 /* a dollar sign */
2733#define CENDVAR 8 /* a '}' character */
2734#define CLP 9 /* a left paren in arithmetic */
2735#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002736#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002737#define CCTL 12 /* like CWORD, except it must be escaped */
2738#define CSPCL 13 /* these terminate a word */
2739#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002740
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002741#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002742#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002743# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002744#endif
2745
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002746#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002747
Mike Frysinger98c52642009-04-02 10:02:37 +00002748#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002749# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002750#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002751# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002752#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002753static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002754#if ENABLE_ASH_ALIAS
2755 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2756#endif
2757 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2758 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2759 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2760 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2761 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2762 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2763 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2764 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2765 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2766 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2767 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002768#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002769 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2770 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2771 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2772#endif
2773#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002774};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002775/* Constants below must match table above */
2776enum {
2777#if ENABLE_ASH_ALIAS
2778 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2779#endif
2780 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2781 CNL_CNL_CNL_CNL , /* 2 */
2782 CWORD_CCTL_CCTL_CWORD , /* 3 */
2783 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2784 CVAR_CVAR_CWORD_CVAR , /* 5 */
2785 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2786 CSPCL_CWORD_CWORD_CLP , /* 7 */
2787 CSPCL_CWORD_CWORD_CRP , /* 8 */
2788 CBACK_CBACK_CCTL_CBACK , /* 9 */
2789 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2790 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2791 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2792 CWORD_CWORD_CWORD_CWORD , /* 13 */
2793 CCTL_CCTL_CCTL_CCTL , /* 14 */
2794};
Eric Andersen2870d962001-07-02 17:27:21 +00002795
Denys Vlasenkocd716832009-11-28 22:14:02 +01002796/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2797 * caller must ensure proper cast on it if c is *char_ptr!
2798 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002799/* Values for syntax param */
2800#define BASESYNTAX 0 /* not in quotes */
2801#define DQSYNTAX 1 /* in double quotes */
2802#define SQSYNTAX 2 /* in single quotes */
2803#define ARISYNTAX 3 /* in arithmetic */
2804#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002805
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002806#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002807
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002808static int
2809SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002810{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002811 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002812# if ENABLE_ASH_ALIAS
2813 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002814 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2815 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2816 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2817 11, 3 /* "}~" */
2818 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002819# else
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002821 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2822 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2823 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2824 10, 2 /* "}~" */
2825 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002826# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002827 const char *s;
2828 int indx;
2829
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002830 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002831 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002832# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002833 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002834 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002835 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002836# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002837 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002838 /* Cast is purely for paranoia here,
2839 * just in case someone passed signed char to us */
2840 if ((unsigned char)c >= CTL_FIRST
2841 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002842 ) {
2843 return CCTL;
2844 }
2845 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002846 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002847 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002848 indx = syntax_index_table[s - spec_symbls];
2849 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002850 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002851}
2852
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002853#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002854
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002855static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002856 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002857 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2867 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2868 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2890 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2892 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2894 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2896 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2897 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2898 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2899 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2902 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2904 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2919 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2949 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2950 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2954 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2982 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2983 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2985 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2987 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2988 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2989 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2990 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2991 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2992 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2993 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2994 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003113 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01003114# if ENABLE_ASH_ALIAS
3115 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3116# endif
Eric Andersen2870d962001-07-02 17:27:21 +00003117};
3118
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003119# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003120
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01003121#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003122
Eric Andersen2870d962001-07-02 17:27:21 +00003123
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003124/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003125
Denis Vlasenko131ae172007-02-18 13:00:19 +00003126#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003127
3128#define ALIASINUSE 1
3129#define ALIASDEAD 2
3130
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003131struct alias {
3132 struct alias *next;
3133 char *name;
3134 char *val;
3135 int flag;
3136};
3137
Denis Vlasenko01631112007-12-16 17:20:38 +00003138
3139static struct alias **atab; // [ATABSIZE];
3140#define INIT_G_alias() do { \
3141 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3142} while (0)
3143
Eric Andersen2870d962001-07-02 17:27:21 +00003144
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003145static struct alias **
3146__lookupalias(const char *name) {
3147 unsigned int hashval;
3148 struct alias **app;
3149 const char *p;
3150 unsigned int ch;
3151
3152 p = name;
3153
3154 ch = (unsigned char)*p;
3155 hashval = ch << 4;
3156 while (ch) {
3157 hashval += ch;
3158 ch = (unsigned char)*++p;
3159 }
3160 app = &atab[hashval % ATABSIZE];
3161
3162 for (; *app; app = &(*app)->next) {
3163 if (strcmp(name, (*app)->name) == 0) {
3164 break;
3165 }
3166 }
3167
3168 return app;
3169}
3170
3171static struct alias *
3172lookupalias(const char *name, int check)
3173{
3174 struct alias *ap = *__lookupalias(name);
3175
3176 if (check && ap && (ap->flag & ALIASINUSE))
3177 return NULL;
3178 return ap;
3179}
3180
3181static struct alias *
3182freealias(struct alias *ap)
3183{
3184 struct alias *next;
3185
3186 if (ap->flag & ALIASINUSE) {
3187 ap->flag |= ALIASDEAD;
3188 return ap;
3189 }
3190
3191 next = ap->next;
3192 free(ap->name);
3193 free(ap->val);
3194 free(ap);
3195 return next;
3196}
Eric Andersencb57d552001-06-28 07:25:16 +00003197
Eric Andersenc470f442003-07-28 09:56:35 +00003198static void
3199setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003200{
3201 struct alias *ap, **app;
3202
3203 app = __lookupalias(name);
3204 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003205 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003206 if (ap) {
3207 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003208 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003209 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003210 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003211 ap->flag &= ~ALIASDEAD;
3212 } else {
3213 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003214 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003215 ap->name = ckstrdup(name);
3216 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003217 /*ap->flag = 0; - ckzalloc did it */
3218 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003219 *app = ap;
3220 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003221 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003222}
3223
Eric Andersenc470f442003-07-28 09:56:35 +00003224static int
3225unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003226{
Eric Andersencb57d552001-06-28 07:25:16 +00003227 struct alias **app;
3228
3229 app = __lookupalias(name);
3230
3231 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003232 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003233 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003234 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003235 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003236 }
3237
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003238 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003239}
3240
Eric Andersenc470f442003-07-28 09:56:35 +00003241static void
3242rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003243{
Eric Andersencb57d552001-06-28 07:25:16 +00003244 struct alias *ap, **app;
3245 int i;
3246
Denis Vlasenkob012b102007-02-19 22:43:01 +00003247 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003248 for (i = 0; i < ATABSIZE; i++) {
3249 app = &atab[i];
3250 for (ap = *app; ap; ap = *app) {
3251 *app = freealias(*app);
3252 if (ap == *app) {
3253 app = &ap->next;
3254 }
3255 }
3256 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003257 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003258}
3259
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003260static void
3261printalias(const struct alias *ap)
3262{
3263 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3264}
3265
Eric Andersencb57d552001-06-28 07:25:16 +00003266/*
3267 * TODO - sort output
3268 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003269static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003270aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003271{
3272 char *n, *v;
3273 int ret = 0;
3274 struct alias *ap;
3275
Denis Vlasenko68404f12008-03-17 09:00:54 +00003276 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003277 int i;
3278
Denis Vlasenko68404f12008-03-17 09:00:54 +00003279 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003280 for (ap = atab[i]; ap; ap = ap->next) {
3281 printalias(ap);
3282 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003283 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003284 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003285 }
3286 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003287 v = strchr(n+1, '=');
3288 if (v == NULL) { /* n+1: funny ksh stuff */
3289 ap = *__lookupalias(n);
3290 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003291 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003292 ret = 1;
3293 } else
3294 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003295 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003296 *v++ = '\0';
3297 setalias(n, v);
3298 }
3299 }
3300
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003301 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003302}
3303
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003304static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003305unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003306{
3307 int i;
3308
3309 while ((i = nextopt("a")) != '\0') {
3310 if (i == 'a') {
3311 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003312 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003313 }
3314 }
3315 for (i = 0; *argptr; argptr++) {
3316 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003317 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003318 i = 1;
3319 }
3320 }
3321
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003322 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003323}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003324
Denis Vlasenko131ae172007-02-18 13:00:19 +00003325#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003326
Eric Andersenc470f442003-07-28 09:56:35 +00003327
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003328/* ============ jobs.c */
3329
3330/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003331#define FORK_FG 0
3332#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003333#define FORK_NOJOB 2
3334
3335/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003336#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3337#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3338#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003340/*
3341 * A job structure contains information about a job. A job is either a
3342 * single process or a set of processes contained in a pipeline. In the
3343 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3344 * array of pids.
3345 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003346struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003347 pid_t ps_pid; /* process id */
3348 int ps_status; /* last process status from wait() */
3349 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003350};
3351
3352struct job {
3353 struct procstat ps0; /* status of process */
3354 struct procstat *ps; /* status or processes when more than one */
3355#if JOBS
3356 int stopstatus; /* status of a stopped job */
3357#endif
3358 uint32_t
3359 nprocs: 16, /* number of processes */
3360 state: 8,
3361#define JOBRUNNING 0 /* at least one proc running */
3362#define JOBSTOPPED 1 /* all procs are stopped */
3363#define JOBDONE 2 /* all procs are completed */
3364#if JOBS
3365 sigint: 1, /* job was killed by SIGINT */
3366 jobctl: 1, /* job running under job control */
3367#endif
3368 waited: 1, /* true if this entry has been waited for */
3369 used: 1, /* true if this entry is in used */
3370 changed: 1; /* true if status has changed */
3371 struct job *prev_job; /* previous job */
3372};
3373
Denis Vlasenko68404f12008-03-17 09:00:54 +00003374static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375static int forkshell(struct job *, union node *, int);
3376static int waitforjob(struct job *);
3377
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003378#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003379enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003380#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003381#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003382static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003383static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003384#endif
3385
3386/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003387 * Ignore a signal.
3388 */
3389static void
3390ignoresig(int signo)
3391{
3392 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3393 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3394 /* No, need to do it */
3395 signal(signo, SIG_IGN);
3396 }
3397 sigmode[signo - 1] = S_HARD_IGN;
3398}
3399
3400/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003401 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003402 */
3403static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003404signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003405{
3406 gotsig[signo - 1] = 1;
3407
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003408 if (signo == SIGINT && !trap[SIGINT]) {
3409 if (!suppress_int) {
3410 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003411 raise_interrupt(); /* does not return */
3412 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003413 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003414 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003415 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003416 }
3417}
3418
3419/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003420 * Set the signal handler for the specified signal. The routine figures
3421 * out what it should be set to.
3422 */
3423static void
3424setsignal(int signo)
3425{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003426 char *t;
3427 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428 struct sigaction act;
3429
3430 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003431 new_act = S_DFL;
3432 if (t != NULL) { /* trap for this sig is set */
3433 new_act = S_CATCH;
3434 if (t[0] == '\0') /* trap is "": ignore this sig */
3435 new_act = S_IGN;
3436 }
3437
3438 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003439 switch (signo) {
3440 case SIGINT:
3441 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003442 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003443 break;
3444 case SIGQUIT:
3445#if DEBUG
3446 if (debug)
3447 break;
3448#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003449 /* man bash:
3450 * "In all cases, bash ignores SIGQUIT. Non-builtin
3451 * commands run by bash have signal handlers
3452 * set to the values inherited by the shell
3453 * from its parent". */
3454 new_act = S_IGN;
3455 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003456 case SIGTERM:
3457 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003458 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003459 break;
3460#if JOBS
3461 case SIGTSTP:
3462 case SIGTTOU:
3463 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003464 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003465 break;
3466#endif
3467 }
3468 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003469//TODO: if !rootshell, we reset SIGQUIT to DFL,
3470//whereas we have to restore it to what shell got on entry
3471//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003472
3473 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003474 cur_act = *t;
3475 if (cur_act == 0) {
3476 /* current setting is not yet known */
3477 if (sigaction(signo, NULL, &act)) {
3478 /* pretend it worked; maybe we should give a warning,
3479 * but other shells don't. We don't alter sigmode,
3480 * so we retry every time.
3481 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003482 return;
3483 }
3484 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003485 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003486 if (mflag
3487 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3488 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003489 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003490 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003491 }
3492 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003493 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003494 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003495
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003496 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003497 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003498 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003499 act.sa_handler = signal_handler;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003500 break;
3501 case S_IGN:
3502 act.sa_handler = SIG_IGN;
3503 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003504 }
Ian Wienand89b3cba2011-04-16 20:05:14 +02003505
3506 /* flags and mask matter only if !DFL and !IGN, but we do it
3507 * for all cases for more deterministic behavior:
3508 */
3509 act.sa_flags = 0;
3510 sigfillset(&act.sa_mask);
3511
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003512 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003513
3514 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003515}
3516
3517/* mode flags for set_curjob */
3518#define CUR_DELETE 2
3519#define CUR_RUNNING 1
3520#define CUR_STOPPED 0
3521
3522/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003523#define DOWAIT_NONBLOCK WNOHANG
3524#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003525
3526#if JOBS
3527/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003528static int initialpgrp; //references:2
3529static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003530#endif
3531/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003532static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003533/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003534static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003535/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003536static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003537/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003538static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003539
3540static void
3541set_curjob(struct job *jp, unsigned mode)
3542{
3543 struct job *jp1;
3544 struct job **jpp, **curp;
3545
3546 /* first remove from list */
3547 jpp = curp = &curjob;
Denys Vlasenko940c7202011-03-02 04:07:14 +01003548 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003549 jp1 = *jpp;
3550 if (jp1 == jp)
3551 break;
3552 jpp = &jp1->prev_job;
Denys Vlasenko940c7202011-03-02 04:07:14 +01003553 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003554 *jpp = jp1->prev_job;
3555
3556 /* Then re-insert in correct position */
3557 jpp = curp;
3558 switch (mode) {
3559 default:
3560#if DEBUG
3561 abort();
3562#endif
3563 case CUR_DELETE:
3564 /* job being deleted */
3565 break;
3566 case CUR_RUNNING:
3567 /* newly created job or backgrounded job,
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01003568 * put after all stopped jobs.
3569 */
Denys Vlasenko940c7202011-03-02 04:07:14 +01003570 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003571 jp1 = *jpp;
3572#if JOBS
3573 if (!jp1 || jp1->state != JOBSTOPPED)
3574#endif
3575 break;
3576 jpp = &jp1->prev_job;
Denys Vlasenko940c7202011-03-02 04:07:14 +01003577 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003578 /* FALLTHROUGH */
3579#if JOBS
3580 case CUR_STOPPED:
3581#endif
3582 /* newly stopped job - becomes curjob */
3583 jp->prev_job = *jpp;
3584 *jpp = jp;
3585 break;
3586 }
3587}
3588
3589#if JOBS || DEBUG
3590static int
3591jobno(const struct job *jp)
3592{
3593 return jp - jobtab + 1;
3594}
3595#endif
3596
3597/*
3598 * Convert a job name to a job structure.
3599 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003600#if !JOBS
3601#define getjob(name, getctl) getjob(name)
3602#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003603static struct job *
3604getjob(const char *name, int getctl)
3605{
3606 struct job *jp;
3607 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003608 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003609 unsigned num;
3610 int c;
3611 const char *p;
3612 char *(*match)(const char *, const char *);
3613
3614 jp = curjob;
3615 p = name;
3616 if (!p)
3617 goto currentjob;
3618
3619 if (*p != '%')
3620 goto err;
3621
3622 c = *++p;
3623 if (!c)
3624 goto currentjob;
3625
3626 if (!p[1]) {
3627 if (c == '+' || c == '%') {
3628 currentjob:
3629 err_msg = "No current job";
3630 goto check;
3631 }
3632 if (c == '-') {
3633 if (jp)
3634 jp = jp->prev_job;
3635 err_msg = "No previous job";
3636 check:
3637 if (!jp)
3638 goto err;
3639 goto gotit;
3640 }
3641 }
3642
3643 if (is_number(p)) {
3644 num = atoi(p);
Denys Vlasenko07f7ea72014-09-08 17:21:52 +02003645 if (num <= njobs) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003646 jp = jobtab + num - 1;
3647 if (jp->used)
3648 goto gotit;
3649 goto err;
3650 }
3651 }
3652
3653 match = prefix;
3654 if (*p == '?') {
3655 match = strstr;
3656 p++;
3657 }
3658
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003659 found = NULL;
3660 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003661 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003662 if (found)
3663 goto err;
3664 found = jp;
3665 err_msg = "%s: ambiguous";
3666 }
3667 jp = jp->prev_job;
3668 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003669 if (!found)
3670 goto err;
3671 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672
3673 gotit:
3674#if JOBS
3675 err_msg = "job %s not created under job control";
3676 if (getctl && jp->jobctl == 0)
3677 goto err;
3678#endif
3679 return jp;
3680 err:
3681 ash_msg_and_raise_error(err_msg, name);
3682}
3683
3684/*
3685 * Mark a job structure as unused.
3686 */
3687static void
3688freejob(struct job *jp)
3689{
3690 struct procstat *ps;
3691 int i;
3692
3693 INT_OFF;
3694 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003695 if (ps->ps_cmd != nullstr)
3696 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003697 }
3698 if (jp->ps != &jp->ps0)
3699 free(jp->ps);
3700 jp->used = 0;
3701 set_curjob(jp, CUR_DELETE);
3702 INT_ON;
3703}
3704
3705#if JOBS
3706static void
3707xtcsetpgrp(int fd, pid_t pgrp)
3708{
3709 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003710 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711}
3712
3713/*
3714 * Turn job control on and off.
3715 *
3716 * Note: This code assumes that the third arg to ioctl is a character
3717 * pointer, which is true on Berkeley systems but not System V. Since
3718 * System V doesn't have job control yet, this isn't a problem now.
3719 *
3720 * Called with interrupts off.
3721 */
3722static void
3723setjobctl(int on)
3724{
3725 int fd;
3726 int pgrp;
3727
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003728 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003729 return;
3730 if (on) {
3731 int ofd;
3732 ofd = fd = open(_PATH_TTY, O_RDWR);
3733 if (fd < 0) {
3734 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3735 * That sometimes helps to acquire controlling tty.
3736 * Obviously, a workaround for bugs when someone
3737 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003738 fd = 2;
3739 while (!isatty(fd))
3740 if (--fd < 0)
3741 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003742 }
3743 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003744 if (ofd >= 0)
3745 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003746 if (fd < 0)
3747 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003748 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003749 close_on_exec_on(fd);
Denys Vlasenko940c7202011-03-02 04:07:14 +01003750 while (1) { /* while we are in the background */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003751 pgrp = tcgetpgrp(fd);
3752 if (pgrp < 0) {
3753 out:
3754 ash_msg("can't access tty; job control turned off");
3755 mflag = on = 0;
3756 goto close;
3757 }
3758 if (pgrp == getpgrp())
3759 break;
3760 killpg(0, SIGTTIN);
Denys Vlasenko940c7202011-03-02 04:07:14 +01003761 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003762 initialpgrp = pgrp;
3763
3764 setsignal(SIGTSTP);
3765 setsignal(SIGTTOU);
3766 setsignal(SIGTTIN);
3767 pgrp = rootpid;
3768 setpgid(0, pgrp);
3769 xtcsetpgrp(fd, pgrp);
3770 } else {
3771 /* turning job control off */
3772 fd = ttyfd;
3773 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003774 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003775 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003776 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003777 setpgid(0, pgrp);
3778 setsignal(SIGTSTP);
3779 setsignal(SIGTTOU);
3780 setsignal(SIGTTIN);
3781 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003782 if (fd >= 0)
3783 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784 fd = -1;
3785 }
3786 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003787 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003788}
3789
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003790static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003791killcmd(int argc, char **argv)
3792{
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003793 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denys Vlasenkob12553f2011-02-21 03:22:20 +01003794 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003795 do {
3796 if (argv[i][0] == '%') {
Denys Vlasenkob12553f2011-02-21 03:22:20 +01003797 /*
3798 * "kill %N" - job kill
3799 * Converting to pgrp / pid kill
3800 */
3801 struct job *jp;
3802 char *dst;
3803 int j, n;
3804
3805 jp = getjob(argv[i], 0);
3806 /*
3807 * In jobs started under job control, we signal
3808 * entire process group by kill -PGRP_ID.
3809 * This happens, f.e., in interactive shell.
3810 *
3811 * Otherwise, we signal each child via
3812 * kill PID1 PID2 PID3.
3813 * Testcases:
3814 * sh -c 'sleep 1|sleep 1 & kill %1'
3815 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3816 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3817 */
3818 n = jp->nprocs; /* can't be 0 (I hope) */
3819 if (jp->jobctl)
3820 n = 1;
3821 dst = alloca(n * sizeof(int)*4);
3822 argv[i] = dst;
3823 for (j = 0; j < n; j++) {
3824 struct procstat *ps = &jp->ps[j];
3825 /* Skip non-running and not-stopped members
3826 * (i.e. dead members) of the job
3827 */
3828 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3829 continue;
3830 /*
3831 * kill_main has matching code to expect
3832 * leading space. Needed to not confuse
3833 * negative pids with "kill -SIGNAL_NO" syntax
3834 */
3835 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3836 }
3837 *dst = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003838 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003839 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003840 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003841 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003842}
3843
3844static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003845showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003846{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003847 struct procstat *ps;
3848 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003849
Denys Vlasenko285ad152009-12-04 23:02:27 +01003850 psend = jp->ps + jp->nprocs;
3851 for (ps = jp->ps + 1; ps < psend; ps++)
3852 printf(" | %s", ps->ps_cmd);
3853 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003854 flush_stdout_stderr();
3855}
3856
3857
3858static int
3859restartjob(struct job *jp, int mode)
3860{
3861 struct procstat *ps;
3862 int i;
3863 int status;
3864 pid_t pgid;
3865
3866 INT_OFF;
3867 if (jp->state == JOBDONE)
3868 goto out;
3869 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003870 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003871 if (mode == FORK_FG)
3872 xtcsetpgrp(ttyfd, pgid);
3873 killpg(pgid, SIGCONT);
3874 ps = jp->ps;
3875 i = jp->nprocs;
3876 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003877 if (WIFSTOPPED(ps->ps_status)) {
3878 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003879 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003880 ps++;
3881 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003882 out:
3883 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3884 INT_ON;
3885 return status;
3886}
3887
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003888static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003889fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003890{
3891 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 int mode;
3893 int retval;
3894
3895 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3896 nextopt(nullstr);
3897 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898 do {
3899 jp = getjob(*argv, 1);
3900 if (mode == FORK_BG) {
3901 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003902 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003903 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003904 out1str(jp->ps[0].ps_cmd);
3905 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003906 retval = restartjob(jp, mode);
3907 } while (*argv && *++argv);
3908 return retval;
3909}
3910#endif
3911
3912static int
3913sprint_status(char *s, int status, int sigonly)
3914{
3915 int col;
3916 int st;
3917
3918 col = 0;
3919 if (!WIFEXITED(status)) {
3920#if JOBS
3921 if (WIFSTOPPED(status))
3922 st = WSTOPSIG(status);
3923 else
3924#endif
3925 st = WTERMSIG(status);
3926 if (sigonly) {
3927 if (st == SIGINT || st == SIGPIPE)
3928 goto out;
3929#if JOBS
3930 if (WIFSTOPPED(status))
3931 goto out;
3932#endif
3933 }
3934 st &= 0x7f;
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01003935//TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 col = fmtstr(s, 32, strsignal(st));
3937 if (WCOREDUMP(status)) {
3938 col += fmtstr(s + col, 16, " (core dumped)");
3939 }
3940 } else if (!sigonly) {
3941 st = WEXITSTATUS(status);
3942 if (st)
3943 col = fmtstr(s, 16, "Done(%d)", st);
3944 else
3945 col = fmtstr(s, 16, "Done");
3946 }
3947 out:
3948 return col;
3949}
3950
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003951static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003952dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003953{
3954 int pid;
3955 int status;
3956 struct job *jp;
3957 struct job *thisjob;
3958 int state;
3959
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003960 TRACE(("dowait(0x%x) called\n", wait_flags));
3961
3962 /* Do a wait system call. If job control is compiled in, we accept
3963 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3964 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003965 if (doing_jobctl)
3966 wait_flags |= WUNTRACED;
3967 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003968 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3969 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003970 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003972
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003973 INT_OFF;
3974 thisjob = NULL;
3975 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003976 struct procstat *ps;
3977 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 if (jp->state == JOBDONE)
3979 continue;
3980 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003981 ps = jp->ps;
3982 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003983 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003984 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003985 TRACE(("Job %d: changing status of proc %d "
3986 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003987 jobno(jp), pid, ps->ps_status, status));
3988 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003989 thisjob = jp;
3990 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003991 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003992 state = JOBRUNNING;
3993#if JOBS
3994 if (state == JOBRUNNING)
3995 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003996 if (WIFSTOPPED(ps->ps_status)) {
3997 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003998 state = JOBSTOPPED;
3999 }
4000#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01004001 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002 if (thisjob)
4003 goto gotjob;
4004 }
4005#if JOBS
4006 if (!WIFSTOPPED(status))
4007#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008 jobless--;
4009 goto out;
4010
4011 gotjob:
4012 if (state != JOBRUNNING) {
4013 thisjob->changed = 1;
4014
4015 if (thisjob->state != state) {
4016 TRACE(("Job %d: changing state from %d to %d\n",
4017 jobno(thisjob), thisjob->state, state));
4018 thisjob->state = state;
4019#if JOBS
4020 if (state == JOBSTOPPED) {
4021 set_curjob(thisjob, CUR_STOPPED);
4022 }
4023#endif
4024 }
4025 }
4026
4027 out:
4028 INT_ON;
4029
4030 if (thisjob && thisjob == job) {
4031 char s[48 + 1];
4032 int len;
4033
4034 len = sprint_status(s, status, 1);
4035 if (len) {
4036 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004037 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004038 out2str(s);
4039 }
4040 }
4041 return pid;
4042}
4043
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004044static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004045blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004046{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004047 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004048 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004049 raise_exception(EXSIG);
4050 return pid;
4051}
4052
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004053#if JOBS
4054static void
4055showjob(FILE *out, struct job *jp, int mode)
4056{
4057 struct procstat *ps;
4058 struct procstat *psend;
4059 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004060 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004061 char s[80];
4062
4063 ps = jp->ps;
4064
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004065 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01004067 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004068 return;
4069 }
4070
4071 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004072 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004073
4074 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004075 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004077 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004078
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004079 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004080 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004081
4082 psend = ps + jp->nprocs;
4083
4084 if (jp->state == JOBRUNNING) {
4085 strcpy(s + col, "Running");
4086 col += sizeof("Running") - 1;
4087 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01004088 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004089 if (jp->state == JOBSTOPPED)
4090 status = jp->stopstatus;
4091 col += sprint_status(s + col, status, 0);
4092 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004093 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004094
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004095 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4096 * or prints several "PID | <cmdN>" lines,
4097 * depending on SHOW_PIDS bit.
4098 * We do not print status of individual processes
4099 * between PID and <cmdN>. bash does it, but not very well:
4100 * first line shows overall job status, not process status,
4101 * making it impossible to know 1st process status.
4102 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004103 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004104 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004105 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004106 s[0] = '\0';
4107 col = 33;
4108 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004109 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004110 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01004111 fprintf(out, "%s%*c%s%s",
4112 s,
4113 33 - col >= 0 ? 33 - col : 0, ' ',
4114 ps == jp->ps ? "" : "| ",
4115 ps->ps_cmd
4116 );
4117 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004118 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004119
4120 jp->changed = 0;
4121
4122 if (jp->state == JOBDONE) {
4123 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4124 freejob(jp);
4125 }
4126}
4127
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004128/*
4129 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4130 * statuses have changed since the last call to showjobs.
4131 */
4132static void
4133showjobs(FILE *out, int mode)
4134{
4135 struct job *jp;
4136
Denys Vlasenko883cea42009-07-11 15:31:59 +02004137 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004138
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004139 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004140 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004141 continue;
4142
4143 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004144 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004145 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004146 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004147 }
4148}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004149
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004150static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004151jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004152{
4153 int mode, m;
4154
4155 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004156 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004157 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004158 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004159 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004160 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004161 }
4162
4163 argv = argptr;
4164 if (*argv) {
4165 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004166 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004167 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004168 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004169 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004170 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004171
4172 return 0;
4173}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004174#endif /* JOBS */
4175
Michael Abbott359da5e2009-12-04 23:03:29 +01004176/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004177static int
4178getstatus(struct job *job)
4179{
4180 int status;
4181 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004182 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004183
Michael Abbott359da5e2009-12-04 23:03:29 +01004184 /* Fetch last member's status */
4185 ps = job->ps + job->nprocs - 1;
4186 status = ps->ps_status;
4187 if (pipefail) {
4188 /* "set -o pipefail" mode: use last _nonzero_ status */
4189 while (status == 0 && --ps >= job->ps)
4190 status = ps->ps_status;
4191 }
4192
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004193 retval = WEXITSTATUS(status);
4194 if (!WIFEXITED(status)) {
4195#if JOBS
4196 retval = WSTOPSIG(status);
4197 if (!WIFSTOPPED(status))
4198#endif
4199 {
4200 /* XXX: limits number of signals */
4201 retval = WTERMSIG(status);
4202#if JOBS
4203 if (retval == SIGINT)
4204 job->sigint = 1;
4205#endif
4206 }
4207 retval += 128;
4208 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004209 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004210 jobno(job), job->nprocs, status, retval));
4211 return retval;
4212}
4213
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004214static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004215waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004216{
4217 struct job *job;
4218 int retval;
4219 struct job *jp;
4220
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004221 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004222 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223
4224 nextopt(nullstr);
4225 retval = 0;
4226
4227 argv = argptr;
4228 if (!*argv) {
4229 /* wait for all jobs */
4230 for (;;) {
4231 jp = curjob;
4232 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004233 if (!jp) /* no running procs */
4234 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004235 if (jp->state == JOBRUNNING)
4236 break;
4237 jp->waited = 1;
4238 jp = jp->prev_job;
4239 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004240 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004241 /* man bash:
4242 * "When bash is waiting for an asynchronous command via
4243 * the wait builtin, the reception of a signal for which a trap
4244 * has been set will cause the wait builtin to return immediately
4245 * with an exit status greater than 128, immediately after which
4246 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004247 *
4248 * blocking_wait_with_raise_on_sig raises signal handlers
4249 * if it gets no pid (pid < 0). However,
4250 * if child sends us a signal *and immediately exits*,
4251 * blocking_wait_with_raise_on_sig gets pid > 0
4252 * and does not handle pending_sig. Check this case: */
4253 if (pending_sig)
4254 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004255 }
4256 }
4257
4258 retval = 127;
4259 do {
4260 if (**argv != '%') {
4261 pid_t pid = number(*argv);
4262 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004263 while (1) {
4264 if (!job)
4265 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004266 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004267 break;
4268 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004269 }
Denys Vlasenkob12553f2011-02-21 03:22:20 +01004270 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004271 job = getjob(*argv, 0);
Denys Vlasenkob12553f2011-02-21 03:22:20 +01004272 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004273 /* loop until process terminated or stopped */
4274 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004275 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004276 job->waited = 1;
4277 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004278 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004279 } while (*++argv);
4280
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004281 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004282 return retval;
4283}
4284
4285static struct job *
4286growjobtab(void)
4287{
4288 size_t len;
4289 ptrdiff_t offset;
4290 struct job *jp, *jq;
4291
4292 len = njobs * sizeof(*jp);
4293 jq = jobtab;
4294 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4295
4296 offset = (char *)jp - (char *)jq;
4297 if (offset) {
4298 /* Relocate pointers */
4299 size_t l = len;
4300
4301 jq = (struct job *)((char *)jq + l);
4302 while (l) {
4303 l -= sizeof(*jp);
4304 jq--;
4305#define joff(p) ((struct job *)((char *)(p) + l))
4306#define jmove(p) (p) = (void *)((char *)(p) + offset)
4307 if (joff(jp)->ps == &jq->ps0)
4308 jmove(joff(jp)->ps);
4309 if (joff(jp)->prev_job)
4310 jmove(joff(jp)->prev_job);
4311 }
4312 if (curjob)
4313 jmove(curjob);
4314#undef joff
4315#undef jmove
4316 }
4317
4318 njobs += 4;
4319 jobtab = jp;
4320 jp = (struct job *)((char *)jp + len);
4321 jq = jp + 3;
4322 do {
4323 jq->used = 0;
4324 } while (--jq >= jp);
4325 return jp;
4326}
4327
4328/*
4329 * Return a new job structure.
4330 * Called with interrupts off.
4331 */
4332static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004333makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004334{
4335 int i;
4336 struct job *jp;
4337
4338 for (i = njobs, jp = jobtab; ; jp++) {
4339 if (--i < 0) {
4340 jp = growjobtab();
4341 break;
4342 }
4343 if (jp->used == 0)
4344 break;
4345 if (jp->state != JOBDONE || !jp->waited)
4346 continue;
4347#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004348 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004349 continue;
4350#endif
4351 freejob(jp);
4352 break;
4353 }
4354 memset(jp, 0, sizeof(*jp));
4355#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004356 /* jp->jobctl is a bitfield.
4357 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004358 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004359 jp->jobctl = 1;
4360#endif
4361 jp->prev_job = curjob;
4362 curjob = jp;
4363 jp->used = 1;
4364 jp->ps = &jp->ps0;
4365 if (nprocs > 1) {
4366 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4367 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004368 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004369 jobno(jp)));
4370 return jp;
4371}
4372
4373#if JOBS
4374/*
4375 * Return a string identifying a command (to be printed by the
4376 * jobs command).
4377 */
4378static char *cmdnextc;
4379
4380static void
4381cmdputs(const char *s)
4382{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004383 static const char vstype[VSTYPE + 1][3] = {
4384 "", "}", "-", "+", "?", "=",
4385 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004386 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004387 };
4388
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004389 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004390 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004391 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004392 unsigned char c;
4393 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004394 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004395
Denys Vlasenko46a14772009-12-10 21:27:13 +01004396 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004397 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4398 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004399 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004400 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004401 switch (c) {
4402 case CTLESC:
4403 c = *p++;
4404 break;
4405 case CTLVAR:
4406 subtype = *p++;
4407 if ((subtype & VSTYPE) == VSLENGTH)
4408 str = "${#";
4409 else
4410 str = "${";
Ron Yorston549deab2015-05-18 09:57:51 +02004411 goto dostr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004412 case CTLENDVAR:
4413 str = "\"}" + !(quoted & 1);
4414 quoted >>= 1;
4415 subtype = 0;
4416 goto dostr;
4417 case CTLBACKQ:
4418 str = "$(...)";
4419 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004420#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004421 case CTLARI:
4422 str = "$((";
4423 goto dostr;
4424 case CTLENDARI:
4425 str = "))";
4426 goto dostr;
4427#endif
4428 case CTLQUOTEMARK:
4429 quoted ^= 1;
4430 c = '"';
4431 break;
4432 case '=':
4433 if (subtype == 0)
4434 break;
4435 if ((subtype & VSTYPE) != VSNORMAL)
4436 quoted <<= 1;
4437 str = vstype[subtype & VSTYPE];
4438 if (subtype & VSNUL)
4439 c = ':';
4440 else
4441 goto checkstr;
4442 break;
4443 case '\'':
4444 case '\\':
4445 case '"':
4446 case '$':
4447 /* These can only happen inside quotes */
4448 cc[0] = c;
4449 str = cc;
4450 c = '\\';
4451 break;
4452 default:
4453 break;
4454 }
4455 USTPUTC(c, nextc);
4456 checkstr:
4457 if (!str)
4458 continue;
4459 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004460 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004461 USTPUTC(c, nextc);
4462 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004463 } /* while *p++ not NUL */
4464
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004465 if (quoted & 1) {
4466 USTPUTC('"', nextc);
4467 }
4468 *nextc = 0;
4469 cmdnextc = nextc;
4470}
4471
4472/* cmdtxt() and cmdlist() call each other */
4473static void cmdtxt(union node *n);
4474
4475static void
4476cmdlist(union node *np, int sep)
4477{
4478 for (; np; np = np->narg.next) {
4479 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004480 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004481 cmdtxt(np);
4482 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004483 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004484 }
4485}
4486
4487static void
4488cmdtxt(union node *n)
4489{
4490 union node *np;
4491 struct nodelist *lp;
4492 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004493
4494 if (!n)
4495 return;
4496 switch (n->type) {
4497 default:
4498#if DEBUG
4499 abort();
4500#endif
4501 case NPIPE:
4502 lp = n->npipe.cmdlist;
4503 for (;;) {
4504 cmdtxt(lp->n);
4505 lp = lp->next;
4506 if (!lp)
4507 break;
4508 cmdputs(" | ");
4509 }
4510 break;
4511 case NSEMI:
4512 p = "; ";
4513 goto binop;
4514 case NAND:
4515 p = " && ";
4516 goto binop;
4517 case NOR:
4518 p = " || ";
4519 binop:
4520 cmdtxt(n->nbinary.ch1);
4521 cmdputs(p);
4522 n = n->nbinary.ch2;
4523 goto donode;
4524 case NREDIR:
4525 case NBACKGND:
4526 n = n->nredir.n;
4527 goto donode;
4528 case NNOT:
4529 cmdputs("!");
4530 n = n->nnot.com;
4531 donode:
4532 cmdtxt(n);
4533 break;
4534 case NIF:
4535 cmdputs("if ");
4536 cmdtxt(n->nif.test);
4537 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004538 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004539 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004540 cmdputs("; else ");
4541 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004542 } else {
4543 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004544 }
4545 p = "; fi";
4546 goto dotail;
4547 case NSUBSHELL:
4548 cmdputs("(");
4549 n = n->nredir.n;
4550 p = ")";
4551 goto dotail;
4552 case NWHILE:
4553 p = "while ";
4554 goto until;
4555 case NUNTIL:
4556 p = "until ";
4557 until:
4558 cmdputs(p);
4559 cmdtxt(n->nbinary.ch1);
4560 n = n->nbinary.ch2;
4561 p = "; done";
4562 dodo:
4563 cmdputs("; do ");
4564 dotail:
4565 cmdtxt(n);
4566 goto dotail2;
4567 case NFOR:
4568 cmdputs("for ");
4569 cmdputs(n->nfor.var);
4570 cmdputs(" in ");
4571 cmdlist(n->nfor.args, 1);
4572 n = n->nfor.body;
4573 p = "; done";
4574 goto dodo;
4575 case NDEFUN:
4576 cmdputs(n->narg.text);
4577 p = "() { ... }";
4578 goto dotail2;
4579 case NCMD:
4580 cmdlist(n->ncmd.args, 1);
4581 cmdlist(n->ncmd.redirect, 0);
4582 break;
4583 case NARG:
4584 p = n->narg.text;
4585 dotail2:
4586 cmdputs(p);
4587 break;
4588 case NHERE:
4589 case NXHERE:
4590 p = "<<...";
4591 goto dotail2;
4592 case NCASE:
4593 cmdputs("case ");
4594 cmdputs(n->ncase.expr->narg.text);
4595 cmdputs(" in ");
4596 for (np = n->ncase.cases; np; np = np->nclist.next) {
4597 cmdtxt(np->nclist.pattern);
4598 cmdputs(") ");
4599 cmdtxt(np->nclist.body);
4600 cmdputs(";; ");
4601 }
4602 p = "esac";
4603 goto dotail2;
4604 case NTO:
4605 p = ">";
4606 goto redir;
4607 case NCLOBBER:
4608 p = ">|";
4609 goto redir;
4610 case NAPPEND:
4611 p = ">>";
4612 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004613#if ENABLE_ASH_BASH_COMPAT
4614 case NTO2:
4615#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004616 case NTOFD:
4617 p = ">&";
4618 goto redir;
4619 case NFROM:
4620 p = "<";
4621 goto redir;
4622 case NFROMFD:
4623 p = "<&";
4624 goto redir;
4625 case NFROMTO:
4626 p = "<>";
4627 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004628 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004629 cmdputs(p);
4630 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004631 cmdputs(utoa(n->ndup.dupfd));
4632 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004633 }
4634 n = n->nfile.fname;
4635 goto donode;
4636 }
4637}
4638
4639static char *
4640commandtext(union node *n)
4641{
4642 char *name;
4643
4644 STARTSTACKSTR(cmdnextc);
4645 cmdtxt(n);
4646 name = stackblock();
4647 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4648 name, cmdnextc, cmdnextc));
4649 return ckstrdup(name);
4650}
4651#endif /* JOBS */
4652
4653/*
4654 * Fork off a subshell. If we are doing job control, give the subshell its
4655 * own process group. Jp is a job structure that the job is to be added to.
4656 * N is the command that will be evaluated by the child. Both jp and n may
4657 * be NULL. The mode parameter can be one of the following:
4658 * FORK_FG - Fork off a foreground process.
4659 * FORK_BG - Fork off a background process.
4660 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4661 * process group even if job control is on.
4662 *
4663 * When job control is turned off, background processes have their standard
4664 * input redirected to /dev/null (except for the second and later processes
4665 * in a pipeline).
4666 *
4667 * Called with interrupts off.
4668 */
4669/*
4670 * Clear traps on a fork.
4671 */
4672static void
4673clear_traps(void)
4674{
4675 char **tp;
4676
4677 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004678 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004679 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004680 if (trap_ptr == trap)
4681 free(*tp);
4682 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004683 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004684 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004685 setsignal(tp - trap);
4686 INT_ON;
4687 }
4688 }
Alexander Shishkinccb97712010-07-25 13:07:39 +02004689 may_have_traps = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004690}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004691
4692/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004693static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004694
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004695/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004696static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004697forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004698{
4699 int oldlvl;
4700
4701 TRACE(("Child shell %d\n", getpid()));
4702 oldlvl = shlvl;
4703 shlvl++;
4704
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004705 /* man bash: "Non-builtin commands run by bash have signal handlers
4706 * set to the values inherited by the shell from its parent".
4707 * Do we do it correctly? */
4708
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004709 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004710
4711 if (mode == FORK_NOJOB /* is it `xxx` ? */
4712 && n && n->type == NCMD /* is it single cmd? */
4713 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004714 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004715 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4716 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4717 ) {
4718 TRACE(("Trap hack\n"));
4719 /* Awful hack for `trap` or $(trap).
4720 *
4721 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4722 * contains an example where "trap" is executed in a subshell:
4723 *
4724 * save_traps=$(trap)
4725 * ...
4726 * eval "$save_traps"
4727 *
4728 * Standard does not say that "trap" in subshell shall print
4729 * parent shell's traps. It only says that its output
4730 * must have suitable form, but then, in the above example
4731 * (which is not supposed to be normative), it implies that.
4732 *
4733 * bash (and probably other shell) does implement it
4734 * (traps are reset to defaults, but "trap" still shows them),
4735 * but as a result, "trap" logic is hopelessly messed up:
4736 *
4737 * # trap
4738 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4739 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4740 * # true | trap <--- trap is in subshell - no output (ditto)
4741 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4742 * trap -- 'echo Ho' SIGWINCH
4743 * # echo `(trap)` <--- in subshell in subshell - output
4744 * trap -- 'echo Ho' SIGWINCH
4745 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4746 * trap -- 'echo Ho' SIGWINCH
4747 *
4748 * The rules when to forget and when to not forget traps
4749 * get really complex and nonsensical.
4750 *
4751 * Our solution: ONLY bare $(trap) or `trap` is special.
4752 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004753 /* Save trap handler strings for trap builtin to print */
Ron Yorstond840c5d2015-07-19 23:05:20 +02004754 trap_ptr = xmemdup(trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004755 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004756 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004757 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004758#if JOBS
4759 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004760 doing_jobctl = 0;
Denys Vlasenkob12553f2011-02-21 03:22:20 +01004761 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004762 pid_t pgrp;
4763
4764 if (jp->nprocs == 0)
4765 pgrp = getpid();
4766 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004767 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004768 /* this can fail because we are doing it in the parent also */
4769 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004770 if (mode == FORK_FG)
4771 xtcsetpgrp(ttyfd, pgrp);
4772 setsignal(SIGTSTP);
4773 setsignal(SIGTTOU);
4774 } else
4775#endif
4776 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004777 /* man bash: "When job control is not in effect,
4778 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004779 ignoresig(SIGINT);
4780 ignoresig(SIGQUIT);
4781 if (jp->nprocs == 0) {
4782 close(0);
4783 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004784 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004785 }
4786 }
Denys Vlasenkob12553f2011-02-21 03:22:20 +01004787 if (oldlvl == 0) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004788 if (iflag) { /* why if iflag only? */
4789 setsignal(SIGINT);
4790 setsignal(SIGTERM);
4791 }
4792 /* man bash:
4793 * "In all cases, bash ignores SIGQUIT. Non-builtin
4794 * commands run by bash have signal handlers
4795 * set to the values inherited by the shell
4796 * from its parent".
4797 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004798 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004799 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004800#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004801 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004802 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004803 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004804 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004805 /* "jobs": we do not want to clear job list for it,
4806 * instead we remove only _its_ own_ job from job list.
4807 * This makes "jobs .... | cat" more useful.
4808 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004809 freejob(curjob);
4810 return;
4811 }
4812#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004813 for (jp = curjob; jp; jp = jp->prev_job)
4814 freejob(jp);
4815 jobless = 0;
4816}
4817
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004818/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004819#if !JOBS
4820#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4821#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004822static void
4823forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4824{
4825 TRACE(("In parent shell: child = %d\n", pid));
4826 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004827 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4828 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004829 jobless++;
4830 return;
4831 }
4832#if JOBS
4833 if (mode != FORK_NOJOB && jp->jobctl) {
4834 int pgrp;
4835
4836 if (jp->nprocs == 0)
4837 pgrp = pid;
4838 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004839 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004840 /* This can fail because we are doing it in the child also */
4841 setpgid(pid, pgrp);
4842 }
4843#endif
4844 if (mode == FORK_BG) {
4845 backgndpid = pid; /* set $! */
4846 set_curjob(jp, CUR_RUNNING);
4847 }
4848 if (jp) {
4849 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004850 ps->ps_pid = pid;
4851 ps->ps_status = -1;
4852 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004853#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004854 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004855 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004856#endif
4857 }
4858}
4859
4860static int
4861forkshell(struct job *jp, union node *n, int mode)
4862{
4863 int pid;
4864
4865 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4866 pid = fork();
4867 if (pid < 0) {
4868 TRACE(("Fork failed, errno=%d", errno));
4869 if (jp)
4870 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004871 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004872 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004873 if (pid == 0) {
4874 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004875 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004876 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004877 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004878 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004879 return pid;
4880}
4881
4882/*
4883 * Wait for job to finish.
4884 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004885 * Under job control we have the problem that while a child process
4886 * is running interrupts generated by the user are sent to the child
4887 * but not to the shell. This means that an infinite loop started by
4888 * an interactive user may be hard to kill. With job control turned off,
4889 * an interactive user may place an interactive program inside a loop.
4890 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004891 * these interrupts to also abort the loop. The approach we take here
4892 * is to have the shell ignore interrupt signals while waiting for a
4893 * foreground process to terminate, and then send itself an interrupt
4894 * signal if the child process was terminated by an interrupt signal.
4895 * Unfortunately, some programs want to do a bit of cleanup and then
4896 * exit on interrupt; unless these processes terminate themselves by
4897 * sending a signal to themselves (instead of calling exit) they will
4898 * confuse this approach.
4899 *
4900 * Called with interrupts off.
4901 */
4902static int
4903waitforjob(struct job *jp)
4904{
4905 int st;
4906
4907 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004908
4909 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004910 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004911 /* In non-interactive shells, we _can_ get
4912 * a keyboard signal here and be EINTRed,
4913 * but we just loop back, waiting for command to complete.
4914 *
4915 * man bash:
4916 * "If bash is waiting for a command to complete and receives
4917 * a signal for which a trap has been set, the trap
4918 * will not be executed until the command completes."
4919 *
4920 * Reality is that even if trap is not set, bash
4921 * will not act on the signal until command completes.
4922 * Try this. sleep5intoff.c:
4923 * #include <signal.h>
4924 * #include <unistd.h>
4925 * int main() {
4926 * sigset_t set;
4927 * sigemptyset(&set);
4928 * sigaddset(&set, SIGINT);
4929 * sigaddset(&set, SIGQUIT);
4930 * sigprocmask(SIG_BLOCK, &set, NULL);
4931 * sleep(5);
4932 * return 0;
4933 * }
4934 * $ bash -c './sleep5intoff; echo hi'
4935 * ^C^C^C^C <--- pressing ^C once a second
4936 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004937 * $ bash -c './sleep5intoff; echo hi'
4938 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4939 * $ _
4940 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004941 dowait(DOWAIT_BLOCK, jp);
4942 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004943 INT_ON;
4944
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004945 st = getstatus(jp);
4946#if JOBS
4947 if (jp->jobctl) {
4948 xtcsetpgrp(ttyfd, rootpid);
4949 /*
4950 * This is truly gross.
4951 * If we're doing job control, then we did a TIOCSPGRP which
4952 * caused us (the shell) to no longer be in the controlling
4953 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4954 * intuit from the subprocess exit status whether a SIGINT
4955 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4956 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004957 if (jp->sigint) /* TODO: do the same with all signals */
4958 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004959 }
4960 if (jp->state == JOBDONE)
4961#endif
4962 freejob(jp);
4963 return st;
4964}
4965
4966/*
4967 * return 1 if there are stopped jobs, otherwise 0
4968 */
4969static int
4970stoppedjobs(void)
4971{
4972 struct job *jp;
4973 int retval;
4974
4975 retval = 0;
4976 if (job_warning)
4977 goto out;
4978 jp = curjob;
4979 if (jp && jp->state == JOBSTOPPED) {
4980 out2str("You have stopped jobs.\n");
4981 job_warning = 2;
4982 retval++;
4983 }
4984 out:
4985 return retval;
4986}
4987
4988
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004989/* ============ redir.c
4990 *
4991 * Code for dealing with input/output redirection.
4992 */
4993
Denys Vlasenko8d0e0cd2011-01-25 23:21:46 +01004994#undef EMPTY
4995#undef CLOSED
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004996#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004997#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004998
4999/*
5000 * Open a file in noclobber mode.
5001 * The code was copied from bash.
5002 */
5003static int
5004noclobberopen(const char *fname)
5005{
5006 int r, fd;
5007 struct stat finfo, finfo2;
5008
5009 /*
5010 * If the file exists and is a regular file, return an error
5011 * immediately.
5012 */
5013 r = stat(fname, &finfo);
5014 if (r == 0 && S_ISREG(finfo.st_mode)) {
5015 errno = EEXIST;
5016 return -1;
5017 }
5018
5019 /*
5020 * If the file was not present (r != 0), make sure we open it
5021 * exclusively so that if it is created before we open it, our open
5022 * will fail. Make sure that we do not truncate an existing file.
5023 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5024 * file was not a regular file, we leave O_EXCL off.
5025 */
5026 if (r != 0)
5027 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5028 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5029
5030 /* If the open failed, return the file descriptor right away. */
5031 if (fd < 0)
5032 return fd;
5033
5034 /*
5035 * OK, the open succeeded, but the file may have been changed from a
5036 * non-regular file to a regular file between the stat and the open.
5037 * We are assuming that the O_EXCL open handles the case where FILENAME
5038 * did not exist and is symlinked to an existing file between the stat
5039 * and open.
5040 */
5041
5042 /*
5043 * If we can open it and fstat the file descriptor, and neither check
5044 * revealed that it was a regular file, and the file has not been
5045 * replaced, return the file descriptor.
5046 */
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02005047 if (fstat(fd, &finfo2) == 0
5048 && !S_ISREG(finfo2.st_mode)
5049 && finfo.st_dev == finfo2.st_dev
5050 && finfo.st_ino == finfo2.st_ino
5051 ) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005052 return fd;
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02005053 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005054
5055 /* The file has been replaced. badness. */
5056 close(fd);
5057 errno = EEXIST;
5058 return -1;
5059}
5060
5061/*
5062 * Handle here documents. Normally we fork off a process to write the
5063 * data to a pipe. If the document is short, we can stuff the data in
5064 * the pipe without forking.
5065 */
5066/* openhere needs this forward reference */
5067static void expandhere(union node *arg, int fd);
5068static int
5069openhere(union node *redir)
5070{
5071 int pip[2];
5072 size_t len = 0;
5073
5074 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005075 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005076 if (redir->type == NHERE) {
5077 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005078 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005079 full_write(pip[1], redir->nhere.doc->narg.text, len);
5080 goto out;
5081 }
5082 }
5083 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005084 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005085 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00005086 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5087 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5088 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5089 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005090 signal(SIGPIPE, SIG_DFL);
5091 if (redir->type == NHERE)
5092 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00005093 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005094 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00005095 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005096 }
5097 out:
5098 close(pip[1]);
5099 return pip[0];
5100}
5101
5102static int
5103openredirect(union node *redir)
5104{
5105 char *fname;
5106 int f;
5107
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02005108 fname = redir->nfile.expfname;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 switch (redir->nfile.type) {
5110 case NFROM:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005111 f = open(fname, O_RDONLY);
5112 if (f < 0)
5113 goto eopen;
5114 break;
5115 case NFROMTO:
Andreas Bühmannda75f442010-06-24 04:32:37 +02005116 f = open(fname, O_RDWR|O_CREAT, 0666);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005117 if (f < 0)
5118 goto ecreate;
5119 break;
5120 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00005121#if ENABLE_ASH_BASH_COMPAT
5122 case NTO2:
5123#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005124 /* Take care of noclobber mode. */
5125 if (Cflag) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005126 f = noclobberopen(fname);
5127 if (f < 0)
5128 goto ecreate;
5129 break;
5130 }
5131 /* FALLTHROUGH */
5132 case NCLOBBER:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005133 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5134 if (f < 0)
5135 goto ecreate;
5136 break;
5137 case NAPPEND:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005138 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5139 if (f < 0)
5140 goto ecreate;
5141 break;
5142 default:
5143#if DEBUG
5144 abort();
5145#endif
5146 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005147/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00005148// case NTOFD:
5149// case NFROMFD:
5150// f = -1;
5151// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005152 case NHERE:
5153 case NXHERE:
5154 f = openhere(redir);
5155 break;
5156 }
5157
5158 return f;
5159 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005160 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005161 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005162 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005163}
5164
5165/*
5166 * Copy a file descriptor to be >= to. Returns -1
5167 * if the source file descriptor is closed, EMPTY if there are no unused
5168 * file descriptors left.
5169 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005170/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5171 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005172enum {
5173 COPYFD_EXACT = (int)~(INT_MAX),
5174 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5175};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176static int
5177copyfd(int from, int to)
5178{
5179 int newfd;
5180
Denis Vlasenko5a867312008-07-24 19:46:38 +00005181 if (to & COPYFD_EXACT) {
5182 to &= ~COPYFD_EXACT;
5183 /*if (from != to)*/
5184 newfd = dup2(from, to);
5185 } else {
5186 newfd = fcntl(from, F_DUPFD, to);
5187 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005188 if (newfd < 0) {
5189 if (errno == EMFILE)
5190 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005191 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005192 ash_msg_and_raise_error("%d: %m", from);
5193 }
5194 return newfd;
5195}
5196
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005197/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005198struct two_fd_t {
5199 int orig, copy;
5200};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005201struct redirtab {
5202 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005203 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005204 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005205 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005206};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005207#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005208
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005209static int need_to_remember(struct redirtab *rp, int fd)
5210{
5211 int i;
5212
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005213 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005214 return 0;
5215
5216 for (i = 0; i < rp->pair_count; i++) {
5217 if (rp->two_fd[i].orig == fd) {
5218 /* already remembered */
5219 return 0;
5220 }
5221 }
5222 return 1;
5223}
5224
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005225/* "hidden" fd is a fd used to read scripts, or a copy of such */
5226static int is_hidden_fd(struct redirtab *rp, int fd)
5227{
5228 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005229 struct parsefile *pf;
5230
5231 if (fd == -1)
5232 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005233 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005234 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005235 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005236 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005237 * $ ash # running ash interactively
5238 * $ . ./script.sh
5239 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005240 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005241 * it's still ok to use it: "read" builtin uses it,
5242 * why should we cripple "exec" builtin?
5243 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005244 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005245 return 1;
5246 }
5247 pf = pf->prev;
5248 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005249
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005250 if (!rp)
5251 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005252 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005253 fd |= COPYFD_RESTORE;
5254 for (i = 0; i < rp->pair_count; i++) {
5255 if (rp->two_fd[i].copy == fd) {
5256 return 1;
5257 }
5258 }
5259 return 0;
5260}
5261
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005262/*
5263 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5264 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005265 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 */
5267/* flags passed to redirect */
5268#define REDIR_PUSH 01 /* save previous values of file descriptors */
5269#define REDIR_SAVEFD2 03 /* set preverrout */
5270static void
5271redirect(union node *redir, int flags)
5272{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005274 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005275 int i;
5276 int fd;
5277 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005278 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005279
Denis Vlasenko01631112007-12-16 17:20:38 +00005280 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005281 if (!redir) {
5282 return;
5283 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005284
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005285 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005286 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005287 INT_OFF;
5288 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005289 union node *tmp = redir;
5290 do {
5291 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005292#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005293 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005294 sv_pos++;
5295#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005296 tmp = tmp->nfile.next;
5297 } while (tmp);
5298 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005299 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005300 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005301 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005302 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005303 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005304 while (sv_pos > 0) {
5305 sv_pos--;
5306 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5307 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005308 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005309
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005310 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005311 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005312 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005313 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005314 right_fd = redir->ndup.dupfd;
5315 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005316 /* redirect from/to same file descriptor? */
5317 if (right_fd == fd)
5318 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005319 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005320 if (is_hidden_fd(sv, right_fd)) {
5321 errno = EBADF; /* as if it is closed */
5322 ash_msg_and_raise_error("%d: %m", right_fd);
5323 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005324 newfd = -1;
5325 } else {
5326 newfd = openredirect(redir); /* always >= 0 */
5327 if (fd == newfd) {
5328 /* Descriptor wasn't open before redirect.
5329 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005330 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005331 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005332 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005333 continue;
5334 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005335 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005336#if ENABLE_ASH_BASH_COMPAT
5337 redirect_more:
5338#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005339 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005340 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005341 /* Careful to not accidentally "save"
5342 * to the same fd as right side fd in N>&M */
5343 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5344 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005345/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5346 * are closed in popredir() in the child, preventing them from leaking
5347 * into child. (popredir() also cleans up the mess in case of failures)
5348 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005349 if (i == -1) {
5350 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005351 if (i != EBADF) {
5352 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005353 if (newfd >= 0)
5354 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005355 errno = i;
5356 ash_msg_and_raise_error("%d: %m", fd);
5357 /* NOTREACHED */
5358 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005359 /* EBADF: it is not open - good, remember to close it */
5360 remember_to_close:
5361 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005362 } else { /* fd is open, save its copy */
5363 /* "exec fd>&-" should not close fds
5364 * which point to script file(s).
5365 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005366 if (is_hidden_fd(sv, fd))
5367 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005368 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005369 if (fd == 2)
5370 copied_fd2 = i;
5371 sv->two_fd[sv_pos].orig = fd;
5372 sv->two_fd[sv_pos].copy = i;
5373 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005374 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005375 if (newfd < 0) {
5376 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005377 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005378 /* Don't want to trigger debugging */
5379 if (fd != -1)
5380 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005381 } else {
5382 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005383 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005384 } else if (fd != newfd) { /* move newfd to fd */
5385 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005386#if ENABLE_ASH_BASH_COMPAT
5387 if (!(redir->nfile.type == NTO2 && fd == 2))
5388#endif
5389 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005390 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005391#if ENABLE_ASH_BASH_COMPAT
5392 if (redir->nfile.type == NTO2 && fd == 1) {
5393 /* We already redirected it to fd 1, now copy it to 2 */
5394 newfd = 1;
5395 fd = 2;
5396 goto redirect_more;
5397 }
5398#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005399 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005400
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005401 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005402 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5403 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005404}
5405
5406/*
5407 * Undo the effects of the last redirection.
5408 */
5409static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005410popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005411{
5412 struct redirtab *rp;
5413 int i;
5414
Denis Vlasenko01631112007-12-16 17:20:38 +00005415 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005416 return;
5417 INT_OFF;
5418 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005419 for (i = 0; i < rp->pair_count; i++) {
5420 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005421 int copy = rp->two_fd[i].copy;
5422 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005423 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005424 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005425 continue;
5426 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005427 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005428 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005429 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005430 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005431 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005432 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005433 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005434 }
5435 }
5436 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005437 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005438 free(rp);
5439 INT_ON;
5440}
5441
5442/*
5443 * Undo all redirections. Called on error or interrupt.
5444 */
5445
5446/*
5447 * Discard all saved file descriptors.
5448 */
5449static void
5450clearredir(int drop)
5451{
5452 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005453 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005454 if (!redirlist)
5455 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005456 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005457 }
5458}
5459
5460static int
5461redirectsafe(union node *redir, int flags)
5462{
5463 int err;
5464 volatile int saveint;
5465 struct jmploc *volatile savehandler = exception_handler;
5466 struct jmploc jmploc;
5467
5468 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005469 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5470 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005471 if (!err) {
5472 exception_handler = &jmploc;
5473 redirect(redir, flags);
5474 }
5475 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005476 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005477 longjmp(exception_handler->loc, 1);
5478 RESTORE_INT(saveint);
5479 return err;
5480}
5481
5482
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005483/* ============ Routines to expand arguments to commands
5484 *
5485 * We have to deal with backquotes, shell variables, and file metacharacters.
5486 */
5487
Mike Frysinger98c52642009-04-02 10:02:37 +00005488#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005489static arith_t
5490ash_arith(const char *s)
5491{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005492 arith_state_t math_state;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005493 arith_t result;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005494
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005495 math_state.lookupvar = lookupvar;
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02005496 math_state.setvar = setvar0;
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005497 //math_state.endofname = endofname;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005498
5499 INT_OFF;
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005500 result = arith(&math_state, s);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005501 if (math_state.errmsg)
5502 ash_msg_and_raise_error(math_state.errmsg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005503 INT_ON;
5504
5505 return result;
5506}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005507#endif
5508
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005509/*
5510 * expandarg flags
5511 */
5512#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5513#define EXP_TILDE 0x2 /* do normal tilde expansion */
5514#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5515#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5516#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
Ron Yorston549deab2015-05-18 09:57:51 +02005517#define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005518#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5519#define EXP_WORD 0x80 /* expand word in parameter expansion */
Ron Yorston3df47f92015-05-18 09:53:26 +02005520#define EXP_QUOTED 0x100 /* expand word in double quotes */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005521/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005522 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005523 */
5524#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5525#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005526#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5527#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
Ron Yorston417622c2015-05-18 09:59:14 +02005528#define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005529
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005530/* Add CTLESC when necessary. */
Ron Yorston549deab2015-05-18 09:57:51 +02005531#define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005532/* Do not skip NUL characters. */
5533#define QUOTES_KEEPNUL EXP_TILDE
5534
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005535/*
5536 * Structure specifying which parts of the string should be searched
5537 * for IFS characters.
5538 */
5539struct ifsregion {
5540 struct ifsregion *next; /* next region in list */
5541 int begoff; /* offset of start of region */
5542 int endoff; /* offset of end of region */
5543 int nulonly; /* search for nul bytes only */
5544};
5545
5546struct arglist {
5547 struct strlist *list;
5548 struct strlist **lastp;
5549};
5550
5551/* output of current string */
5552static char *expdest;
5553/* list of back quote expressions */
5554static struct nodelist *argbackq;
5555/* first struct in list of ifs regions */
5556static struct ifsregion ifsfirst;
5557/* last struct in list */
5558static struct ifsregion *ifslastp;
5559/* holds expanded arg list */
5560static struct arglist exparg;
5561
5562/*
5563 * Our own itoa().
5564 */
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005565#if !ENABLE_SH_MATH_SUPPORT
5566/* cvtnum() is used even if math support is off (to prepare $? values and such) */
5567typedef long arith_t;
5568# define ARITH_FMT "%ld"
5569#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005570static int
5571cvtnum(arith_t num)
5572{
5573 int len;
5574
5575 expdest = makestrspace(32, expdest);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005576 len = fmtstr(expdest, 32, ARITH_FMT, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005577 STADJUST(len, expdest);
5578 return len;
5579}
5580
5581static size_t
5582esclen(const char *start, const char *p)
5583{
5584 size_t esc = 0;
5585
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005586 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005587 esc++;
5588 }
5589 return esc;
5590}
5591
5592/*
5593 * Remove any CTLESC characters from a string.
5594 */
5595static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005596rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005597{
Ron Yorston417622c2015-05-18 09:59:14 +02005598 static const char qchars[] ALIGN1 = {
5599 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005600
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005601 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005602 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005603 unsigned protect_against_glob;
5604 unsigned globbing;
Ron Yorston417622c2015-05-18 09:59:14 +02005605 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005606
Ron Yorston417622c2015-05-18 09:59:14 +02005607 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005608 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005609 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005610
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005611 q = p;
5612 r = str;
5613 if (flag & RMESCAPE_ALLOC) {
5614 size_t len = p - str;
5615 size_t fulllen = len + strlen(p) + 1;
5616
5617 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005618 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005619 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005620 /* p and str may be invalidated by makestrspace */
5621 str = (char *)stackblock() + strloc;
5622 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005623 } else if (flag & RMESCAPE_HEAP) {
5624 r = ckmalloc(fulllen);
5625 } else {
5626 r = stalloc(fulllen);
5627 }
5628 q = r;
5629 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005630 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005631 }
5632 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005633
Ron Yorston549deab2015-05-18 09:57:51 +02005634 inquotes = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005635 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005636 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005637 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005638 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005639// Note: both inquotes and protect_against_glob only affect whether
5640// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005641 inquotes = ~inquotes;
5642 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005643 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005644 continue;
5645 }
Ron Yorston549deab2015-05-18 09:57:51 +02005646 if ((unsigned char)*p == CTLESC) {
5647 p++;
5648 if (protect_against_glob) {
5649 *q++ = '\\';
5650 }
5651 } else if (*p == '\\' && !inquotes) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005652 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005653 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005654 goto copy;
5655 }
Ron Yorston417622c2015-05-18 09:59:14 +02005656#if ENABLE_ASH_BASH_COMPAT
5657 else if (*p == '/' && slash) {
5658 /* stop handling globbing and mark location of slash */
5659 globbing = slash = 0;
5660 *p = CTLESC;
5661 }
5662#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005663 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664 copy:
5665 *q++ = *p++;
5666 }
5667 *q = '\0';
5668 if (flag & RMESCAPE_GROW) {
5669 expdest = r;
5670 STADJUST(q - r + 1, expdest);
5671 }
5672 return r;
5673}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005674#define pmatch(a, b) !fnmatch((a), (b), 0)
5675
5676/*
5677 * Prepare a pattern for a expmeta (internal glob(3)) call.
5678 *
5679 * Returns an stalloced string.
5680 */
5681static char *
Ron Yorston549deab2015-05-18 09:57:51 +02005682preglob(const char *pattern, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005683{
Ron Yorston549deab2015-05-18 09:57:51 +02005684 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005685}
5686
5687/*
5688 * Put a string on the stack.
5689 */
5690static void
5691memtodest(const char *p, size_t len, int syntax, int quotes)
5692{
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005693 char *q;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005695 if (!len)
5696 return;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005697
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005698 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5699
5700 do {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005701 unsigned char c = *p++;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005702 if (c) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005703 int n = SIT(c, syntax);
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005704 if ((quotes & QUOTES_ESC) &&
Ron Yorston549deab2015-05-18 09:57:51 +02005705 ((n == CCTL) ||
5706 (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
5707 n == CBACK)))
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005708 USTPUTC(CTLESC, q);
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005709 } else if (!(quotes & QUOTES_KEEPNUL))
5710 continue;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005711 USTPUTC(c, q);
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005712 } while (--len);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005713
5714 expdest = q;
5715}
5716
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005717static size_t
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005718strtodest(const char *p, int syntax, int quotes)
5719{
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005720 size_t len = strlen(p);
5721 memtodest(p, len, syntax, quotes);
5722 return len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005723}
5724
5725/*
5726 * Record the fact that we have to scan this region of the
5727 * string for IFS characters.
5728 */
5729static void
5730recordregion(int start, int end, int nulonly)
5731{
5732 struct ifsregion *ifsp;
5733
5734 if (ifslastp == NULL) {
5735 ifsp = &ifsfirst;
5736 } else {
5737 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005738 ifsp = ckzalloc(sizeof(*ifsp));
5739 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005740 ifslastp->next = ifsp;
5741 INT_ON;
5742 }
5743 ifslastp = ifsp;
5744 ifslastp->begoff = start;
5745 ifslastp->endoff = end;
5746 ifslastp->nulonly = nulonly;
5747}
5748
5749static void
5750removerecordregions(int endoff)
5751{
5752 if (ifslastp == NULL)
5753 return;
5754
5755 if (ifsfirst.endoff > endoff) {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005756 while (ifsfirst.next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005757 struct ifsregion *ifsp;
5758 INT_OFF;
5759 ifsp = ifsfirst.next->next;
5760 free(ifsfirst.next);
5761 ifsfirst.next = ifsp;
5762 INT_ON;
5763 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005764 if (ifsfirst.begoff > endoff) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005765 ifslastp = NULL;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005766 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005767 ifslastp = &ifsfirst;
5768 ifsfirst.endoff = endoff;
5769 }
5770 return;
5771 }
5772
5773 ifslastp = &ifsfirst;
5774 while (ifslastp->next && ifslastp->next->begoff < endoff)
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005775 ifslastp = ifslastp->next;
5776 while (ifslastp->next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005777 struct ifsregion *ifsp;
5778 INT_OFF;
5779 ifsp = ifslastp->next->next;
5780 free(ifslastp->next);
5781 ifslastp->next = ifsp;
5782 INT_ON;
5783 }
5784 if (ifslastp->endoff > endoff)
5785 ifslastp->endoff = endoff;
5786}
5787
5788static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005789exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005790{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005791 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005792 char *name;
5793 struct passwd *pw;
5794 const char *home;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02005795 int quotes = flags & QUOTES_ESC;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796
5797 name = p + 1;
5798
5799 while ((c = *++p) != '\0') {
5800 switch (c) {
5801 case CTLESC:
5802 return startp;
5803 case CTLQUOTEMARK:
5804 return startp;
5805 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005806 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005807 goto done;
5808 break;
5809 case '/':
5810 case CTLENDVAR:
5811 goto done;
5812 }
5813 }
5814 done:
5815 *p = '\0';
5816 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005817 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005818 } else {
5819 pw = getpwnam(name);
5820 if (pw == NULL)
5821 goto lose;
5822 home = pw->pw_dir;
5823 }
5824 if (!home || !*home)
5825 goto lose;
5826 *p = c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005827 strtodest(home, SQSYNTAX, quotes);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005828 return p;
5829 lose:
5830 *p = c;
5831 return startp;
5832}
5833
5834/*
5835 * Execute a command inside back quotes. If it's a builtin command, we
5836 * want to save its output in a block obtained from malloc. Otherwise
5837 * we fork off a subprocess and get the output of the command via a pipe.
5838 * Should be called with interrupts off.
5839 */
5840struct backcmd { /* result of evalbackcmd */
5841 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005842 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005843 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005844 struct job *jp; /* job structure for command */
5845};
5846
5847/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005848static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005850static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005851
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005852static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005853evalbackcmd(union node *n, struct backcmd *result)
5854{
5855 int saveherefd;
5856
5857 result->fd = -1;
5858 result->buf = NULL;
5859 result->nleft = 0;
5860 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005861 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005862 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863
5864 saveherefd = herefd;
5865 herefd = -1;
5866
5867 {
5868 int pip[2];
5869 struct job *jp;
5870
5871 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005872 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005873 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005874 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5875 FORCE_INT_ON;
5876 close(pip[0]);
5877 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005878 /*close(1);*/
5879 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 close(pip[1]);
5881 }
5882 eflag = 0;
5883 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5884 /* NOTREACHED */
5885 }
5886 close(pip[1]);
5887 result->fd = pip[0];
5888 result->jp = jp;
5889 }
5890 herefd = saveherefd;
5891 out:
5892 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5893 result->fd, result->buf, result->nleft, result->jp));
5894}
5895
5896/*
5897 * Expand stuff in backwards quotes.
5898 */
5899static void
Ron Yorston549deab2015-05-18 09:57:51 +02005900expbackq(union node *cmd, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901{
5902 struct backcmd in;
5903 int i;
5904 char buf[128];
5905 char *p;
5906 char *dest;
5907 int startloc;
Ron Yorston549deab2015-05-18 09:57:51 +02005908 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005909 struct stackmark smark;
5910
5911 INT_OFF;
5912 setstackmark(&smark);
5913 dest = expdest;
5914 startloc = dest - (char *)stackblock();
5915 grabstackstr(dest);
5916 evalbackcmd(cmd, &in);
5917 popstackmark(&smark);
5918
5919 p = in.buf;
5920 i = in.nleft;
5921 if (i == 0)
5922 goto read;
5923 for (;;) {
Ron Yorston549deab2015-05-18 09:57:51 +02005924 memtodest(p, i, syntax, flag & QUOTES_ESC);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005925 read:
5926 if (in.fd < 0)
5927 break;
Ron Yorston61d6ae22015-04-19 10:50:25 +01005928 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 TRACE(("expbackq: read returns %d\n", i));
5930 if (i <= 0)
5931 break;
5932 p = buf;
5933 }
5934
Denis Vlasenko60818682007-09-28 22:07:23 +00005935 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005936 if (in.fd >= 0) {
5937 close(in.fd);
5938 back_exitstatus = waitforjob(in.jp);
5939 }
5940 INT_ON;
5941
5942 /* Eat all trailing newlines */
5943 dest = expdest;
5944 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5945 STUNPUTC(dest);
5946 expdest = dest;
5947
Ron Yorston549deab2015-05-18 09:57:51 +02005948 if (!(flag & EXP_QUOTED))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005949 recordregion(startloc, dest - (char *)stackblock(), 0);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005950 TRACE(("evalbackq: size:%d:'%.*s'\n",
5951 (int)((dest - (char *)stackblock()) - startloc),
5952 (int)((dest - (char *)stackblock()) - startloc),
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005953 stackblock() + startloc));
5954}
5955
Mike Frysinger98c52642009-04-02 10:02:37 +00005956#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005957/*
5958 * Expand arithmetic expression. Backup to start of expression,
5959 * evaluate, place result in (backed up) result, adjust string position.
5960 */
5961static void
Ron Yorston549deab2015-05-18 09:57:51 +02005962expari(int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005963{
5964 char *p, *start;
5965 int begoff;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005966 int len;
5967
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005968 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005969
5970 /*
5971 * This routine is slightly over-complicated for
5972 * efficiency. Next we scan backwards looking for the
5973 * start of arithmetic.
5974 */
5975 start = stackblock();
5976 p = expdest - 1;
5977 *p = '\0';
5978 p--;
Denys Vlasenko940c7202011-03-02 04:07:14 +01005979 while (1) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005980 int esc;
5981
Denys Vlasenkocd716832009-11-28 22:14:02 +01005982 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005983 p--;
5984#if DEBUG
5985 if (p < start) {
5986 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5987 }
5988#endif
5989 }
5990
5991 esc = esclen(start, p);
5992 if (!(esc % 2)) {
5993 break;
5994 }
5995
5996 p -= esc + 1;
Denys Vlasenko940c7202011-03-02 04:07:14 +01005997 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005998
5999 begoff = p - start;
6000
6001 removerecordregions(begoff);
6002
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006003 expdest = p;
6004
Ron Yorston549deab2015-05-18 09:57:51 +02006005 if (flag & QUOTES_ESC)
6006 rmescapes(p + 1, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006007
Ron Yorston549deab2015-05-18 09:57:51 +02006008 len = cvtnum(ash_arith(p + 1));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006009
Ron Yorston549deab2015-05-18 09:57:51 +02006010 if (!(flag & EXP_QUOTED))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006011 recordregion(begoff, begoff + len, 0);
6012}
6013#endif
6014
6015/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006016static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006017
6018/*
6019 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6020 * characters to allow for further processing. Otherwise treat
6021 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006022 *
6023 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6024 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6025 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006026 */
6027static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006028argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006029{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006030 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006031 '=',
6032 ':',
6033 CTLQUOTEMARK,
6034 CTLENDVAR,
6035 CTLESC,
6036 CTLVAR,
6037 CTLBACKQ,
Mike Frysinger98c52642009-04-02 10:02:37 +00006038#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006039 CTLENDARI,
6040#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01006041 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006042 };
6043 const char *reject = spclchars;
Ron Yorston3df47f92015-05-18 09:53:26 +02006044 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006045 int inquotes;
6046 size_t length;
6047 int startloc;
6048
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006049 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006050 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006051 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006052 reject++;
6053 }
6054 inquotes = 0;
6055 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006056 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006057 char *q;
6058
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006059 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060 tilde:
6061 q = p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006062 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006063 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006064 }
6065 start:
6066 startloc = expdest - (char *)stackblock();
6067 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006068 unsigned char c;
6069
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006070 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006071 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006072 if (c) {
6073 if (!(c & 0x80)
Denys Vlasenko958581a2010-09-12 15:04:27 +02006074 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006075 ) {
6076 /* c == '=' || c == ':' || c == CTLENDARI */
6077 length++;
6078 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006079 }
6080 if (length > 0) {
6081 int newloc;
6082 expdest = stack_nputstr(p, length, expdest);
6083 newloc = expdest - (char *)stackblock();
6084 if (breakall && !inquotes && newloc > startloc) {
6085 recordregion(startloc, newloc, 0);
6086 }
6087 startloc = newloc;
6088 }
6089 p += length + 1;
6090 length = 0;
6091
6092 switch (c) {
6093 case '\0':
6094 goto breakloop;
6095 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006096 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006097 p--;
6098 continue;
6099 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006100 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006101 reject++;
6102 /* fall through */
6103 case ':':
6104 /*
6105 * sort of a hack - expand tildes in variable
6106 * assignments (after the first '=' and after ':'s).
6107 */
6108 if (*--p == '~') {
6109 goto tilde;
6110 }
6111 continue;
6112 }
6113
6114 switch (c) {
6115 case CTLENDVAR: /* ??? */
6116 goto breakloop;
6117 case CTLQUOTEMARK:
Ron Yorston549deab2015-05-18 09:57:51 +02006118 inquotes ^= EXP_QUOTED;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006119 /* "$@" syntax adherence hack */
Ron Yorston549deab2015-05-18 09:57:51 +02006120 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6121 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006122 goto start;
6123 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006124 addquote:
Ron Yorston549deab2015-05-18 09:57:51 +02006125 if (flags & QUOTES_ESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006126 p--;
6127 length++;
6128 startloc++;
6129 }
6130 break;
6131 case CTLESC:
6132 startloc++;
6133 length++;
Ron Yorston549deab2015-05-18 09:57:51 +02006134
6135 /*
6136 * Quoted parameter expansion pattern: remove quote
6137 * unless inside inner quotes or we have a literal
6138 * backslash.
6139 */
6140 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6141 EXP_QPAT && *p != '\\')
6142 break;
6143
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006144 goto addquote;
6145 case CTLVAR:
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02006146 TRACE(("argstr: evalvar('%s')\n", p));
Ron Yorston549deab2015-05-18 09:57:51 +02006147 p = evalvar(p, flags | inquotes, var_str_list);
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02006148 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149 goto start;
6150 case CTLBACKQ:
Ron Yorston549deab2015-05-18 09:57:51 +02006151 expbackq(argbackq->n, flags | inquotes);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006152 argbackq = argbackq->next;
6153 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00006154#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006155 case CTLENDARI:
6156 p--;
Ron Yorston549deab2015-05-18 09:57:51 +02006157 expari(flags | inquotes);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006158 goto start;
6159#endif
6160 }
6161 }
Denys Vlasenko958581a2010-09-12 15:04:27 +02006162 breakloop: ;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006163}
6164
6165static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006166scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6167 char *pattern, int quotes, int zero)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006168{
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006169 char *loc, *loc2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006170 char c;
6171
6172 loc = startp;
6173 loc2 = rmesc;
6174 do {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006175 int match;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006176 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006177
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006178 c = *loc2;
6179 if (zero) {
6180 *loc2 = '\0';
6181 s = rmesc;
6182 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006183 match = pmatch(pattern, s);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006185 *loc2 = c;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006186 if (match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006188 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006189 loc++;
6190 loc++;
6191 loc2++;
6192 } while (c);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006193 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006194}
6195
6196static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006197scanright(char *startp, char *rmesc, char *rmescend,
6198 char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006199{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006200#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6201 int try2optimize = match_at_start;
6202#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006203 int esc = 0;
6204 char *loc;
6205 char *loc2;
6206
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006207 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6208 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6209 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6210 * Logic:
6211 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6212 * and on each iteration they go back two/one char until they reach the beginning.
6213 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6214 */
6215 /* TODO: document in what other circumstances we are called. */
6216
6217 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006218 int match;
6219 char c = *loc2;
6220 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006221 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006222 *loc2 = '\0';
6223 s = rmesc;
6224 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006225 match = pmatch(pattern, s);
6226 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006227 *loc2 = c;
6228 if (match)
6229 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006230#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6231 if (try2optimize) {
6232 /* Maybe we can optimize this:
6233 * if pattern ends with unescaped *, we can avoid checking
6234 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6235 * it wont match truncated "raw_value_of_" strings too.
6236 */
6237 unsigned plen = strlen(pattern);
6238 /* Does it end with "*"? */
6239 if (plen != 0 && pattern[--plen] == '*') {
6240 /* "xxxx*" is not escaped */
6241 /* "xxx\*" is escaped */
6242 /* "xx\\*" is not escaped */
6243 /* "x\\\*" is escaped */
6244 int slashes = 0;
6245 while (plen != 0 && pattern[--plen] == '\\')
6246 slashes++;
6247 if (!(slashes & 1))
6248 break; /* ends with unescaped "*" */
6249 }
6250 try2optimize = 0;
6251 }
6252#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006253 loc--;
6254 if (quotes) {
6255 if (--esc < 0) {
6256 esc = esclen(startp, loc);
6257 }
6258 if (esc % 2) {
6259 esc--;
6260 loc--;
6261 }
6262 }
6263 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006264 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006265}
6266
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006267static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006268static void
6269varunset(const char *end, const char *var, const char *umsg, int varflags)
6270{
6271 const char *msg;
6272 const char *tail;
6273
6274 tail = nullstr;
6275 msg = "parameter not set";
6276 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006277 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006278 if (varflags & VSNUL)
6279 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006280 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006281 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006282 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006283 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006284 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006285}
6286
6287static const char *
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006288subevalvar(char *p, char *varname, int strloc, int subtype,
Ron Yorston549deab2015-05-18 09:57:51 +02006289 int startloc, int varflags, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006290{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006291 struct nodelist *saveargbackq = argbackq;
Ron Yorston549deab2015-05-18 09:57:51 +02006292 int quotes = flag & QUOTES_ESC;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006293 char *startp;
6294 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006295 char *rmesc, *rmescend;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006296 char *str;
Ron Yorston417622c2015-05-18 09:59:14 +02006297 IF_ASH_BASH_COMPAT(char *repl = NULL;)
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006298 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006299 int saveherefd = herefd;
Denys Vlasenko0b4980c2012-09-25 12:49:29 +02006300 int amount, resetloc;
6301 IF_ASH_BASH_COMPAT(int workloc;)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006302 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006303 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006304
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006305 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6306 // p, varname, strloc, subtype, startloc, varflags, quotes);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006307
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006308 herefd = -1;
Ron Yorstoneb6b48b2015-05-18 09:51:35 +02006309 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
Ron Yorston549deab2015-05-18 09:57:51 +02006310 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6311 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006312 STPUTC('\0', expdest);
6313 herefd = saveherefd;
6314 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006315 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006316
6317 switch (subtype) {
6318 case VSASSIGN:
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02006319 setvar0(varname, startp);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006320 amount = startp - expdest;
6321 STADJUST(amount, expdest);
6322 return startp;
6323
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006324 case VSQUESTION:
6325 varunset(p, varname, startp, varflags);
6326 /* NOTREACHED */
6327
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006328#if ENABLE_ASH_BASH_COMPAT
6329 case VSSUBSTR:
6330 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006331 /* Read POS in ${var:POS:LEN} */
6332 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006333 len = str - startp - 1;
6334
6335 /* *loc != '\0', guaranteed by parser */
6336 if (quotes) {
6337 char *ptr;
6338
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006339 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006340 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006341 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006342 len--;
6343 ptr++;
6344 }
6345 }
6346 }
6347 orig_len = len;
6348
6349 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006350 /* ${var::LEN} */
6351 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006352 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006353 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006354 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006355 while (*loc && *loc != ':') {
6356 /* TODO?
6357 * bash complains on: var=qwe; echo ${var:1a:123}
6358 if (!isdigit(*loc))
6359 ash_msg_and_raise_error(msg_illnum, str);
6360 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006361 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006362 }
6363 if (*loc++ == ':') {
6364 len = number(loc);
6365 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006366 }
Denys Vlasenko08a5dab2014-11-17 20:27:18 +01006367 if (pos < 0) {
6368 /* ${VAR:$((-n)):l} starts n chars from the end */
6369 pos = orig_len + pos;
6370 }
6371 if ((unsigned)pos >= orig_len) {
6372 /* apart from obvious ${VAR:999999:l},
6373 * covers ${VAR:$((-9999999)):l} - result is ""
6374 * (bash-compat)
6375 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006376 pos = 0;
6377 len = 0;
6378 }
6379 if (len > (orig_len - pos))
6380 len = orig_len - pos;
6381
6382 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006383 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006384 str++;
6385 }
6386 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006387 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006388 *loc++ = *str++;
6389 *loc++ = *str++;
6390 }
6391 *loc = '\0';
6392 amount = loc - expdest;
6393 STADJUST(amount, expdest);
6394 return loc;
6395#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006396 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006397
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006398 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006399
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006400 /* We'll comeback here if we grow the stack while handling
6401 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6402 * stack will need rebasing, and we'll need to remove our work
6403 * areas each time
6404 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006405 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006406
6407 amount = expdest - ((char *)stackblock() + resetloc);
6408 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006409 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006410
6411 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006412 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006413 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006414 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415 if (rmesc != startp) {
6416 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006417 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006418 }
6419 }
6420 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006421 str = (char *)stackblock() + strloc;
Ron Yorston417622c2015-05-18 09:59:14 +02006422 /*
6423 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6424 * The result is a_\_z_c (not a\_\_z_c)!
6425 *
6426 * The search pattern and replace string treat backslashes differently!
6427 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6428 * and string. It's only used on the first call.
6429 */
6430 preglob(str, IF_ASH_BASH_COMPAT(
6431 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6432 RMESCAPE_SLASH :) 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006433
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006434#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko0b4980c2012-09-25 12:49:29 +02006435 workloc = expdest - (char *)stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006436 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006437 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006438
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006439 if (!repl) {
Ron Yorston417622c2015-05-18 09:59:14 +02006440 if ((repl=strchr(str, CTLESC)))
6441 *repl++ = '\0';
6442 else
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006443 repl = nullstr;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006444 }
Ron Yorston417622c2015-05-18 09:59:14 +02006445 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006446
6447 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006448 if (str[0] == '\0')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006449 return NULL;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006450
6451 len = 0;
6452 idx = startp;
6453 end = str - 1;
6454 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006455 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006456 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006457 //bb_error_msg("scanright('%s'):'%s'", str, loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006458 if (!loc) {
6459 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006460 char *restart_detect = stackblock();
6461 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006462 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006463 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006464 idx++;
6465 len++;
6466 STPUTC(*idx, expdest);
6467 }
6468 if (stackblock() != restart_detect)
6469 goto restart;
6470 idx++;
6471 len++;
6472 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006473 /* continue; - prone to quadratic behavior, smarter code: */
6474 if (idx >= end)
6475 break;
6476 if (str[0] == '*') {
6477 /* Pattern is "*foo". If "*foo" does not match "long_string",
6478 * it would never match "ong_string" etc, no point in trying.
6479 */
6480 goto skip_matching;
6481 }
6482 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006483 }
6484
6485 if (subtype == VSREPLACEALL) {
6486 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006487 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006488 idx++;
6489 idx++;
6490 rmesc++;
6491 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006492 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006493 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006494 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006495
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006496 //bb_error_msg("repl:'%s'", repl);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006497 for (loc = (char*)repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006498 char *restart_detect = stackblock();
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006499 if (quotes && *loc == '\\') {
6500 STPUTC(CTLESC, expdest);
6501 len++;
6502 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006503 STPUTC(*loc, expdest);
6504 if (stackblock() != restart_detect)
6505 goto restart;
6506 len++;
6507 }
6508
6509 if (subtype == VSREPLACE) {
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006510 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006511 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006512 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006513 STPUTC(*idx, expdest);
6514 if (stackblock() != restart_detect)
6515 goto restart;
6516 len++;
6517 idx++;
6518 }
6519 break;
6520 }
6521 }
6522
6523 /* We've put the replaced text into a buffer at workloc, now
6524 * move it to the right place and adjust the stack.
6525 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006526 STPUTC('\0', expdest);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006527 startp = (char *)stackblock() + startloc;
6528 memmove(startp, (char *)stackblock() + workloc, len + 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006529 //bb_error_msg("startp:'%s'", startp);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006530 amount = expdest - (startp + len);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006531 STADJUST(-amount, expdest);
6532 return startp;
6533 }
6534#endif /* ENABLE_ASH_BASH_COMPAT */
6535
6536 subtype -= VSTRIMRIGHT;
6537#if DEBUG
6538 if (subtype < 0 || subtype > 7)
6539 abort();
6540#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006541 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006542 zero = subtype >> 1;
6543 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6544 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6545
6546 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6547 if (loc) {
6548 if (zero) {
6549 memmove(startp, loc, str - loc);
6550 loc = startp + (str - loc) - 1;
6551 }
6552 *loc = '\0';
6553 amount = loc - expdest;
6554 STADJUST(amount, expdest);
6555 }
6556 return loc;
6557}
6558
6559/*
6560 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006561 * name parameter (examples):
6562 * ash -c 'echo $1' name:'1='
6563 * ash -c 'echo $qwe' name:'qwe='
6564 * ash -c 'echo $$' name:'$='
6565 * ash -c 'echo ${$}' name:'$='
6566 * ash -c 'echo ${$##q}' name:'$=q'
6567 * ash -c 'echo ${#$}' name:'$='
6568 * note: examples with bad shell syntax:
6569 * ash -c 'echo ${#$1}' name:'$=1'
6570 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006572static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006573varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006574{
Mike Frysinger98c52642009-04-02 10:02:37 +00006575 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006576 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006577 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006578 ssize_t len = 0;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006579 int sep;
Ron Yorston549deab2015-05-18 09:57:51 +02006580 int quoted = flags & EXP_QUOTED;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006581 int subtype = varflags & VSTYPE;
6582 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6583 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006584 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006585
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006586 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6587
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006588 switch (*name) {
6589 case '$':
6590 num = rootpid;
6591 goto numvar;
6592 case '?':
6593 num = exitstatus;
6594 goto numvar;
6595 case '#':
6596 num = shellparam.nparam;
6597 goto numvar;
6598 case '!':
6599 num = backgndpid;
6600 if (num == 0)
6601 return -1;
6602 numvar:
6603 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006604 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006605 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006606 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006607 for (i = NOPTS - 1; i >= 0; i--) {
6608 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006609 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006610 len++;
6611 }
6612 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006613 check_1char_name:
6614#if 0
6615 /* handles cases similar to ${#$1} */
6616 if (name[2] != '\0')
6617 raise_error_syntax("bad substitution");
6618#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006619 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006620 case '@': {
6621 char **ap;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006622 char sepc;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006623
6624 if (quoted && (flags & EXP_FULL)) {
6625 /* note: this is not meant as PEOF value */
6626 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006627 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006628 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006629 /* fall through */
6630 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006631 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006632 param:
6633 ap = shellparam.p;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006634 sepc = sep;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006635 if (!ap)
6636 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006637 while ((p = *ap++) != NULL) {
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006638 len += strtodest(p, syntax, quotes);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006639
6640 if (*ap && sep) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006641 len++;
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006642 memtodest(&sepc, 1, syntax, quotes);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 }
6644 }
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006645 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006646 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006647 case '0':
6648 case '1':
6649 case '2':
6650 case '3':
6651 case '4':
6652 case '5':
6653 case '6':
6654 case '7':
6655 case '8':
6656 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006657 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006658 if (num < 0 || num > shellparam.nparam)
6659 return -1;
6660 p = num ? shellparam.p[num - 1] : arg0;
6661 goto value;
6662 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006663 /* NB: name has form "VAR=..." */
6664
6665 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6666 * which should be considered before we check variables. */
6667 if (var_str_list) {
6668 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6669 p = NULL;
6670 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006671 char *str, *eq;
6672 str = var_str_list->text;
6673 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006674 if (!eq) /* stop at first non-assignment */
6675 break;
6676 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006677 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006678 && strncmp(str, name, name_len) == 0
6679 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006680 p = eq;
6681 /* goto value; - WRONG! */
6682 /* think "A=1 A=2 B=$A" */
6683 }
6684 var_str_list = var_str_list->next;
6685 } while (var_str_list);
6686 if (p)
6687 goto value;
6688 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006689 p = lookupvar(name);
6690 value:
6691 if (!p)
6692 return -1;
6693
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006694 len = strtodest(p, syntax, quotes);
Denys Vlasenkoc76236f2014-12-29 00:04:18 +01006695#if ENABLE_UNICODE_SUPPORT
6696 if (subtype == VSLENGTH && len > 0) {
6697 reinit_unicode_for_ash();
6698 if (unicode_status == UNICODE_ON) {
6699 len = unicode_strlen(p);
6700 }
6701 }
6702#endif
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006703 break;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006704 }
6705
Ron Yorstond68d1fb2015-05-18 09:49:28 +02006706 if (discard)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006707 STADJUST(-len, expdest);
6708 return len;
6709}
6710
6711/*
6712 * Expand a variable, and return a pointer to the next character in the
6713 * input string.
6714 */
6715static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006716evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006717{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006718 char varflags;
6719 char subtype;
Ron Yorston549deab2015-05-18 09:57:51 +02006720 int quoted;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006721 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006722 char *var;
6723 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006724 int startloc;
6725 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006726
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006727 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006728 subtype = varflags & VSTYPE;
Ron Yorston549deab2015-05-18 09:57:51 +02006729 quoted = flags & EXP_QUOTED;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006730 var = p;
6731 easy = (!quoted || (*var == '@' && shellparam.nparam));
6732 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006733 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006734
6735 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006736 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006737 if (varflags & VSNUL)
6738 varlen--;
6739
6740 if (subtype == VSPLUS) {
6741 varlen = -1 - varlen;
6742 goto vsplus;
6743 }
6744
6745 if (subtype == VSMINUS) {
6746 vsplus:
6747 if (varlen < 0) {
6748 argstr(
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006749 p,
Ron Yorston549deab2015-05-18 09:57:51 +02006750 flags | EXP_TILDE | EXP_WORD,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006751 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006752 );
6753 goto end;
6754 }
6755 if (easy)
6756 goto record;
6757 goto end;
6758 }
6759
6760 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6761 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006762 if (subevalvar(p, var, /* strloc: */ 0,
6763 subtype, startloc, varflags,
Ron Yorston549deab2015-05-18 09:57:51 +02006764 /* quotes: */ flags & ~QUOTES_ESC,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006765 var_str_list)
6766 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006767 varflags &= ~VSNUL;
6768 /*
6769 * Remove any recorded regions beyond
6770 * start of variable
6771 */
6772 removerecordregions(startloc);
6773 goto again;
6774 }
6775 goto end;
6776 }
6777 if (easy)
6778 goto record;
6779 goto end;
6780 }
6781
6782 if (varlen < 0 && uflag)
6783 varunset(p, var, 0, 0);
6784
6785 if (subtype == VSLENGTH) {
Denys Vlasenkoc76236f2014-12-29 00:04:18 +01006786 cvtnum(varlen > 0 ? varlen : 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006787 goto record;
6788 }
6789
6790 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006791 if (easy)
6792 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006793 goto end;
6794 }
6795
6796#if DEBUG
6797 switch (subtype) {
6798 case VSTRIMLEFT:
6799 case VSTRIMLEFTMAX:
6800 case VSTRIMRIGHT:
6801 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006802#if ENABLE_ASH_BASH_COMPAT
6803 case VSSUBSTR:
6804 case VSREPLACE:
6805 case VSREPLACEALL:
6806#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006807 break;
6808 default:
6809 abort();
6810 }
6811#endif
6812
6813 if (varlen >= 0) {
6814 /*
6815 * Terminate the string and start recording the pattern
6816 * right after it
6817 */
6818 STPUTC('\0', expdest);
6819 patloc = expdest - (char *)stackblock();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006820 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
Ron Yorston549deab2015-05-18 09:57:51 +02006821 startloc, varflags, flags, var_str_list)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006822 int amount = expdest - (
6823 (char *)stackblock() + patloc - 1
6824 );
6825 STADJUST(-amount, expdest);
6826 }
6827 /* Remove any recorded regions beyond start of variable */
6828 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006829 record:
6830 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006831 }
6832
6833 end:
6834 if (subtype != VSNORMAL) { /* skip to end of alternative */
6835 int nesting = 1;
6836 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006837 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006838 if (c == CTLESC)
6839 p++;
Ron Yorston549deab2015-05-18 09:57:51 +02006840 else if (c == CTLBACKQ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006841 if (varlen >= 0)
6842 argbackq = argbackq->next;
6843 } else if (c == CTLVAR) {
6844 if ((*p++ & VSTYPE) != VSNORMAL)
6845 nesting++;
6846 } else if (c == CTLENDVAR) {
6847 if (--nesting == 0)
6848 break;
6849 }
6850 }
6851 }
6852 return p;
6853}
6854
6855/*
6856 * Break the argument string into pieces based upon IFS and add the
6857 * strings to the argument list. The regions of the string to be
6858 * searched for IFS characters have been stored by recordregion.
6859 */
6860static void
6861ifsbreakup(char *string, struct arglist *arglist)
6862{
6863 struct ifsregion *ifsp;
6864 struct strlist *sp;
6865 char *start;
6866 char *p;
6867 char *q;
6868 const char *ifs, *realifs;
6869 int ifsspc;
6870 int nulonly;
6871
6872 start = string;
6873 if (ifslastp != NULL) {
6874 ifsspc = 0;
6875 nulonly = 0;
6876 realifs = ifsset() ? ifsval() : defifs;
6877 ifsp = &ifsfirst;
6878 do {
6879 p = string + ifsp->begoff;
6880 nulonly = ifsp->nulonly;
6881 ifs = nulonly ? nullstr : realifs;
6882 ifsspc = 0;
6883 while (p < string + ifsp->endoff) {
6884 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006885 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006886 p++;
6887 if (!strchr(ifs, *p)) {
6888 p++;
6889 continue;
6890 }
6891 if (!nulonly)
6892 ifsspc = (strchr(defifs, *p) != NULL);
6893 /* Ignore IFS whitespace at start */
6894 if (q == start && ifsspc) {
6895 p++;
6896 start = p;
6897 continue;
6898 }
6899 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006900 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901 sp->text = start;
6902 *arglist->lastp = sp;
6903 arglist->lastp = &sp->next;
6904 p++;
6905 if (!nulonly) {
6906 for (;;) {
6907 if (p >= string + ifsp->endoff) {
6908 break;
6909 }
6910 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006911 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006912 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006913 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006914 p = q;
6915 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006916 }
6917 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006918 if (ifsspc) {
6919 p++;
6920 ifsspc = 0;
6921 } else {
6922 p = q;
6923 break;
6924 }
6925 } else
6926 p++;
6927 }
6928 }
6929 start = p;
6930 } /* while */
6931 ifsp = ifsp->next;
6932 } while (ifsp != NULL);
6933 if (nulonly)
6934 goto add;
6935 }
6936
6937 if (!*start)
6938 return;
6939
6940 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006941 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006942 sp->text = start;
6943 *arglist->lastp = sp;
6944 arglist->lastp = &sp->next;
6945}
6946
6947static void
6948ifsfree(void)
6949{
6950 struct ifsregion *p;
6951
6952 INT_OFF;
6953 p = ifsfirst.next;
6954 do {
6955 struct ifsregion *ifsp;
6956 ifsp = p->next;
6957 free(p);
6958 p = ifsp;
6959 } while (p);
6960 ifslastp = NULL;
6961 ifsfirst.next = NULL;
6962 INT_ON;
6963}
6964
6965/*
6966 * Add a file name to the list.
6967 */
6968static void
6969addfname(const char *name)
6970{
6971 struct strlist *sp;
6972
Denis Vlasenko597906c2008-02-20 16:38:54 +00006973 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006974 sp->text = ststrdup(name);
6975 *exparg.lastp = sp;
6976 exparg.lastp = &sp->next;
6977}
6978
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006979/*
6980 * Do metacharacter (i.e. *, ?, [...]) expansion.
6981 */
6982static void
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006983expmeta(char *expdir, char *enddir, char *name)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006984{
6985 char *p;
6986 const char *cp;
6987 char *start;
6988 char *endname;
6989 int metaflag;
6990 struct stat statb;
6991 DIR *dirp;
6992 struct dirent *dp;
6993 int atend;
6994 int matchdot;
Ron Yorstonca25af92015-09-04 10:32:41 +01006995 int esc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006996
6997 metaflag = 0;
6998 start = name;
Ron Yorstonca25af92015-09-04 10:32:41 +01006999 for (p = name; esc = 0, *p; p += esc + 1) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007000 if (*p == '*' || *p == '?')
7001 metaflag = 1;
7002 else if (*p == '[') {
7003 char *q = p + 1;
7004 if (*q == '!')
7005 q++;
7006 for (;;) {
7007 if (*q == '\\')
7008 q++;
7009 if (*q == '/' || *q == '\0')
7010 break;
7011 if (*++q == ']') {
7012 metaflag = 1;
7013 break;
7014 }
7015 }
Ron Yorstonca25af92015-09-04 10:32:41 +01007016 } else {
7017 if (*p == '\\')
7018 esc++;
7019 if (p[esc] == '/') {
7020 if (metaflag)
7021 break;
7022 start = p + esc + 1;
7023 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007024 }
7025 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007026 if (metaflag == 0) { /* we've reached the end of the file name */
7027 if (enddir != expdir)
7028 metaflag++;
7029 p = name;
7030 do {
7031 if (*p == '\\')
7032 p++;
7033 *enddir++ = *p;
7034 } while (*p++);
7035 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7036 addfname(expdir);
7037 return;
7038 }
7039 endname = p;
7040 if (name < start) {
7041 p = name;
7042 do {
7043 if (*p == '\\')
7044 p++;
7045 *enddir++ = *p++;
7046 } while (p < start);
7047 }
7048 if (enddir == expdir) {
7049 cp = ".";
7050 } else if (enddir == expdir + 1 && *expdir == '/') {
7051 cp = "/";
7052 } else {
7053 cp = expdir;
7054 enddir[-1] = '\0';
7055 }
7056 dirp = opendir(cp);
7057 if (dirp == NULL)
7058 return;
7059 if (enddir != expdir)
7060 enddir[-1] = '/';
7061 if (*endname == 0) {
7062 atend = 1;
7063 } else {
7064 atend = 0;
Ron Yorstonca25af92015-09-04 10:32:41 +01007065 *endname = '\0';
7066 endname += esc + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007067 }
7068 matchdot = 0;
7069 p = start;
7070 if (*p == '\\')
7071 p++;
7072 if (*p == '.')
7073 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007074 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007075 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007076 continue;
7077 if (pmatch(start, dp->d_name)) {
7078 if (atend) {
7079 strcpy(enddir, dp->d_name);
7080 addfname(expdir);
7081 } else {
7082 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7083 continue;
7084 p[-1] = '/';
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007085 expmeta(expdir, p, endname);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007086 }
7087 }
7088 }
7089 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007090 if (!atend)
Ron Yorstonca25af92015-09-04 10:32:41 +01007091 endname[-esc - 1] = esc ? '\\' : '/';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007092}
7093
7094static struct strlist *
7095msort(struct strlist *list, int len)
7096{
7097 struct strlist *p, *q = NULL;
7098 struct strlist **lpp;
7099 int half;
7100 int n;
7101
7102 if (len <= 1)
7103 return list;
7104 half = len >> 1;
7105 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007106 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007107 q = p;
7108 p = p->next;
7109 }
7110 q->next = NULL; /* terminate first half of list */
7111 q = msort(list, half); /* sort first half of list */
7112 p = msort(p, len - half); /* sort second half */
7113 lpp = &list;
7114 for (;;) {
7115#if ENABLE_LOCALE_SUPPORT
7116 if (strcoll(p->text, q->text) < 0)
7117#else
7118 if (strcmp(p->text, q->text) < 0)
7119#endif
7120 {
7121 *lpp = p;
7122 lpp = &p->next;
7123 p = *lpp;
7124 if (p == NULL) {
7125 *lpp = q;
7126 break;
7127 }
7128 } else {
7129 *lpp = q;
7130 lpp = &q->next;
7131 q = *lpp;
7132 if (q == NULL) {
7133 *lpp = p;
7134 break;
7135 }
7136 }
7137 }
7138 return list;
7139}
7140
7141/*
7142 * Sort the results of file name expansion. It calculates the number of
7143 * strings to sort and then calls msort (short for merge sort) to do the
7144 * work.
7145 */
7146static struct strlist *
7147expsort(struct strlist *str)
7148{
7149 int len;
7150 struct strlist *sp;
7151
7152 len = 0;
7153 for (sp = str; sp; sp = sp->next)
7154 len++;
7155 return msort(str, len);
7156}
7157
7158static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007159expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007160{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007161 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007162 '*', '?', '[', 0
7163 };
7164 /* TODO - EXP_REDIR */
7165
7166 while (str) {
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007167 char *expdir;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007168 struct strlist **savelastp;
7169 struct strlist *sp;
7170 char *p;
7171
7172 if (fflag)
7173 goto nometa;
7174 if (!strpbrk(str->text, metachars))
7175 goto nometa;
7176 savelastp = exparg.lastp;
7177
7178 INT_OFF;
Ron Yorston549deab2015-05-18 09:57:51 +02007179 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007180 {
7181 int i = strlen(str->text);
7182 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7183 }
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007184 expmeta(expdir, expdir, p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007185 free(expdir);
7186 if (p != str->text)
7187 free(p);
7188 INT_ON;
7189 if (exparg.lastp == savelastp) {
7190 /*
7191 * no matches
7192 */
7193 nometa:
7194 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007195 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007196 exparg.lastp = &str->next;
7197 } else {
7198 *exparg.lastp = NULL;
7199 *savelastp = sp = expsort(*savelastp);
7200 while (sp->next != NULL)
7201 sp = sp->next;
7202 exparg.lastp = &sp->next;
7203 }
7204 str = str->next;
7205 }
7206}
7207
7208/*
7209 * Perform variable substitution and command substitution on an argument,
7210 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7211 * perform splitting and file name expansion. When arglist is NULL, perform
7212 * here document expansion.
7213 */
7214static void
7215expandarg(union node *arg, struct arglist *arglist, int flag)
7216{
7217 struct strlist *sp;
7218 char *p;
7219
7220 argbackq = arg->narg.backquote;
7221 STARTSTACKSTR(expdest);
7222 ifsfirst.next = NULL;
7223 ifslastp = NULL;
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02007224 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007225 argstr(arg->narg.text, flag,
7226 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007227 p = _STPUTC('\0', expdest);
7228 expdest = p - 1;
7229 if (arglist == NULL) {
7230 return; /* here document expanded */
7231 }
7232 p = grabstackstr(p);
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02007233 TRACE(("expandarg: p:'%s'\n", p));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007234 exparg.lastp = &exparg.list;
7235 /*
7236 * TODO - EXP_REDIR
7237 */
7238 if (flag & EXP_FULL) {
7239 ifsbreakup(p, &exparg);
7240 *exparg.lastp = NULL;
7241 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007242 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007243 } else {
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02007244 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007245 rmescapes(p, 0);
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02007246 TRACE(("expandarg: rmescapes:'%s'\n", p));
7247 }
Denis Vlasenko597906c2008-02-20 16:38:54 +00007248 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007249 sp->text = p;
7250 *exparg.lastp = sp;
7251 exparg.lastp = &sp->next;
7252 }
7253 if (ifsfirst.next)
7254 ifsfree();
7255 *exparg.lastp = NULL;
7256 if (exparg.list) {
7257 *arglist->lastp = exparg.list;
7258 arglist->lastp = exparg.lastp;
7259 }
7260}
7261
7262/*
7263 * Expand shell variables and backquotes inside a here document.
7264 */
7265static void
7266expandhere(union node *arg, int fd)
7267{
7268 herefd = fd;
Ron Yorston549deab2015-05-18 09:57:51 +02007269 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007270 full_write(fd, stackblock(), expdest - (char *)stackblock());
7271}
7272
7273/*
7274 * Returns true if the pattern matches the string.
7275 */
7276static int
7277patmatch(char *pattern, const char *string)
7278{
Ron Yorston549deab2015-05-18 09:57:51 +02007279 return pmatch(preglob(pattern, 0), string);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007280}
7281
7282/*
7283 * See if a pattern matches in a case statement.
7284 */
7285static int
7286casematch(union node *pattern, char *val)
7287{
7288 struct stackmark smark;
7289 int result;
7290
7291 setstackmark(&smark);
7292 argbackq = pattern->narg.backquote;
7293 STARTSTACKSTR(expdest);
7294 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007295 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7296 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007297 STACKSTRNUL(expdest);
7298 result = patmatch(stackblock(), val);
7299 popstackmark(&smark);
7300 return result;
7301}
7302
7303
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007304/* ============ find_command */
7305
7306struct builtincmd {
7307 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007308 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007309 /* unsigned flags; */
7310};
7311#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007312/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007313 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007314#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007315#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007316
7317struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007318 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007319 union param {
7320 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007321 /* index >= 0 for commands without path (slashes) */
7322 /* (TODO: what exactly does the value mean? PATH position?) */
7323 /* index == -1 for commands with slashes */
7324 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007325 const struct builtincmd *cmd;
7326 struct funcnode *func;
7327 } u;
7328};
7329/* values of cmdtype */
7330#define CMDUNKNOWN -1 /* no entry in table for command */
7331#define CMDNORMAL 0 /* command is an executable program */
7332#define CMDFUNCTION 1 /* command is a shell function */
7333#define CMDBUILTIN 2 /* command is a shell builtin */
7334
7335/* action to find_command() */
7336#define DO_ERR 0x01 /* prints errors */
7337#define DO_ABS 0x02 /* checks absolute paths */
7338#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7339#define DO_ALTPATH 0x08 /* using alternate path */
7340#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7341
7342static void find_command(char *, struct cmdentry *, int, const char *);
7343
7344
7345/* ============ Hashing commands */
7346
7347/*
7348 * When commands are first encountered, they are entered in a hash table.
7349 * This ensures that a full path search will not have to be done for them
7350 * on each invocation.
7351 *
7352 * We should investigate converting to a linear search, even though that
7353 * would make the command name "hash" a misnomer.
7354 */
7355
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007356struct tblentry {
7357 struct tblentry *next; /* next entry in hash chain */
7358 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007359 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007360 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007361 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007362};
7363
Denis Vlasenko01631112007-12-16 17:20:38 +00007364static struct tblentry **cmdtable;
7365#define INIT_G_cmdtable() do { \
7366 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7367} while (0)
7368
7369static int builtinloc = -1; /* index in path of %builtin, or -1 */
7370
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007371
7372static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007373tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007374{
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007375#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007376 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007377 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007378 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007379 while (*envp)
7380 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007381 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007382 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007383 /* re-exec ourselves with the new arguments */
7384 execve(bb_busybox_exec_path, argv, envp);
7385 /* If they called chroot or otherwise made the binary no longer
7386 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007387 }
7388#endif
7389
7390 repeat:
7391#ifdef SYSV
7392 do {
7393 execve(cmd, argv, envp);
7394 } while (errno == EINTR);
7395#else
7396 execve(cmd, argv, envp);
7397#endif
Denys Vlasenkoaefe1c22011-03-07 12:02:40 +01007398 if (cmd == (char*) bb_busybox_exec_path) {
7399 /* We already visited ENOEXEC branch below, don't do it again */
7400//TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007401 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007402 return;
7403 }
7404 if (errno == ENOEXEC) {
Denys Vlasenkoaefe1c22011-03-07 12:02:40 +01007405 /* Run "cmd" as a shell script:
7406 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7407 * "If the execve() function fails with ENOEXEC, the shell
7408 * shall execute a command equivalent to having a shell invoked
7409 * with the command name as its first operand,
7410 * with any remaining arguments passed to the new shell"
7411 *
7412 * That is, do not use $SHELL, user's shell, or /bin/sh;
7413 * just call ourselves.
Denys Vlasenko2bef5262011-12-16 00:25:17 +01007414 *
7415 * Note that bash reads ~80 chars of the file, and if it sees
7416 * a zero byte before it sees newline, it doesn't try to
7417 * interpret it, but fails with "cannot execute binary file"
Denys Vlasenkocda6ea92011-12-16 00:44:36 +01007418 * message and exit code 126. For one, this prevents attempts
7419 * to interpret foreign ELF binaries as shell scripts.
Denys Vlasenkoaefe1c22011-03-07 12:02:40 +01007420 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007421 char **ap;
7422 char **new;
7423
7424 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007425 continue;
Denys Vlasenkoaefe1c22011-03-07 12:02:40 +01007426 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7427 new[0] = (char*) "ash";
7428 new[1] = cmd;
7429 ap = new + 2;
7430 while ((*ap++ = *++argv) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007431 continue;
Denys Vlasenkoaefe1c22011-03-07 12:02:40 +01007432 cmd = (char*) bb_busybox_exec_path;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007433 argv = new;
7434 goto repeat;
7435 }
7436}
7437
7438/*
7439 * Exec a program. Never returns. If you change this routine, you may
7440 * have to change the find_command routine as well.
7441 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007442static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007443static void
7444shellexec(char **argv, const char *path, int idx)
7445{
7446 char *cmdname;
7447 int e;
7448 char **envp;
7449 int exerrno;
Denys Vlasenko83f103b2011-12-20 06:10:35 +01007450 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007451
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007452 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007453 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007454 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007455#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007456 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007457#endif
7458 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007459 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denys Vlasenko83f103b2011-12-20 06:10:35 +01007460 if (applet_no >= 0) {
7461 /* We tried execing ourself, but it didn't work.
7462 * Maybe /proc/self/exe doesn't exist?
7463 * Try $PATH search.
7464 */
7465 goto try_PATH;
7466 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007467 e = errno;
7468 } else {
Denys Vlasenko83f103b2011-12-20 06:10:35 +01007469 try_PATH:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007470 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007471 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007472 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007473 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007474 if (errno != ENOENT && errno != ENOTDIR)
7475 e = errno;
7476 }
7477 stunalloc(cmdname);
7478 }
7479 }
7480
7481 /* Map to POSIX errors */
7482 switch (e) {
7483 case EACCES:
7484 exerrno = 126;
7485 break;
7486 case ENOENT:
7487 exerrno = 127;
7488 break;
7489 default:
7490 exerrno = 2;
7491 break;
7492 }
7493 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007494 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7495 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007496 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7497 /* NOTREACHED */
7498}
7499
7500static void
7501printentry(struct tblentry *cmdp)
7502{
7503 int idx;
7504 const char *path;
7505 char *name;
7506
7507 idx = cmdp->param.index;
7508 path = pathval();
7509 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007510 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007511 stunalloc(name);
7512 } while (--idx >= 0);
7513 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7514}
7515
7516/*
7517 * Clear out command entries. The argument specifies the first entry in
7518 * PATH which has changed.
7519 */
7520static void
7521clearcmdentry(int firstchange)
7522{
7523 struct tblentry **tblp;
7524 struct tblentry **pp;
7525 struct tblentry *cmdp;
7526
7527 INT_OFF;
7528 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7529 pp = tblp;
7530 while ((cmdp = *pp) != NULL) {
7531 if ((cmdp->cmdtype == CMDNORMAL &&
7532 cmdp->param.index >= firstchange)
7533 || (cmdp->cmdtype == CMDBUILTIN &&
7534 builtinloc >= firstchange)
7535 ) {
7536 *pp = cmdp->next;
7537 free(cmdp);
7538 } else {
7539 pp = &cmdp->next;
7540 }
7541 }
7542 }
7543 INT_ON;
7544}
7545
7546/*
7547 * Locate a command in the command hash table. If "add" is nonzero,
7548 * add the command to the table if it is not already present. The
7549 * variable "lastcmdentry" is set to point to the address of the link
7550 * pointing to the entry, so that delete_cmd_entry can delete the
7551 * entry.
7552 *
7553 * Interrupts must be off if called with add != 0.
7554 */
7555static struct tblentry **lastcmdentry;
7556
7557static struct tblentry *
7558cmdlookup(const char *name, int add)
7559{
7560 unsigned int hashval;
7561 const char *p;
7562 struct tblentry *cmdp;
7563 struct tblentry **pp;
7564
7565 p = name;
7566 hashval = (unsigned char)*p << 4;
7567 while (*p)
7568 hashval += (unsigned char)*p++;
7569 hashval &= 0x7FFF;
7570 pp = &cmdtable[hashval % CMDTABLESIZE];
7571 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7572 if (strcmp(cmdp->cmdname, name) == 0)
7573 break;
7574 pp = &cmdp->next;
7575 }
7576 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007577 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7578 + strlen(name)
7579 /* + 1 - already done because
7580 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007581 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007582 cmdp->cmdtype = CMDUNKNOWN;
7583 strcpy(cmdp->cmdname, name);
7584 }
7585 lastcmdentry = pp;
7586 return cmdp;
7587}
7588
7589/*
7590 * Delete the command entry returned on the last lookup.
7591 */
7592static void
7593delete_cmd_entry(void)
7594{
7595 struct tblentry *cmdp;
7596
7597 INT_OFF;
7598 cmdp = *lastcmdentry;
7599 *lastcmdentry = cmdp->next;
7600 if (cmdp->cmdtype == CMDFUNCTION)
7601 freefunc(cmdp->param.func);
7602 free(cmdp);
7603 INT_ON;
7604}
7605
7606/*
7607 * Add a new command entry, replacing any existing command entry for
7608 * the same name - except special builtins.
7609 */
7610static void
7611addcmdentry(char *name, struct cmdentry *entry)
7612{
7613 struct tblentry *cmdp;
7614
7615 cmdp = cmdlookup(name, 1);
7616 if (cmdp->cmdtype == CMDFUNCTION) {
7617 freefunc(cmdp->param.func);
7618 }
7619 cmdp->cmdtype = entry->cmdtype;
7620 cmdp->param = entry->u;
7621 cmdp->rehash = 0;
7622}
7623
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007624static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007625hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007626{
7627 struct tblentry **pp;
7628 struct tblentry *cmdp;
7629 int c;
7630 struct cmdentry entry;
7631 char *name;
7632
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007633 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634 clearcmdentry(0);
7635 return 0;
7636 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007637
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007638 if (*argptr == NULL) {
7639 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7640 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7641 if (cmdp->cmdtype == CMDNORMAL)
7642 printentry(cmdp);
7643 }
7644 }
7645 return 0;
7646 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007647
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007648 c = 0;
7649 while ((name = *argptr) != NULL) {
7650 cmdp = cmdlookup(name, 0);
7651 if (cmdp != NULL
7652 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007653 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7654 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007656 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657 find_command(name, &entry, DO_ERR, pathval());
7658 if (entry.cmdtype == CMDUNKNOWN)
7659 c = 1;
7660 argptr++;
7661 }
7662 return c;
7663}
7664
7665/*
7666 * Called when a cd is done. Marks all commands so the next time they
7667 * are executed they will be rehashed.
7668 */
7669static void
7670hashcd(void)
7671{
7672 struct tblentry **pp;
7673 struct tblentry *cmdp;
7674
7675 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7676 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007677 if (cmdp->cmdtype == CMDNORMAL
7678 || (cmdp->cmdtype == CMDBUILTIN
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02007679 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007680 && builtinloc > 0)
7681 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007682 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007683 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007684 }
7685 }
7686}
7687
7688/*
7689 * Fix command hash table when PATH changed.
7690 * Called before PATH is changed. The argument is the new value of PATH;
7691 * pathval() still returns the old value at this point.
7692 * Called with interrupts off.
7693 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007694static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007695changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007696{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007697 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007698 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007699 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007700 int idx_bltin;
7701
7702 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007703 firstchange = 9999; /* assume no change */
7704 idx = 0;
7705 idx_bltin = -1;
7706 for (;;) {
7707 if (*old != *new) {
7708 firstchange = idx;
7709 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007710 || (*old == ':' && *new == '\0')
7711 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007712 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007713 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007714 old = new; /* ignore subsequent differences */
7715 }
7716 if (*new == '\0')
7717 break;
7718 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7719 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007720 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007721 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007722 new++;
7723 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007724 }
7725 if (builtinloc < 0 && idx_bltin >= 0)
7726 builtinloc = idx_bltin; /* zap builtins */
7727 if (builtinloc >= 0 && idx_bltin < 0)
7728 firstchange = 0;
7729 clearcmdentry(firstchange);
7730 builtinloc = idx_bltin;
7731}
7732
7733#define TEOF 0
7734#define TNL 1
7735#define TREDIR 2
7736#define TWORD 3
7737#define TSEMI 4
7738#define TBACKGND 5
7739#define TAND 6
7740#define TOR 7
7741#define TPIPE 8
7742#define TLP 9
7743#define TRP 10
7744#define TENDCASE 11
7745#define TENDBQUOTE 12
7746#define TNOT 13
7747#define TCASE 14
7748#define TDO 15
7749#define TDONE 16
7750#define TELIF 17
7751#define TELSE 18
7752#define TESAC 19
7753#define TFI 20
7754#define TFOR 21
7755#define TIF 22
7756#define TIN 23
7757#define TTHEN 24
7758#define TUNTIL 25
7759#define TWHILE 26
7760#define TBEGIN 27
7761#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007762typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007763
7764/* first char is indicating which tokens mark the end of a list */
7765static const char *const tokname_array[] = {
7766 "\1end of file",
7767 "\0newline",
7768 "\0redirection",
7769 "\0word",
7770 "\0;",
7771 "\0&",
7772 "\0&&",
7773 "\0||",
7774 "\0|",
7775 "\0(",
7776 "\1)",
7777 "\1;;",
7778 "\1`",
7779#define KWDOFFSET 13
7780 /* the following are keywords */
7781 "\0!",
7782 "\0case",
7783 "\1do",
7784 "\1done",
7785 "\1elif",
7786 "\1else",
7787 "\1esac",
7788 "\1fi",
7789 "\0for",
7790 "\0if",
7791 "\0in",
7792 "\1then",
7793 "\0until",
7794 "\0while",
7795 "\0{",
7796 "\1}",
7797};
7798
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007799/* Wrapper around strcmp for qsort/bsearch/... */
7800static int
7801pstrcmp(const void *a, const void *b)
7802{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007803 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007804}
7805
7806static const char *const *
7807findkwd(const char *s)
7808{
7809 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007810 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7811 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007812}
7813
7814/*
7815 * Locate and print what a word is...
7816 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007817static int
7818describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007819{
7820 struct cmdentry entry;
7821 struct tblentry *cmdp;
7822#if ENABLE_ASH_ALIAS
7823 const struct alias *ap;
7824#endif
7825 const char *path = pathval();
7826
7827 if (describe_command_verbose) {
7828 out1str(command);
7829 }
7830
7831 /* First look at the keywords */
7832 if (findkwd(command)) {
7833 out1str(describe_command_verbose ? " is a shell keyword" : command);
7834 goto out;
7835 }
7836
7837#if ENABLE_ASH_ALIAS
7838 /* Then look at the aliases */
7839 ap = lookupalias(command, 0);
7840 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007841 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007842 out1str("alias ");
7843 printalias(ap);
7844 return 0;
7845 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007846 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007847 goto out;
7848 }
7849#endif
7850 /* Then check if it is a tracked alias */
7851 cmdp = cmdlookup(command, 0);
7852 if (cmdp != NULL) {
7853 entry.cmdtype = cmdp->cmdtype;
7854 entry.u = cmdp->param;
7855 } else {
7856 /* Finally use brute force */
7857 find_command(command, &entry, DO_ABS, path);
7858 }
7859
7860 switch (entry.cmdtype) {
7861 case CMDNORMAL: {
7862 int j = entry.u.index;
7863 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007864 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007865 p = command;
7866 } else {
7867 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007868 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007869 stunalloc(p);
7870 } while (--j >= 0);
7871 }
7872 if (describe_command_verbose) {
7873 out1fmt(" is%s %s",
7874 (cmdp ? " a tracked alias for" : nullstr), p
7875 );
7876 } else {
7877 out1str(p);
7878 }
7879 break;
7880 }
7881
7882 case CMDFUNCTION:
7883 if (describe_command_verbose) {
7884 out1str(" is a shell function");
7885 } else {
7886 out1str(command);
7887 }
7888 break;
7889
7890 case CMDBUILTIN:
7891 if (describe_command_verbose) {
7892 out1fmt(" is a %sshell builtin",
7893 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7894 "special " : nullstr
7895 );
7896 } else {
7897 out1str(command);
7898 }
7899 break;
7900
7901 default:
7902 if (describe_command_verbose) {
7903 out1str(": not found\n");
7904 }
7905 return 127;
7906 }
7907 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007908 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007909 return 0;
7910}
7911
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007912static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007913typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007914{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007915 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007916 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007917 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007918
Denis Vlasenko46846e22007-05-20 13:08:31 +00007919 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007920 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007921 i++;
7922 verbose = 0;
7923 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007924 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007925 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007926 }
7927 return err;
7928}
7929
7930#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007931static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007932commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007933{
7934 int c;
7935 enum {
7936 VERIFY_BRIEF = 1,
7937 VERIFY_VERBOSE = 2,
7938 } verify = 0;
7939
7940 while ((c = nextopt("pvV")) != '\0')
7941 if (c == 'V')
7942 verify |= VERIFY_VERBOSE;
7943 else if (c == 'v')
7944 verify |= VERIFY_BRIEF;
7945#if DEBUG
7946 else if (c != 'p')
7947 abort();
7948#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007949 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7950 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007951 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007952 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007953
7954 return 0;
7955}
7956#endif
7957
7958
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007959/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007960
Denis Vlasenko340299a2008-11-21 10:36:36 +00007961static int funcblocksize; /* size of structures in function */
7962static int funcstringsize; /* size of strings in node */
7963static void *funcblock; /* block to allocate function from */
7964static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007965
Eric Andersencb57d552001-06-28 07:25:16 +00007966/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007967#define EV_EXIT 01 /* exit after evaluating tree */
7968#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007969#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007970
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007971static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007972 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7973 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7974 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7975 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7976 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7977 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7978 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7979 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7980 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7981 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7982 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7983 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7984 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7985 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7986 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7987 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7988 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007989#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007990 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007991#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007992 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7993 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7994 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7995 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7996 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7997 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7998 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7999 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8000 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008001};
8002
8003static void calcsize(union node *n);
8004
8005static void
8006sizenodelist(struct nodelist *lp)
8007{
8008 while (lp) {
8009 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8010 calcsize(lp->n);
8011 lp = lp->next;
8012 }
8013}
8014
8015static void
8016calcsize(union node *n)
8017{
8018 if (n == NULL)
8019 return;
8020 funcblocksize += nodesize[n->type];
8021 switch (n->type) {
8022 case NCMD:
8023 calcsize(n->ncmd.redirect);
8024 calcsize(n->ncmd.args);
8025 calcsize(n->ncmd.assign);
8026 break;
8027 case NPIPE:
8028 sizenodelist(n->npipe.cmdlist);
8029 break;
8030 case NREDIR:
8031 case NBACKGND:
8032 case NSUBSHELL:
8033 calcsize(n->nredir.redirect);
8034 calcsize(n->nredir.n);
8035 break;
8036 case NAND:
8037 case NOR:
8038 case NSEMI:
8039 case NWHILE:
8040 case NUNTIL:
8041 calcsize(n->nbinary.ch2);
8042 calcsize(n->nbinary.ch1);
8043 break;
8044 case NIF:
8045 calcsize(n->nif.elsepart);
8046 calcsize(n->nif.ifpart);
8047 calcsize(n->nif.test);
8048 break;
8049 case NFOR:
8050 funcstringsize += strlen(n->nfor.var) + 1;
8051 calcsize(n->nfor.body);
8052 calcsize(n->nfor.args);
8053 break;
8054 case NCASE:
8055 calcsize(n->ncase.cases);
8056 calcsize(n->ncase.expr);
8057 break;
8058 case NCLIST:
8059 calcsize(n->nclist.body);
8060 calcsize(n->nclist.pattern);
8061 calcsize(n->nclist.next);
8062 break;
8063 case NDEFUN:
8064 case NARG:
8065 sizenodelist(n->narg.backquote);
8066 funcstringsize += strlen(n->narg.text) + 1;
8067 calcsize(n->narg.next);
8068 break;
8069 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008070#if ENABLE_ASH_BASH_COMPAT
8071 case NTO2:
8072#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008073 case NCLOBBER:
8074 case NFROM:
8075 case NFROMTO:
8076 case NAPPEND:
8077 calcsize(n->nfile.fname);
8078 calcsize(n->nfile.next);
8079 break;
8080 case NTOFD:
8081 case NFROMFD:
8082 calcsize(n->ndup.vname);
8083 calcsize(n->ndup.next);
8084 break;
8085 case NHERE:
8086 case NXHERE:
8087 calcsize(n->nhere.doc);
8088 calcsize(n->nhere.next);
8089 break;
8090 case NNOT:
8091 calcsize(n->nnot.com);
8092 break;
8093 };
8094}
8095
8096static char *
8097nodeckstrdup(char *s)
8098{
8099 char *rtn = funcstring;
8100
8101 strcpy(funcstring, s);
8102 funcstring += strlen(s) + 1;
8103 return rtn;
8104}
8105
8106static union node *copynode(union node *);
8107
8108static struct nodelist *
8109copynodelist(struct nodelist *lp)
8110{
8111 struct nodelist *start;
8112 struct nodelist **lpp;
8113
8114 lpp = &start;
8115 while (lp) {
8116 *lpp = funcblock;
8117 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8118 (*lpp)->n = copynode(lp->n);
8119 lp = lp->next;
8120 lpp = &(*lpp)->next;
8121 }
8122 *lpp = NULL;
8123 return start;
8124}
8125
8126static union node *
8127copynode(union node *n)
8128{
8129 union node *new;
8130
8131 if (n == NULL)
8132 return NULL;
8133 new = funcblock;
8134 funcblock = (char *) funcblock + nodesize[n->type];
8135
8136 switch (n->type) {
8137 case NCMD:
8138 new->ncmd.redirect = copynode(n->ncmd.redirect);
8139 new->ncmd.args = copynode(n->ncmd.args);
8140 new->ncmd.assign = copynode(n->ncmd.assign);
8141 break;
8142 case NPIPE:
8143 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008144 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008145 break;
8146 case NREDIR:
8147 case NBACKGND:
8148 case NSUBSHELL:
8149 new->nredir.redirect = copynode(n->nredir.redirect);
8150 new->nredir.n = copynode(n->nredir.n);
8151 break;
8152 case NAND:
8153 case NOR:
8154 case NSEMI:
8155 case NWHILE:
8156 case NUNTIL:
8157 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8158 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8159 break;
8160 case NIF:
8161 new->nif.elsepart = copynode(n->nif.elsepart);
8162 new->nif.ifpart = copynode(n->nif.ifpart);
8163 new->nif.test = copynode(n->nif.test);
8164 break;
8165 case NFOR:
8166 new->nfor.var = nodeckstrdup(n->nfor.var);
8167 new->nfor.body = copynode(n->nfor.body);
8168 new->nfor.args = copynode(n->nfor.args);
8169 break;
8170 case NCASE:
8171 new->ncase.cases = copynode(n->ncase.cases);
8172 new->ncase.expr = copynode(n->ncase.expr);
8173 break;
8174 case NCLIST:
8175 new->nclist.body = copynode(n->nclist.body);
8176 new->nclist.pattern = copynode(n->nclist.pattern);
8177 new->nclist.next = copynode(n->nclist.next);
8178 break;
8179 case NDEFUN:
8180 case NARG:
8181 new->narg.backquote = copynodelist(n->narg.backquote);
8182 new->narg.text = nodeckstrdup(n->narg.text);
8183 new->narg.next = copynode(n->narg.next);
8184 break;
8185 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008186#if ENABLE_ASH_BASH_COMPAT
8187 case NTO2:
8188#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008189 case NCLOBBER:
8190 case NFROM:
8191 case NFROMTO:
8192 case NAPPEND:
8193 new->nfile.fname = copynode(n->nfile.fname);
8194 new->nfile.fd = n->nfile.fd;
8195 new->nfile.next = copynode(n->nfile.next);
8196 break;
8197 case NTOFD:
8198 case NFROMFD:
8199 new->ndup.vname = copynode(n->ndup.vname);
8200 new->ndup.dupfd = n->ndup.dupfd;
8201 new->ndup.fd = n->ndup.fd;
8202 new->ndup.next = copynode(n->ndup.next);
8203 break;
8204 case NHERE:
8205 case NXHERE:
8206 new->nhere.doc = copynode(n->nhere.doc);
8207 new->nhere.fd = n->nhere.fd;
8208 new->nhere.next = copynode(n->nhere.next);
8209 break;
8210 case NNOT:
8211 new->nnot.com = copynode(n->nnot.com);
8212 break;
8213 };
8214 new->type = n->type;
8215 return new;
8216}
8217
8218/*
8219 * Make a copy of a parse tree.
8220 */
8221static struct funcnode *
8222copyfunc(union node *n)
8223{
8224 struct funcnode *f;
8225 size_t blocksize;
8226
8227 funcblocksize = offsetof(struct funcnode, n);
8228 funcstringsize = 0;
8229 calcsize(n);
8230 blocksize = funcblocksize;
8231 f = ckmalloc(blocksize + funcstringsize);
8232 funcblock = (char *) f + offsetof(struct funcnode, n);
8233 funcstring = (char *) f + blocksize;
8234 copynode(n);
8235 f->count = 0;
8236 return f;
8237}
8238
8239/*
8240 * Define a shell function.
8241 */
8242static void
8243defun(char *name, union node *func)
8244{
8245 struct cmdentry entry;
8246
8247 INT_OFF;
8248 entry.cmdtype = CMDFUNCTION;
8249 entry.u.func = copyfunc(func);
8250 addcmdentry(name, &entry);
8251 INT_ON;
8252}
8253
Denis Vlasenko4b875702009-03-19 13:30:04 +00008254/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008255#define SKIPBREAK (1 << 0)
8256#define SKIPCONT (1 << 1)
8257#define SKIPFUNC (1 << 2)
8258#define SKIPFILE (1 << 3)
8259#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008260static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008261static int skipcount; /* number of levels to skip */
8262static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008263static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008264
Denis Vlasenko4b875702009-03-19 13:30:04 +00008265/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008266static int evalstring(char *s, int mask);
8267
Denis Vlasenko4b875702009-03-19 13:30:04 +00008268/* Called to execute a trap.
8269 * Single callsite - at the end of evaltree().
Denys Vlasenkob563f622010-09-25 17:15:13 +02008270 * If we return non-zero, evaltree raises EXEXIT exception.
Denis Vlasenko4b875702009-03-19 13:30:04 +00008271 *
8272 * Perhaps we should avoid entering new trap handlers
8273 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008274 */
8275static int
8276dotrap(void)
8277{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008278 uint8_t *g;
8279 int sig;
8280 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008281
8282 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008283 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008284 xbarrier();
8285
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008286 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008287 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8288 int want_exexit;
8289 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008290
Denis Vlasenko4b875702009-03-19 13:30:04 +00008291 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008292 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008293 t = trap[sig];
8294 /* non-trapped SIGINT is handled separately by raise_interrupt,
8295 * don't upset it by resetting gotsig[SIGINT-1] */
8296 if (sig == SIGINT && !t)
8297 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008298
8299 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008300 *g = 0;
8301 if (!t)
8302 continue;
8303 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008304 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008305 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008306 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008307 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008308 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008309 }
8310
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008311 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008312 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008313}
8314
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008315/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008316static void evalloop(union node *, int);
8317static void evalfor(union node *, int);
8318static void evalcase(union node *, int);
8319static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008320static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008321static void evalpipe(union node *, int);
8322static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008323static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008324static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008325
Eric Andersen62483552001-07-10 06:09:16 +00008326/*
Eric Andersenc470f442003-07-28 09:56:35 +00008327 * Evaluate a parse tree. The value is left in the global variable
8328 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008329 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008330static void
Eric Andersenc470f442003-07-28 09:56:35 +00008331evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008332{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008333 struct jmploc *volatile savehandler = exception_handler;
8334 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008335 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008336 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008337 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008338 int int_level;
8339
8340 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008341
Eric Andersenc470f442003-07-28 09:56:35 +00008342 if (n == NULL) {
8343 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008344 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008345 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008346 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008347
8348 exception_handler = &jmploc;
8349 {
8350 int err = setjmp(jmploc.loc);
8351 if (err) {
8352 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008353 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008354 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8355 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008356 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008357 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008358 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008359 TRACE(("exception %d in evaltree, propagating err=%d\n",
8360 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008361 exception_handler = savehandler;
8362 longjmp(exception_handler->loc, err);
8363 }
8364 }
8365
Eric Andersenc470f442003-07-28 09:56:35 +00008366 switch (n->type) {
8367 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008368#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008369 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008370 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008371 break;
8372#endif
8373 case NNOT:
8374 evaltree(n->nnot.com, EV_TESTED);
8375 status = !exitstatus;
8376 goto setstatus;
8377 case NREDIR:
8378 expredir(n->nredir.redirect);
8379 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8380 if (!status) {
8381 evaltree(n->nredir.n, flags & EV_TESTED);
8382 status = exitstatus;
8383 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008384 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008385 goto setstatus;
8386 case NCMD:
8387 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008388 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008389 if (eflag && !(flags & EV_TESTED))
8390 checkexit = ~0;
8391 goto calleval;
8392 case NFOR:
8393 evalfn = evalfor;
8394 goto calleval;
8395 case NWHILE:
8396 case NUNTIL:
8397 evalfn = evalloop;
8398 goto calleval;
8399 case NSUBSHELL:
8400 case NBACKGND:
8401 evalfn = evalsubshell;
8402 goto calleval;
8403 case NPIPE:
8404 evalfn = evalpipe;
8405 goto checkexit;
8406 case NCASE:
8407 evalfn = evalcase;
8408 goto calleval;
8409 case NAND:
8410 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008411 case NSEMI: {
8412
Eric Andersenc470f442003-07-28 09:56:35 +00008413#if NAND + 1 != NOR
8414#error NAND + 1 != NOR
8415#endif
8416#if NOR + 1 != NSEMI
8417#error NOR + 1 != NSEMI
8418#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008419 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008420 evaltree(
8421 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008422 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008423 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008424 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008425 break;
8426 if (!evalskip) {
8427 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008428 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008429 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008430 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008431 evalfn(n, flags);
8432 break;
8433 }
8434 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008435 }
Eric Andersenc470f442003-07-28 09:56:35 +00008436 case NIF:
8437 evaltree(n->nif.test, EV_TESTED);
8438 if (evalskip)
8439 break;
8440 if (exitstatus == 0) {
8441 n = n->nif.ifpart;
8442 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008443 }
8444 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008445 n = n->nif.elsepart;
8446 goto evaln;
8447 }
8448 goto success;
8449 case NDEFUN:
8450 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008451 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008452 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008453 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008454 exitstatus = status;
8455 break;
8456 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008457
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008458 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008459 exception_handler = savehandler;
Denys Vlasenkob563f622010-09-25 17:15:13 +02008460
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008461 out1:
Denys Vlasenkob563f622010-09-25 17:15:13 +02008462 /* Order of checks below is important:
8463 * signal handlers trigger before exit caused by "set -e".
8464 */
8465 if (pending_sig && dotrap())
8466 goto exexit;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008467 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008468 evalskip |= SKIPEVAL;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008469
8470 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008471 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008472 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008473 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008474
8475 RESTORE_INT(int_level);
8476 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008477}
8478
Eric Andersenc470f442003-07-28 09:56:35 +00008479#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8480static
8481#endif
8482void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8483
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008484static void
Eric Andersenc470f442003-07-28 09:56:35 +00008485evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008486{
8487 int status;
8488
8489 loopnest++;
8490 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008491 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008492 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008493 int i;
8494
Eric Andersencb57d552001-06-28 07:25:16 +00008495 evaltree(n->nbinary.ch1, EV_TESTED);
8496 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008497 skipping:
8498 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008499 evalskip = 0;
8500 continue;
8501 }
8502 if (evalskip == SKIPBREAK && --skipcount <= 0)
8503 evalskip = 0;
8504 break;
8505 }
Eric Andersenc470f442003-07-28 09:56:35 +00008506 i = exitstatus;
8507 if (n->type != NWHILE)
8508 i = !i;
8509 if (i != 0)
8510 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008511 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008512 status = exitstatus;
8513 if (evalskip)
8514 goto skipping;
8515 }
8516 loopnest--;
8517 exitstatus = status;
8518}
8519
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008520static void
Eric Andersenc470f442003-07-28 09:56:35 +00008521evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008522{
8523 struct arglist arglist;
8524 union node *argp;
8525 struct strlist *sp;
8526 struct stackmark smark;
8527
8528 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008529 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008530 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008531 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Ron Yorston549deab2015-05-18 09:57:51 +02008532 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008533 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008534 if (evalskip)
8535 goto out;
8536 }
8537 *arglist.lastp = NULL;
8538
8539 exitstatus = 0;
8540 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008541 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008542 for (sp = arglist.list; sp; sp = sp->next) {
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008543 setvar0(n->nfor.var, sp->text);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008544 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008545 if (evalskip) {
8546 if (evalskip == SKIPCONT && --skipcount <= 0) {
8547 evalskip = 0;
8548 continue;
8549 }
8550 if (evalskip == SKIPBREAK && --skipcount <= 0)
8551 evalskip = 0;
8552 break;
8553 }
8554 }
8555 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008556 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008557 popstackmark(&smark);
8558}
8559
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008560static void
Eric Andersenc470f442003-07-28 09:56:35 +00008561evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008562{
8563 union node *cp;
8564 union node *patp;
8565 struct arglist arglist;
8566 struct stackmark smark;
8567
8568 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008569 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008570 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008571 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008572 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008573 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8574 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008575 if (casematch(patp, arglist.list->text)) {
8576 if (evalskip == 0) {
8577 evaltree(cp->nclist.body, flags);
8578 }
8579 goto out;
8580 }
8581 }
8582 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008583 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008584 popstackmark(&smark);
8585}
8586
Eric Andersenc470f442003-07-28 09:56:35 +00008587/*
8588 * Kick off a subshell to evaluate a tree.
8589 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008590static void
Eric Andersenc470f442003-07-28 09:56:35 +00008591evalsubshell(union node *n, int flags)
8592{
8593 struct job *jp;
8594 int backgnd = (n->type == NBACKGND);
8595 int status;
8596
8597 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008598 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008599 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008600 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008601 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008602 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008603 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008604 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008605 flags |= EV_EXIT;
8606 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008607 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008608 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008609 redirect(n->nredir.redirect, 0);
8610 evaltreenr(n->nredir.n, flags);
8611 /* never returns */
8612 }
8613 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008614 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008615 status = waitforjob(jp);
8616 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008617 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008618}
8619
Eric Andersenc470f442003-07-28 09:56:35 +00008620/*
8621 * Compute the names of the files in a redirection list.
8622 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008623static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008624static void
8625expredir(union node *n)
8626{
8627 union node *redir;
8628
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008629 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008630 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008631
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008632 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008633 fn.lastp = &fn.list;
8634 switch (redir->type) {
8635 case NFROMTO:
8636 case NFROM:
8637 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008638#if ENABLE_ASH_BASH_COMPAT
8639 case NTO2:
8640#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008641 case NCLOBBER:
8642 case NAPPEND:
8643 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denys Vlasenkof451b2c2012-06-09 02:06:57 +02008644 TRACE(("expredir expanded to '%s'\n", fn.list->text));
Denis Vlasenko559691a2008-10-05 18:39:31 +00008645#if ENABLE_ASH_BASH_COMPAT
8646 store_expfname:
8647#endif
Denys Vlasenko7c4b13e2013-01-17 13:02:27 +01008648#if 0
8649// By the design of stack allocator, the loop of this kind:
8650// while true; do while true; do break; done </dev/null; done
8651// will look like a memory leak: ash plans to free expfname's
8652// of "/dev/null" as soon as it finishes running the loop
8653// (in this case, never).
8654// This "fix" is wrong:
Jon Tollefson4ba6c5d2012-11-13 19:26:53 +01008655 if (redir->nfile.expfname)
8656 stunalloc(redir->nfile.expfname);
Denys Vlasenko7c4b13e2013-01-17 13:02:27 +01008657// It results in corrupted state of stacked allocations.
8658#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008659 redir->nfile.expfname = fn.list->text;
8660 break;
8661 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008662 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008663 if (redir->ndup.vname) {
8664 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008665 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008666 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008667#if ENABLE_ASH_BASH_COMPAT
8668//FIXME: we used expandarg with different args!
8669 if (!isdigit_str9(fn.list->text)) {
8670 /* >&file, not >&fd */
8671 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8672 ash_msg_and_raise_error("redir error");
8673 redir->type = NTO2;
8674 goto store_expfname;
8675 }
8676#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008677 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008678 }
8679 break;
8680 }
8681 }
8682}
8683
Eric Andersencb57d552001-06-28 07:25:16 +00008684/*
Eric Andersencb57d552001-06-28 07:25:16 +00008685 * Evaluate a pipeline. All the processes in the pipeline are children
8686 * of the process creating the pipeline. (This differs from some versions
8687 * of the shell, which make the last process in a pipeline the parent
8688 * of all the rest.)
8689 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008690static void
Eric Andersenc470f442003-07-28 09:56:35 +00008691evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008692{
8693 struct job *jp;
8694 struct nodelist *lp;
8695 int pipelen;
8696 int prevfd;
8697 int pip[2];
8698
Eric Andersenc470f442003-07-28 09:56:35 +00008699 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008700 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008701 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008702 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008703 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008704 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008705 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008706 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008707 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008708 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008709 pip[1] = -1;
8710 if (lp->next) {
8711 if (pipe(pip) < 0) {
8712 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008713 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008714 }
8715 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008716 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008717 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008718 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008719 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008720 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008721 if (prevfd > 0) {
8722 dup2(prevfd, 0);
8723 close(prevfd);
8724 }
8725 if (pip[1] > 1) {
8726 dup2(pip[1], 1);
8727 close(pip[1]);
8728 }
Eric Andersenc470f442003-07-28 09:56:35 +00008729 evaltreenr(lp->n, flags);
8730 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008731 }
8732 if (prevfd >= 0)
8733 close(prevfd);
8734 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008735 /* Don't want to trigger debugging */
8736 if (pip[1] != -1)
8737 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008738 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008739 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008740 exitstatus = waitforjob(jp);
8741 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008742 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008743 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008744}
8745
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008746/*
8747 * Controls whether the shell is interactive or not.
8748 */
8749static void
8750setinteractive(int on)
8751{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008752 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008753
8754 if (++on == is_interactive)
8755 return;
8756 is_interactive = on;
8757 setsignal(SIGINT);
8758 setsignal(SIGQUIT);
8759 setsignal(SIGTERM);
8760#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8761 if (is_interactive > 1) {
8762 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008763 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008764
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008765 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008766 /* note: ash and hush share this string */
8767 out1fmt("\n\n%s %s\n"
Denys Vlasenko2ec34962014-09-08 16:52:39 +02008768 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8769 "\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008770 bb_banner,
8771 "built-in shell (ash)"
8772 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008773 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008774 }
8775 }
8776#endif
8777}
8778
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008779static void
8780optschanged(void)
8781{
8782#if DEBUG
8783 opentrace();
8784#endif
8785 setinteractive(iflag);
8786 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008787#if ENABLE_FEATURE_EDITING_VI
8788 if (viflag)
8789 line_input_state->flags |= VI_MODE;
8790 else
8791 line_input_state->flags &= ~VI_MODE;
8792#else
8793 viflag = 0; /* forcibly keep the option off */
8794#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008795}
8796
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008797static struct localvar *localvars;
8798
8799/*
8800 * Called after a function returns.
8801 * Interrupts must be off.
8802 */
8803static void
8804poplocalvars(void)
8805{
8806 struct localvar *lvp;
8807 struct var *vp;
8808
8809 while ((lvp = localvars) != NULL) {
8810 localvars = lvp->next;
8811 vp = lvp->vp;
Denys Vlasenkob563f622010-09-25 17:15:13 +02008812 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008813 if (vp == NULL) { /* $- saved */
8814 memcpy(optlist, lvp->text, sizeof(optlist));
8815 free((char*)lvp->text);
8816 optschanged();
8817 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008818 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008819 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008820 if (vp->var_func)
8821 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008822 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008823 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008824 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008825 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008826 }
8827 free(lvp);
8828 }
8829}
8830
8831static int
8832evalfun(struct funcnode *func, int argc, char **argv, int flags)
8833{
8834 volatile struct shparam saveparam;
8835 struct localvar *volatile savelocalvars;
8836 struct jmploc *volatile savehandler;
8837 struct jmploc jmploc;
8838 int e;
8839
8840 saveparam = shellparam;
8841 savelocalvars = localvars;
8842 e = setjmp(jmploc.loc);
8843 if (e) {
8844 goto funcdone;
8845 }
8846 INT_OFF;
8847 savehandler = exception_handler;
8848 exception_handler = &jmploc;
8849 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008850 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008851 func->count++;
8852 funcnest++;
8853 INT_ON;
8854 shellparam.nparam = argc - 1;
8855 shellparam.p = argv + 1;
8856#if ENABLE_ASH_GETOPTS
8857 shellparam.optind = 1;
8858 shellparam.optoff = -1;
8859#endif
8860 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008861 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008862 INT_OFF;
8863 funcnest--;
8864 freefunc(func);
8865 poplocalvars();
8866 localvars = savelocalvars;
8867 freeparam(&shellparam);
8868 shellparam = saveparam;
8869 exception_handler = savehandler;
8870 INT_ON;
8871 evalskip &= ~SKIPFUNC;
8872 return e;
8873}
8874
Denis Vlasenko131ae172007-02-18 13:00:19 +00008875#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008876static char **
8877parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008878{
8879 char *cp, c;
8880
8881 for (;;) {
8882 cp = *++argv;
8883 if (!cp)
8884 return 0;
8885 if (*cp++ != '-')
8886 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008887 c = *cp++;
8888 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008889 break;
8890 if (c == '-' && !*cp) {
8891 argv++;
8892 break;
8893 }
8894 do {
8895 switch (c) {
8896 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008897 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008898 break;
8899 default:
8900 /* run 'typecmd' for other options */
8901 return 0;
8902 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008903 c = *cp++;
8904 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008905 }
8906 return argv;
8907}
8908#endif
8909
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008910/*
8911 * Make a variable a local variable. When a variable is made local, it's
8912 * value and flags are saved in a localvar structure. The saved values
8913 * will be restored when the shell function returns. We handle the name
Denys Vlasenkoe0a4e102015-05-13 02:20:14 +02008914 * "-" as a special case: it makes changes to "set +-options" local
8915 * (options will be restored on return from the function).
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008916 */
8917static void
8918mklocal(char *name)
8919{
8920 struct localvar *lvp;
8921 struct var **vpp;
8922 struct var *vp;
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008923 char *eq = strchr(name, '=');
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008924
8925 INT_OFF;
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008926 /* Cater for duplicate "local". Examples:
8927 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
8928 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
8929 */
8930 lvp = localvars;
8931 while (lvp) {
Eugene Rudoy1285aa62015-04-26 23:32:00 +02008932 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008933 if (eq)
8934 setvareq(name, 0);
8935 /* else:
8936 * it's a duplicate "local VAR" declaration, do nothing
8937 */
8938 return;
8939 }
8940 lvp = lvp->next;
8941 }
8942
8943 lvp = ckzalloc(sizeof(*lvp));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008944 if (LONE_DASH(name)) {
8945 char *p;
8946 p = ckmalloc(sizeof(optlist));
8947 lvp->text = memcpy(p, optlist, sizeof(optlist));
8948 vp = NULL;
8949 } else {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008950 vpp = hashvar(name);
8951 vp = *findvar(vpp, name);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008952 if (vp == NULL) {
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008953 /* variable did not exist yet */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008954 if (eq)
8955 setvareq(name, VSTRFIXED);
8956 else
8957 setvar(name, NULL, VSTRFIXED);
8958 vp = *vpp; /* the new variable */
8959 lvp->flags = VUNSET;
8960 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008961 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008962 lvp->flags = vp->flags;
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008963 /* make sure neither "struct var" nor string gets freed
8964 * during (un)setting:
8965 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008966 vp->flags |= VSTRFIXED|VTEXTFIXED;
8967 if (eq)
8968 setvareq(name, 0);
Denys Vlasenko109ee5d2014-03-16 18:41:11 +01008969 else
8970 /* "local VAR" unsets VAR: */
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02008971 setvar0(name, NULL);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008972 }
8973 }
8974 lvp->vp = vp;
8975 lvp->next = localvars;
8976 localvars = lvp;
8977 INT_ON;
8978}
8979
8980/*
8981 * The "local" command.
8982 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008983static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008984localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008985{
8986 char *name;
8987
8988 argv = argptr;
8989 while ((name = *argv++) != NULL) {
8990 mklocal(name);
8991 }
8992 return 0;
8993}
8994
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008995static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008996falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008997{
8998 return 1;
8999}
9000
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009001static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009002truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009003{
9004 return 0;
9005}
9006
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009007static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009008execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009009{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009010 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009011 iflag = 0; /* exit on error */
9012 mflag = 0;
9013 optschanged();
9014 shellexec(argv + 1, pathval(), 0);
9015 }
9016 return 0;
9017}
9018
9019/*
9020 * The return command.
9021 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009022static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009023returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009024{
9025 /*
9026 * If called outside a function, do what ksh does;
9027 * skip the rest of the file.
9028 */
9029 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9030 return argv[1] ? number(argv[1]) : exitstatus;
9031}
9032
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009033/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009034static int breakcmd(int, char **) FAST_FUNC;
9035static int dotcmd(int, char **) FAST_FUNC;
9036static int evalcmd(int, char **) FAST_FUNC;
9037static int exitcmd(int, char **) FAST_FUNC;
9038static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009039#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009040static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009041#endif
Denys Vlasenko2ec34962014-09-08 16:52:39 +02009042#if ENABLE_ASH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009043static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00009044#endif
Flemming Madsend96ffda2013-04-07 18:47:24 +02009045#if MAX_HISTORY
9046static int historycmd(int, char **) FAST_FUNC;
9047#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00009048#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009049static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009050#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009051static int readcmd(int, char **) FAST_FUNC;
9052static int setcmd(int, char **) FAST_FUNC;
9053static int shiftcmd(int, char **) FAST_FUNC;
9054static int timescmd(int, char **) FAST_FUNC;
9055static int trapcmd(int, char **) FAST_FUNC;
9056static int umaskcmd(int, char **) FAST_FUNC;
9057static int unsetcmd(int, char **) FAST_FUNC;
9058static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009059
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009060#define BUILTIN_NOSPEC "0"
9061#define BUILTIN_SPECIAL "1"
9062#define BUILTIN_REGULAR "2"
9063#define BUILTIN_SPEC_REG "3"
9064#define BUILTIN_ASSIGN "4"
9065#define BUILTIN_SPEC_ASSG "5"
9066#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009067#define BUILTIN_SPEC_REG_ASSG "7"
9068
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009069/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02009070#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009071static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02009072#endif
9073#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009074static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02009075#endif
9076#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009077static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02009078#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00009079
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009080/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009081static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009082 { BUILTIN_SPEC_REG "." , dotcmd },
9083 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009084#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009085 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00009086#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009087 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009088#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00009089#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009090#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009091 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009092#endif
9093#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009094 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009095#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009096 { BUILTIN_SPEC_REG "break" , breakcmd },
9097 { BUILTIN_REGULAR "cd" , cdcmd },
9098 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009099#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009100 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009101#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009102 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009103#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009104 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009105#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009106 { BUILTIN_SPEC_REG "eval" , evalcmd },
9107 { BUILTIN_SPEC_REG "exec" , execcmd },
9108 { BUILTIN_SPEC_REG "exit" , exitcmd },
9109 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9110 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009111#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009112 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009113#endif
9114#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009115 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009116#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009117 { BUILTIN_NOSPEC "hash" , hashcmd },
Denys Vlasenko2ec34962014-09-08 16:52:39 +02009118#if ENABLE_ASH_HELP
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009119 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009120#endif
Flemming Madsend96ffda2013-04-07 18:47:24 +02009121#if MAX_HISTORY
9122 { BUILTIN_NOSPEC "history" , historycmd },
9123#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009124#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009125 { BUILTIN_REGULAR "jobs" , jobscmd },
9126 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009127#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00009128#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009129 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009130#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009131 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009132#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009133 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009134#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009135 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9136 { BUILTIN_REGULAR "read" , readcmd },
9137 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9138 { BUILTIN_SPEC_REG "return" , returncmd },
9139 { BUILTIN_SPEC_REG "set" , setcmd },
9140 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009141#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009142 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009143#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009144#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009145 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009146#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009147 { BUILTIN_SPEC_REG "times" , timescmd },
9148 { BUILTIN_SPEC_REG "trap" , trapcmd },
9149 { BUILTIN_REGULAR "true" , truecmd },
9150 { BUILTIN_NOSPEC "type" , typecmd },
9151 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9152 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009153#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009154 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009155#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009156 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9157 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009158};
9159
Denis Vlasenko80591b02008-03-25 07:49:43 +00009160/* Should match the above table! */
9161#define COMMANDCMD (builtintab + \
9162 2 + \
9163 1 * ENABLE_ASH_BUILTIN_TEST + \
9164 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9165 1 * ENABLE_ASH_ALIAS + \
9166 1 * ENABLE_ASH_JOB_CONTROL + \
9167 3)
9168#define EXECCMD (builtintab + \
9169 2 + \
9170 1 * ENABLE_ASH_BUILTIN_TEST + \
9171 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9172 1 * ENABLE_ASH_ALIAS + \
9173 1 * ENABLE_ASH_JOB_CONTROL + \
9174 3 + \
9175 1 * ENABLE_ASH_CMDCMD + \
9176 1 + \
9177 ENABLE_ASH_BUILTIN_ECHO + \
9178 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009179
9180/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009181 * Search the table of builtin commands.
9182 */
9183static struct builtincmd *
9184find_builtin(const char *name)
9185{
9186 struct builtincmd *bp;
9187
9188 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00009189 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009190 pstrcmp
9191 );
9192 return bp;
9193}
9194
9195/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009196 * Execute a simple command.
9197 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009198static int
9199isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009200{
9201 const char *q = endofname(p);
9202 if (p == q)
9203 return 0;
9204 return *q == '=';
9205}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009206static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009207bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009208{
9209 /* Preserve exitstatus of a previous possible redirection
9210 * as POSIX mandates */
9211 return back_exitstatus;
9212}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009213static void
Eric Andersenc470f442003-07-28 09:56:35 +00009214evalcommand(union node *cmd, int flags)
9215{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009216 static const struct builtincmd null_bltin = {
9217 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009218 };
Eric Andersenc470f442003-07-28 09:56:35 +00009219 struct stackmark smark;
9220 union node *argp;
9221 struct arglist arglist;
9222 struct arglist varlist;
9223 char **argv;
9224 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009225 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009226 struct cmdentry cmdentry;
9227 struct job *jp;
9228 char *lastarg;
9229 const char *path;
9230 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009231 int status;
9232 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009233 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009234 smallint cmd_is_exec;
9235 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009236
9237 /* First expand the arguments. */
9238 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9239 setstackmark(&smark);
9240 back_exitstatus = 0;
9241
9242 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009243 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009244 varlist.lastp = &varlist.list;
9245 *varlist.lastp = NULL;
9246 arglist.lastp = &arglist.list;
9247 *arglist.lastp = NULL;
9248
9249 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009250 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009251 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9252 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9253 }
9254
Eric Andersenc470f442003-07-28 09:56:35 +00009255 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9256 struct strlist **spp;
9257
9258 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009259 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009260 expandarg(argp, &arglist, EXP_VARTILDE);
9261 else
9262 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9263
Eric Andersenc470f442003-07-28 09:56:35 +00009264 for (sp = *spp; sp; sp = sp->next)
9265 argc++;
9266 }
9267
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009268 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009269 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009270 TRACE(("evalcommand arg: %s\n", sp->text));
9271 *nargv++ = sp->text;
9272 }
9273 *nargv = NULL;
9274
9275 lastarg = NULL;
9276 if (iflag && funcnest == 0 && argc > 0)
9277 lastarg = nargv[-1];
9278
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009279 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009280 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009281 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009282
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009283 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009284 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9285 struct strlist **spp;
9286 char *p;
9287
9288 spp = varlist.lastp;
9289 expandarg(argp, &varlist, EXP_VARTILDE);
9290
9291 /*
9292 * Modify the command lookup path, if a PATH= assignment
9293 * is present
9294 */
9295 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009296 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009297 path = p;
9298 }
9299
9300 /* Print the command if xflag is set. */
9301 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009302 int n;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009303 const char *p = " %s" + 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009304
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009305 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009306 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009307 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009308 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009309 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009310 sp = sp->next;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009311 p = " %s";
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009312 }
9313 sp = arglist.list;
9314 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009315 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009316 }
9317
9318 cmd_is_exec = 0;
9319 spclbltin = -1;
9320
9321 /* Now locate the command. */
9322 if (argc) {
Eric Andersenc470f442003-07-28 09:56:35 +00009323 int cmd_flag = DO_ERR;
Denys Vlasenko0b4980c2012-09-25 12:49:29 +02009324#if ENABLE_ASH_CMDCMD
9325 const char *oldpath = path + 5;
9326#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009327 path += 5;
Eric Andersenc470f442003-07-28 09:56:35 +00009328 for (;;) {
9329 find_command(argv[0], &cmdentry, cmd_flag, path);
9330 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009331 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009332 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009333 goto bail;
9334 }
9335
9336 /* implement bltin and command here */
9337 if (cmdentry.cmdtype != CMDBUILTIN)
9338 break;
9339 if (spclbltin < 0)
9340 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9341 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009342 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009343#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009344 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009345 path = oldpath;
9346 nargv = parse_command_args(argv, &path);
9347 if (!nargv)
9348 break;
9349 argc -= nargv - argv;
9350 argv = nargv;
9351 cmd_flag |= DO_NOFUNC;
9352 } else
9353#endif
9354 break;
9355 }
9356 }
9357
9358 if (status) {
9359 /* We have a redirection error. */
9360 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009361 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009362 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009363 exitstatus = status;
9364 goto out;
9365 }
9366
9367 /* Execute the command. */
9368 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009369 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009370
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009371#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009372/* (1) BUG: if variables are set, we need to fork, or save/restore them
9373 * around run_nofork_applet() call.
9374 * (2) Should this check also be done in forkshell()?
9375 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9376 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009377 /* find_command() encodes applet_no as (-2 - applet_no) */
9378 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009379 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009380 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009381 /* run <applet>_main() */
9382 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009383 break;
9384 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009385#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009386 /* Can we avoid forking off? For example, very last command
9387 * in a script or a subshell does not need forking,
9388 * we can just exec it.
9389 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009390 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009391 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009392 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009393 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009394 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009395 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009396 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009397 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009398 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009399 break;
9400 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009401 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009402 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009403 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009404 }
9405 listsetvar(varlist.list, VEXPORT|VSTACK);
9406 shellexec(argv, path, cmdentry.u.index);
9407 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009408 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009409 case CMDBUILTIN:
9410 cmdenviron = varlist.list;
9411 if (cmdenviron) {
9412 struct strlist *list = cmdenviron;
9413 int i = VNOSET;
9414 if (spclbltin > 0 || argc == 0) {
9415 i = 0;
9416 if (cmd_is_exec && argc > 1)
9417 i = VEXPORT;
9418 }
9419 listsetvar(list, i);
9420 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009421 /* Tight loop with builtins only:
9422 * "while kill -0 $child; do true; done"
9423 * will never exit even if $child died, unless we do this
9424 * to reap the zombie and make kill detect that it's gone: */
9425 dowait(DOWAIT_NONBLOCK, NULL);
9426
Eric Andersenc470f442003-07-28 09:56:35 +00009427 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9428 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009429 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009430 if (i == EXEXIT)
9431 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009432 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009433 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009434 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009435 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009436 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009437 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009438 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009439 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009440 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009441 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009442 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009443 }
9444 break;
9445
9446 case CMDFUNCTION:
9447 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009448 /* See above for the rationale */
9449 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009450 if (evalfun(cmdentry.u.func, argc, argv, flags))
9451 goto raise;
9452 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009453 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009454
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009455 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009456 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009457 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009458 /* dsl: I think this is intended to be used to support
9459 * '_' in 'vi' command mode during line editing...
9460 * However I implemented that within libedit itself.
9461 */
Denys Vlasenko0a0acb52015-04-18 19:36:38 +02009462 setvar0("_", lastarg);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009463 }
Eric Andersenc470f442003-07-28 09:56:35 +00009464 popstackmark(&smark);
9465}
9466
9467static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009468evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9469{
Eric Andersenc470f442003-07-28 09:56:35 +00009470 char *volatile savecmdname;
9471 struct jmploc *volatile savehandler;
9472 struct jmploc jmploc;
9473 int i;
9474
9475 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009476 i = setjmp(jmploc.loc);
9477 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009478 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009479 savehandler = exception_handler;
9480 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009481 commandname = argv[0];
9482 argptr = argv + 1;
9483 optptr = NULL; /* initialize nextopt */
9484 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009485 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009486 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009487 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009488 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009489 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009490 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009491
9492 return i;
9493}
9494
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009495static int
9496goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009497{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02009498 return endofname(p)[0] == '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009499}
9500
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009501
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009502/*
9503 * Search for a command. This is called before we fork so that the
9504 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009505 * the child. The check for "goodname" is an overly conservative
9506 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009507 */
Eric Andersenc470f442003-07-28 09:56:35 +00009508static void
9509prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009510{
9511 struct cmdentry entry;
9512
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009513 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9514 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009515}
9516
Eric Andersencb57d552001-06-28 07:25:16 +00009517
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009518/* ============ Builtin commands
9519 *
9520 * Builtin commands whose functions are closely tied to evaluation
9521 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009522 */
9523
9524/*
Eric Andersencb57d552001-06-28 07:25:16 +00009525 * Handle break and continue commands. Break, continue, and return are
9526 * all handled by setting the evalskip flag. The evaluation routines
9527 * above all check this flag, and if it is set they start skipping
9528 * commands rather than executing them. The variable skipcount is
9529 * the number of loops to break/continue, or the number of function
9530 * levels to return. (The latter is always 1.) It should probably
9531 * be an error to break out of more loops than exist, but it isn't
9532 * in the standard shell so we don't make it one here.
9533 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009534static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009535breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009536{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009537 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009538
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009539 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009540 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009541 if (n > loopnest)
9542 n = loopnest;
9543 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009544 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009545 skipcount = n;
9546 }
9547 return 0;
9548}
9549
Eric Andersenc470f442003-07-28 09:56:35 +00009550
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009551/* ============ input.c
9552 *
Eric Andersen90898442003-08-06 11:20:52 +00009553 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009554 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009555
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009556enum {
9557 INPUT_PUSH_FILE = 1,
9558 INPUT_NOFILE_OK = 2,
9559};
Eric Andersencb57d552001-06-28 07:25:16 +00009560
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009561static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009562/* values of checkkwd variable */
9563#define CHKALIAS 0x1
9564#define CHKKWD 0x2
9565#define CHKNL 0x4
9566
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009567/*
9568 * Push a string back onto the input at this current parsefile level.
9569 * We handle aliases this way.
9570 */
9571#if !ENABLE_ASH_ALIAS
9572#define pushstring(s, ap) pushstring(s)
9573#endif
9574static void
9575pushstring(char *s, struct alias *ap)
9576{
9577 struct strpush *sp;
9578 int len;
9579
9580 len = strlen(s);
9581 INT_OFF;
9582 if (g_parsefile->strpush) {
9583 sp = ckzalloc(sizeof(*sp));
9584 sp->prev = g_parsefile->strpush;
9585 } else {
9586 sp = &(g_parsefile->basestrpush);
9587 }
9588 g_parsefile->strpush = sp;
9589 sp->prev_string = g_parsefile->next_to_pgetc;
9590 sp->prev_left_in_line = g_parsefile->left_in_line;
9591#if ENABLE_ASH_ALIAS
9592 sp->ap = ap;
9593 if (ap) {
9594 ap->flag |= ALIASINUSE;
9595 sp->string = s;
9596 }
9597#endif
9598 g_parsefile->next_to_pgetc = s;
9599 g_parsefile->left_in_line = len;
9600 INT_ON;
9601}
9602
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009603static void
9604popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009605{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009606 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009607
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009608 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009609#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009610 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009611 if (g_parsefile->next_to_pgetc[-1] == ' '
9612 || g_parsefile->next_to_pgetc[-1] == '\t'
9613 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009614 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009615 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009616 if (sp->string != sp->ap->val) {
9617 free(sp->string);
9618 }
9619 sp->ap->flag &= ~ALIASINUSE;
9620 if (sp->ap->flag & ALIASDEAD) {
9621 unalias(sp->ap->name);
9622 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009623 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009624#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009625 g_parsefile->next_to_pgetc = sp->prev_string;
9626 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009627 g_parsefile->strpush = sp->prev;
9628 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009629 free(sp);
9630 INT_ON;
9631}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009632
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009633//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9634//it peeks whether it is &>, and then pushes back both chars.
9635//This function needs to save last *next_to_pgetc to buf[0]
9636//to make two pungetc() reliable. Currently,
9637// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009638static int
9639preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009640{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009641 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009642 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009643
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009644 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009645#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009646 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009647 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
Ron Yorston61d6ae22015-04-19 10:50:25 +01009648 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009649 else {
Denys Vlasenko66c5b122011-02-08 05:07:02 +01009650 int timeout = -1;
9651# if ENABLE_ASH_IDLE_TIMEOUT
9652 if (iflag) {
9653 const char *tmout_var = lookupvar("TMOUT");
9654 if (tmout_var) {
9655 timeout = atoi(tmout_var) * 1000;
9656 if (timeout <= 0)
9657 timeout = -1;
9658 }
9659 }
9660# endif
Denys Vlasenko8c52f802011-02-04 17:36:21 +01009661# if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009662 line_input_state->path_lookup = pathval();
Denys Vlasenko8c52f802011-02-04 17:36:21 +01009663# endif
Denys Vlasenkoe9ab07c2014-08-13 18:00:08 +02009664 reinit_unicode_for_ash();
Denys Vlasenko66c5b122011-02-08 05:07:02 +01009665 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009666 if (nr == 0) {
9667 /* Ctrl+C pressed */
9668 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009669 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009670 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009671 raise(SIGINT);
9672 return 1;
9673 }
Eric Andersenc470f442003-07-28 09:56:35 +00009674 goto retry;
9675 }
Denys Vlasenko66c5b122011-02-08 05:07:02 +01009676 if (nr < 0) {
9677 if (errno == 0) {
9678 /* Ctrl+D pressed */
9679 nr = 0;
9680 }
9681# if ENABLE_ASH_IDLE_TIMEOUT
9682 else if (errno == EAGAIN && timeout > 0) {
9683 printf("\007timed out waiting for input: auto-logout\n");
9684 exitshell();
9685 }
9686# endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009687 }
Eric Andersencb57d552001-06-28 07:25:16 +00009688 }
9689#else
Ron Yorston61d6ae22015-04-19 10:50:25 +01009690 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009691#endif
9692
Denys Vlasenko80c5b682011-05-08 21:21:10 +02009693#if 0 /* disabled: nonblock_immune_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009694 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009695 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009696 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009697 if (flags >= 0 && (flags & O_NONBLOCK)) {
9698 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009699 if (fcntl(0, F_SETFL, flags) >= 0) {
9700 out2str("sh: turning off NDELAY mode\n");
9701 goto retry;
9702 }
9703 }
9704 }
9705 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009706#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009707 return nr;
9708}
9709
9710/*
9711 * Refill the input buffer and return the next input character:
9712 *
9713 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009714 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9715 * or we are reading from a string so we can't refill the buffer,
9716 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009717 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009718 * 4) Process input up to the next newline, deleting nul characters.
9719 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009720//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9721#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009722static int
Eric Andersenc470f442003-07-28 09:56:35 +00009723preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009724{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009725 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009726 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009727
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009728 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009729#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009730 if (g_parsefile->left_in_line == -1
9731 && g_parsefile->strpush->ap
9732 && g_parsefile->next_to_pgetc[-1] != ' '
9733 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009734 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009735 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009736 return PEOA;
9737 }
Eric Andersen2870d962001-07-02 17:27:21 +00009738#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009739 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009740 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009741 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9742 g_parsefile->left_in_line,
9743 g_parsefile->next_to_pgetc,
9744 g_parsefile->next_to_pgetc);
9745 if (--g_parsefile->left_in_line >= 0)
9746 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009747 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009748 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009749 * "pgetc" needs refilling.
9750 */
9751
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009752 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009753 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009754 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009755 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009756 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009757 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009758 /* even in failure keep left_in_line and next_to_pgetc
9759 * in lock step, for correct multi-layer pungetc.
9760 * left_in_line was decremented before preadbuffer(),
9761 * must inc next_to_pgetc: */
9762 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009763 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009764 }
Eric Andersencb57d552001-06-28 07:25:16 +00009765
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009766 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009767 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009768 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009769 again:
9770 more = preadfd();
9771 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009772 /* don't try reading again */
9773 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009774 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009775 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009776 return PEOF;
9777 }
9778 }
9779
Denis Vlasenko727752d2008-11-28 03:41:47 +00009780 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009781 * Set g_parsefile->left_in_line
9782 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009783 * NUL chars are deleted.
9784 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009785 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009786 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009787 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009788
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009789 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009790
Denis Vlasenko727752d2008-11-28 03:41:47 +00009791 c = *q;
9792 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009793 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009794 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009795 q++;
9796 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009797 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009798 break;
9799 }
Eric Andersencb57d552001-06-28 07:25:16 +00009800 }
9801
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009802 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009803 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9804 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009805 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009806 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009807 }
9808 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009809 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009810
Eric Andersencb57d552001-06-28 07:25:16 +00009811 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009812 char save = *q;
9813 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009814 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009815 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009816 }
9817
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009818 pgetc_debug("preadbuffer at %d:%p'%s'",
9819 g_parsefile->left_in_line,
9820 g_parsefile->next_to_pgetc,
9821 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009822 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009823}
9824
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009825#define pgetc_as_macro() \
9826 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009827 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009828 : preadbuffer() \
9829 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009830
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009831static int
9832pgetc(void)
9833{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009834 pgetc_debug("pgetc_fast at %d:%p'%s'",
9835 g_parsefile->left_in_line,
9836 g_parsefile->next_to_pgetc,
9837 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009838 return pgetc_as_macro();
9839}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009840
9841#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009842# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009843#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009844# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009845#endif
9846
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009847#if ENABLE_ASH_ALIAS
9848static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009849pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009850{
9851 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009852 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009853 pgetc_debug("pgetc_fast at %d:%p'%s'",
9854 g_parsefile->left_in_line,
9855 g_parsefile->next_to_pgetc,
9856 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009857 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009858 } while (c == PEOA);
9859 return c;
9860}
9861#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009862# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009863#endif
9864
9865/*
9866 * Read a line from the script.
9867 */
9868static char *
9869pfgets(char *line, int len)
9870{
9871 char *p = line;
9872 int nleft = len;
9873 int c;
9874
9875 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009876 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009877 if (c == PEOF) {
9878 if (p == line)
9879 return NULL;
9880 break;
9881 }
9882 *p++ = c;
9883 if (c == '\n')
9884 break;
9885 }
9886 *p = '\0';
9887 return line;
9888}
9889
Eric Andersenc470f442003-07-28 09:56:35 +00009890/*
9891 * Undo the last call to pgetc. Only one character may be pushed back.
9892 * PEOF may be pushed back.
9893 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009894static void
Eric Andersenc470f442003-07-28 09:56:35 +00009895pungetc(void)
9896{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009897 g_parsefile->left_in_line++;
9898 g_parsefile->next_to_pgetc--;
9899 pgetc_debug("pushed back to %d:%p'%s'",
9900 g_parsefile->left_in_line,
9901 g_parsefile->next_to_pgetc,
9902 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009903}
9904
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009905/*
9906 * To handle the "." command, a stack of input files is used. Pushfile
9907 * adds a new entry to the stack and popfile restores the previous level.
9908 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009909static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009910pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009911{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009912 struct parsefile *pf;
9913
Denis Vlasenko597906c2008-02-20 16:38:54 +00009914 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009915 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009916 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009917 /*pf->strpush = NULL; - ckzalloc did it */
9918 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009919 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009920}
9921
9922static void
9923popfile(void)
9924{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009925 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009926
Denis Vlasenkob012b102007-02-19 22:43:01 +00009927 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009928 if (pf->pf_fd >= 0)
9929 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009930 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009931 while (pf->strpush)
9932 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009933 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009934 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009935 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009936}
9937
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009938/*
9939 * Return to top level.
9940 */
9941static void
9942popallfiles(void)
9943{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009944 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009945 popfile();
9946}
9947
9948/*
9949 * Close the file(s) that the shell is reading commands from. Called
9950 * after a fork is done.
9951 */
9952static void
9953closescript(void)
9954{
9955 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009956 if (g_parsefile->pf_fd > 0) {
9957 close(g_parsefile->pf_fd);
9958 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009959 }
9960}
9961
9962/*
9963 * Like setinputfile, but takes an open file descriptor. Call this with
9964 * interrupts off.
9965 */
9966static void
9967setinputfd(int fd, int push)
9968{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009969 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009970 if (push) {
9971 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009972 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009973 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009974 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009975 if (g_parsefile->buf == NULL)
9976 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009977 g_parsefile->left_in_buffer = 0;
9978 g_parsefile->left_in_line = 0;
9979 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009980}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009981
Eric Andersenc470f442003-07-28 09:56:35 +00009982/*
9983 * Set the input to take input from a file. If push is set, push the
9984 * old input onto the stack first.
9985 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009986static int
9987setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009988{
9989 int fd;
9990 int fd2;
9991
Denis Vlasenkob012b102007-02-19 22:43:01 +00009992 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009993 fd = open(fname, O_RDONLY);
9994 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009995 if (flags & INPUT_NOFILE_OK)
9996 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009997 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009998 }
Eric Andersenc470f442003-07-28 09:56:35 +00009999 if (fd < 10) {
10000 fd2 = copyfd(fd, 10);
10001 close(fd);
10002 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010003 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +000010004 fd = fd2;
10005 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000010006 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010007 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +000010008 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000010009 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +000010010}
10011
Eric Andersencb57d552001-06-28 07:25:16 +000010012/*
10013 * Like setinputfile, but takes input from a string.
10014 */
Eric Andersenc470f442003-07-28 09:56:35 +000010015static void
10016setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +000010017{
Denis Vlasenkob012b102007-02-19 22:43:01 +000010018 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010019 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010020 g_parsefile->next_to_pgetc = string;
10021 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010022 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010023 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010024 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010025}
10026
10027
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010028/* ============ mail.c
10029 *
10030 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +000010031 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010032
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010033#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +000010034
Eric Andersencb57d552001-06-28 07:25:16 +000010035#define MAXMBOXES 10
10036
Eric Andersenc470f442003-07-28 09:56:35 +000010037/* times of mailboxes */
10038static time_t mailtime[MAXMBOXES];
10039/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010040static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +000010041
Eric Andersencb57d552001-06-28 07:25:16 +000010042/*
Eric Andersenc470f442003-07-28 09:56:35 +000010043 * Print appropriate message(s) if mail has arrived.
10044 * If mail_var_path_changed is set,
10045 * then the value of MAIL has mail_var_path_changed,
10046 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +000010047 */
Eric Andersenc470f442003-07-28 09:56:35 +000010048static void
10049chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +000010050{
Eric Andersencb57d552001-06-28 07:25:16 +000010051 const char *mpath;
10052 char *p;
10053 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +000010054 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +000010055 struct stackmark smark;
10056 struct stat statb;
10057
Eric Andersencb57d552001-06-28 07:25:16 +000010058 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +000010059 mpath = mpathset() ? mpathval() : mailval();
10060 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020010061 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +000010062 if (p == NULL)
10063 break;
10064 if (*p == '\0')
10065 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010066 for (q = p; *q; q++)
10067 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +000010068#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +000010069 if (q[-1] != '/')
10070 abort();
10071#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010072 q[-1] = '\0'; /* delete trailing '/' */
10073 if (stat(p, &statb) < 0) {
10074 *mtp = 0;
10075 continue;
Eric Andersencb57d552001-06-28 07:25:16 +000010076 }
Eric Andersenc470f442003-07-28 09:56:35 +000010077 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
10078 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +020010079 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +000010080 pathopt ? pathopt : "you have mail"
10081 );
10082 }
10083 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +000010084 }
Eric Andersenc470f442003-07-28 09:56:35 +000010085 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010086 popstackmark(&smark);
10087}
Eric Andersencb57d552001-06-28 07:25:16 +000010088
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010089static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010090changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000010091{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010092 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010093}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010094
Denis Vlasenko131ae172007-02-18 13:00:19 +000010095#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +000010096
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010097
10098/* ============ ??? */
10099
Eric Andersencb57d552001-06-28 07:25:16 +000010100/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010101 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +000010102 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010103static void
10104setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010105{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010106 char **newparam;
10107 char **ap;
10108 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +000010109
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010110 for (nparam = 0; argv[nparam]; nparam++)
10111 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010112 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10113 while (*argv) {
10114 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +000010115 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010116 *ap = NULL;
10117 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +000010118 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010119 shellparam.nparam = nparam;
10120 shellparam.p = newparam;
10121#if ENABLE_ASH_GETOPTS
10122 shellparam.optind = 1;
10123 shellparam.optoff = -1;
10124#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010125}
10126
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010127/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010128 * Process shell options. The global variable argptr contains a pointer
10129 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010130 *
10131 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10132 * For a non-interactive shell, an error condition encountered
10133 * by a special built-in ... shall cause the shell to write a diagnostic message
10134 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +000010135 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010136 * ...
10137 * Utility syntax error (option or operand error) Shall exit
10138 * ...
10139 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10140 * we see that bash does not do that (set "finishes" with error code 1 instead,
10141 * and shell continues), and people rely on this behavior!
10142 * Testcase:
10143 * set -o barfoo 2>/dev/null
10144 * echo $?
10145 *
10146 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010147 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010148static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010149plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +000010150{
10151 int i;
10152
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010153 if (name) {
10154 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010155 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000010156 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010157 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010158 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010159 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010160 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010161 return 1;
Eric Andersen62483552001-07-10 06:09:16 +000010162 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010163 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010164 if (val) {
10165 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10166 } else {
10167 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10168 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010169 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010170 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010171}
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010172static void
10173setoption(int flag, int val)
10174{
10175 int i;
10176
10177 for (i = 0; i < NOPTS; i++) {
10178 if (optletters(i) == flag) {
10179 optlist[i] = val;
10180 return;
10181 }
10182 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010183 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010184 /* NOTREACHED */
10185}
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010186static int
Eric Andersenc470f442003-07-28 09:56:35 +000010187options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +000010188{
10189 char *p;
10190 int val;
10191 int c;
10192
10193 if (cmdline)
10194 minusc = NULL;
10195 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010196 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010197 if (c != '-' && c != '+')
10198 break;
10199 argptr++;
10200 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010201 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +000010202 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010203 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +000010204 if (!cmdline) {
10205 /* "-" means turn off -x and -v */
10206 if (p[0] == '\0')
10207 xflag = vflag = 0;
10208 /* "--" means reset params */
10209 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +000010210 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010211 }
Denys Vlasenkob0b83432011-03-07 12:34:59 +010010212 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010213 }
Eric Andersencb57d552001-06-28 07:25:16 +000010214 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010215 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010216 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010217 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010218 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010219 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010220 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010221 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010222 /* it already printed err message */
10223 return 1; /* error */
10224 }
Eric Andersencb57d552001-06-28 07:25:16 +000010225 if (*argptr)
10226 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010227 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10228 isloginsh = 1;
10229 /* bash does not accept +-login, we also won't */
10230 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010231 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010232 isloginsh = 1;
10233 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010234 } else {
10235 setoption(c, val);
10236 }
10237 }
10238 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010239 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010240}
10241
Eric Andersencb57d552001-06-28 07:25:16 +000010242/*
Eric Andersencb57d552001-06-28 07:25:16 +000010243 * The shift builtin command.
10244 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010245static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010246shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010247{
10248 int n;
10249 char **ap1, **ap2;
10250
10251 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010252 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010253 n = number(argv[1]);
10254 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010255 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010256 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010257 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010258 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010259 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010260 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010261 }
10262 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010263 while ((*ap2++ = *ap1++) != NULL)
10264 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010265#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010266 shellparam.optind = 1;
10267 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010268#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010269 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010270 return 0;
10271}
10272
Eric Andersencb57d552001-06-28 07:25:16 +000010273/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010274 * POSIX requires that 'set' (but not export or readonly) output the
10275 * variables in lexicographic order - by the locale's collating order (sigh).
10276 * Maybe we could keep them in an ordered balanced binary tree
10277 * instead of hashed lists.
10278 * For now just roll 'em through qsort for printing...
10279 */
10280static int
10281showvars(const char *sep_prefix, int on, int off)
10282{
10283 const char *sep;
10284 char **ep, **epend;
10285
10286 ep = listvars(on, off, &epend);
10287 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10288
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010289 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010290
10291 for (; ep < epend; ep++) {
10292 const char *p;
10293 const char *q;
10294
10295 p = strchrnul(*ep, '=');
10296 q = nullstr;
10297 if (*p)
10298 q = single_quote(++p);
10299 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10300 }
10301 return 0;
10302}
10303
10304/*
Eric Andersencb57d552001-06-28 07:25:16 +000010305 * The set command builtin.
10306 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010307static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010308setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010309{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010310 int retval;
10311
Denis Vlasenko68404f12008-03-17 09:00:54 +000010312 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010313 return showvars(nullstr, 0, VUNSET);
Denys Vlasenkob0b83432011-03-07 12:34:59 +010010314
Denis Vlasenkob012b102007-02-19 22:43:01 +000010315 INT_OFF;
Denys Vlasenkob0b83432011-03-07 12:34:59 +010010316 retval = options(/*cmdline:*/ 0);
10317 if (retval == 0) { /* if no parse error... */
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010318 optschanged();
10319 if (*argptr != NULL) {
10320 setparam(argptr);
10321 }
Eric Andersencb57d552001-06-28 07:25:16 +000010322 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010323 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010324 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010325}
10326
Denis Vlasenko131ae172007-02-18 13:00:19 +000010327#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010328static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010329change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010330{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010331 uint32_t t;
10332
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010333 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010334 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010335 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010336 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010337 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010338 vrandom.flags &= ~VNOFUNC;
10339 } else {
10340 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010341 t = strtoul(value, NULL, 10);
10342 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010343 }
Eric Andersenef02f822004-03-11 13:34:24 +000010344}
Eric Andersen16767e22004-03-16 05:14:10 +000010345#endif
10346
Denis Vlasenko131ae172007-02-18 13:00:19 +000010347#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010348static int
Eric Andersenc470f442003-07-28 09:56:35 +000010349getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010350{
10351 char *p, *q;
10352 char c = '?';
10353 int done = 0;
10354 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010355 char s[12];
10356 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010357
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010358 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010359 return 1;
10360 optnext = optfirst + *param_optind - 1;
10361
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010362 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010363 p = NULL;
10364 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010365 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010366 if (p == NULL || *p == '\0') {
10367 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010368 p = *optnext;
10369 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010370 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010371 p = NULL;
10372 done = 1;
10373 goto out;
10374 }
10375 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010376 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010377 goto atend;
10378 }
10379
10380 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010381 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010382 if (*q == '\0') {
10383 if (optstr[0] == ':') {
10384 s[0] = c;
10385 s[1] = '\0';
10386 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010387 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010388 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010389 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010390 }
10391 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010392 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010393 }
10394 if (*++q == ':')
10395 q++;
10396 }
10397
10398 if (*++q == ':') {
10399 if (*p == '\0' && (p = *optnext) == NULL) {
10400 if (optstr[0] == ':') {
10401 s[0] = c;
10402 s[1] = '\0';
10403 err |= setvarsafe("OPTARG", s, 0);
10404 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010405 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010406 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010407 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010408 c = '?';
10409 }
Eric Andersenc470f442003-07-28 09:56:35 +000010410 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010411 }
10412
10413 if (p == *optnext)
10414 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010415 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010416 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010417 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010418 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010419 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010420 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010421 *param_optind = optnext - optfirst + 1;
10422 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010423 err |= setvarsafe("OPTIND", s, VNOFUNC);
10424 s[0] = c;
10425 s[1] = '\0';
10426 err |= setvarsafe(optvar, s, 0);
10427 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010428 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010429 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010430 flush_stdout_stderr();
10431 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010432 }
10433 return done;
10434}
Eric Andersenc470f442003-07-28 09:56:35 +000010435
10436/*
10437 * The getopts builtin. Shellparam.optnext points to the next argument
10438 * to be processed. Shellparam.optptr points to the next character to
10439 * be processed in the current argument. If shellparam.optnext is NULL,
10440 * then it's the first time getopts has been called.
10441 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010442static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010443getoptscmd(int argc, char **argv)
10444{
10445 char **optbase;
10446
10447 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010448 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010449 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010450 optbase = shellparam.p;
10451 if (shellparam.optind > shellparam.nparam + 1) {
10452 shellparam.optind = 1;
10453 shellparam.optoff = -1;
10454 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010455 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010456 optbase = &argv[3];
10457 if (shellparam.optind > argc - 2) {
10458 shellparam.optind = 1;
10459 shellparam.optoff = -1;
10460 }
10461 }
10462
10463 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010464 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010465}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010466#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010467
Eric Andersencb57d552001-06-28 07:25:16 +000010468
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010469/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010470
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010471struct heredoc {
10472 struct heredoc *next; /* next here document in list */
10473 union node *here; /* redirection node */
10474 char *eofmark; /* string indicating end of input */
10475 smallint striptabs; /* if set, strip leading tabs */
10476};
10477
10478static smallint tokpushback; /* last token pushed back */
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010479static smallint quoteflag; /* set if (part of) last token was quoted */
10480static token_id_t lasttoken; /* last token read (integer id Txxx) */
10481static struct heredoc *heredoclist; /* list of here documents to read */
10482static char *wordtext; /* text of last word returned by readtoken */
10483static struct nodelist *backquotelist;
10484static union node *redirnode;
10485static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010486
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010487static const char *
10488tokname(char *buf, int tok)
10489{
10490 if (tok < TSEMI)
10491 return tokname_array[tok] + 1;
10492 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10493 return buf;
10494}
10495
10496/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010497 * Called when an unexpected token is read during the parse. The argument
10498 * is the token that is expected, or -1 if more than one type of token can
10499 * occur at this point.
10500 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010501static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010502static void
10503raise_error_unexpected_syntax(int token)
10504{
10505 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010506 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010507 int l;
10508
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010509 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010510 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010511 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010512 raise_error_syntax(msg);
10513 /* NOTREACHED */
10514}
Eric Andersencb57d552001-06-28 07:25:16 +000010515
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010516#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010517
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010518/* parsing is heavily cross-recursive, need these forward decls */
10519static union node *andor(void);
10520static union node *pipeline(void);
10521static union node *parse_command(void);
10522static void parseheredoc(void);
Denys Vlasenko7e661022015-02-05 21:00:17 +010010523static char nexttoken_ends_list(void);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010524static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010525
Eric Andersenc470f442003-07-28 09:56:35 +000010526static union node *
10527list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010528{
10529 union node *n1, *n2, *n3;
10530 int tok;
10531
Eric Andersenc470f442003-07-28 09:56:35 +000010532 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denys Vlasenko7e661022015-02-05 21:00:17 +010010533 if (nlflag == 2 && nexttoken_ends_list())
Eric Andersencb57d552001-06-28 07:25:16 +000010534 return NULL;
10535 n1 = NULL;
10536 for (;;) {
10537 n2 = andor();
10538 tok = readtoken();
10539 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010540 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010541 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010542 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010543 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010544 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010545 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010546 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010547 n2 = n3;
10548 }
10549 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010550 }
10551 }
10552 if (n1 == NULL) {
10553 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010554 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010555 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010556 n3->type = NSEMI;
10557 n3->nbinary.ch1 = n1;
10558 n3->nbinary.ch2 = n2;
10559 n1 = n3;
10560 }
10561 switch (tok) {
10562 case TBACKGND:
10563 case TSEMI:
10564 tok = readtoken();
10565 /* fall through */
10566 case TNL:
10567 if (tok == TNL) {
10568 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010569 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010570 return n1;
10571 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010572 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010573 }
Eric Andersenc470f442003-07-28 09:56:35 +000010574 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denys Vlasenko7e661022015-02-05 21:00:17 +010010575 if (nexttoken_ends_list()) {
10576 /* Testcase: "<<EOF; then <W".
10577 * It used to segfault w/o this check:
10578 */
10579 if (heredoclist) {
10580 raise_error_unexpected_syntax(-1);
10581 }
Eric Andersencb57d552001-06-28 07:25:16 +000010582 return n1;
Denys Vlasenko7e661022015-02-05 21:00:17 +010010583 }
Eric Andersencb57d552001-06-28 07:25:16 +000010584 break;
10585 case TEOF:
10586 if (heredoclist)
10587 parseheredoc();
10588 else
Eric Andersenc470f442003-07-28 09:56:35 +000010589 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010590 return n1;
10591 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010592 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010593 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010594 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010595 return n1;
10596 }
10597 }
10598}
10599
Eric Andersenc470f442003-07-28 09:56:35 +000010600static union node *
10601andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010602{
Eric Andersencb57d552001-06-28 07:25:16 +000010603 union node *n1, *n2, *n3;
10604 int t;
10605
Eric Andersencb57d552001-06-28 07:25:16 +000010606 n1 = pipeline();
10607 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010608 t = readtoken();
10609 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010610 t = NAND;
10611 } else if (t == TOR) {
10612 t = NOR;
10613 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010614 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010615 return n1;
10616 }
Eric Andersenc470f442003-07-28 09:56:35 +000010617 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010619 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010620 n3->type = t;
10621 n3->nbinary.ch1 = n1;
10622 n3->nbinary.ch2 = n2;
10623 n1 = n3;
10624 }
10625}
10626
Eric Andersenc470f442003-07-28 09:56:35 +000010627static union node *
10628pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010629{
Eric Andersencb57d552001-06-28 07:25:16 +000010630 union node *n1, *n2, *pipenode;
10631 struct nodelist *lp, *prev;
10632 int negate;
10633
10634 negate = 0;
10635 TRACE(("pipeline: entered\n"));
10636 if (readtoken() == TNOT) {
10637 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010638 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010639 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010640 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010641 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010642 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010643 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010644 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010645 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010646 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010647 pipenode->npipe.cmdlist = lp;
10648 lp->n = n1;
10649 do {
10650 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010651 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010652 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010653 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010654 prev->next = lp;
10655 } while (readtoken() == TPIPE);
10656 lp->next = NULL;
10657 n1 = pipenode;
10658 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010659 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010660 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010661 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010662 n2->type = NNOT;
10663 n2->nnot.com = n1;
10664 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010665 }
10666 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010667}
10668
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010669static union node *
10670makename(void)
10671{
10672 union node *n;
10673
Denis Vlasenko597906c2008-02-20 16:38:54 +000010674 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010675 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010676 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010677 n->narg.text = wordtext;
10678 n->narg.backquote = backquotelist;
10679 return n;
10680}
10681
10682static void
10683fixredir(union node *n, const char *text, int err)
10684{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010685 int fd;
10686
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010687 TRACE(("Fix redir %s %d\n", text, err));
10688 if (!err)
10689 n->ndup.vname = NULL;
10690
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010691 fd = bb_strtou(text, NULL, 10);
10692 if (!errno && fd >= 0)
10693 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010694 else if (LONE_DASH(text))
10695 n->ndup.dupfd = -1;
10696 else {
10697 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010698 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010699 n->ndup.vname = makename();
10700 }
10701}
10702
10703/*
10704 * Returns true if the text contains nothing to expand (no dollar signs
10705 * or backquotes).
10706 */
10707static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010708noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010709{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010710 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010711
Denys Vlasenkocd716832009-11-28 22:14:02 +010010712 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010713 if (c == CTLQUOTEMARK)
10714 continue;
10715 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010716 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010717 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010718 return 0;
10719 }
10720 return 1;
10721}
10722
10723static void
10724parsefname(void)
10725{
10726 union node *n = redirnode;
10727
10728 if (readtoken() != TWORD)
10729 raise_error_unexpected_syntax(-1);
10730 if (n->type == NHERE) {
10731 struct heredoc *here = heredoc;
10732 struct heredoc *p;
10733 int i;
10734
10735 if (quoteflag == 0)
10736 n->type = NXHERE;
10737 TRACE(("Here document %d\n", n->type));
10738 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010739 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010740 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010741 here->eofmark = wordtext;
10742 here->next = NULL;
10743 if (heredoclist == NULL)
10744 heredoclist = here;
10745 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010746 for (p = heredoclist; p->next; p = p->next)
10747 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010748 p->next = here;
10749 }
10750 } else if (n->type == NTOFD || n->type == NFROMFD) {
10751 fixredir(n, wordtext, 0);
10752 } else {
10753 n->nfile.fname = makename();
10754 }
10755}
Eric Andersencb57d552001-06-28 07:25:16 +000010756
Eric Andersenc470f442003-07-28 09:56:35 +000010757static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010758simplecmd(void)
10759{
10760 union node *args, **app;
10761 union node *n = NULL;
10762 union node *vars, **vpp;
10763 union node **rpp, *redir;
10764 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010765#if ENABLE_ASH_BASH_COMPAT
10766 smallint double_brackets_flag = 0;
10767#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010768
10769 args = NULL;
10770 app = &args;
10771 vars = NULL;
10772 vpp = &vars;
10773 redir = NULL;
10774 rpp = &redir;
10775
10776 savecheckkwd = CHKALIAS;
10777 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010778 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010779 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010780 t = readtoken();
10781 switch (t) {
10782#if ENABLE_ASH_BASH_COMPAT
10783 case TAND: /* "&&" */
10784 case TOR: /* "||" */
10785 if (!double_brackets_flag) {
10786 tokpushback = 1;
10787 goto out;
10788 }
10789 wordtext = (char *) (t == TAND ? "-a" : "-o");
10790#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010791 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010792 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010793 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010794 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010795 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010796#if ENABLE_ASH_BASH_COMPAT
10797 if (strcmp("[[", wordtext) == 0)
10798 double_brackets_flag = 1;
10799 else if (strcmp("]]", wordtext) == 0)
10800 double_brackets_flag = 0;
10801#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010802 n->narg.backquote = backquotelist;
10803 if (savecheckkwd && isassignment(wordtext)) {
10804 *vpp = n;
10805 vpp = &n->narg.next;
10806 } else {
10807 *app = n;
10808 app = &n->narg.next;
10809 savecheckkwd = 0;
10810 }
10811 break;
10812 case TREDIR:
10813 *rpp = n = redirnode;
10814 rpp = &n->nfile.next;
10815 parsefname(); /* read name of redirection file */
10816 break;
10817 case TLP:
10818 if (args && app == &args->narg.next
10819 && !vars && !redir
10820 ) {
10821 struct builtincmd *bcmd;
10822 const char *name;
10823
10824 /* We have a function */
10825 if (readtoken() != TRP)
10826 raise_error_unexpected_syntax(TRP);
10827 name = n->narg.text;
10828 if (!goodname(name)
10829 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10830 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010831 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010832 }
10833 n->type = NDEFUN;
10834 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10835 n->narg.next = parse_command();
10836 return n;
10837 }
10838 /* fall through */
10839 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010840 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010841 goto out;
10842 }
10843 }
10844 out:
10845 *app = NULL;
10846 *vpp = NULL;
10847 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010848 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010849 n->type = NCMD;
10850 n->ncmd.args = args;
10851 n->ncmd.assign = vars;
10852 n->ncmd.redirect = redir;
10853 return n;
10854}
10855
10856static union node *
10857parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010858{
Eric Andersencb57d552001-06-28 07:25:16 +000010859 union node *n1, *n2;
10860 union node *ap, **app;
10861 union node *cp, **cpp;
10862 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010863 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010864 int t;
10865
10866 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010867 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010868
Eric Andersencb57d552001-06-28 07:25:16 +000010869 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010870 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010871 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010872 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010873 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010874 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010875 n1->type = NIF;
10876 n1->nif.test = list(0);
10877 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010878 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010879 n1->nif.ifpart = list(0);
10880 n2 = n1;
10881 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010882 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010883 n2 = n2->nif.elsepart;
10884 n2->type = NIF;
10885 n2->nif.test = list(0);
10886 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010887 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010888 n2->nif.ifpart = list(0);
10889 }
10890 if (lasttoken == TELSE)
10891 n2->nif.elsepart = list(0);
10892 else {
10893 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010894 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010895 }
Eric Andersenc470f442003-07-28 09:56:35 +000010896 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010897 break;
10898 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010899 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010900 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010901 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010902 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010903 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010904 got = readtoken();
10905 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010906 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010907 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010908 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010909 }
10910 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010911 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010912 break;
10913 }
10914 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010915 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010916 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010917 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010918 n1->type = NFOR;
10919 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010920 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010921 if (readtoken() == TIN) {
10922 app = &ap;
10923 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010924 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010925 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010926 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010927 n2->narg.text = wordtext;
10928 n2->narg.backquote = backquotelist;
10929 *app = n2;
10930 app = &n2->narg.next;
10931 }
10932 *app = NULL;
10933 n1->nfor.args = ap;
10934 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010935 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010936 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010937 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010938 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010939 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010940 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010941 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010942 n1->nfor.args = n2;
10943 /*
10944 * Newline or semicolon here is optional (but note
10945 * that the original Bourne shell only allowed NL).
10946 */
10947 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010948 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010949 }
Eric Andersenc470f442003-07-28 09:56:35 +000010950 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010951 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010952 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010953 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010954 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010955 break;
10956 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010957 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010958 n1->type = NCASE;
10959 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010960 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010961 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010962 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010963 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010964 n2->narg.text = wordtext;
10965 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010966 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010967 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010968 } while (readtoken() == TNL);
10969 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010970 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010971 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010972 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010973 checkkwd = CHKNL | CHKKWD;
10974 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010975 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010976 if (lasttoken == TLP)
10977 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010978 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010979 cp->type = NCLIST;
10980 app = &cp->nclist.pattern;
10981 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010982 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010983 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010984 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010985 ap->narg.text = wordtext;
10986 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010987 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010988 break;
10989 app = &ap->narg.next;
10990 readtoken();
10991 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010992 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010993 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010994 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010995 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010996
Eric Andersenc470f442003-07-28 09:56:35 +000010997 cpp = &cp->nclist.next;
10998
10999 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011000 t = readtoken();
11001 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000011002 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011003 raise_error_unexpected_syntax(TENDCASE);
11004 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000011005 }
Eric Andersenc470f442003-07-28 09:56:35 +000011006 }
Eric Andersencb57d552001-06-28 07:25:16 +000011007 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000011008 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000011009 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000011010 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000011011 n1->type = NSUBSHELL;
11012 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011013 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011014 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000011015 break;
11016 case TBEGIN:
11017 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000011018 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000011019 break;
Eric Andersencb57d552001-06-28 07:25:16 +000011020 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000011021 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011022 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011023 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000011024 }
11025
Eric Andersenc470f442003-07-28 09:56:35 +000011026 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011027 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000011028
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011029 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000011030 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000011031 checkkwd = CHKKWD | CHKALIAS;
11032 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000011033 while (readtoken() == TREDIR) {
11034 *rpp = n2 = redirnode;
11035 rpp = &n2->nfile.next;
11036 parsefname();
11037 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011038 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011039 *rpp = NULL;
11040 if (redir) {
11041 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011042 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000011043 n2->type = NREDIR;
11044 n2->nredir.n = n1;
11045 n1 = n2;
11046 }
11047 n1->nredir.redirect = redir;
11048 }
Eric Andersencb57d552001-06-28 07:25:16 +000011049 return n1;
11050}
11051
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011052#if ENABLE_ASH_BASH_COMPAT
11053static int decode_dollar_squote(void)
11054{
11055 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11056 int c, cnt;
11057 char *p;
11058 char buf[4];
11059
11060 c = pgetc();
11061 p = strchr(C_escapes, c);
11062 if (p) {
11063 buf[0] = c;
11064 p = buf;
11065 cnt = 3;
11066 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11067 do {
11068 c = pgetc();
11069 *++p = c;
11070 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11071 pungetc();
11072 } else if (c == 'x') { /* \xHH */
11073 do {
11074 c = pgetc();
11075 *++p = c;
11076 } while (isxdigit(c) && --cnt);
11077 pungetc();
11078 if (cnt == 3) { /* \x but next char is "bad" */
11079 c = 'x';
11080 goto unrecognized;
11081 }
11082 } else { /* simple seq like \\ or \t */
11083 p++;
11084 }
11085 *p = '\0';
11086 p = buf;
11087 c = bb_process_escape_sequence((void*)&p);
11088 } else { /* unrecognized "\z": print both chars unless ' or " */
11089 if (c != '\'' && c != '"') {
11090 unrecognized:
11091 c |= 0x100; /* "please encode \, then me" */
11092 }
11093 }
11094 return c;
11095}
11096#endif
11097
Eric Andersencb57d552001-06-28 07:25:16 +000011098/*
11099 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11100 * is not NULL, read a here document. In the latter case, eofmark is the
11101 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010011102 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000011103 * is the first character of the input token or document.
11104 *
11105 * Because C does not have internal subroutines, I have simulated them
11106 * using goto's to implement the subroutine linkage. The following macros
11107 * will run code that appears at the end of readtoken1.
11108 */
Eric Andersen2870d962001-07-02 17:27:21 +000011109#define CHECKEND() {goto checkend; checkend_return:;}
11110#define PARSEREDIR() {goto parseredir; parseredir_return:;}
11111#define PARSESUB() {goto parsesub; parsesub_return:;}
11112#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11113#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11114#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000011115static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010011116readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000011117{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011118 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010011119 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000011120 char *out;
11121 int len;
11122 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011123 struct nodelist *bqlist;
11124 smallint quotef;
11125 smallint dblquote;
11126 smallint oldstyle;
11127 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000011128#if ENABLE_ASH_EXPAND_PRMT
11129 smallint pssyntax; /* we are expanding a prompt string */
11130#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011131 int varnest; /* levels of variables expansion */
11132 int arinest; /* levels of arithmetic expansion */
11133 int parenlevel; /* levels of parens in arithmetic */
11134 int dqvarnest; /* levels of variables expansion within double quotes */
11135
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011136 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011137
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011138 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000011139 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011140 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011141 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000011142#if ENABLE_ASH_EXPAND_PRMT
11143 pssyntax = (syntax == PSSYNTAX);
11144 if (pssyntax)
11145 syntax = DQSYNTAX;
11146#endif
11147 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011148 varnest = 0;
11149 arinest = 0;
11150 parenlevel = 0;
11151 dqvarnest = 0;
11152
11153 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011154 loop:
11155 /* For each line, until end of word */
Denys Vlasenko958581a2010-09-12 15:04:27 +020011156 CHECKEND(); /* set c to PEOF if at end of here document */
11157 for (;;) { /* until end of line or end of word */
11158 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11159 switch (SIT(c, syntax)) {
11160 case CNL: /* '\n' */
11161 if (syntax == BASESYNTAX)
11162 goto endword; /* exit outer loop */
11163 USTPUTC(c, out);
11164 g_parsefile->linno++;
11165 setprompt_if(doprompt, 2);
11166 c = pgetc();
11167 goto loop; /* continue outer loop */
11168 case CWORD:
11169 USTPUTC(c, out);
11170 break;
11171 case CCTL:
11172 if (eofmark == NULL || dblquote)
11173 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011174#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko958581a2010-09-12 15:04:27 +020011175 if (c == '\\' && bash_dollar_squote) {
11176 c = decode_dollar_squote();
11177 if (c & 0x100) {
11178 USTPUTC('\\', out);
11179 c = (unsigned char)c;
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011180 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011181 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011182#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011183 USTPUTC(c, out);
11184 break;
11185 case CBACK: /* backslash */
11186 c = pgetc_without_PEOA();
11187 if (c == PEOF) {
11188 USTPUTC(CTLESC, out);
11189 USTPUTC('\\', out);
11190 pungetc();
11191 } else if (c == '\n') {
11192 setprompt_if(doprompt, 2);
11193 } else {
11194#if ENABLE_ASH_EXPAND_PRMT
11195 if (c == '$' && pssyntax) {
Eric Andersenc470f442003-07-28 09:56:35 +000011196 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011197 USTPUTC('\\', out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011198 }
Denis Vlasenko46a53062007-09-24 18:30:02 +000011199#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011200 /* Backslash is retained if we are in "str" and next char isn't special */
11201 if (dblquote
11202 && c != '\\'
11203 && c != '`'
11204 && c != '$'
11205 && (c != '"' || eofmark != NULL)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011206 ) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011207 USTPUTC('\\', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011208 }
Ron Yorston549deab2015-05-18 09:57:51 +020011209 USTPUTC(CTLESC, out);
Denys Vlasenko0ff78a02010-08-30 15:20:07 +020011210 USTPUTC(c, out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011211 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011212 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011213 break;
11214 case CSQUOTE:
11215 syntax = SQSYNTAX;
11216 quotemark:
11217 if (eofmark == NULL) {
11218 USTPUTC(CTLQUOTEMARK, out);
11219 }
11220 break;
11221 case CDQUOTE:
11222 syntax = DQSYNTAX;
11223 dblquote = 1;
11224 goto quotemark;
11225 case CENDQUOTE:
11226 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Ron Yorston7e4ed262015-05-18 09:54:43 +020011227 if (eofmark != NULL && varnest == 0) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011228 USTPUTC(c, out);
11229 } else {
11230 if (dqvarnest == 0) {
11231 syntax = BASESYNTAX;
11232 dblquote = 0;
11233 }
11234 quotef = 1;
11235 goto quotemark;
11236 }
11237 break;
11238 case CVAR: /* '$' */
11239 PARSESUB(); /* parse substitution */
11240 break;
11241 case CENDVAR: /* '}' */
11242 if (varnest > 0) {
11243 varnest--;
11244 if (dqvarnest > 0) {
11245 dqvarnest--;
11246 }
11247 c = CTLENDVAR;
11248 }
11249 USTPUTC(c, out);
11250 break;
11251#if ENABLE_SH_MATH_SUPPORT
11252 case CLP: /* '(' in arithmetic */
11253 parenlevel++;
11254 USTPUTC(c, out);
11255 break;
11256 case CRP: /* ')' in arithmetic */
11257 if (parenlevel > 0) {
11258 parenlevel--;
11259 } else {
11260 if (pgetc() == ')') {
Ron Yorstonad88bde2015-05-18 09:56:16 +020011261 c = CTLENDARI;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011262 if (--arinest == 0) {
11263 syntax = prevsyntax;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011264 }
11265 } else {
11266 /*
11267 * unbalanced parens
11268 * (don't 2nd guess - no error)
11269 */
11270 pungetc();
11271 }
11272 }
11273 USTPUTC(c, out);
11274 break;
11275#endif
11276 case CBQUOTE: /* '`' */
11277 PARSEBACKQOLD();
11278 break;
11279 case CENDFILE:
11280 goto endword; /* exit outer loop */
11281 case CIGN:
11282 break;
11283 default:
11284 if (varnest == 0) {
11285#if ENABLE_ASH_BASH_COMPAT
11286 if (c == '&') {
11287 if (pgetc() == '>')
11288 c = 0x100 + '>'; /* flag &> */
11289 pungetc();
11290 }
11291#endif
11292 goto endword; /* exit outer loop */
11293 }
11294 IF_ASH_ALIAS(if (c != PEOA))
11295 USTPUTC(c, out);
11296 }
11297 c = pgetc_fast();
11298 } /* for (;;) */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011299 endword:
Denys Vlasenko958581a2010-09-12 15:04:27 +020011300
Mike Frysinger98c52642009-04-02 10:02:37 +000011301#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011302 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011303 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011304#endif
Ron Yorston0e056f72015-07-01 16:45:40 +010011305 if (syntax != BASESYNTAX && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011306 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011307 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011308 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011309 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011310 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011311 }
11312 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011313 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011314 out = stackblock();
11315 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011316 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011317 && quotef == 0
11318 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011319 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011320 PARSEREDIR(); /* passed as params: out, c */
11321 lasttoken = TREDIR;
11322 return lasttoken;
11323 }
11324 /* else: non-number X seen, interpret it
11325 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011326 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011327 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011328 }
11329 quoteflag = quotef;
11330 backquotelist = bqlist;
11331 grabstackblock(len);
11332 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011333 lasttoken = TWORD;
11334 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011335/* end of readtoken routine */
11336
Eric Andersencb57d552001-06-28 07:25:16 +000011337/*
11338 * Check to see whether we are at the end of the here document. When this
11339 * is called, c is set to the first character of the next input line. If
11340 * we are at the end of the here document, this routine sets the c to PEOF.
11341 */
Eric Andersenc470f442003-07-28 09:56:35 +000011342checkend: {
11343 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011344#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011345 if (c == PEOA)
11346 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011347#endif
11348 if (striptabs) {
11349 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011350 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011351 }
Eric Andersenc470f442003-07-28 09:56:35 +000011352 }
11353 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011354 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011355 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011356
Eric Andersenc470f442003-07-28 09:56:35 +000011357 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011358 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11359 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011360 if (*p == '\n' && *q == '\0') {
11361 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011362 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011363 needprompt = doprompt;
11364 } else {
11365 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011366 }
11367 }
11368 }
11369 }
Eric Andersenc470f442003-07-28 09:56:35 +000011370 goto checkend_return;
11371}
Eric Andersencb57d552001-06-28 07:25:16 +000011372
Eric Andersencb57d552001-06-28 07:25:16 +000011373/*
11374 * Parse a redirection operator. The variable "out" points to a string
11375 * specifying the fd to be redirected. The variable "c" contains the
11376 * first character of the redirection operator.
11377 */
Eric Andersenc470f442003-07-28 09:56:35 +000011378parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011379 /* out is already checked to be a valid number or "" */
11380 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011381 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011382
Denis Vlasenko597906c2008-02-20 16:38:54 +000011383 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011384 if (c == '>') {
11385 np->nfile.fd = 1;
11386 c = pgetc();
11387 if (c == '>')
11388 np->type = NAPPEND;
11389 else if (c == '|')
11390 np->type = NCLOBBER;
11391 else if (c == '&')
11392 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011393 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011394 else {
11395 np->type = NTO;
11396 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011397 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011398 }
11399#if ENABLE_ASH_BASH_COMPAT
11400 else if (c == 0x100 + '>') { /* this flags &> redirection */
11401 np->nfile.fd = 1;
11402 pgetc(); /* this is '>', no need to check */
11403 np->type = NTO2;
11404 }
11405#endif
11406 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011407 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011408 c = pgetc();
11409 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011410 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011411 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011412 np = stzalloc(sizeof(struct nhere));
11413 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011414 }
11415 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011416 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011417 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011418 c = pgetc();
11419 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011420 heredoc->striptabs = 1;
11421 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011422 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011423 pungetc();
11424 }
11425 break;
11426
11427 case '&':
11428 np->type = NFROMFD;
11429 break;
11430
11431 case '>':
11432 np->type = NFROMTO;
11433 break;
11434
11435 default:
11436 np->type = NFROM;
11437 pungetc();
11438 break;
11439 }
Eric Andersencb57d552001-06-28 07:25:16 +000011440 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011441 if (fd >= 0)
11442 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011443 redirnode = np;
11444 goto parseredir_return;
11445}
Eric Andersencb57d552001-06-28 07:25:16 +000011446
Eric Andersencb57d552001-06-28 07:25:16 +000011447/*
11448 * Parse a substitution. At this point, we have read the dollar sign
11449 * and nothing else.
11450 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011451
11452/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11453 * (assuming ascii char codes, as the original implementation did) */
11454#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011455 (((unsigned)(c) - 33 < 32) \
11456 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011457parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011458 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011459 int typeloc;
11460 int flags;
Eric Andersencb57d552001-06-28 07:25:16 +000011461
Eric Andersenc470f442003-07-28 09:56:35 +000011462 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011463 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011464 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011465 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011466#if ENABLE_ASH_BASH_COMPAT
11467 if (c == '\'')
11468 bash_dollar_squote = 1;
11469 else
11470#endif
11471 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011472 pungetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011473 } else if (c == '(') {
11474 /* $(command) or $((arith)) */
Eric Andersenc470f442003-07-28 09:56:35 +000011475 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011476#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011477 PARSEARITH();
11478#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011479 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011480#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011481 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011482 pungetc();
11483 PARSEBACKQNEW();
11484 }
11485 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011486 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
Eric Andersenc470f442003-07-28 09:56:35 +000011487 USTPUTC(CTLVAR, out);
11488 typeloc = out - (char *)stackblock();
11489 USTPUTC(VSNORMAL, out);
11490 subtype = VSNORMAL;
11491 if (c == '{') {
11492 c = pgetc();
11493 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011494 c = pgetc();
11495 if (c == '}')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011496 c = '#'; /* ${#} - same as $# */
Eric Andersenc470f442003-07-28 09:56:35 +000011497 else
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011498 subtype = VSLENGTH; /* ${#VAR} */
11499 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011500 subtype = 0;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011501 }
Eric Andersenc470f442003-07-28 09:56:35 +000011502 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011503 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011504 /* $[{[#]]NAME[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011505 do {
11506 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011507 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011508 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011509 } else if (isdigit(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011510 /* $[{[#]]NUM[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011511 do {
11512 STPUTC(c, out);
11513 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011514 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011515 } else if (is_special(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011516 /* $[{[#]]<specialchar>[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011517 USTPUTC(c, out);
11518 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011519 } else {
11520 badsub:
11521 raise_error_syntax("bad substitution");
11522 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011523 if (c != '}' && subtype == VSLENGTH) {
11524 /* ${#VAR didn't end with } */
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011525 goto badsub;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011526 }
Eric Andersencb57d552001-06-28 07:25:16 +000011527
Eric Andersenc470f442003-07-28 09:56:35 +000011528 STPUTC('=', out);
11529 flags = 0;
11530 if (subtype == 0) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011531 /* ${VAR...} but not $VAR or ${#VAR} */
11532 /* c == first char after VAR */
Eric Andersenc470f442003-07-28 09:56:35 +000011533 switch (c) {
11534 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011535 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011536#if ENABLE_ASH_BASH_COMPAT
11537 if (c == ':' || c == '$' || isdigit(c)) {
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011538//TODO: support more general format ${v:EXPR:EXPR},
11539// where EXPR follows $(()) rules
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011540 subtype = VSSUBSTR;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011541 pungetc();
11542 break; /* "goto do_pungetc" is bigger (!) */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011543 }
11544#endif
11545 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011546 /*FALLTHROUGH*/
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011547 default: {
11548 static const char types[] ALIGN1 = "}-+?=";
11549 const char *p = strchr(types, c);
Eric Andersenc470f442003-07-28 09:56:35 +000011550 if (p == NULL)
11551 goto badsub;
11552 subtype = p - types + VSNORMAL;
11553 break;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011554 }
Eric Andersenc470f442003-07-28 09:56:35 +000011555 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011556 case '#': {
11557 int cc = c;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011558 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011559 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011560 if (c != cc)
11561 goto do_pungetc;
11562 subtype++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011563 break;
11564 }
11565#if ENABLE_ASH_BASH_COMPAT
11566 case '/':
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011567 /* ${v/[/]pattern/repl} */
11568//TODO: encode pattern and repl separately.
11569// Currently ${v/$var_with_slash/repl} is horribly broken
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011570 subtype = VSREPLACE;
11571 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011572 if (c != '/')
11573 goto do_pungetc;
11574 subtype++; /* VSREPLACEALL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011575 break;
11576#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011577 }
Eric Andersenc470f442003-07-28 09:56:35 +000011578 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011579 do_pungetc:
Eric Andersenc470f442003-07-28 09:56:35 +000011580 pungetc();
11581 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011582 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011583 if (subtype != VSNORMAL) {
11584 varnest++;
Ron Yorston7e4ed262015-05-18 09:54:43 +020011585 if (dblquote) {
Eric Andersenc470f442003-07-28 09:56:35 +000011586 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011587 }
11588 }
11589 }
Eric Andersenc470f442003-07-28 09:56:35 +000011590 goto parsesub_return;
11591}
Eric Andersencb57d552001-06-28 07:25:16 +000011592
Eric Andersencb57d552001-06-28 07:25:16 +000011593/*
11594 * Called to parse command substitutions. Newstyle is set if the command
11595 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11596 * list of commands (passed by reference), and savelen is the number of
11597 * characters on the top of the stack which must be preserved.
11598 */
Eric Andersenc470f442003-07-28 09:56:35 +000011599parsebackq: {
11600 struct nodelist **nlpp;
Eric Andersenc470f442003-07-28 09:56:35 +000011601 union node *n;
Ron Yorston072fc602015-07-01 16:46:18 +010011602 char *str;
Eric Andersenc470f442003-07-28 09:56:35 +000011603 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011604 smallint saveprompt = 0;
11605
Eric Andersenc470f442003-07-28 09:56:35 +000011606 str = NULL;
11607 savelen = out - (char *)stackblock();
11608 if (savelen > 0) {
Ron Yorston072fc602015-07-01 16:46:18 +010011609 str = alloca(savelen);
Eric Andersenc470f442003-07-28 09:56:35 +000011610 memcpy(str, stackblock(), savelen);
11611 }
Eric Andersenc470f442003-07-28 09:56:35 +000011612 if (oldstyle) {
11613 /* We must read until the closing backquote, giving special
Denys Vlasenko60cb48c2013-01-14 15:57:44 +010011614 * treatment to some slashes, and then push the string and
11615 * reread it as input, interpreting it normally.
11616 */
Eric Andersenc470f442003-07-28 09:56:35 +000011617 char *pout;
Eric Andersenc470f442003-07-28 09:56:35 +000011618 size_t psavelen;
11619 char *pstr;
11620
Eric Andersenc470f442003-07-28 09:56:35 +000011621 STARTSTACKSTR(pout);
11622 for (;;) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011623 int pc;
11624
11625 setprompt_if(needprompt, 2);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011626 pc = pgetc();
11627 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011628 case '`':
11629 goto done;
11630
11631 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011632 pc = pgetc();
11633 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011634 g_parsefile->linno++;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011635 setprompt_if(doprompt, 2);
Eric Andersenc470f442003-07-28 09:56:35 +000011636 /*
11637 * If eating a newline, avoid putting
11638 * the newline into the new character
11639 * stream (via the STPUTC after the
11640 * switch).
11641 */
11642 continue;
11643 }
11644 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011645 && (!dblquote || pc != '"')
11646 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011647 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011648 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011649 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011650 break;
11651 }
11652 /* fall through */
11653
11654 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011655 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011656 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011657 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011658
11659 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011660 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011661 needprompt = doprompt;
11662 break;
11663
11664 default:
11665 break;
11666 }
11667 STPUTC(pc, pout);
11668 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011669 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011670 STPUTC('\0', pout);
11671 psavelen = pout - (char *)stackblock();
11672 if (psavelen > 0) {
11673 pstr = grabstackstr(pout);
11674 setinputstring(pstr);
11675 }
11676 }
11677 nlpp = &bqlist;
11678 while (*nlpp)
11679 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011680 *nlpp = stzalloc(sizeof(**nlpp));
11681 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011682
11683 if (oldstyle) {
11684 saveprompt = doprompt;
11685 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011686 }
11687
Eric Andersenc470f442003-07-28 09:56:35 +000011688 n = list(2);
11689
11690 if (oldstyle)
11691 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011692 else if (readtoken() != TRP)
11693 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011694
11695 (*nlpp)->n = n;
11696 if (oldstyle) {
11697 /*
11698 * Start reading from old file again, ignoring any pushed back
11699 * tokens left from the backquote parsing
11700 */
11701 popfile();
11702 tokpushback = 0;
11703 }
11704 while (stackblocksize() <= savelen)
11705 growstackblock();
11706 STARTSTACKSTR(out);
11707 if (str) {
11708 memcpy(out, str, savelen);
11709 STADJUST(savelen, out);
Eric Andersenc470f442003-07-28 09:56:35 +000011710 }
Ron Yorston549deab2015-05-18 09:57:51 +020011711 USTPUTC(CTLBACKQ, out);
Eric Andersenc470f442003-07-28 09:56:35 +000011712 if (oldstyle)
11713 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011714 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011715}
11716
Mike Frysinger98c52642009-04-02 10:02:37 +000011717#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011718/*
11719 * Parse an arithmetic expansion (indicate start of one and set state)
11720 */
Eric Andersenc470f442003-07-28 09:56:35 +000011721parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011722 if (++arinest == 1) {
11723 prevsyntax = syntax;
11724 syntax = ARISYNTAX;
Eric Andersencb57d552001-06-28 07:25:16 +000011725 }
Ron Yorstonad88bde2015-05-18 09:56:16 +020011726 USTPUTC(CTLARI, out);
Eric Andersenc470f442003-07-28 09:56:35 +000011727 goto parsearith_return;
11728}
11729#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011730} /* end of readtoken */
11731
Eric Andersencb57d552001-06-28 07:25:16 +000011732/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011733 * Read the next input token.
11734 * If the token is a word, we set backquotelist to the list of cmds in
11735 * backquotes. We set quoteflag to true if any part of the word was
11736 * quoted.
11737 * If the token is TREDIR, then we set redirnode to a structure containing
11738 * the redirection.
11739 * In all cases, the variable startlinno is set to the number of the line
11740 * on which the token starts.
11741 *
11742 * [Change comment: here documents and internal procedures]
11743 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11744 * word parsing code into a separate routine. In this case, readtoken
11745 * doesn't need to have any internal procedures, but parseword does.
11746 * We could also make parseoperator in essence the main routine, and
11747 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011748 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011749#define NEW_xxreadtoken
11750#ifdef NEW_xxreadtoken
11751/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011752static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011753 '\n', '(', ')', /* singles */
11754 '&', '|', ';', /* doubles */
11755 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011756};
Eric Andersencb57d552001-06-28 07:25:16 +000011757
Denis Vlasenko834dee72008-10-07 09:18:30 +000011758#define xxreadtoken_singles 3
11759#define xxreadtoken_doubles 3
11760
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011761static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011762 TNL, TLP, TRP, /* only single occurrence allowed */
11763 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11764 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011765 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011766};
11767
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011768static int
11769xxreadtoken(void)
11770{
11771 int c;
11772
11773 if (tokpushback) {
11774 tokpushback = 0;
11775 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011776 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011777 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011778 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011779 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011780 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011781 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011782 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011783
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011784 if (c == '#') {
11785 while ((c = pgetc()) != '\n' && c != PEOF)
11786 continue;
11787 pungetc();
11788 } else if (c == '\\') {
11789 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011790 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011791 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011792 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011793 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011794 setprompt_if(doprompt, 2);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011795 } else {
11796 const char *p;
11797
11798 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11799 if (c != PEOF) {
11800 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011801 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011802 needprompt = doprompt;
11803 }
11804
11805 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011806 if (p == NULL)
11807 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011808
Denis Vlasenko834dee72008-10-07 09:18:30 +000011809 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11810 int cc = pgetc();
11811 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011812 p += xxreadtoken_doubles + 1;
11813 } else {
11814 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011815#if ENABLE_ASH_BASH_COMPAT
11816 if (c == '&' && cc == '>') /* &> */
11817 break; /* return readtoken1(...) */
11818#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011819 }
11820 }
11821 }
11822 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11823 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011824 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011825 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011826
11827 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011828}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011829#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011830#define RETURN(token) return lasttoken = token
11831static int
11832xxreadtoken(void)
11833{
11834 int c;
11835
11836 if (tokpushback) {
11837 tokpushback = 0;
11838 return lasttoken;
11839 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011840 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011841 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011842 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011843 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011844 switch (c) {
11845 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011846 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011847 continue;
11848 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011849 while ((c = pgetc()) != '\n' && c != PEOF)
11850 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011851 pungetc();
11852 continue;
11853 case '\\':
11854 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011855 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011856 setprompt_if(doprompt, 2);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011857 continue;
11858 }
11859 pungetc();
11860 goto breakloop;
11861 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011862 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011863 needprompt = doprompt;
11864 RETURN(TNL);
11865 case PEOF:
11866 RETURN(TEOF);
11867 case '&':
11868 if (pgetc() == '&')
11869 RETURN(TAND);
11870 pungetc();
11871 RETURN(TBACKGND);
11872 case '|':
11873 if (pgetc() == '|')
11874 RETURN(TOR);
11875 pungetc();
11876 RETURN(TPIPE);
11877 case ';':
11878 if (pgetc() == ';')
11879 RETURN(TENDCASE);
11880 pungetc();
11881 RETURN(TSEMI);
11882 case '(':
11883 RETURN(TLP);
11884 case ')':
11885 RETURN(TRP);
11886 default:
11887 goto breakloop;
11888 }
11889 }
11890 breakloop:
11891 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11892#undef RETURN
11893}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011894#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011895
11896static int
11897readtoken(void)
11898{
11899 int t;
11900#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011901 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011902#endif
11903
11904#if ENABLE_ASH_ALIAS
11905 top:
11906#endif
11907
11908 t = xxreadtoken();
11909
11910 /*
11911 * eat newlines
11912 */
11913 if (checkkwd & CHKNL) {
11914 while (t == TNL) {
11915 parseheredoc();
11916 t = xxreadtoken();
11917 }
11918 }
11919
11920 if (t != TWORD || quoteflag) {
11921 goto out;
11922 }
11923
11924 /*
11925 * check for keywords
11926 */
11927 if (checkkwd & CHKKWD) {
11928 const char *const *pp;
11929
11930 pp = findkwd(wordtext);
11931 if (pp) {
11932 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011933 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011934 goto out;
11935 }
11936 }
11937
11938 if (checkkwd & CHKALIAS) {
11939#if ENABLE_ASH_ALIAS
11940 struct alias *ap;
11941 ap = lookupalias(wordtext, 1);
11942 if (ap != NULL) {
11943 if (*ap->val) {
11944 pushstring(ap->val, ap);
11945 }
11946 goto top;
11947 }
11948#endif
11949 }
11950 out:
11951 checkkwd = 0;
11952#if DEBUG
11953 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011954 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011955 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011956 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011957#endif
11958 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011959}
11960
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011961static char
Denys Vlasenko7e661022015-02-05 21:00:17 +010011962nexttoken_ends_list(void)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011963{
11964 int t;
11965
11966 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011967 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011968 return tokname_array[t][0];
11969}
Eric Andersencb57d552001-06-28 07:25:16 +000011970
11971/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011972 * Read and parse a command. Returns NODE_EOF on end of file.
11973 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011974 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011975static union node *
11976parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011977{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011978 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011979
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011980 tokpushback = 0;
11981 doprompt = interact;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011982 setprompt_if(doprompt, doprompt);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011983 needprompt = 0;
11984 t = readtoken();
11985 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011986 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011987 if (t == TNL)
11988 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011989 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011990 return list(1);
11991}
11992
11993/*
11994 * Input any here documents.
11995 */
11996static void
11997parseheredoc(void)
11998{
11999 struct heredoc *here;
12000 union node *n;
12001
12002 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000012003 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012004
12005 while (here) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020012006 setprompt_if(needprompt, 2);
12007 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012008 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000012009 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012010 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000012011 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012012 n->narg.text = wordtext;
12013 n->narg.backquote = backquotelist;
12014 here->here->nhere.doc = n;
12015 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000012016 }
Eric Andersencb57d552001-06-28 07:25:16 +000012017}
12018
12019
12020/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012021 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000012022 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012023#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012024static const char *
12025expandstr(const char *ps)
12026{
12027 union node n;
12028
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012029 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12030 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012031 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000012032 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012033 popfile();
12034
12035 n.narg.type = NARG;
12036 n.narg.next = NULL;
12037 n.narg.text = wordtext;
12038 n.narg.backquote = backquotelist;
12039
Ron Yorston549deab2015-05-18 09:57:51 +020012040 expandarg(&n, NULL, EXP_QUOTED);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012041 return stackblock();
12042}
12043#endif
12044
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012045/*
12046 * Execute a command or commands contained in a string.
12047 */
12048static int
12049evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000012050{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012051 union node *n;
12052 struct stackmark smark;
12053 int skip;
12054
12055 setinputstring(s);
12056 setstackmark(&smark);
12057
12058 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012059 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012060 evaltree(n, 0);
12061 popstackmark(&smark);
12062 skip = evalskip;
12063 if (skip)
12064 break;
12065 }
12066 popfile();
12067
12068 skip &= mask;
12069 evalskip = skip;
12070 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000012071}
12072
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012073/*
12074 * The eval command.
12075 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012076static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012077evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012078{
12079 char *p;
12080 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012081
Denis Vlasenko68404f12008-03-17 09:00:54 +000012082 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012083 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012084 argv += 2;
12085 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012086 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012087 for (;;) {
12088 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012089 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012090 if (p == NULL)
12091 break;
12092 STPUTC(' ', concat);
12093 }
12094 STPUTC('\0', concat);
12095 p = grabstackstr(concat);
12096 }
12097 evalstring(p, ~SKIPEVAL);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012098 }
12099 return exitstatus;
12100}
12101
12102/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010012103 * Read and execute commands.
12104 * "Top" is nonzero for the top level command loop;
12105 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012106 */
12107static int
12108cmdloop(int top)
12109{
12110 union node *n;
12111 struct stackmark smark;
12112 int inter;
12113 int numeof = 0;
12114
12115 TRACE(("cmdloop(%d) called\n", top));
12116 for (;;) {
12117 int skip;
12118
12119 setstackmark(&smark);
12120#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000012121 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012122 showjobs(stderr, SHOW_CHANGED);
12123#endif
12124 inter = 0;
12125 if (iflag && top) {
12126 inter++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012127 chkmail();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012128 }
12129 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020012130#if DEBUG
12131 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020012132 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000012133#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012134 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012135 if (!top || numeof >= 50)
12136 break;
12137 if (!stoppedjobs()) {
12138 if (!Iflag)
12139 break;
12140 out2str("\nUse \"exit\" to leave shell.\n");
12141 }
12142 numeof++;
12143 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000012144 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12145 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012146 numeof = 0;
12147 evaltree(n, 0);
12148 }
12149 popstackmark(&smark);
12150 skip = evalskip;
12151
12152 if (skip) {
12153 evalskip = 0;
12154 return skip & SKIPEVAL;
12155 }
12156 }
12157 return 0;
12158}
12159
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012160/*
12161 * Take commands from a file. To be compatible we should do a path
12162 * search for the file, which is necessary to find sub-commands.
12163 */
12164static char *
12165find_dot_file(char *name)
12166{
12167 char *fullname;
12168 const char *path = pathval();
12169 struct stat statb;
12170
12171 /* don't try this for absolute or relative paths */
12172 if (strchr(name, '/'))
12173 return name;
12174
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012175 /* IIRC standards do not say whether . is to be searched.
12176 * And it is even smaller this way, making it unconditional for now:
12177 */
12178 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12179 fullname = name;
12180 goto try_cur_dir;
12181 }
12182
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012183 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012184 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012185 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12186 /*
12187 * Don't bother freeing here, since it will
12188 * be freed by the caller.
12189 */
12190 return fullname;
12191 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012192 if (fullname != name)
12193 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012194 }
12195
12196 /* not found in the PATH */
12197 ash_msg_and_raise_error("%s: not found", name);
12198 /* NOTREACHED */
12199}
12200
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012201static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012202dotcmd(int argc, char **argv)
12203{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012204 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012205 struct strlist *sp;
12206 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012207
12208 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012209 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012210
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012211 if (!argv[1]) {
12212 /* bash says: "bash: .: filename argument required" */
12213 return 2; /* bash compat */
12214 }
12215
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012216 /* "false; . empty_file; echo $?" should print 0, not 1: */
12217 exitstatus = 0;
12218
Denys Vlasenko091f8312013-03-17 14:25:22 +010012219 /* This aborts if file isn't found, which is POSIXly correct.
12220 * bash returns exitcode 1 instead.
12221 */
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012222 fullname = find_dot_file(argv[1]);
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012223 argv += 2;
12224 argc -= 2;
12225 if (argc) { /* argc > 0, argv[0] != NULL */
12226 saveparam = shellparam;
12227 shellparam.malloced = 0;
12228 shellparam.nparam = argc;
12229 shellparam.p = argv;
12230 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012231
Denys Vlasenko091f8312013-03-17 14:25:22 +010012232 /* This aborts if file can't be opened, which is POSIXly correct.
12233 * bash returns exitcode 1 instead.
12234 */
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012235 setinputfile(fullname, INPUT_PUSH_FILE);
12236 commandname = fullname;
12237 cmdloop(0);
12238 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012239
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012240 if (argc) {
12241 freeparam(&shellparam);
12242 shellparam = saveparam;
12243 };
12244
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012245 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012246}
12247
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012248static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012249exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012250{
12251 if (stoppedjobs())
12252 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012253 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012254 exitstatus = number(argv[1]);
12255 raise_exception(EXEXIT);
12256 /* NOTREACHED */
12257}
12258
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012259/*
12260 * Read a file containing shell functions.
12261 */
12262static void
12263readcmdfile(char *name)
12264{
12265 setinputfile(name, INPUT_PUSH_FILE);
12266 cmdloop(0);
12267 popfile();
12268}
12269
12270
Denis Vlasenkocc571512007-02-23 21:10:35 +000012271/* ============ find_command inplementation */
12272
12273/*
12274 * Resolve a command name. If you change this routine, you may have to
12275 * change the shellexec routine as well.
12276 */
12277static void
12278find_command(char *name, struct cmdentry *entry, int act, const char *path)
12279{
12280 struct tblentry *cmdp;
12281 int idx;
12282 int prev;
12283 char *fullname;
12284 struct stat statb;
12285 int e;
12286 int updatetbl;
12287 struct builtincmd *bcmd;
12288
12289 /* If name contains a slash, don't use PATH or hash table */
12290 if (strchr(name, '/') != NULL) {
12291 entry->u.index = -1;
12292 if (act & DO_ABS) {
12293 while (stat(name, &statb) < 0) {
12294#ifdef SYSV
12295 if (errno == EINTR)
12296 continue;
12297#endif
12298 entry->cmdtype = CMDUNKNOWN;
12299 return;
12300 }
12301 }
12302 entry->cmdtype = CMDNORMAL;
12303 return;
12304 }
12305
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012306/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012307
12308 updatetbl = (path == pathval());
12309 if (!updatetbl) {
12310 act |= DO_ALTPATH;
12311 if (strstr(path, "%builtin") != NULL)
12312 act |= DO_ALTBLTIN;
12313 }
12314
12315 /* If name is in the table, check answer will be ok */
12316 cmdp = cmdlookup(name, 0);
12317 if (cmdp != NULL) {
12318 int bit;
12319
12320 switch (cmdp->cmdtype) {
12321 default:
12322#if DEBUG
12323 abort();
12324#endif
12325 case CMDNORMAL:
12326 bit = DO_ALTPATH;
12327 break;
12328 case CMDFUNCTION:
12329 bit = DO_NOFUNC;
12330 break;
12331 case CMDBUILTIN:
12332 bit = DO_ALTBLTIN;
12333 break;
12334 }
12335 if (act & bit) {
12336 updatetbl = 0;
12337 cmdp = NULL;
12338 } else if (cmdp->rehash == 0)
12339 /* if not invalidated by cd, we're done */
12340 goto success;
12341 }
12342
12343 /* If %builtin not in path, check for builtin next */
12344 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012345 if (bcmd) {
12346 if (IS_BUILTIN_REGULAR(bcmd))
12347 goto builtin_success;
12348 if (act & DO_ALTPATH) {
12349 if (!(act & DO_ALTBLTIN))
12350 goto builtin_success;
12351 } else if (builtinloc <= 0) {
12352 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012353 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012354 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012355
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012356#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012357 {
12358 int applet_no = find_applet_by_name(name);
12359 if (applet_no >= 0) {
12360 entry->cmdtype = CMDNORMAL;
12361 entry->u.index = -2 - applet_no;
12362 return;
12363 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012364 }
12365#endif
12366
Denis Vlasenkocc571512007-02-23 21:10:35 +000012367 /* We have to search path. */
12368 prev = -1; /* where to start */
12369 if (cmdp && cmdp->rehash) { /* doing a rehash */
12370 if (cmdp->cmdtype == CMDBUILTIN)
12371 prev = builtinloc;
12372 else
12373 prev = cmdp->param.index;
12374 }
12375
12376 e = ENOENT;
12377 idx = -1;
12378 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012379 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012380 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012381 /* NB: code below will still use fullname
12382 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012383 idx++;
12384 if (pathopt) {
12385 if (prefix(pathopt, "builtin")) {
12386 if (bcmd)
12387 goto builtin_success;
12388 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012389 }
12390 if ((act & DO_NOFUNC)
12391 || !prefix(pathopt, "func")
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +020012392 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012393 continue;
12394 }
12395 }
12396 /* if rehash, don't redo absolute path names */
12397 if (fullname[0] == '/' && idx <= prev) {
12398 if (idx < prev)
12399 continue;
12400 TRACE(("searchexec \"%s\": no change\n", name));
12401 goto success;
12402 }
12403 while (stat(fullname, &statb) < 0) {
12404#ifdef SYSV
12405 if (errno == EINTR)
12406 continue;
12407#endif
12408 if (errno != ENOENT && errno != ENOTDIR)
12409 e = errno;
12410 goto loop;
12411 }
12412 e = EACCES; /* if we fail, this will be the error */
12413 if (!S_ISREG(statb.st_mode))
12414 continue;
12415 if (pathopt) { /* this is a %func directory */
12416 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012417 /* NB: stalloc will return space pointed by fullname
12418 * (because we don't have any intervening allocations
12419 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012420 readcmdfile(fullname);
12421 cmdp = cmdlookup(name, 0);
12422 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12423 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12424 stunalloc(fullname);
12425 goto success;
12426 }
12427 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12428 if (!updatetbl) {
12429 entry->cmdtype = CMDNORMAL;
12430 entry->u.index = idx;
12431 return;
12432 }
12433 INT_OFF;
12434 cmdp = cmdlookup(name, 1);
12435 cmdp->cmdtype = CMDNORMAL;
12436 cmdp->param.index = idx;
12437 INT_ON;
12438 goto success;
12439 }
12440
12441 /* We failed. If there was an entry for this command, delete it */
12442 if (cmdp && updatetbl)
12443 delete_cmd_entry();
12444 if (act & DO_ERR)
12445 ash_msg("%s: %s", name, errmsg(e, "not found"));
12446 entry->cmdtype = CMDUNKNOWN;
12447 return;
12448
12449 builtin_success:
12450 if (!updatetbl) {
12451 entry->cmdtype = CMDBUILTIN;
12452 entry->u.cmd = bcmd;
12453 return;
12454 }
12455 INT_OFF;
12456 cmdp = cmdlookup(name, 1);
12457 cmdp->cmdtype = CMDBUILTIN;
12458 cmdp->param.cmd = bcmd;
12459 INT_ON;
12460 success:
12461 cmdp->rehash = 0;
12462 entry->cmdtype = cmdp->cmdtype;
12463 entry->u = cmdp->param;
12464}
12465
12466
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012467/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012468
Eric Andersencb57d552001-06-28 07:25:16 +000012469/*
Eric Andersencb57d552001-06-28 07:25:16 +000012470 * The trap builtin.
12471 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012472static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012473trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012474{
12475 char *action;
12476 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012477 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012478
Eric Andersenc470f442003-07-28 09:56:35 +000012479 nextopt(nullstr);
12480 ap = argptr;
12481 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012482 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012483 char *tr = trap_ptr[signo];
12484 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012485 /* note: bash adds "SIG", but only if invoked
12486 * as "bash". If called as "sh", or if set -o posix,
12487 * then it prints short signal names.
12488 * We are printing short names: */
12489 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012490 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012491 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012492 /* trap_ptr != trap only if we are in special-cased `trap` code.
12493 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012494 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012495 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012496 }
12497 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012498 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012499 if (trap_ptr != trap) {
12500 free(trap_ptr);
12501 trap_ptr = trap;
12502 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012503 */
Eric Andersencb57d552001-06-28 07:25:16 +000012504 return 0;
12505 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012506
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012507 action = NULL;
12508 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012509 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012510 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012511 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012512 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012513 if (signo < 0) {
12514 /* Mimic bash message exactly */
12515 ash_msg("%s: invalid signal specification", *ap);
12516 exitcode = 1;
12517 goto next;
12518 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012519 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012520 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012521 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012522 action = NULL;
12523 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012524 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012525 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012526 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012527 if (action)
12528 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012529 trap[signo] = action;
12530 if (signo != 0)
12531 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012532 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012533 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012534 ap++;
12535 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012536 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012537}
12538
Eric Andersenc470f442003-07-28 09:56:35 +000012539
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012540/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012541
Denys Vlasenko2ec34962014-09-08 16:52:39 +020012542#if ENABLE_ASH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012543static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012544helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012545{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012546 unsigned col;
12547 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012548
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012549 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012550 "Built-in commands:\n"
12551 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012552 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012553 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012554 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012555 if (col > 60) {
12556 out1fmt("\n");
12557 col = 0;
12558 }
12559 }
Denys Vlasenko2ec34962014-09-08 16:52:39 +020012560# if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012561 {
12562 const char *a = applet_names;
12563 while (*a) {
12564 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12565 if (col > 60) {
12566 out1fmt("\n");
12567 col = 0;
12568 }
12569 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012570 }
12571 }
Denys Vlasenko2ec34962014-09-08 16:52:39 +020012572# endif
Eric Andersenc470f442003-07-28 09:56:35 +000012573 out1fmt("\n\n");
12574 return EXIT_SUCCESS;
12575}
Denys Vlasenko2ec34962014-09-08 16:52:39 +020012576#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012577
Flemming Madsend96ffda2013-04-07 18:47:24 +020012578#if MAX_HISTORY
12579static int FAST_FUNC
12580historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12581{
12582 show_history(line_input_state);
12583 return EXIT_SUCCESS;
12584}
12585#endif
12586
Eric Andersencb57d552001-06-28 07:25:16 +000012587/*
Eric Andersencb57d552001-06-28 07:25:16 +000012588 * The export and readonly commands.
12589 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012590static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012591exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012592{
12593 struct var *vp;
12594 char *name;
12595 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012596 char **aptr;
Denys Vlasenkod5275882012-10-01 13:41:17 +020012597 char opt;
12598 int flag;
12599 int flag_off;
Eric Andersencb57d552001-06-28 07:25:16 +000012600
Denys Vlasenkod5275882012-10-01 13:41:17 +020012601 /* "readonly" in bash accepts, but ignores -n.
12602 * We do the same: it saves a conditional in nextopt's param.
12603 */
12604 flag_off = 0;
12605 while ((opt = nextopt("np")) != '\0') {
12606 if (opt == 'n')
12607 flag_off = VEXPORT;
12608 }
12609 flag = VEXPORT;
12610 if (argv[0][0] == 'r') {
12611 flag = VREADONLY;
12612 flag_off = 0; /* readonly ignores -n */
12613 }
12614 flag_off = ~flag_off;
12615
12616 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12617 {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012618 aptr = argptr;
12619 name = *aptr;
12620 if (name) {
12621 do {
12622 p = strchr(name, '=');
12623 if (p != NULL) {
12624 p++;
12625 } else {
12626 vp = *findvar(hashvar(name), name);
12627 if (vp) {
Denys Vlasenkod5275882012-10-01 13:41:17 +020012628 vp->flags = ((vp->flags | flag) & flag_off);
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012629 continue;
12630 }
Eric Andersencb57d552001-06-28 07:25:16 +000012631 }
Denys Vlasenkod5275882012-10-01 13:41:17 +020012632 setvar(name, p, (flag & flag_off));
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012633 } while ((name = *++aptr) != NULL);
12634 return 0;
12635 }
Eric Andersencb57d552001-06-28 07:25:16 +000012636 }
Denys Vlasenkod5275882012-10-01 13:41:17 +020012637
12638 /* No arguments. Show the list of exported or readonly vars.
12639 * -n is ignored.
12640 */
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012641 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012642 return 0;
12643}
12644
Eric Andersencb57d552001-06-28 07:25:16 +000012645/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012646 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012647 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012648static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012649unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012650{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012651 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012652
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012653 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012654 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012655 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012656}
12657
Eric Andersencb57d552001-06-28 07:25:16 +000012658/*
Eric Andersencb57d552001-06-28 07:25:16 +000012659 * The unset builtin command. We unset the function before we unset the
12660 * variable to allow a function to be unset when there is a readonly variable
12661 * with the same name.
12662 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012663static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012664unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012665{
12666 char **ap;
12667 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012668 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012669 int ret = 0;
12670
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012671 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012672 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012673 }
Eric Andersencb57d552001-06-28 07:25:16 +000012674
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012675 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012676 if (flag != 'f') {
12677 i = unsetvar(*ap);
12678 ret |= i;
12679 if (!(i & 2))
12680 continue;
12681 }
12682 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012683 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012684 }
Eric Andersenc470f442003-07-28 09:56:35 +000012685 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012686}
12687
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012688static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012689 ' ', offsetof(struct tms, tms_utime),
12690 '\n', offsetof(struct tms, tms_stime),
12691 ' ', offsetof(struct tms, tms_cutime),
12692 '\n', offsetof(struct tms, tms_cstime),
12693 0
12694};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012695static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012696timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012697{
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012698 unsigned long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012699 const unsigned char *p;
12700 struct tms buf;
12701
Bartosz Golaszewski5d2e4092014-06-22 14:01:13 +020012702 clk_tck = bb_clk_tck();
Eric Andersencb57d552001-06-28 07:25:16 +000012703 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012704
12705 p = timescmd_str;
12706 do {
12707 t = *(clock_t *)(((char *) &buf) + p[1]);
12708 s = t / clk_tck;
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012709 t = t % clk_tck;
12710 out1fmt("%lum%lu.%03lus%c",
12711 s / 60, s % 60,
12712 (t * 1000) / clk_tck,
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012713 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012714 p += 2;
12715 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012716
Eric Andersencb57d552001-06-28 07:25:16 +000012717 return 0;
12718}
12719
Mike Frysinger98c52642009-04-02 10:02:37 +000012720#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012721/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012722 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012723 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012724 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012725 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012726 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012727static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012728letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012729{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012730 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012731
Denis Vlasenko68404f12008-03-17 09:00:54 +000012732 argv++;
12733 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012734 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012735 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012736 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012737 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012738
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012739 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012740}
Eric Andersenc470f442003-07-28 09:56:35 +000012741#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012742
Eric Andersenc470f442003-07-28 09:56:35 +000012743/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012744 * The read builtin. Options:
12745 * -r Do not interpret '\' specially
12746 * -s Turn off echo (tty only)
12747 * -n NCHARS Read NCHARS max
12748 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12749 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12750 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012751 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012752 * TODO: bash also has:
12753 * -a ARRAY Read into array[0],[1],etc
12754 * -d DELIM End on DELIM char, not newline
12755 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012756 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012757static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012758readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012759{
Denys Vlasenko73067272010-01-12 22:11:24 +010012760 char *opt_n = NULL;
12761 char *opt_p = NULL;
12762 char *opt_t = NULL;
12763 char *opt_u = NULL;
12764 int read_flags = 0;
12765 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012766 int i;
12767
Denys Vlasenko73067272010-01-12 22:11:24 +010012768 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012769 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012770 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012771 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012772 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012773 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012774 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012775 break;
12776 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012777 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012778 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012779 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012780 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012781 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012782 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012783 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012784 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012785 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012786 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012787 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012788 default:
12789 break;
12790 }
Eric Andersenc470f442003-07-28 09:56:35 +000012791 }
Paul Fox02eb9342005-09-07 16:56:02 +000012792
Denys Vlasenko9e71e3c2012-09-06 13:28:10 +020012793 /* "read -s" needs to save/restore termios, can't allow ^C
12794 * to jump out of it.
12795 */
12796 INT_OFF;
Denys Vlasenko0a0acb52015-04-18 19:36:38 +020012797 r = shell_builtin_read(setvar0,
Denys Vlasenko73067272010-01-12 22:11:24 +010012798 argptr,
12799 bltinlookup("IFS"), /* can be NULL */
12800 read_flags,
12801 opt_n,
12802 opt_p,
12803 opt_t,
12804 opt_u
12805 );
Denys Vlasenko9e71e3c2012-09-06 13:28:10 +020012806 INT_ON;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012807
Denys Vlasenko73067272010-01-12 22:11:24 +010012808 if ((uintptr_t)r > 1)
12809 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012810
Denys Vlasenko73067272010-01-12 22:11:24 +010012811 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012812}
12813
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012814static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012815umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012816{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012817 static const char permuser[3] ALIGN1 = "ugo";
12818 static const char permmode[3] ALIGN1 = "rwx";
12819 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012820 S_IRUSR, S_IWUSR, S_IXUSR,
12821 S_IRGRP, S_IWGRP, S_IXGRP,
12822 S_IROTH, S_IWOTH, S_IXOTH
12823 };
12824
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012825 /* TODO: use bb_parse_mode() instead */
12826
Eric Andersenc470f442003-07-28 09:56:35 +000012827 char *ap;
12828 mode_t mask;
12829 int i;
12830 int symbolic_mode = 0;
12831
12832 while (nextopt("S") != '\0') {
12833 symbolic_mode = 1;
12834 }
12835
Denis Vlasenkob012b102007-02-19 22:43:01 +000012836 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012837 mask = umask(0);
12838 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012839 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012840
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012841 ap = *argptr;
12842 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012843 if (symbolic_mode) {
12844 char buf[18];
12845 char *p = buf;
12846
12847 for (i = 0; i < 3; i++) {
12848 int j;
12849
12850 *p++ = permuser[i];
12851 *p++ = '=';
12852 for (j = 0; j < 3; j++) {
12853 if ((mask & permmask[3 * i + j]) == 0) {
12854 *p++ = permmode[j];
12855 }
12856 }
12857 *p++ = ',';
12858 }
12859 *--p = 0;
12860 puts(buf);
12861 } else {
12862 out1fmt("%.4o\n", mask);
12863 }
12864 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012865 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012866 mask = 0;
12867 do {
12868 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012869 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012870 mask = (mask << 3) + (*ap - '0');
12871 } while (*++ap != '\0');
12872 umask(mask);
12873 } else {
12874 mask = ~mask & 0777;
12875 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012876 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012877 }
12878 umask(~mask & 0777);
12879 }
12880 }
12881 return 0;
12882}
12883
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012884static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012885ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012886{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012887 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012888}
12889
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012890/* ============ main() and helpers */
12891
12892/*
12893 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012894 */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012895static void
12896exitshell(void)
12897{
12898 struct jmploc loc;
12899 char *p;
12900 int status;
12901
Denys Vlasenkobede2152011-09-04 16:12:33 +020012902#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12903 save_history(line_input_state);
12904#endif
12905
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012906 status = exitstatus;
12907 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12908 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012909 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012910/* dash bug: it just does _exit(exitstatus) here
12911 * but we have to do setjobctl(0) first!
12912 * (bug is still not fixed in dash-0.5.3 - if you run dash
12913 * under Midnight Commander, on exit from dash MC is backgrounded) */
12914 status = exitstatus;
12915 goto out;
12916 }
12917 exception_handler = &loc;
12918 p = trap[0];
12919 if (p) {
12920 trap[0] = NULL;
12921 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012922 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012923 }
12924 flush_stdout_stderr();
12925 out:
12926 setjobctl(0);
12927 _exit(status);
12928 /* NOTREACHED */
12929}
12930
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012931static void
12932init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012933{
12934 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012935 /* we will never free this */
12936 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012937
12938 /* from trap.c: */
12939 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012940 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12941 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12942 */
Denys Vlasenkocacb2cd2010-10-05 00:13:02 +020012943 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012944
12945 /* from var.c: */
12946 {
12947 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012948 const char *p;
12949 struct stat st1, st2;
12950
12951 initvar();
12952 for (envp = environ; envp && *envp; envp++) {
12953 if (strchr(*envp, '=')) {
12954 setvareq(*envp, VEXPORT|VTEXTFIXED);
12955 }
12956 }
12957
Denys Vlasenko0a0acb52015-04-18 19:36:38 +020012958 setvar0("PPID", utoa(getppid()));
Bernhard Reutner-Fischer80f8cdf2013-11-08 14:25:24 +010012959#if ENABLE_ASH_BASH_COMPAT
12960 p = lookupvar("SHLVL");
Denys Vlasenko5680e982014-01-07 16:12:48 +010012961 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020012962 if (!lookupvar("HOSTNAME")) {
12963 struct utsname uts;
12964 uname(&uts);
Denys Vlasenko0a0acb52015-04-18 19:36:38 +020012965 setvar0("HOSTNAME", uts.nodename);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020012966 }
Bernhard Reutner-Fischer80f8cdf2013-11-08 14:25:24 +010012967#endif
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012968 p = lookupvar("PWD");
Denys Vlasenkob0b83432011-03-07 12:34:59 +010012969 if (p) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012970 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
Denys Vlasenkob0b83432011-03-07 12:34:59 +010012971 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
12972 ) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012973 p = '\0';
Denys Vlasenkob0b83432011-03-07 12:34:59 +010012974 }
12975 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012976 setpwd(p, 0);
12977 }
12978}
12979
Denys Vlasenkob0b83432011-03-07 12:34:59 +010012980
12981//usage:#define ash_trivial_usage
Denys Vlasenko6b6af532011-03-08 10:24:17 +010012982//usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +010012983//usage:#define ash_full_usage "\n\n"
12984//usage: "Unix shell interpreter"
12985
12986//usage:#if ENABLE_FEATURE_SH_IS_ASH
12987//usage:# define sh_trivial_usage ash_trivial_usage
12988//usage:# define sh_full_usage ash_full_usage
12989//usage:#endif
12990//usage:#if ENABLE_FEATURE_BASH_IS_ASH
12991//usage:# define bash_trivial_usage ash_trivial_usage
12992//usage:# define bash_full_usage ash_full_usage
12993//usage:#endif
12994
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012995/*
12996 * Process the shell command line arguments.
12997 */
12998static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012999procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013000{
13001 int i;
13002 const char *xminusc;
13003 char **xargv;
13004
13005 xargv = argv;
13006 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013007 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013008 xargv++;
13009 for (i = 0; i < NOPTS; i++)
13010 optlist[i] = 2;
13011 argptr = xargv;
Denys Vlasenkob0b83432011-03-07 12:34:59 +010013012 if (options(/*cmdline:*/ 1)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013013 /* it already printed err message */
13014 raise_exception(EXERROR);
13015 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013016 xargv = argptr;
13017 xminusc = minusc;
13018 if (*xargv == NULL) {
13019 if (xminusc)
13020 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13021 sflag = 1;
13022 }
13023 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13024 iflag = 1;
13025 if (mflag == 2)
13026 mflag = iflag;
13027 for (i = 0; i < NOPTS; i++)
13028 if (optlist[i] == 2)
13029 optlist[i] = 0;
13030#if DEBUG == 2
13031 debug = 1;
13032#endif
13033 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13034 if (xminusc) {
13035 minusc = *xargv++;
13036 if (*xargv)
13037 goto setarg0;
13038 } else if (!sflag) {
13039 setinputfile(*xargv, 0);
13040 setarg0:
13041 arg0 = *xargv++;
13042 commandname = arg0;
13043 }
13044
13045 shellparam.p = xargv;
13046#if ENABLE_ASH_GETOPTS
13047 shellparam.optind = 1;
13048 shellparam.optoff = -1;
13049#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013050 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013051 while (*xargv) {
13052 shellparam.nparam++;
13053 xargv++;
13054 }
13055 optschanged();
13056}
13057
13058/*
13059 * Read /etc/profile or .profile.
13060 */
13061static void
13062read_profile(const char *name)
13063{
13064 int skip;
13065
13066 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13067 return;
13068 skip = cmdloop(0);
13069 popfile();
13070 if (skip)
13071 exitshell();
13072}
13073
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013074/*
13075 * This routine is called when an error or an interrupt occurs in an
13076 * interactive shell and control is returned to the main command loop.
13077 */
13078static void
13079reset(void)
13080{
13081 /* from eval.c: */
13082 evalskip = 0;
13083 loopnest = 0;
13084 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013085 g_parsefile->left_in_buffer = 0;
13086 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013087 popallfiles();
13088 /* from parser.c: */
13089 tokpushback = 0;
13090 checkkwd = 0;
13091 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013092 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013093}
13094
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013095#if PROFILE
13096static short profile_buf[16384];
13097extern int etext();
13098#endif
13099
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013100/*
13101 * Main routine. We initialize things, parse the arguments, execute
13102 * profiles if we're a login shell, and then call cmdloop to execute
13103 * commands. The setjmp call sets up the location to jump to when an
13104 * exception occurs. When an exception occurs the variable "state"
13105 * is used to figure out how far we had gotten.
13106 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013107int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013108int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013109{
Mike Frysinger98c52642009-04-02 10:02:37 +000013110 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013111 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013112 struct jmploc jmploc;
13113 struct stackmark smark;
13114
Denis Vlasenko01631112007-12-16 17:20:38 +000013115 /* Initialize global data */
13116 INIT_G_misc();
13117 INIT_G_memstack();
13118 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013119#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013120 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013121#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013122 INIT_G_cmdtable();
13123
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013124#if PROFILE
13125 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13126#endif
13127
13128#if ENABLE_FEATURE_EDITING
13129 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13130#endif
13131 state = 0;
13132 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013133 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013134 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013135
13136 reset();
13137
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013138 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013139 if (e == EXERROR)
13140 exitstatus = 2;
13141 s = state;
Denys Vlasenkob563f622010-09-25 17:15:13 +020013142 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013143 exitshell();
Denys Vlasenkob563f622010-09-25 17:15:13 +020013144 }
13145 if (e == EXINT) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013146 outcslow('\n', stderr);
Denys Vlasenkob563f622010-09-25 17:15:13 +020013147 }
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013148
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013149 popstackmark(&smark);
13150 FORCE_INT_ON; /* enable interrupts */
13151 if (s == 1)
13152 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013153 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013154 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013155 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013156 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013157 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013158 }
13159 exception_handler = &jmploc;
13160#if DEBUG
13161 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013162 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013163 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013164#endif
13165 rootpid = getpid();
13166
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013167 init();
13168 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013169 procargs(argv);
13170
Denys Vlasenko6088e132010-12-25 23:58:42 +010013171 if (argv[0] && argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013172 isloginsh = 1;
13173 if (isloginsh) {
Stefan Hellermann4ef14392013-03-15 02:45:50 +010013174 const char *hp;
13175
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013176 state = 1;
13177 read_profile("/etc/profile");
13178 state1:
13179 state = 2;
Stefan Hellermann4ef14392013-03-15 02:45:50 +010013180 hp = lookupvar("HOME");
13181 if (hp) {
13182 hp = concat_path_file(hp, ".profile");
13183 read_profile(hp);
13184 free((char*)hp);
13185 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013186 }
13187 state2:
13188 state = 3;
13189 if (
13190#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013191 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013192#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013193 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013194 ) {
13195 shinit = lookupvar("ENV");
13196 if (shinit != NULL && *shinit != '\0') {
13197 read_profile(shinit);
13198 }
13199 }
13200 state3:
13201 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013202 if (minusc) {
13203 /* evalstring pushes parsefile stack.
13204 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013205 * is one of stacked source fds.
13206 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020013207 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020013208 // ^^ not necessary since now we special-case fd 0
13209 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013210 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013211 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013212
13213 if (sflag || minusc == NULL) {
Denys Vlasenko4840ae82011-09-04 15:28:03 +020013214#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013215 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013216 const char *hp = lookupvar("HISTFILE");
Stefan Hellermannaeb717a2013-03-03 15:29:32 +010013217 if (!hp) {
13218 hp = lookupvar("HOME");
Stefan Hellermann4ef14392013-03-15 02:45:50 +010013219 if (hp) {
Stefan Hellermannaeb717a2013-03-03 15:29:32 +010013220 hp = concat_path_file(hp, ".ash_history");
Denys Vlasenko0a0acb52015-04-18 19:36:38 +020013221 setvar0("HISTFILE", hp);
Stefan Hellermannaeb717a2013-03-03 15:29:32 +010013222 free((char*)hp);
13223 hp = lookupvar("HISTFILE");
13224 }
13225 }
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013226 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013227 line_input_state->hist_file = hp;
Denys Vlasenko2c4de5b2011-03-31 13:16:52 +020013228# if ENABLE_FEATURE_SH_HISTFILESIZE
13229 hp = lookupvar("HISTFILESIZE");
13230 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13231# endif
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013232 }
13233#endif
13234 state4: /* XXX ??? - why isn't this before the "if" statement */
13235 cmdloop(1);
13236 }
13237#if PROFILE
13238 monitor(0);
13239#endif
13240#ifdef GPROF
13241 {
13242 extern void _mcleanup(void);
13243 _mcleanup();
13244 }
13245#endif
Denys Vlasenkob563f622010-09-25 17:15:13 +020013246 TRACE(("End of main reached\n"));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013247 exitshell();
13248 /* NOTREACHED */
13249}
13250
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251
Eric Andersendf82f612001-06-28 07:46:40 +000013252/*-
13253 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013254 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013255 *
13256 * This code is derived from software contributed to Berkeley by
13257 * Kenneth Almquist.
13258 *
13259 * Redistribution and use in source and binary forms, with or without
13260 * modification, are permitted provided that the following conditions
13261 * are met:
13262 * 1. Redistributions of source code must retain the above copyright
13263 * notice, this list of conditions and the following disclaimer.
13264 * 2. Redistributions in binary form must reproduce the above copyright
13265 * notice, this list of conditions and the following disclaimer in the
13266 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013267 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013268 * may be used to endorse or promote products derived from this software
13269 * without specific prior written permission.
13270 *
13271 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13272 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13273 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13274 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13275 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13276 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13277 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13278 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13279 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13280 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13281 * SUCH DAMAGE.
13282 */