blob: f631e3d25d9e145ada45e706cadfe10aa4465dee [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020016 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000039#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000040#include <paths.h>
41#include <setjmp.h>
42#include <fnmatch.h>
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020043#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010044
45#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000046#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020047#if ENABLE_ASH_RANDOM_SUPPORT
48# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020049#else
50# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020051#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000052
Denys Vlasenko1fcbff22010-06-26 02:40:08 +020053#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +010054#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000055/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020056# undef CONFIG_FEATURE_SH_STANDALONE
57# undef ENABLE_FEATURE_SH_STANDALONE
58# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010059# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020060# define ENABLE_FEATURE_SH_STANDALONE 0
61# define IF_FEATURE_SH_STANDALONE(...)
62# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000063#endif
64
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000065#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000066# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000067#endif
68
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010069#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000070# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000071#endif
72
Denys Vlasenko771f1992010-07-16 14:31:34 +020073//applet:IF_ASH(APPLET(ash, _BB_DIR_BIN, _BB_SUID_DROP))
74//applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, _BB_DIR_BIN, _BB_SUID_DROP, sh))
75//applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, _BB_DIR_BIN, _BB_SUID_DROP, bash))
76
Denys Vlasenkod383b492010-09-06 10:22:13 +020077//kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
Denys Vlasenko771f1992010-07-16 14:31:34 +020078//kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
79
80//config:config ASH
81//config: bool "ash"
82//config: default y
83//config: depends on !NOMMU
84//config: help
85//config: Tha 'ash' shell adds about 60k in the default configuration and is
86//config: the most complete and most pedantically correct shell included with
87//config: busybox. This shell is actually a derivative of the Debian 'dash'
88//config: shell (by Herbert Xu), which was created by porting the 'ash' shell
89//config: (written by Kenneth Almquist) from NetBSD.
90//config:
91//config:config ASH_BASH_COMPAT
92//config: bool "bash-compatible extensions"
93//config: default y
94//config: depends on ASH
95//config: help
96//config: Enable bash-compatible extensions.
97//config:
98//config:config ASH_JOB_CONTROL
99//config: bool "Job control"
100//config: default y
101//config: depends on ASH
102//config: help
103//config: Enable job control in the ash shell.
104//config:
105//config:config ASH_ALIAS
106//config: bool "alias support"
107//config: default y
108//config: depends on ASH
109//config: help
110//config: Enable alias support in the ash shell.
111//config:
112//config:config ASH_GETOPTS
113//config: bool "Builtin getopt to parse positional parameters"
114//config: default y
115//config: depends on ASH
116//config: help
117//config: Enable getopts builtin in the ash shell.
118//config:
119//config:config ASH_BUILTIN_ECHO
120//config: bool "Builtin version of 'echo'"
121//config: default y
122//config: depends on ASH
123//config: help
124//config: Enable support for echo, builtin to ash.
125//config:
126//config:config ASH_BUILTIN_PRINTF
127//config: bool "Builtin version of 'printf'"
128//config: default y
129//config: depends on ASH
130//config: help
131//config: Enable support for printf, builtin to ash.
132//config:
133//config:config ASH_BUILTIN_TEST
134//config: bool "Builtin version of 'test'"
135//config: default y
136//config: depends on ASH
137//config: help
138//config: Enable support for test, builtin to ash.
139//config:
140//config:config ASH_CMDCMD
141//config: bool "'command' command to override shell builtins"
142//config: default y
143//config: depends on ASH
144//config: help
145//config: Enable support for the ash 'command' builtin, which allows
146//config: you to run the specified command with the specified arguments,
147//config: even when there is an ash builtin command with the same name.
148//config:
149//config:config ASH_MAIL
150//config: bool "Check for new mail on interactive shells"
151//config: default n
152//config: depends on ASH
153//config: help
154//config: Enable "check for new mail" in the ash shell.
155//config:
156//config:config ASH_OPTIMIZE_FOR_SIZE
157//config: bool "Optimize for size instead of speed"
158//config: default y
159//config: depends on ASH
160//config: help
161//config: Compile ash for reduced size at the price of speed.
162//config:
163//config:config ASH_RANDOM_SUPPORT
164//config: bool "Pseudorandom generator and $RANDOM variable"
165//config: default y
166//config: depends on ASH
167//config: help
168//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
169//config: Each read of "$RANDOM" will generate a new pseudorandom value.
170//config: You can reset the generator by using a specified start value.
171//config: After "unset RANDOM" the generator will switch off and this
172//config: variable will no longer have special treatment.
173//config:
174//config:config ASH_EXPAND_PRMT
175//config: bool "Expand prompt string"
176//config: default y
177//config: depends on ASH
178//config: help
179//config: "PS#" may contain volatile content, such as backquote commands.
180//config: This option recreates the prompt string from the environment
181//config: variable each time it is displayed.
Denys Vlasenko51ca7762010-07-16 17:16:40 +0200182//config:
Denys Vlasenko771f1992010-07-16 14:31:34 +0200183
184//usage:#define ash_trivial_usage NOUSAGE_STR
185//usage:#define ash_full_usage ""
186//usage:#define sh_trivial_usage NOUSAGE_STR
187//usage:#define sh_full_usage ""
188//usage:#define bash_trivial_usage NOUSAGE_STR
189//usage:#define bash_full_usage ""
190
Denis Vlasenkob012b102007-02-19 22:43:01 +0000191
Denis Vlasenko01631112007-12-16 17:20:38 +0000192/* ============ Hash table sizes. Configurable. */
193
194#define VTABSIZE 39
195#define ATABSIZE 39
196#define CMDTABLESIZE 31 /* should be prime */
197
198
Denis Vlasenkob012b102007-02-19 22:43:01 +0000199/* ============ Shell options */
200
201static const char *const optletters_optnames[] = {
202 "e" "errexit",
203 "f" "noglob",
204 "I" "ignoreeof",
205 "i" "interactive",
206 "m" "monitor",
207 "n" "noexec",
208 "s" "stdin",
209 "x" "xtrace",
210 "v" "verbose",
211 "C" "noclobber",
212 "a" "allexport",
213 "b" "notify",
214 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100215 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100216#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100217 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100218#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000219#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000220 ,"\0" "nolog"
221 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000222#endif
223};
224
Denys Vlasenko285ad152009-12-04 23:02:27 +0100225#define optletters(n) optletters_optnames[n][0]
226#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000227
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000228enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000229
Eric Andersenc470f442003-07-28 09:56:35 +0000230
Denis Vlasenkob012b102007-02-19 22:43:01 +0000231/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000232
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200233#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000234
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000235/*
Eric Andersenc470f442003-07-28 09:56:35 +0000236 * We enclose jmp_buf in a structure so that we can declare pointers to
237 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000238 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000239 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000240 * exception handlers, the user should save the value of handler on entry
241 * to an inner scope, set handler to point to a jmploc structure for the
242 * inner scope, and restore handler on exit from the scope.
243 */
Eric Andersenc470f442003-07-28 09:56:35 +0000244struct jmploc {
245 jmp_buf loc;
246};
Denis Vlasenko01631112007-12-16 17:20:38 +0000247
248struct globals_misc {
249 /* pid of main shell */
250 int rootpid;
251 /* shell level: 0 for the main shell, 1 for its children, and so on */
252 int shlvl;
253#define rootshell (!shlvl)
254 char *minusc; /* argument to -c option */
255
256 char *curdir; // = nullstr; /* current working directory */
257 char *physdir; // = nullstr; /* physical working directory */
258
259 char *arg0; /* value of $0 */
260
261 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000262
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200263 volatile int suppress_int; /* counter */
264 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000265 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200266 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000267 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000268 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000269#define EXINT 0 /* SIGINT received */
270#define EXERROR 1 /* a generic error */
271#define EXSHELLPROC 2 /* execute a shell procedure */
272#define EXEXEC 3 /* command execution failed */
273#define EXEXIT 4 /* exit the shell */
274#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000275
Denis Vlasenko01631112007-12-16 17:20:38 +0000276 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000277 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000278
279 char optlist[NOPTS];
280#define eflag optlist[0]
281#define fflag optlist[1]
282#define Iflag optlist[2]
283#define iflag optlist[3]
284#define mflag optlist[4]
285#define nflag optlist[5]
286#define sflag optlist[6]
287#define xflag optlist[7]
288#define vflag optlist[8]
289#define Cflag optlist[9]
290#define aflag optlist[10]
291#define bflag optlist[11]
292#define uflag optlist[12]
293#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100294#if ENABLE_ASH_BASH_COMPAT
295# define pipefail optlist[14]
296#else
297# define pipefail 0
298#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000299#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100300# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
301# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000302#endif
303
304 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000305 /*
306 * Sigmode records the current value of the signal handlers for the various
307 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000308 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000309 */
310 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000311#define S_DFL 1 /* default signal handling (SIG_DFL) */
312#define S_CATCH 2 /* signal is caught */
313#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000314#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000315
Denis Vlasenko01631112007-12-16 17:20:38 +0000316 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000317 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200318 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000319 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200320 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000321
322 /* Rarely referenced stuff */
323#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200324 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000325#endif
326 pid_t backgndpid; /* pid of last background process */
327 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000328};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000329extern struct globals_misc *const ash_ptr_to_globals_misc;
330#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000331#define rootpid (G_misc.rootpid )
332#define shlvl (G_misc.shlvl )
333#define minusc (G_misc.minusc )
334#define curdir (G_misc.curdir )
335#define physdir (G_misc.physdir )
336#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000337#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000338#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200339#define suppress_int (G_misc.suppress_int )
340#define pending_int (G_misc.pending_int )
341#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000342#define isloginsh (G_misc.isloginsh )
343#define nullstr (G_misc.nullstr )
344#define optlist (G_misc.optlist )
345#define sigmode (G_misc.sigmode )
346#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200347#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000348#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200349#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200350#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000351#define backgndpid (G_misc.backgndpid )
352#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000353#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000354 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
355 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000356 curdir = nullstr; \
357 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200358 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000359} while (0)
360
361
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000362/* ============ DEBUG */
363#if DEBUG
364static void trace_printf(const char *fmt, ...);
365static void trace_vprintf(const char *fmt, va_list va);
366# define TRACE(param) trace_printf param
367# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000368# define close(fd) do { \
369 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000370 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200371 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000372 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000373} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000374#else
375# define TRACE(param)
376# define TRACEV(param)
377#endif
378
379
Denis Vlasenko559691a2008-10-05 18:39:31 +0000380/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000381#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
382
Denis Vlasenko559691a2008-10-05 18:39:31 +0000383static int isdigit_str9(const char *str)
384{
385 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
386 while (--maxlen && isdigit(*str))
387 str++;
388 return (*str == '\0');
389}
Denis Vlasenko01631112007-12-16 17:20:38 +0000390
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200391static const char *var_end(const char *var)
392{
393 while (*var)
394 if (*var++ == '=')
395 break;
396 return var;
397}
398
Denis Vlasenko559691a2008-10-05 18:39:31 +0000399
400/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000401/*
Eric Andersen2870d962001-07-02 17:27:21 +0000402 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000403 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000404 * much more efficient and portable. (But hacking the kernel is so much
405 * more fun than worrying about efficiency and portability. :-))
406 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000407#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200408 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000409 xbarrier(); \
410} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000411
412/*
413 * Called to raise an exception. Since C doesn't include exceptions, we
414 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000415 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000416 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000417static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000418static void
419raise_exception(int e)
420{
421#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000422 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000423 abort();
424#endif
425 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000426 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000427 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000428}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000429#if DEBUG
430#define raise_exception(e) do { \
431 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
432 raise_exception(e); \
433} while (0)
434#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000435
436/*
437 * Called from trap.c when a SIGINT is received. (If the user specifies
438 * that SIGINT is to be trapped or ignored using the trap builtin, then
439 * this routine is not called.) Suppressint is nonzero when interrupts
440 * are held using the INT_OFF macro. (The test for iflag is just
441 * defensive programming.)
442 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000443static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000444static void
445raise_interrupt(void)
446{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000447 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000448
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200449 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000450 /* Signal is not automatically unmasked after it is raised,
451 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000452 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200453 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000454
Denis Vlasenko4b875702009-03-19 13:30:04 +0000455 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000456 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
457 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000458 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000459 signal(SIGINT, SIG_DFL);
460 raise(SIGINT);
461 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000462 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000463 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000464 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000465 /* NOTREACHED */
466}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000467#if DEBUG
468#define raise_interrupt() do { \
469 TRACE(("raising interrupt on line %d\n", __LINE__)); \
470 raise_interrupt(); \
471} while (0)
472#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000473
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000474static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000475int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000476{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000477 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200478 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000479 raise_interrupt();
480 }
481}
482#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000483static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000484force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000485{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000486 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200487 suppress_int = 0;
488 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000489 raise_interrupt();
490}
491#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000492
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200493#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000494
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000495#define RESTORE_INT(v) do { \
496 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200497 suppress_int = (v); \
498 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000499 raise_interrupt(); \
500} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000501
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000502
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000503/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000504
Eric Andersenc470f442003-07-28 09:56:35 +0000505static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000506outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000507{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000508 INT_OFF;
509 fputs(p, file);
510 INT_ON;
511}
512
513static void
514flush_stdout_stderr(void)
515{
516 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100517 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000518 INT_ON;
519}
520
521static void
522outcslow(int c, FILE *dest)
523{
524 INT_OFF;
525 putc(c, dest);
526 fflush(dest);
527 INT_ON;
528}
529
530static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
531static int
532out1fmt(const char *fmt, ...)
533{
534 va_list ap;
535 int r;
536
537 INT_OFF;
538 va_start(ap, fmt);
539 r = vprintf(fmt, ap);
540 va_end(ap);
541 INT_ON;
542 return r;
543}
544
545static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
546static int
547fmtstr(char *outbuf, size_t length, const char *fmt, ...)
548{
549 va_list ap;
550 int ret;
551
552 va_start(ap, fmt);
553 INT_OFF;
554 ret = vsnprintf(outbuf, length, fmt, ap);
555 va_end(ap);
556 INT_ON;
557 return ret;
558}
559
560static void
561out1str(const char *p)
562{
563 outstr(p, stdout);
564}
565
566static void
567out2str(const char *p)
568{
569 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100570 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000571}
572
573
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000574/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000575
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000576/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100577#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200578#define CTLESC ((unsigned char)'\201') /* escape next character */
579#define CTLVAR ((unsigned char)'\202') /* variable defn */
580#define CTLENDVAR ((unsigned char)'\203')
581#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000582#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
583/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200584#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
585#define CTLENDARI ((unsigned char)'\207')
586#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100587#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000588
589/* variable substitution byte (follows CTLVAR) */
590#define VSTYPE 0x0f /* type of variable substitution */
591#define VSNUL 0x10 /* colon--treat the empty string as unset */
592#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
593
594/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000595#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
596#define VSMINUS 0x2 /* ${var-text} */
597#define VSPLUS 0x3 /* ${var+text} */
598#define VSQUESTION 0x4 /* ${var?message} */
599#define VSASSIGN 0x5 /* ${var=text} */
600#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
601#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
602#define VSTRIMLEFT 0x8 /* ${var#pattern} */
603#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
604#define VSLENGTH 0xa /* ${#var} */
605#if ENABLE_ASH_BASH_COMPAT
606#define VSSUBSTR 0xc /* ${var:position:length} */
607#define VSREPLACE 0xd /* ${var/pattern/replacement} */
608#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
609#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000610
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000611static const char dolatstr[] ALIGN1 = {
612 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
613};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000614
Denis Vlasenko559691a2008-10-05 18:39:31 +0000615#define NCMD 0
616#define NPIPE 1
617#define NREDIR 2
618#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000619#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000620#define NAND 5
621#define NOR 6
622#define NSEMI 7
623#define NIF 8
624#define NWHILE 9
625#define NUNTIL 10
626#define NFOR 11
627#define NCASE 12
628#define NCLIST 13
629#define NDEFUN 14
630#define NARG 15
631#define NTO 16
632#if ENABLE_ASH_BASH_COMPAT
633#define NTO2 17
634#endif
635#define NCLOBBER 18
636#define NFROM 19
637#define NFROMTO 20
638#define NAPPEND 21
639#define NTOFD 22
640#define NFROMFD 23
641#define NHERE 24
642#define NXHERE 25
643#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000644#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000645
646union node;
647
648struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000649 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000650 union node *assign;
651 union node *args;
652 union node *redirect;
653};
654
655struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000656 smallint type;
657 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000658 struct nodelist *cmdlist;
659};
660
661struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000662 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000663 union node *n;
664 union node *redirect;
665};
666
667struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000668 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000669 union node *ch1;
670 union node *ch2;
671};
672
673struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000674 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000675 union node *test;
676 union node *ifpart;
677 union node *elsepart;
678};
679
680struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000681 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000682 union node *args;
683 union node *body;
684 char *var;
685};
686
687struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000688 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000689 union node *expr;
690 union node *cases;
691};
692
693struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000694 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000695 union node *next;
696 union node *pattern;
697 union node *body;
698};
699
700struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000701 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000702 union node *next;
703 char *text;
704 struct nodelist *backquote;
705};
706
Denis Vlasenko559691a2008-10-05 18:39:31 +0000707/* nfile and ndup layout must match!
708 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
709 * that it is actually NTO2 (>&file), and change its type.
710 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000711struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000712 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000713 union node *next;
714 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000715 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000716 union node *fname;
717 char *expfname;
718};
719
720struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000721 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000722 union node *next;
723 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000724 int dupfd;
725 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000726 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000727};
728
729struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000730 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000731 union node *next;
732 int fd;
733 union node *doc;
734};
735
736struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000737 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000738 union node *com;
739};
740
741union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000742 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000743 struct ncmd ncmd;
744 struct npipe npipe;
745 struct nredir nredir;
746 struct nbinary nbinary;
747 struct nif nif;
748 struct nfor nfor;
749 struct ncase ncase;
750 struct nclist nclist;
751 struct narg narg;
752 struct nfile nfile;
753 struct ndup ndup;
754 struct nhere nhere;
755 struct nnot nnot;
756};
757
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200758/*
759 * NODE_EOF is returned by parsecmd when it encounters an end of file.
760 * It must be distinct from NULL.
761 */
762#define NODE_EOF ((union node *) -1L)
763
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000764struct nodelist {
765 struct nodelist *next;
766 union node *n;
767};
768
769struct funcnode {
770 int count;
771 union node n;
772};
773
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000774/*
775 * Free a parse tree.
776 */
777static void
778freefunc(struct funcnode *f)
779{
780 if (f && --f->count < 0)
781 free(f);
782}
783
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000784
785/* ============ Debugging output */
786
787#if DEBUG
788
789static FILE *tracefile;
790
791static void
792trace_printf(const char *fmt, ...)
793{
794 va_list va;
795
796 if (debug != 1)
797 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000798 if (DEBUG_TIME)
799 fprintf(tracefile, "%u ", (int) time(NULL));
800 if (DEBUG_PID)
801 fprintf(tracefile, "[%u] ", (int) getpid());
802 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200803 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000804 va_start(va, fmt);
805 vfprintf(tracefile, fmt, va);
806 va_end(va);
807}
808
809static void
810trace_vprintf(const char *fmt, va_list va)
811{
812 if (debug != 1)
813 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000814 if (DEBUG_TIME)
815 fprintf(tracefile, "%u ", (int) time(NULL));
816 if (DEBUG_PID)
817 fprintf(tracefile, "[%u] ", (int) getpid());
818 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200819 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000820 vfprintf(tracefile, fmt, va);
821}
822
823static void
824trace_puts(const char *s)
825{
826 if (debug != 1)
827 return;
828 fputs(s, tracefile);
829}
830
831static void
832trace_puts_quoted(char *s)
833{
834 char *p;
835 char c;
836
837 if (debug != 1)
838 return;
839 putc('"', tracefile);
840 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100841 switch ((unsigned char)*p) {
842 case '\n': c = 'n'; goto backslash;
843 case '\t': c = 't'; goto backslash;
844 case '\r': c = 'r'; goto backslash;
845 case '\"': c = '\"'; goto backslash;
846 case '\\': c = '\\'; goto backslash;
847 case CTLESC: c = 'e'; goto backslash;
848 case CTLVAR: c = 'v'; goto backslash;
849 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
850 case CTLBACKQ: c = 'q'; goto backslash;
851 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000852 backslash:
853 putc('\\', tracefile);
854 putc(c, tracefile);
855 break;
856 default:
857 if (*p >= ' ' && *p <= '~')
858 putc(*p, tracefile);
859 else {
860 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100861 putc((*p >> 6) & 03, tracefile);
862 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000863 putc(*p & 07, tracefile);
864 }
865 break;
866 }
867 }
868 putc('"', tracefile);
869}
870
871static void
872trace_puts_args(char **ap)
873{
874 if (debug != 1)
875 return;
876 if (!*ap)
877 return;
878 while (1) {
879 trace_puts_quoted(*ap);
880 if (!*++ap) {
881 putc('\n', tracefile);
882 break;
883 }
884 putc(' ', tracefile);
885 }
886}
887
888static void
889opentrace(void)
890{
891 char s[100];
892#ifdef O_APPEND
893 int flags;
894#endif
895
896 if (debug != 1) {
897 if (tracefile)
898 fflush(tracefile);
899 /* leave open because libedit might be using it */
900 return;
901 }
902 strcpy(s, "./trace");
903 if (tracefile) {
904 if (!freopen(s, "a", tracefile)) {
905 fprintf(stderr, "Can't re-open %s\n", s);
906 debug = 0;
907 return;
908 }
909 } else {
910 tracefile = fopen(s, "a");
911 if (tracefile == NULL) {
912 fprintf(stderr, "Can't open %s\n", s);
913 debug = 0;
914 return;
915 }
916 }
917#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000918 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000919 if (flags >= 0)
920 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
921#endif
922 setlinebuf(tracefile);
923 fputs("\nTracing started.\n", tracefile);
924}
925
926static void
927indent(int amount, char *pfx, FILE *fp)
928{
929 int i;
930
931 for (i = 0; i < amount; i++) {
932 if (pfx && i == amount - 1)
933 fputs(pfx, fp);
934 putc('\t', fp);
935 }
936}
937
938/* little circular references here... */
939static void shtree(union node *n, int ind, char *pfx, FILE *fp);
940
941static void
942sharg(union node *arg, FILE *fp)
943{
944 char *p;
945 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100946 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000947
948 if (arg->type != NARG) {
949 out1fmt("<node type %d>\n", arg->type);
950 abort();
951 }
952 bqlist = arg->narg.backquote;
953 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100954 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000955 case CTLESC:
Dan Fandrich77d48722010-09-07 23:38:28 -0700956 p++;
957 putc(*p, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000958 break;
959 case CTLVAR:
960 putc('$', fp);
961 putc('{', fp);
962 subtype = *++p;
963 if (subtype == VSLENGTH)
964 putc('#', fp);
965
Dan Fandrich77d48722010-09-07 23:38:28 -0700966 while (*p != '=') {
967 putc(*p, fp);
968 p++;
969 }
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000970
971 if (subtype & VSNUL)
972 putc(':', fp);
973
974 switch (subtype & VSTYPE) {
975 case VSNORMAL:
976 putc('}', fp);
977 break;
978 case VSMINUS:
979 putc('-', fp);
980 break;
981 case VSPLUS:
982 putc('+', fp);
983 break;
984 case VSQUESTION:
985 putc('?', fp);
986 break;
987 case VSASSIGN:
988 putc('=', fp);
989 break;
990 case VSTRIMLEFT:
991 putc('#', fp);
992 break;
993 case VSTRIMLEFTMAX:
994 putc('#', fp);
995 putc('#', fp);
996 break;
997 case VSTRIMRIGHT:
998 putc('%', fp);
999 break;
1000 case VSTRIMRIGHTMAX:
1001 putc('%', fp);
1002 putc('%', fp);
1003 break;
1004 case VSLENGTH:
1005 break;
1006 default:
1007 out1fmt("<subtype %d>", subtype);
1008 }
1009 break;
1010 case CTLENDVAR:
1011 putc('}', fp);
1012 break;
1013 case CTLBACKQ:
1014 case CTLBACKQ|CTLQUOTE:
1015 putc('$', fp);
1016 putc('(', fp);
1017 shtree(bqlist->n, -1, NULL, fp);
1018 putc(')', fp);
1019 break;
1020 default:
1021 putc(*p, fp);
1022 break;
1023 }
1024 }
1025}
1026
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02001027static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001028shcmd(union node *cmd, FILE *fp)
1029{
1030 union node *np;
1031 int first;
1032 const char *s;
1033 int dftfd;
1034
1035 first = 1;
1036 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001037 if (!first)
1038 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001039 sharg(np, fp);
1040 first = 0;
1041 }
1042 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001043 if (!first)
1044 putc(' ', fp);
1045 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001046 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001047 case NTO: s = ">>"+1; dftfd = 1; break;
1048 case NCLOBBER: s = ">|"; dftfd = 1; break;
1049 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001050#if ENABLE_ASH_BASH_COMPAT
1051 case NTO2:
1052#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001053 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +00001054 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00001055 case NFROMFD: s = "<&"; break;
1056 case NFROMTO: s = "<>"; break;
1057 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001058 }
1059 if (np->nfile.fd != dftfd)
1060 fprintf(fp, "%d", np->nfile.fd);
1061 fputs(s, fp);
1062 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1063 fprintf(fp, "%d", np->ndup.dupfd);
1064 } else {
1065 sharg(np->nfile.fname, fp);
1066 }
1067 first = 0;
1068 }
1069}
1070
1071static void
1072shtree(union node *n, int ind, char *pfx, FILE *fp)
1073{
1074 struct nodelist *lp;
1075 const char *s;
1076
1077 if (n == NULL)
1078 return;
1079
1080 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +02001081
1082 if (n == NODE_EOF) {
1083 fputs("<EOF>", fp);
1084 return;
1085 }
1086
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001087 switch (n->type) {
1088 case NSEMI:
1089 s = "; ";
1090 goto binop;
1091 case NAND:
1092 s = " && ";
1093 goto binop;
1094 case NOR:
1095 s = " || ";
1096 binop:
1097 shtree(n->nbinary.ch1, ind, NULL, fp);
1098 /* if (ind < 0) */
1099 fputs(s, fp);
1100 shtree(n->nbinary.ch2, ind, NULL, fp);
1101 break;
1102 case NCMD:
1103 shcmd(n, fp);
1104 if (ind >= 0)
1105 putc('\n', fp);
1106 break;
1107 case NPIPE:
1108 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02001109 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001110 if (lp->next)
1111 fputs(" | ", fp);
1112 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00001113 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001114 fputs(" &", fp);
1115 if (ind >= 0)
1116 putc('\n', fp);
1117 break;
1118 default:
1119 fprintf(fp, "<node type %d>", n->type);
1120 if (ind >= 0)
1121 putc('\n', fp);
1122 break;
1123 }
1124}
1125
1126static void
1127showtree(union node *n)
1128{
1129 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001130 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001131}
1132
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001133#endif /* DEBUG */
1134
1135
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001136/* ============ Parser data */
1137
1138/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001139 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1140 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001141struct strlist {
1142 struct strlist *next;
1143 char *text;
1144};
1145
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001146struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001147
Denis Vlasenkob012b102007-02-19 22:43:01 +00001148struct strpush {
1149 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001150 char *prev_string;
1151 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001152#if ENABLE_ASH_ALIAS
1153 struct alias *ap; /* if push was associated with an alias */
1154#endif
1155 char *string; /* remember the string since it may change */
1156};
1157
1158struct parsefile {
1159 struct parsefile *prev; /* preceding file on stack */
1160 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001161 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001162 int left_in_line; /* number of chars left in this line */
1163 int left_in_buffer; /* number of chars left in this buffer past the line */
1164 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001165 char *buf; /* input buffer */
1166 struct strpush *strpush; /* for pushing strings at this level */
1167 struct strpush basestrpush; /* so pushing one is fast */
1168};
1169
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001170static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001171static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001172static int startlinno; /* line # where last token started */
1173static char *commandname; /* currently executing command */
1174static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001175static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001176
1177
1178/* ============ Message printing */
1179
1180static void
1181ash_vmsg(const char *msg, va_list ap)
1182{
1183 fprintf(stderr, "%s: ", arg0);
1184 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001185 if (strcmp(arg0, commandname))
1186 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001187 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001188 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001189 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001190 vfprintf(stderr, msg, ap);
1191 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001192}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001193
1194/*
1195 * Exverror is called to raise the error exception. If the second argument
1196 * is not NULL then error prints an error message using printf style
1197 * formatting. It then raises the error exception.
1198 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001199static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001200static void
1201ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001202{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001203#if DEBUG
1204 if (msg) {
1205 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1206 TRACEV((msg, ap));
1207 TRACE(("\") pid=%d\n", getpid()));
1208 } else
1209 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1210 if (msg)
1211#endif
1212 ash_vmsg(msg, ap);
1213
1214 flush_stdout_stderr();
1215 raise_exception(cond);
1216 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001217}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001218
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001219static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001220static void
1221ash_msg_and_raise_error(const char *msg, ...)
1222{
1223 va_list ap;
1224
1225 va_start(ap, msg);
1226 ash_vmsg_and_raise(EXERROR, msg, ap);
1227 /* NOTREACHED */
1228 va_end(ap);
1229}
1230
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001231static void raise_error_syntax(const char *) NORETURN;
1232static void
1233raise_error_syntax(const char *msg)
1234{
1235 ash_msg_and_raise_error("syntax error: %s", msg);
1236 /* NOTREACHED */
1237}
1238
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001239static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001240static void
1241ash_msg_and_raise(int cond, const char *msg, ...)
1242{
1243 va_list ap;
1244
1245 va_start(ap, msg);
1246 ash_vmsg_and_raise(cond, msg, ap);
1247 /* NOTREACHED */
1248 va_end(ap);
1249}
1250
1251/*
1252 * error/warning routines for external builtins
1253 */
1254static void
1255ash_msg(const char *fmt, ...)
1256{
1257 va_list ap;
1258
1259 va_start(ap, fmt);
1260 ash_vmsg(fmt, ap);
1261 va_end(ap);
1262}
1263
1264/*
1265 * Return a string describing an error. The returned string may be a
1266 * pointer to a static buffer that will be overwritten on the next call.
1267 * Action describes the operation that got the error.
1268 */
1269static const char *
1270errmsg(int e, const char *em)
1271{
1272 if (e == ENOENT || e == ENOTDIR) {
1273 return em;
1274 }
1275 return strerror(e);
1276}
1277
1278
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001279/* ============ Memory allocation */
1280
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001281#if 0
1282/* I consider these wrappers nearly useless:
1283 * ok, they return you to nearest exception handler, but
1284 * how much memory do you leak in the process, making
1285 * memory starvation worse?
1286 */
1287static void *
1288ckrealloc(void * p, size_t nbytes)
1289{
1290 p = realloc(p, nbytes);
1291 if (!p)
1292 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1293 return p;
1294}
1295
1296static void *
1297ckmalloc(size_t nbytes)
1298{
1299 return ckrealloc(NULL, nbytes);
1300}
1301
1302static void *
1303ckzalloc(size_t nbytes)
1304{
1305 return memset(ckmalloc(nbytes), 0, nbytes);
1306}
1307
1308static char *
1309ckstrdup(const char *s)
1310{
1311 char *p = strdup(s);
1312 if (!p)
1313 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1314 return p;
1315}
1316#else
1317/* Using bbox equivalents. They exit if out of memory */
1318# define ckrealloc xrealloc
1319# define ckmalloc xmalloc
1320# define ckzalloc xzalloc
1321# define ckstrdup xstrdup
1322#endif
1323
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001324/*
1325 * It appears that grabstackstr() will barf with such alignments
1326 * because stalloc() will return a string allocated in a new stackblock.
1327 */
1328#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1329enum {
1330 /* Most machines require the value returned from malloc to be aligned
1331 * in some way. The following macro will get this right
1332 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001333 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001334 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001336};
1337
1338struct stack_block {
1339 struct stack_block *prev;
1340 char space[MINSIZE];
1341};
1342
1343struct stackmark {
1344 struct stack_block *stackp;
1345 char *stacknxt;
1346 size_t stacknleft;
1347 struct stackmark *marknext;
1348};
1349
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350
Denis Vlasenko01631112007-12-16 17:20:38 +00001351struct globals_memstack {
1352 struct stack_block *g_stackp; // = &stackbase;
1353 struct stackmark *markp;
1354 char *g_stacknxt; // = stackbase.space;
1355 char *sstrend; // = stackbase.space + MINSIZE;
1356 size_t g_stacknleft; // = MINSIZE;
1357 int herefd; // = -1;
1358 struct stack_block stackbase;
1359};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001360extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1361#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001362#define g_stackp (G_memstack.g_stackp )
1363#define markp (G_memstack.markp )
1364#define g_stacknxt (G_memstack.g_stacknxt )
1365#define sstrend (G_memstack.sstrend )
1366#define g_stacknleft (G_memstack.g_stacknleft)
1367#define herefd (G_memstack.herefd )
1368#define stackbase (G_memstack.stackbase )
1369#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001370 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1371 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001372 g_stackp = &stackbase; \
1373 g_stacknxt = stackbase.space; \
1374 g_stacknleft = MINSIZE; \
1375 sstrend = stackbase.space + MINSIZE; \
1376 herefd = -1; \
1377} while (0)
1378
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001379
Denis Vlasenko01631112007-12-16 17:20:38 +00001380#define stackblock() ((void *)g_stacknxt)
1381#define stackblocksize() g_stacknleft
1382
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001383/*
1384 * Parse trees for commands are allocated in lifo order, so we use a stack
1385 * to make this more efficient, and also to avoid all sorts of exception
1386 * handling code to handle interrupts in the middle of a parse.
1387 *
1388 * The size 504 was chosen because the Ultrix malloc handles that size
1389 * well.
1390 */
1391static void *
1392stalloc(size_t nbytes)
1393{
1394 char *p;
1395 size_t aligned;
1396
1397 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001398 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001399 size_t len;
1400 size_t blocksize;
1401 struct stack_block *sp;
1402
1403 blocksize = aligned;
1404 if (blocksize < MINSIZE)
1405 blocksize = MINSIZE;
1406 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1407 if (len < blocksize)
1408 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1409 INT_OFF;
1410 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001411 sp->prev = g_stackp;
1412 g_stacknxt = sp->space;
1413 g_stacknleft = blocksize;
1414 sstrend = g_stacknxt + blocksize;
1415 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001416 INT_ON;
1417 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001418 p = g_stacknxt;
1419 g_stacknxt += aligned;
1420 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001421 return p;
1422}
1423
Denis Vlasenko597906c2008-02-20 16:38:54 +00001424static void *
1425stzalloc(size_t nbytes)
1426{
1427 return memset(stalloc(nbytes), 0, nbytes);
1428}
1429
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001430static void
1431stunalloc(void *p)
1432{
1433#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001434 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001435 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001436 abort();
1437 }
1438#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001439 g_stacknleft += g_stacknxt - (char *)p;
1440 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001441}
1442
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001443/*
1444 * Like strdup but works with the ash stack.
1445 */
1446static char *
1447ststrdup(const char *p)
1448{
1449 size_t len = strlen(p) + 1;
1450 return memcpy(stalloc(len), p, len);
1451}
1452
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001453static void
1454setstackmark(struct stackmark *mark)
1455{
Denis Vlasenko01631112007-12-16 17:20:38 +00001456 mark->stackp = g_stackp;
1457 mark->stacknxt = g_stacknxt;
1458 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001459 mark->marknext = markp;
1460 markp = mark;
1461}
1462
1463static void
1464popstackmark(struct stackmark *mark)
1465{
1466 struct stack_block *sp;
1467
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001468 if (!mark->stackp)
1469 return;
1470
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001471 INT_OFF;
1472 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001473 while (g_stackp != mark->stackp) {
1474 sp = g_stackp;
1475 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001476 free(sp);
1477 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001478 g_stacknxt = mark->stacknxt;
1479 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001480 sstrend = mark->stacknxt + mark->stacknleft;
1481 INT_ON;
1482}
1483
1484/*
1485 * When the parser reads in a string, it wants to stick the string on the
1486 * stack and only adjust the stack pointer when it knows how big the
1487 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1488 * of space on top of the stack and stackblocklen returns the length of
1489 * this block. Growstackblock will grow this space by at least one byte,
1490 * possibly moving it (like realloc). Grabstackblock actually allocates the
1491 * part of the block that has been used.
1492 */
1493static void
1494growstackblock(void)
1495{
1496 size_t newlen;
1497
Denis Vlasenko01631112007-12-16 17:20:38 +00001498 newlen = g_stacknleft * 2;
1499 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001500 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1501 if (newlen < 128)
1502 newlen += 128;
1503
Denis Vlasenko01631112007-12-16 17:20:38 +00001504 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001505 struct stack_block *oldstackp;
1506 struct stackmark *xmark;
1507 struct stack_block *sp;
1508 struct stack_block *prevstackp;
1509 size_t grosslen;
1510
1511 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001512 oldstackp = g_stackp;
1513 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001514 prevstackp = sp->prev;
1515 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1516 sp = ckrealloc(sp, grosslen);
1517 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001518 g_stackp = sp;
1519 g_stacknxt = sp->space;
1520 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001521 sstrend = sp->space + newlen;
1522
1523 /*
1524 * Stack marks pointing to the start of the old block
1525 * must be relocated to point to the new block
1526 */
1527 xmark = markp;
1528 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001529 xmark->stackp = g_stackp;
1530 xmark->stacknxt = g_stacknxt;
1531 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001532 xmark = xmark->marknext;
1533 }
1534 INT_ON;
1535 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001536 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001537 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001538 char *p = stalloc(newlen);
1539
1540 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001541 g_stacknxt = memcpy(p, oldspace, oldlen);
1542 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001543 }
1544}
1545
1546static void
1547grabstackblock(size_t len)
1548{
1549 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001550 g_stacknxt += len;
1551 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001552}
1553
1554/*
1555 * The following routines are somewhat easier to use than the above.
1556 * The user declares a variable of type STACKSTR, which may be declared
1557 * to be a register. The macro STARTSTACKSTR initializes things. Then
1558 * the user uses the macro STPUTC to add characters to the string. In
1559 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1560 * grown as necessary. When the user is done, she can just leave the
1561 * string there and refer to it using stackblock(). Or she can allocate
1562 * the space for it using grabstackstr(). If it is necessary to allow
1563 * someone else to use the stack temporarily and then continue to grow
1564 * the string, the user should use grabstack to allocate the space, and
1565 * then call ungrabstr(p) to return to the previous mode of operation.
1566 *
1567 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1568 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1569 * is space for at least one character.
1570 */
1571static void *
1572growstackstr(void)
1573{
1574 size_t len = stackblocksize();
1575 if (herefd >= 0 && len >= 1024) {
1576 full_write(herefd, stackblock(), len);
1577 return stackblock();
1578 }
1579 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001580 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001581}
1582
1583/*
1584 * Called from CHECKSTRSPACE.
1585 */
1586static char *
1587makestrspace(size_t newlen, char *p)
1588{
Denis Vlasenko01631112007-12-16 17:20:38 +00001589 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001590 size_t size = stackblocksize();
1591
1592 for (;;) {
1593 size_t nleft;
1594
1595 size = stackblocksize();
1596 nleft = size - len;
1597 if (nleft >= newlen)
1598 break;
1599 growstackblock();
1600 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001601 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001602}
1603
1604static char *
1605stack_nputstr(const char *s, size_t n, char *p)
1606{
1607 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001608 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001609 return p;
1610}
1611
1612static char *
1613stack_putstr(const char *s, char *p)
1614{
1615 return stack_nputstr(s, strlen(s), p);
1616}
1617
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001618static char *
1619_STPUTC(int c, char *p)
1620{
1621 if (p == sstrend)
1622 p = growstackstr();
1623 *p++ = c;
1624 return p;
1625}
1626
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001627#define STARTSTACKSTR(p) ((p) = stackblock())
1628#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001629#define CHECKSTRSPACE(n, p) do { \
1630 char *q = (p); \
1631 size_t l = (n); \
1632 size_t m = sstrend - q; \
1633 if (l > m) \
1634 (p) = makestrspace(l, q); \
1635} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001636#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001637#define STACKSTRNUL(p) do { \
1638 if ((p) == sstrend) \
1639 (p) = growstackstr(); \
1640 *(p) = '\0'; \
1641} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001642#define STUNPUTC(p) (--(p))
1643#define STTOPC(p) ((p)[-1])
1644#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001645
1646#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001647#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648#define stackstrend() ((void *)sstrend)
1649
1650
1651/* ============ String helpers */
1652
1653/*
1654 * prefix -- see if pfx is a prefix of string.
1655 */
1656static char *
1657prefix(const char *string, const char *pfx)
1658{
1659 while (*pfx) {
1660 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001661 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001662 }
1663 return (char *) string;
1664}
1665
1666/*
1667 * Check for a valid number. This should be elsewhere.
1668 */
1669static int
1670is_number(const char *p)
1671{
1672 do {
1673 if (!isdigit(*p))
1674 return 0;
1675 } while (*++p != '\0');
1676 return 1;
1677}
1678
1679/*
1680 * Convert a string of digits to an integer, printing an error message on
1681 * failure.
1682 */
1683static int
1684number(const char *s)
1685{
1686 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001687 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001688 return atoi(s);
1689}
1690
1691/*
1692 * Produce a possibly single quoted string suitable as input to the shell.
1693 * The return string is allocated on the stack.
1694 */
1695static char *
1696single_quote(const char *s)
1697{
1698 char *p;
1699
1700 STARTSTACKSTR(p);
1701
1702 do {
1703 char *q;
1704 size_t len;
1705
1706 len = strchrnul(s, '\'') - s;
1707
1708 q = p = makestrspace(len + 3, p);
1709
1710 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001711 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001712 *q++ = '\'';
1713 s += len;
1714
1715 STADJUST(q - p, p);
1716
Denys Vlasenkocd716832009-11-28 22:14:02 +01001717 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001718 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001719 len = 0;
1720 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001721
1722 q = p = makestrspace(len + 3, p);
1723
1724 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001725 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001727
1728 STADJUST(q - p, p);
1729 } while (*s);
1730
Denys Vlasenkocd716832009-11-28 22:14:02 +01001731 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001732
1733 return stackblock();
1734}
1735
1736
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001737/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001738
1739static char **argptr; /* argument list for builtin commands */
1740static char *optionarg; /* set by nextopt (like getopt) */
1741static char *optptr; /* used by nextopt */
1742
1743/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001744 * XXX - should get rid of. Have all builtins use getopt(3).
1745 * The library getopt must have the BSD extension static variable
1746 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001747 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001748 * Standard option processing (a la getopt) for builtin routines.
1749 * The only argument that is passed to nextopt is the option string;
1750 * the other arguments are unnecessary. It returns the character,
1751 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001752 */
1753static int
1754nextopt(const char *optstring)
1755{
1756 char *p;
1757 const char *q;
1758 char c;
1759
1760 p = optptr;
1761 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001762 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001764 if (p == NULL)
1765 return '\0';
1766 if (*p != '-')
1767 return '\0';
1768 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769 return '\0';
1770 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001771 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001773 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001775 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001777 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001778 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001779 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001780 if (*++q == ':')
1781 q++;
1782 }
1783 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001784 if (*p == '\0') {
1785 p = *argptr++;
1786 if (p == NULL)
1787 ash_msg_and_raise_error("no arg for -%c option", c);
1788 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789 optionarg = p;
1790 p = NULL;
1791 }
1792 optptr = p;
1793 return c;
1794}
1795
1796
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001797/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001798
Denis Vlasenko01631112007-12-16 17:20:38 +00001799/*
1800 * The parsefile structure pointed to by the global variable parsefile
1801 * contains information about the current file being read.
1802 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001803struct shparam {
1804 int nparam; /* # of positional parameters (without $0) */
1805#if ENABLE_ASH_GETOPTS
1806 int optind; /* next parameter to be processed by getopts */
1807 int optoff; /* used by getopts */
1808#endif
1809 unsigned char malloced; /* if parameter list dynamically allocated */
1810 char **p; /* parameter list */
1811};
1812
1813/*
1814 * Free the list of positional parameters.
1815 */
1816static void
1817freeparam(volatile struct shparam *param)
1818{
Denis Vlasenko01631112007-12-16 17:20:38 +00001819 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001820 char **ap, **ap1;
1821 ap = ap1 = param->p;
1822 while (*ap)
1823 free(*ap++);
1824 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001825 }
1826}
1827
1828#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001829static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001830#endif
1831
1832struct var {
1833 struct var *next; /* next entry in hash list */
1834 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001835 const char *var_text; /* name=value */
1836 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001837 /* the variable gets set/unset */
1838};
1839
1840struct localvar {
1841 struct localvar *next; /* next local variable in list */
1842 struct var *vp; /* the variable that was made local */
1843 int flags; /* saved flags */
1844 const char *text; /* saved text */
1845};
1846
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847/* flags */
1848#define VEXPORT 0x01 /* variable is exported */
1849#define VREADONLY 0x02 /* variable cannot be modified */
1850#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1851#define VTEXTFIXED 0x08 /* text is statically allocated */
1852#define VSTACK 0x10 /* text is allocated on the stack */
1853#define VUNSET 0x20 /* the variable is not set */
1854#define VNOFUNC 0x40 /* don't call the callback function */
1855#define VNOSET 0x80 /* do not set variable - just readonly test */
1856#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001857#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001858# define VDYNAMIC 0x200 /* dynamic variable */
1859#else
1860# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001861#endif
1862
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001863
Denis Vlasenko01631112007-12-16 17:20:38 +00001864/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001865#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001866static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001867change_lc_all(const char *value)
1868{
1869 if (value && *value != '\0')
1870 setlocale(LC_ALL, value);
1871}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001872static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001873change_lc_ctype(const char *value)
1874{
1875 if (value && *value != '\0')
1876 setlocale(LC_CTYPE, value);
1877}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001878#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001879#if ENABLE_ASH_MAIL
1880static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001881static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001882#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001883static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001884#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001885static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001886#endif
1887
Denis Vlasenko01631112007-12-16 17:20:38 +00001888static const struct {
1889 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001890 const char *var_text;
1891 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001892} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001893 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001894#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001895 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1896 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001897#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001898 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1899 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1900 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1901 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001902#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001903 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001904#endif
1905#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001906 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001907#endif
1908#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001909 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1910 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001911#endif
1912#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001913 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001914#endif
1915};
1916
Denis Vlasenko0b769642008-07-24 07:54:57 +00001917struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001918
1919struct globals_var {
1920 struct shparam shellparam; /* $@ current positional parameters */
1921 struct redirtab *redirlist;
1922 int g_nullredirs;
1923 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1924 struct var *vartab[VTABSIZE];
1925 struct var varinit[ARRAY_SIZE(varinit_data)];
1926};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001927extern struct globals_var *const ash_ptr_to_globals_var;
1928#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001929#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001930//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001931#define g_nullredirs (G_var.g_nullredirs )
1932#define preverrout_fd (G_var.preverrout_fd)
1933#define vartab (G_var.vartab )
1934#define varinit (G_var.varinit )
1935#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001936 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001937 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1938 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001939 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001940 varinit[i].flags = varinit_data[i].flags; \
1941 varinit[i].var_text = varinit_data[i].var_text; \
1942 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001943 } \
1944} while (0)
1945
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001946#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001947#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001948# define vmail (&vifs)[1]
1949# define vmpath (&vmail)[1]
1950# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001951#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001952# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001953#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001954#define vps1 (&vpath)[1]
1955#define vps2 (&vps1)[1]
1956#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001957#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001958# define voptind (&vps4)[1]
1959# if ENABLE_ASH_RANDOM_SUPPORT
1960# define vrandom (&voptind)[1]
1961# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001962#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001963# if ENABLE_ASH_RANDOM_SUPPORT
1964# define vrandom (&vps4)[1]
1965# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001967
1968/*
1969 * The following macros access the values of the above variables.
1970 * They have to skip over the name. They return the null string
1971 * for unset variables.
1972 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001973#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001974#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001975#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001976# define mailval() (vmail.var_text + 5)
1977# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001978# define mpathset() ((vmpath.flags & VUNSET) == 0)
1979#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001980#define pathval() (vpath.var_text + 5)
1981#define ps1val() (vps1.var_text + 4)
1982#define ps2val() (vps2.var_text + 4)
1983#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001984#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001985# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001986#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001987
Denis Vlasenko01631112007-12-16 17:20:38 +00001988#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001989static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001990getoptsreset(const char *value)
1991{
1992 shellparam.optind = number(value);
1993 shellparam.optoff = -1;
1994}
1995#endif
1996
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02001997/* math.h has these, otherwise define our private copies */
1998#if !ENABLE_SH_MATH_SUPPORT
1999#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2000#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001/*
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002002 * Return the pointer to the first char which is not part of a legal variable name
2003 * (a letter or underscore followed by letters, underscores, and digits).
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002004 */
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002005static const char*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002006endofname(const char *name)
2007{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002008 if (!is_name(*name))
2009 return name;
2010 while (*++name) {
2011 if (!is_in_name(*name))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002012 break;
2013 }
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002014 return name;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002015}
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002016#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002017
2018/*
2019 * Compares two strings up to the first = or '\0'. The first
2020 * string must be terminated by '='; the second may be terminated by
2021 * either '=' or '\0'.
2022 */
2023static int
2024varcmp(const char *p, const char *q)
2025{
2026 int c, d;
2027
2028 while ((c = *p) == (d = *q)) {
2029 if (!c || c == '=')
2030 goto out;
2031 p++;
2032 q++;
2033 }
2034 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002035 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002036 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00002037 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002038 out:
2039 return c - d;
2040}
2041
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002042/*
2043 * Find the appropriate entry in the hash table from the name.
2044 */
2045static struct var **
2046hashvar(const char *p)
2047{
2048 unsigned hashval;
2049
2050 hashval = ((unsigned char) *p) << 4;
2051 while (*p && *p != '=')
2052 hashval += (unsigned char) *p++;
2053 return &vartab[hashval % VTABSIZE];
2054}
2055
2056static int
2057vpcmp(const void *a, const void *b)
2058{
2059 return varcmp(*(const char **)a, *(const char **)b);
2060}
2061
2062/*
2063 * This routine initializes the builtin variables.
2064 */
2065static void
2066initvar(void)
2067{
2068 struct var *vp;
2069 struct var *end;
2070 struct var **vpp;
2071
2072 /*
2073 * PS1 depends on uid
2074 */
2075#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002076 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002077#else
2078 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002079 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002080#endif
2081 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002082 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002083 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002084 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002085 vp->next = *vpp;
2086 *vpp = vp;
2087 } while (++vp < end);
2088}
2089
2090static struct var **
2091findvar(struct var **vpp, const char *name)
2092{
2093 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002094 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002095 break;
2096 }
2097 }
2098 return vpp;
2099}
2100
2101/*
2102 * Find the value of a variable. Returns NULL if not set.
2103 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01002104static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002105lookupvar(const char *name)
2106{
2107 struct var *v;
2108
2109 v = *findvar(hashvar(name), name);
2110 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002111#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002112 /*
2113 * Dynamic variables are implemented roughly the same way they are
2114 * in bash. Namely, they're "special" so long as they aren't unset.
2115 * As soon as they're unset, they're no longer dynamic, and dynamic
2116 * lookup will no longer happen at that point. -- PFM.
2117 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002118 if (v->flags & VDYNAMIC)
2119 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002120#endif
2121 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002122 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002123 }
2124 return NULL;
2125}
2126
2127/*
2128 * Search the environment of a builtin command.
2129 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002130static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002131bltinlookup(const char *name)
2132{
2133 struct strlist *sp;
2134
2135 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002136 if (varcmp(sp->text, name) == 0)
2137 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002138 }
2139 return lookupvar(name);
2140}
2141
2142/*
2143 * Same as setvar except that the variable and value are passed in
2144 * the first argument as name=value. Since the first argument will
2145 * be actually stored in the table, it should not be a string that
2146 * will go away.
2147 * Called with interrupts off.
2148 */
2149static void
2150setvareq(char *s, int flags)
2151{
2152 struct var *vp, **vpp;
2153
2154 vpp = hashvar(s);
2155 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2156 vp = *findvar(vpp, s);
2157 if (vp) {
2158 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2159 const char *n;
2160
2161 if (flags & VNOSAVE)
2162 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002163 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002164 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2165 }
2166
2167 if (flags & VNOSET)
2168 return;
2169
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002170 if (vp->var_func && !(flags & VNOFUNC))
2171 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002172
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002173 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2174 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002175
2176 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2177 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002178 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002179 if (flags & VNOSET)
2180 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002181 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002182 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002183 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002184 *vpp = vp;
2185 }
2186 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2187 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002188 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002189 vp->flags = flags;
2190}
2191
2192/*
2193 * Set the value of a variable. The flags argument is ored with the
2194 * flags of the variable. If val is NULL, the variable is unset.
2195 */
2196static void
2197setvar(const char *name, const char *val, int flags)
2198{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002199 const char *q;
2200 char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002201 char *nameeq;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002202 size_t namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002203 size_t vallen;
2204
2205 q = endofname(name);
2206 p = strchrnul(q, '=');
2207 namelen = p - name;
2208 if (!namelen || p != q)
2209 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2210 vallen = 0;
2211 if (val == NULL) {
2212 flags |= VUNSET;
2213 } else {
2214 vallen = strlen(val);
2215 }
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002216
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002217 INT_OFF;
2218 nameeq = ckmalloc(namelen + vallen + 2);
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002219 p = memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002220 if (val) {
2221 *p++ = '=';
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02002222 p = memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002223 }
2224 *p = '\0';
2225 setvareq(nameeq, flags | VNOSAVE);
2226 INT_ON;
2227}
2228
Denys Vlasenko03dad222010-01-12 23:29:57 +01002229static void FAST_FUNC
2230setvar2(const char *name, const char *val)
2231{
2232 setvar(name, val, 0);
2233}
2234
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002235#if ENABLE_ASH_GETOPTS
2236/*
2237 * Safe version of setvar, returns 1 on success 0 on failure.
2238 */
2239static int
2240setvarsafe(const char *name, const char *val, int flags)
2241{
2242 int err;
2243 volatile int saveint;
2244 struct jmploc *volatile savehandler = exception_handler;
2245 struct jmploc jmploc;
2246
2247 SAVE_INT(saveint);
2248 if (setjmp(jmploc.loc))
2249 err = 1;
2250 else {
2251 exception_handler = &jmploc;
2252 setvar(name, val, flags);
2253 err = 0;
2254 }
2255 exception_handler = savehandler;
2256 RESTORE_INT(saveint);
2257 return err;
2258}
2259#endif
2260
2261/*
2262 * Unset the specified variable.
2263 */
2264static int
2265unsetvar(const char *s)
2266{
2267 struct var **vpp;
2268 struct var *vp;
2269 int retval;
2270
2271 vpp = findvar(hashvar(s), s);
2272 vp = *vpp;
2273 retval = 2;
2274 if (vp) {
2275 int flags = vp->flags;
2276
2277 retval = 1;
2278 if (flags & VREADONLY)
2279 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002280#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002281 vp->flags &= ~VDYNAMIC;
2282#endif
2283 if (flags & VUNSET)
2284 goto ok;
2285 if ((flags & VSTRFIXED) == 0) {
2286 INT_OFF;
2287 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002288 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002289 *vpp = vp->next;
2290 free(vp);
2291 INT_ON;
2292 } else {
2293 setvar(s, 0, 0);
2294 vp->flags &= ~VEXPORT;
2295 }
2296 ok:
2297 retval = 0;
2298 }
2299 out:
2300 return retval;
2301}
2302
2303/*
2304 * Process a linked list of variable assignments.
2305 */
2306static void
2307listsetvar(struct strlist *list_set_var, int flags)
2308{
2309 struct strlist *lp = list_set_var;
2310
2311 if (!lp)
2312 return;
2313 INT_OFF;
2314 do {
2315 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002316 lp = lp->next;
2317 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002318 INT_ON;
2319}
2320
2321/*
2322 * Generate a list of variables satisfying the given conditions.
2323 */
2324static char **
2325listvars(int on, int off, char ***end)
2326{
2327 struct var **vpp;
2328 struct var *vp;
2329 char **ep;
2330 int mask;
2331
2332 STARTSTACKSTR(ep);
2333 vpp = vartab;
2334 mask = on | off;
2335 do {
2336 for (vp = *vpp; vp; vp = vp->next) {
2337 if ((vp->flags & mask) == on) {
2338 if (ep == stackstrend())
2339 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002340 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002341 }
2342 }
2343 } while (++vpp < vartab + VTABSIZE);
2344 if (ep == stackstrend())
2345 ep = growstackstr();
2346 if (end)
2347 *end = ep;
2348 *ep++ = NULL;
2349 return grabstackstr(ep);
2350}
2351
2352
2353/* ============ Path search helper
2354 *
2355 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002356 * of the path before the first call; path_advance will update
2357 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002358 * the possible path expansions in sequence. If an option (indicated by
2359 * a percent sign) appears in the path entry then the global variable
2360 * pathopt will be set to point to it; otherwise pathopt will be set to
2361 * NULL.
2362 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002363static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002364
2365static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002366path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002367{
2368 const char *p;
2369 char *q;
2370 const char *start;
2371 size_t len;
2372
2373 if (*path == NULL)
2374 return NULL;
2375 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002376 for (p = start; *p && *p != ':' && *p != '%'; p++)
2377 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002378 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2379 while (stackblocksize() < len)
2380 growstackblock();
2381 q = stackblock();
2382 if (p != start) {
2383 memcpy(q, start, p - start);
2384 q += p - start;
2385 *q++ = '/';
2386 }
2387 strcpy(q, name);
2388 pathopt = NULL;
2389 if (*p == '%') {
2390 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002391 while (*p && *p != ':')
2392 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002393 }
2394 if (*p == ':')
2395 *path = p + 1;
2396 else
2397 *path = NULL;
2398 return stalloc(len);
2399}
2400
2401
2402/* ============ Prompt */
2403
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002404static smallint doprompt; /* if set, prompt the user */
2405static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002406
2407#if ENABLE_FEATURE_EDITING
2408static line_input_t *line_input_state;
2409static const char *cmdedit_prompt;
2410static void
2411putprompt(const char *s)
2412{
2413 if (ENABLE_ASH_EXPAND_PRMT) {
2414 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002415 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002416 return;
2417 }
2418 cmdedit_prompt = s;
2419}
2420#else
2421static void
2422putprompt(const char *s)
2423{
2424 out2str(s);
2425}
2426#endif
2427
2428#if ENABLE_ASH_EXPAND_PRMT
2429/* expandstr() needs parsing machinery, so it is far away ahead... */
2430static const char *expandstr(const char *ps);
2431#else
2432#define expandstr(s) s
2433#endif
2434
2435static void
Denys Vlasenko958581a2010-09-12 15:04:27 +02002436setprompt_if(smallint do_set, int whichprompt)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002437{
2438 const char *prompt;
Denys Vlasenko958581a2010-09-12 15:04:27 +02002439 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2440
2441 if (!do_set)
2442 return;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002443
2444 needprompt = 0;
2445
2446 switch (whichprompt) {
2447 case 1:
2448 prompt = ps1val();
2449 break;
2450 case 2:
2451 prompt = ps2val();
2452 break;
2453 default: /* 0 */
2454 prompt = nullstr;
2455 }
2456#if ENABLE_ASH_EXPAND_PRMT
2457 setstackmark(&smark);
2458 stalloc(stackblocksize());
2459#endif
2460 putprompt(expandstr(prompt));
2461#if ENABLE_ASH_EXPAND_PRMT
2462 popstackmark(&smark);
2463#endif
2464}
2465
2466
2467/* ============ The cd and pwd commands */
2468
2469#define CD_PHYSICAL 1
2470#define CD_PRINT 2
2471
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002472static int
2473cdopt(void)
2474{
2475 int flags = 0;
2476 int i, j;
2477
2478 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002479 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002480 if (i != j) {
2481 flags ^= CD_PHYSICAL;
2482 j = i;
2483 }
2484 }
2485
2486 return flags;
2487}
2488
2489/*
2490 * Update curdir (the name of the current directory) in response to a
2491 * cd command.
2492 */
2493static const char *
2494updatepwd(const char *dir)
2495{
2496 char *new;
2497 char *p;
2498 char *cdcomppath;
2499 const char *lim;
2500
2501 cdcomppath = ststrdup(dir);
2502 STARTSTACKSTR(new);
2503 if (*dir != '/') {
2504 if (curdir == nullstr)
2505 return 0;
2506 new = stack_putstr(curdir, new);
2507 }
2508 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002509 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002510 if (*dir != '/') {
2511 if (new[-1] != '/')
2512 USTPUTC('/', new);
2513 if (new > lim && *lim == '/')
2514 lim++;
2515 } else {
2516 USTPUTC('/', new);
2517 cdcomppath++;
2518 if (dir[1] == '/' && dir[2] != '/') {
2519 USTPUTC('/', new);
2520 cdcomppath++;
2521 lim++;
2522 }
2523 }
2524 p = strtok(cdcomppath, "/");
2525 while (p) {
2526 switch (*p) {
2527 case '.':
2528 if (p[1] == '.' && p[2] == '\0') {
2529 while (new > lim) {
2530 STUNPUTC(new);
2531 if (new[-1] == '/')
2532 break;
2533 }
2534 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002535 }
2536 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002537 break;
2538 /* fall through */
2539 default:
2540 new = stack_putstr(p, new);
2541 USTPUTC('/', new);
2542 }
2543 p = strtok(0, "/");
2544 }
2545 if (new > lim)
2546 STUNPUTC(new);
2547 *new = 0;
2548 return stackblock();
2549}
2550
2551/*
2552 * Find out what the current directory is. If we already know the current
2553 * directory, this routine returns immediately.
2554 */
2555static char *
2556getpwd(void)
2557{
Denis Vlasenko01631112007-12-16 17:20:38 +00002558 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002559 return dir ? dir : nullstr;
2560}
2561
2562static void
2563setpwd(const char *val, int setold)
2564{
2565 char *oldcur, *dir;
2566
2567 oldcur = dir = curdir;
2568
2569 if (setold) {
2570 setvar("OLDPWD", oldcur, VEXPORT);
2571 }
2572 INT_OFF;
2573 if (physdir != nullstr) {
2574 if (physdir != oldcur)
2575 free(physdir);
2576 physdir = nullstr;
2577 }
2578 if (oldcur == val || !val) {
2579 char *s = getpwd();
2580 physdir = s;
2581 if (!val)
2582 dir = s;
2583 } else
2584 dir = ckstrdup(val);
2585 if (oldcur != dir && oldcur != nullstr) {
2586 free(oldcur);
2587 }
2588 curdir = dir;
2589 INT_ON;
2590 setvar("PWD", dir, VEXPORT);
2591}
2592
2593static void hashcd(void);
2594
2595/*
2596 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2597 * know that the current directory has changed.
2598 */
2599static int
2600docd(const char *dest, int flags)
2601{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002602 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002603 int err;
2604
2605 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2606
2607 INT_OFF;
2608 if (!(flags & CD_PHYSICAL)) {
2609 dir = updatepwd(dest);
2610 if (dir)
2611 dest = dir;
2612 }
2613 err = chdir(dest);
2614 if (err)
2615 goto out;
2616 setpwd(dir, 1);
2617 hashcd();
2618 out:
2619 INT_ON;
2620 return err;
2621}
2622
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002623static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002624cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002625{
2626 const char *dest;
2627 const char *path;
2628 const char *p;
2629 char c;
2630 struct stat statb;
2631 int flags;
2632
2633 flags = cdopt();
2634 dest = *argptr;
2635 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002636 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002637 else if (LONE_DASH(dest)) {
2638 dest = bltinlookup("OLDPWD");
2639 flags |= CD_PRINT;
2640 }
2641 if (!dest)
2642 dest = nullstr;
2643 if (*dest == '/')
2644 goto step7;
2645 if (*dest == '.') {
2646 c = dest[1];
2647 dotdot:
2648 switch (c) {
2649 case '\0':
2650 case '/':
2651 goto step6;
2652 case '.':
2653 c = dest[2];
2654 if (c != '.')
2655 goto dotdot;
2656 }
2657 }
2658 if (!*dest)
2659 dest = ".";
2660 path = bltinlookup("CDPATH");
2661 if (!path) {
2662 step6:
2663 step7:
2664 p = dest;
2665 goto docd;
2666 }
2667 do {
2668 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002669 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002670 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2671 if (c && c != ':')
2672 flags |= CD_PRINT;
2673 docd:
2674 if (!docd(p, flags))
2675 goto out;
2676 break;
2677 }
2678 } while (path);
2679 ash_msg_and_raise_error("can't cd to %s", dest);
2680 /* NOTREACHED */
2681 out:
2682 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002683 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002684 return 0;
2685}
2686
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002687static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002688pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002689{
2690 int flags;
2691 const char *dir = curdir;
2692
2693 flags = cdopt();
2694 if (flags) {
2695 if (physdir == nullstr)
2696 setpwd(dir, 0);
2697 dir = physdir;
2698 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002699 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002700 return 0;
2701}
2702
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002703
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002704/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002705
Denis Vlasenko834dee72008-10-07 09:18:30 +00002706
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002707#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002708
Eric Andersenc470f442003-07-28 09:56:35 +00002709/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002710#define CWORD 0 /* character is nothing special */
2711#define CNL 1 /* newline character */
2712#define CBACK 2 /* a backslash character */
2713#define CSQUOTE 3 /* single quote */
2714#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002715#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002716#define CBQUOTE 6 /* backwards single quote */
2717#define CVAR 7 /* a dollar sign */
2718#define CENDVAR 8 /* a '}' character */
2719#define CLP 9 /* a left paren in arithmetic */
2720#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002721#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002722#define CCTL 12 /* like CWORD, except it must be escaped */
2723#define CSPCL 13 /* these terminate a word */
2724#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002725
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002726#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002727#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002728# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002729#endif
2730
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002731#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002732
Mike Frysinger98c52642009-04-02 10:02:37 +00002733#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002734# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002735#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002736# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002737#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002738static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002739#if ENABLE_ASH_ALIAS
2740 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2741#endif
2742 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2743 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2744 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2745 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2746 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2747 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2748 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2749 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2750 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2751 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2752 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002753#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002754 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2755 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2756 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2757#endif
2758#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002759};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002760/* Constants below must match table above */
2761enum {
2762#if ENABLE_ASH_ALIAS
2763 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2764#endif
2765 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2766 CNL_CNL_CNL_CNL , /* 2 */
2767 CWORD_CCTL_CCTL_CWORD , /* 3 */
2768 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2769 CVAR_CVAR_CWORD_CVAR , /* 5 */
2770 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2771 CSPCL_CWORD_CWORD_CLP , /* 7 */
2772 CSPCL_CWORD_CWORD_CRP , /* 8 */
2773 CBACK_CBACK_CCTL_CBACK , /* 9 */
2774 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2775 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2776 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2777 CWORD_CWORD_CWORD_CWORD , /* 13 */
2778 CCTL_CCTL_CCTL_CCTL , /* 14 */
2779};
Eric Andersen2870d962001-07-02 17:27:21 +00002780
Denys Vlasenkocd716832009-11-28 22:14:02 +01002781/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2782 * caller must ensure proper cast on it if c is *char_ptr!
2783 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002784/* Values for syntax param */
2785#define BASESYNTAX 0 /* not in quotes */
2786#define DQSYNTAX 1 /* in double quotes */
2787#define SQSYNTAX 2 /* in single quotes */
2788#define ARISYNTAX 3 /* in arithmetic */
2789#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002790
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002791#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002792
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002793static int
2794SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002795{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002796 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002797# if ENABLE_ASH_ALIAS
2798 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002799 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2800 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2801 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2802 11, 3 /* "}~" */
2803 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002804# else
2805 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002806 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2807 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2808 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2809 10, 2 /* "}~" */
2810 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002811# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002812 const char *s;
2813 int indx;
2814
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002815 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002816 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002817# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002818 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002819 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002820 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002821# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002822 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002823 /* Cast is purely for paranoia here,
2824 * just in case someone passed signed char to us */
2825 if ((unsigned char)c >= CTL_FIRST
2826 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002827 ) {
2828 return CCTL;
2829 }
2830 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002831 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002832 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002833 indx = syntax_index_table[s - spec_symbls];
2834 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002835 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002836}
2837
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002838#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002839
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002840static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002841 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002842 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2853 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2875 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2876 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2877 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2879 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2881 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2882 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2883 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2884 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2885 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2887 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2888 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2889 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2935 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2939 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2967 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2968 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2969 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2970 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2972 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2973 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2974 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2975 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2976 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2977 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2978 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2979 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003098 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01003099# if ENABLE_ASH_ALIAS
3100 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3101# endif
Eric Andersen2870d962001-07-02 17:27:21 +00003102};
3103
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01003104# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003105
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01003106#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003107
Eric Andersen2870d962001-07-02 17:27:21 +00003108
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003109/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003110
Denis Vlasenko131ae172007-02-18 13:00:19 +00003111#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003112
3113#define ALIASINUSE 1
3114#define ALIASDEAD 2
3115
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003116struct alias {
3117 struct alias *next;
3118 char *name;
3119 char *val;
3120 int flag;
3121};
3122
Denis Vlasenko01631112007-12-16 17:20:38 +00003123
3124static struct alias **atab; // [ATABSIZE];
3125#define INIT_G_alias() do { \
3126 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3127} while (0)
3128
Eric Andersen2870d962001-07-02 17:27:21 +00003129
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003130static struct alias **
3131__lookupalias(const char *name) {
3132 unsigned int hashval;
3133 struct alias **app;
3134 const char *p;
3135 unsigned int ch;
3136
3137 p = name;
3138
3139 ch = (unsigned char)*p;
3140 hashval = ch << 4;
3141 while (ch) {
3142 hashval += ch;
3143 ch = (unsigned char)*++p;
3144 }
3145 app = &atab[hashval % ATABSIZE];
3146
3147 for (; *app; app = &(*app)->next) {
3148 if (strcmp(name, (*app)->name) == 0) {
3149 break;
3150 }
3151 }
3152
3153 return app;
3154}
3155
3156static struct alias *
3157lookupalias(const char *name, int check)
3158{
3159 struct alias *ap = *__lookupalias(name);
3160
3161 if (check && ap && (ap->flag & ALIASINUSE))
3162 return NULL;
3163 return ap;
3164}
3165
3166static struct alias *
3167freealias(struct alias *ap)
3168{
3169 struct alias *next;
3170
3171 if (ap->flag & ALIASINUSE) {
3172 ap->flag |= ALIASDEAD;
3173 return ap;
3174 }
3175
3176 next = ap->next;
3177 free(ap->name);
3178 free(ap->val);
3179 free(ap);
3180 return next;
3181}
Eric Andersencb57d552001-06-28 07:25:16 +00003182
Eric Andersenc470f442003-07-28 09:56:35 +00003183static void
3184setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003185{
3186 struct alias *ap, **app;
3187
3188 app = __lookupalias(name);
3189 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003190 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003191 if (ap) {
3192 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003193 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003194 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003195 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003196 ap->flag &= ~ALIASDEAD;
3197 } else {
3198 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003199 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003200 ap->name = ckstrdup(name);
3201 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003202 /*ap->flag = 0; - ckzalloc did it */
3203 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003204 *app = ap;
3205 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003206 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003207}
3208
Eric Andersenc470f442003-07-28 09:56:35 +00003209static int
3210unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003211{
Eric Andersencb57d552001-06-28 07:25:16 +00003212 struct alias **app;
3213
3214 app = __lookupalias(name);
3215
3216 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003217 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003218 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003219 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003220 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003221 }
3222
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003223 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003224}
3225
Eric Andersenc470f442003-07-28 09:56:35 +00003226static void
3227rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003228{
Eric Andersencb57d552001-06-28 07:25:16 +00003229 struct alias *ap, **app;
3230 int i;
3231
Denis Vlasenkob012b102007-02-19 22:43:01 +00003232 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003233 for (i = 0; i < ATABSIZE; i++) {
3234 app = &atab[i];
3235 for (ap = *app; ap; ap = *app) {
3236 *app = freealias(*app);
3237 if (ap == *app) {
3238 app = &ap->next;
3239 }
3240 }
3241 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003242 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003243}
3244
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003245static void
3246printalias(const struct alias *ap)
3247{
3248 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3249}
3250
Eric Andersencb57d552001-06-28 07:25:16 +00003251/*
3252 * TODO - sort output
3253 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003254static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003255aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003256{
3257 char *n, *v;
3258 int ret = 0;
3259 struct alias *ap;
3260
Denis Vlasenko68404f12008-03-17 09:00:54 +00003261 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003262 int i;
3263
Denis Vlasenko68404f12008-03-17 09:00:54 +00003264 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003265 for (ap = atab[i]; ap; ap = ap->next) {
3266 printalias(ap);
3267 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003268 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003269 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003270 }
3271 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003272 v = strchr(n+1, '=');
3273 if (v == NULL) { /* n+1: funny ksh stuff */
3274 ap = *__lookupalias(n);
3275 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003276 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003277 ret = 1;
3278 } else
3279 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003280 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003281 *v++ = '\0';
3282 setalias(n, v);
3283 }
3284 }
3285
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003286 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003287}
3288
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003289static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003290unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003291{
3292 int i;
3293
3294 while ((i = nextopt("a")) != '\0') {
3295 if (i == 'a') {
3296 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003297 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003298 }
3299 }
3300 for (i = 0; *argptr; argptr++) {
3301 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003302 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003303 i = 1;
3304 }
3305 }
3306
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003307 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003308}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003309
Denis Vlasenko131ae172007-02-18 13:00:19 +00003310#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003311
Eric Andersenc470f442003-07-28 09:56:35 +00003312
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003313/* ============ jobs.c */
3314
3315/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003316#define FORK_FG 0
3317#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003318#define FORK_NOJOB 2
3319
3320/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003321#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3322#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3323#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003324
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003325/*
3326 * A job structure contains information about a job. A job is either a
3327 * single process or a set of processes contained in a pipeline. In the
3328 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3329 * array of pids.
3330 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003332 pid_t ps_pid; /* process id */
3333 int ps_status; /* last process status from wait() */
3334 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003335};
3336
3337struct job {
3338 struct procstat ps0; /* status of process */
3339 struct procstat *ps; /* status or processes when more than one */
3340#if JOBS
3341 int stopstatus; /* status of a stopped job */
3342#endif
3343 uint32_t
3344 nprocs: 16, /* number of processes */
3345 state: 8,
3346#define JOBRUNNING 0 /* at least one proc running */
3347#define JOBSTOPPED 1 /* all procs are stopped */
3348#define JOBDONE 2 /* all procs are completed */
3349#if JOBS
3350 sigint: 1, /* job was killed by SIGINT */
3351 jobctl: 1, /* job running under job control */
3352#endif
3353 waited: 1, /* true if this entry has been waited for */
3354 used: 1, /* true if this entry is in used */
3355 changed: 1; /* true if status has changed */
3356 struct job *prev_job; /* previous job */
3357};
3358
Denis Vlasenko68404f12008-03-17 09:00:54 +00003359static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003360static int forkshell(struct job *, union node *, int);
3361static int waitforjob(struct job *);
3362
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003363#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003364enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003365#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003366#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003367static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369#endif
3370
3371/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003372 * Ignore a signal.
3373 */
3374static void
3375ignoresig(int signo)
3376{
3377 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3378 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3379 /* No, need to do it */
3380 signal(signo, SIG_IGN);
3381 }
3382 sigmode[signo - 1] = S_HARD_IGN;
3383}
3384
3385/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003386 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003387 */
3388static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003389signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003390{
3391 gotsig[signo - 1] = 1;
3392
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003393 if (signo == SIGINT && !trap[SIGINT]) {
3394 if (!suppress_int) {
3395 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003396 raise_interrupt(); /* does not return */
3397 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003398 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003399 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003400 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003401 }
3402}
3403
3404/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405 * Set the signal handler for the specified signal. The routine figures
3406 * out what it should be set to.
3407 */
3408static void
3409setsignal(int signo)
3410{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003411 char *t;
3412 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003413 struct sigaction act;
3414
3415 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003416 new_act = S_DFL;
3417 if (t != NULL) { /* trap for this sig is set */
3418 new_act = S_CATCH;
3419 if (t[0] == '\0') /* trap is "": ignore this sig */
3420 new_act = S_IGN;
3421 }
3422
3423 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003424 switch (signo) {
3425 case SIGINT:
3426 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003427 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428 break;
3429 case SIGQUIT:
3430#if DEBUG
3431 if (debug)
3432 break;
3433#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003434 /* man bash:
3435 * "In all cases, bash ignores SIGQUIT. Non-builtin
3436 * commands run by bash have signal handlers
3437 * set to the values inherited by the shell
3438 * from its parent". */
3439 new_act = S_IGN;
3440 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003441 case SIGTERM:
3442 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003443 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003444 break;
3445#if JOBS
3446 case SIGTSTP:
3447 case SIGTTOU:
3448 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003449 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003450 break;
3451#endif
3452 }
3453 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003454//TODO: if !rootshell, we reset SIGQUIT to DFL,
3455//whereas we have to restore it to what shell got on entry
3456//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003457
3458 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003459 cur_act = *t;
3460 if (cur_act == 0) {
3461 /* current setting is not yet known */
3462 if (sigaction(signo, NULL, &act)) {
3463 /* pretend it worked; maybe we should give a warning,
3464 * but other shells don't. We don't alter sigmode,
3465 * so we retry every time.
3466 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003467 return;
3468 }
3469 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003470 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003471 if (mflag
3472 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3473 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003474 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003475 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003476 }
3477 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003478 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003479 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003480
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003481 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003482 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003483 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003484 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003485 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3486 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003487 break;
3488 case S_IGN:
3489 act.sa_handler = SIG_IGN;
3490 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003491 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003492 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003493
3494 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003495}
3496
3497/* mode flags for set_curjob */
3498#define CUR_DELETE 2
3499#define CUR_RUNNING 1
3500#define CUR_STOPPED 0
3501
3502/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003503#define DOWAIT_NONBLOCK WNOHANG
3504#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003505
3506#if JOBS
3507/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003508static int initialpgrp; //references:2
3509static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003510#endif
3511/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003512static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003513/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003514static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003515/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003516static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003517/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003518static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003519
3520static void
3521set_curjob(struct job *jp, unsigned mode)
3522{
3523 struct job *jp1;
3524 struct job **jpp, **curp;
3525
3526 /* first remove from list */
3527 jpp = curp = &curjob;
3528 do {
3529 jp1 = *jpp;
3530 if (jp1 == jp)
3531 break;
3532 jpp = &jp1->prev_job;
3533 } while (1);
3534 *jpp = jp1->prev_job;
3535
3536 /* Then re-insert in correct position */
3537 jpp = curp;
3538 switch (mode) {
3539 default:
3540#if DEBUG
3541 abort();
3542#endif
3543 case CUR_DELETE:
3544 /* job being deleted */
3545 break;
3546 case CUR_RUNNING:
3547 /* newly created job or backgrounded job,
3548 put after all stopped jobs. */
3549 do {
3550 jp1 = *jpp;
3551#if JOBS
3552 if (!jp1 || jp1->state != JOBSTOPPED)
3553#endif
3554 break;
3555 jpp = &jp1->prev_job;
3556 } while (1);
3557 /* FALLTHROUGH */
3558#if JOBS
3559 case CUR_STOPPED:
3560#endif
3561 /* newly stopped job - becomes curjob */
3562 jp->prev_job = *jpp;
3563 *jpp = jp;
3564 break;
3565 }
3566}
3567
3568#if JOBS || DEBUG
3569static int
3570jobno(const struct job *jp)
3571{
3572 return jp - jobtab + 1;
3573}
3574#endif
3575
3576/*
3577 * Convert a job name to a job structure.
3578 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003579#if !JOBS
3580#define getjob(name, getctl) getjob(name)
3581#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003582static struct job *
3583getjob(const char *name, int getctl)
3584{
3585 struct job *jp;
3586 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003587 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003588 unsigned num;
3589 int c;
3590 const char *p;
3591 char *(*match)(const char *, const char *);
3592
3593 jp = curjob;
3594 p = name;
3595 if (!p)
3596 goto currentjob;
3597
3598 if (*p != '%')
3599 goto err;
3600
3601 c = *++p;
3602 if (!c)
3603 goto currentjob;
3604
3605 if (!p[1]) {
3606 if (c == '+' || c == '%') {
3607 currentjob:
3608 err_msg = "No current job";
3609 goto check;
3610 }
3611 if (c == '-') {
3612 if (jp)
3613 jp = jp->prev_job;
3614 err_msg = "No previous job";
3615 check:
3616 if (!jp)
3617 goto err;
3618 goto gotit;
3619 }
3620 }
3621
3622 if (is_number(p)) {
3623 num = atoi(p);
3624 if (num < njobs) {
3625 jp = jobtab + num - 1;
3626 if (jp->used)
3627 goto gotit;
3628 goto err;
3629 }
3630 }
3631
3632 match = prefix;
3633 if (*p == '?') {
3634 match = strstr;
3635 p++;
3636 }
3637
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003638 found = NULL;
3639 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003640 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003641 if (found)
3642 goto err;
3643 found = jp;
3644 err_msg = "%s: ambiguous";
3645 }
3646 jp = jp->prev_job;
3647 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003648 if (!found)
3649 goto err;
3650 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003651
3652 gotit:
3653#if JOBS
3654 err_msg = "job %s not created under job control";
3655 if (getctl && jp->jobctl == 0)
3656 goto err;
3657#endif
3658 return jp;
3659 err:
3660 ash_msg_and_raise_error(err_msg, name);
3661}
3662
3663/*
3664 * Mark a job structure as unused.
3665 */
3666static void
3667freejob(struct job *jp)
3668{
3669 struct procstat *ps;
3670 int i;
3671
3672 INT_OFF;
3673 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003674 if (ps->ps_cmd != nullstr)
3675 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003676 }
3677 if (jp->ps != &jp->ps0)
3678 free(jp->ps);
3679 jp->used = 0;
3680 set_curjob(jp, CUR_DELETE);
3681 INT_ON;
3682}
3683
3684#if JOBS
3685static void
3686xtcsetpgrp(int fd, pid_t pgrp)
3687{
3688 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003689 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003690}
3691
3692/*
3693 * Turn job control on and off.
3694 *
3695 * Note: This code assumes that the third arg to ioctl is a character
3696 * pointer, which is true on Berkeley systems but not System V. Since
3697 * System V doesn't have job control yet, this isn't a problem now.
3698 *
3699 * Called with interrupts off.
3700 */
3701static void
3702setjobctl(int on)
3703{
3704 int fd;
3705 int pgrp;
3706
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003707 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003708 return;
3709 if (on) {
3710 int ofd;
3711 ofd = fd = open(_PATH_TTY, O_RDWR);
3712 if (fd < 0) {
3713 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3714 * That sometimes helps to acquire controlling tty.
3715 * Obviously, a workaround for bugs when someone
3716 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003717 fd = 2;
3718 while (!isatty(fd))
3719 if (--fd < 0)
3720 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003721 }
3722 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003723 if (ofd >= 0)
3724 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003725 if (fd < 0)
3726 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003727 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003728 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003729 do { /* while we are in the background */
3730 pgrp = tcgetpgrp(fd);
3731 if (pgrp < 0) {
3732 out:
3733 ash_msg("can't access tty; job control turned off");
3734 mflag = on = 0;
3735 goto close;
3736 }
3737 if (pgrp == getpgrp())
3738 break;
3739 killpg(0, SIGTTIN);
3740 } while (1);
3741 initialpgrp = pgrp;
3742
3743 setsignal(SIGTSTP);
3744 setsignal(SIGTTOU);
3745 setsignal(SIGTTIN);
3746 pgrp = rootpid;
3747 setpgid(0, pgrp);
3748 xtcsetpgrp(fd, pgrp);
3749 } else {
3750 /* turning job control off */
3751 fd = ttyfd;
3752 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003753 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003754 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003755 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003756 setpgid(0, pgrp);
3757 setsignal(SIGTSTP);
3758 setsignal(SIGTTOU);
3759 setsignal(SIGTTIN);
3760 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003761 if (fd >= 0)
3762 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003763 fd = -1;
3764 }
3765 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003766 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003767}
3768
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003769static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003770killcmd(int argc, char **argv)
3771{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003772 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003773 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003774 do {
3775 if (argv[i][0] == '%') {
3776 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003777 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003778 /* Enough space for ' -NNN<nul>' */
3779 argv[i] = alloca(sizeof(int)*3 + 3);
3780 /* kill_main has matching code to expect
3781 * leading space. Needed to not confuse
3782 * negative pids with "kill -SIGNAL_NO" syntax */
3783 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003785 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003786 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003787 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003788}
3789
3790static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003791showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003792{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003793 struct procstat *ps;
3794 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003795
Denys Vlasenko285ad152009-12-04 23:02:27 +01003796 psend = jp->ps + jp->nprocs;
3797 for (ps = jp->ps + 1; ps < psend; ps++)
3798 printf(" | %s", ps->ps_cmd);
3799 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003800 flush_stdout_stderr();
3801}
3802
3803
3804static int
3805restartjob(struct job *jp, int mode)
3806{
3807 struct procstat *ps;
3808 int i;
3809 int status;
3810 pid_t pgid;
3811
3812 INT_OFF;
3813 if (jp->state == JOBDONE)
3814 goto out;
3815 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003816 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003817 if (mode == FORK_FG)
3818 xtcsetpgrp(ttyfd, pgid);
3819 killpg(pgid, SIGCONT);
3820 ps = jp->ps;
3821 i = jp->nprocs;
3822 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003823 if (WIFSTOPPED(ps->ps_status)) {
3824 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003825 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003826 ps++;
3827 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003828 out:
3829 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3830 INT_ON;
3831 return status;
3832}
3833
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003834static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003835fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003836{
3837 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003838 int mode;
3839 int retval;
3840
3841 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3842 nextopt(nullstr);
3843 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003844 do {
3845 jp = getjob(*argv, 1);
3846 if (mode == FORK_BG) {
3847 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003848 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003849 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003850 out1str(jp->ps[0].ps_cmd);
3851 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003852 retval = restartjob(jp, mode);
3853 } while (*argv && *++argv);
3854 return retval;
3855}
3856#endif
3857
3858static int
3859sprint_status(char *s, int status, int sigonly)
3860{
3861 int col;
3862 int st;
3863
3864 col = 0;
3865 if (!WIFEXITED(status)) {
3866#if JOBS
3867 if (WIFSTOPPED(status))
3868 st = WSTOPSIG(status);
3869 else
3870#endif
3871 st = WTERMSIG(status);
3872 if (sigonly) {
3873 if (st == SIGINT || st == SIGPIPE)
3874 goto out;
3875#if JOBS
3876 if (WIFSTOPPED(status))
3877 goto out;
3878#endif
3879 }
3880 st &= 0x7f;
3881 col = fmtstr(s, 32, strsignal(st));
3882 if (WCOREDUMP(status)) {
3883 col += fmtstr(s + col, 16, " (core dumped)");
3884 }
3885 } else if (!sigonly) {
3886 st = WEXITSTATUS(status);
3887 if (st)
3888 col = fmtstr(s, 16, "Done(%d)", st);
3889 else
3890 col = fmtstr(s, 16, "Done");
3891 }
3892 out:
3893 return col;
3894}
3895
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003896static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003897dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898{
3899 int pid;
3900 int status;
3901 struct job *jp;
3902 struct job *thisjob;
3903 int state;
3904
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003905 TRACE(("dowait(0x%x) called\n", wait_flags));
3906
3907 /* Do a wait system call. If job control is compiled in, we accept
3908 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3909 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003910 if (doing_jobctl)
3911 wait_flags |= WUNTRACED;
3912 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003913 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3914 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003915 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003916 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003917
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003918 INT_OFF;
3919 thisjob = NULL;
3920 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003921 struct procstat *ps;
3922 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003923 if (jp->state == JOBDONE)
3924 continue;
3925 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003926 ps = jp->ps;
3927 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003928 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003929 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930 TRACE(("Job %d: changing status of proc %d "
3931 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003932 jobno(jp), pid, ps->ps_status, status));
3933 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 thisjob = jp;
3935 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003936 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 state = JOBRUNNING;
3938#if JOBS
3939 if (state == JOBRUNNING)
3940 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003941 if (WIFSTOPPED(ps->ps_status)) {
3942 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003943 state = JOBSTOPPED;
3944 }
3945#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003946 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003947 if (thisjob)
3948 goto gotjob;
3949 }
3950#if JOBS
3951 if (!WIFSTOPPED(status))
3952#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003953 jobless--;
3954 goto out;
3955
3956 gotjob:
3957 if (state != JOBRUNNING) {
3958 thisjob->changed = 1;
3959
3960 if (thisjob->state != state) {
3961 TRACE(("Job %d: changing state from %d to %d\n",
3962 jobno(thisjob), thisjob->state, state));
3963 thisjob->state = state;
3964#if JOBS
3965 if (state == JOBSTOPPED) {
3966 set_curjob(thisjob, CUR_STOPPED);
3967 }
3968#endif
3969 }
3970 }
3971
3972 out:
3973 INT_ON;
3974
3975 if (thisjob && thisjob == job) {
3976 char s[48 + 1];
3977 int len;
3978
3979 len = sprint_status(s, status, 1);
3980 if (len) {
3981 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003982 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003983 out2str(s);
3984 }
3985 }
3986 return pid;
3987}
3988
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003989static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003990blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003991{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003992 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003993 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003994 raise_exception(EXSIG);
3995 return pid;
3996}
3997
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003998#if JOBS
3999static void
4000showjob(FILE *out, struct job *jp, int mode)
4001{
4002 struct procstat *ps;
4003 struct procstat *psend;
4004 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004005 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006 char s[80];
4007
4008 ps = jp->ps;
4009
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004010 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01004012 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004013 return;
4014 }
4015
4016 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00004017 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004018
4019 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004020 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004021 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004022 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004023
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004024 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004025 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004026
4027 psend = ps + jp->nprocs;
4028
4029 if (jp->state == JOBRUNNING) {
4030 strcpy(s + col, "Running");
4031 col += sizeof("Running") - 1;
4032 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01004033 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004034 if (jp->state == JOBSTOPPED)
4035 status = jp->stopstatus;
4036 col += sprint_status(s + col, status, 0);
4037 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004038 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004039
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004040 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4041 * or prints several "PID | <cmdN>" lines,
4042 * depending on SHOW_PIDS bit.
4043 * We do not print status of individual processes
4044 * between PID and <cmdN>. bash does it, but not very well:
4045 * first line shows overall job status, not process status,
4046 * making it impossible to know 1st process status.
4047 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004048 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004049 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004050 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004051 s[0] = '\0';
4052 col = 33;
4053 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004054 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004055 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01004056 fprintf(out, "%s%*c%s%s",
4057 s,
4058 33 - col >= 0 ? 33 - col : 0, ' ',
4059 ps == jp->ps ? "" : "| ",
4060 ps->ps_cmd
4061 );
4062 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004063 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004064
4065 jp->changed = 0;
4066
4067 if (jp->state == JOBDONE) {
4068 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4069 freejob(jp);
4070 }
4071}
4072
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004073/*
4074 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4075 * statuses have changed since the last call to showjobs.
4076 */
4077static void
4078showjobs(FILE *out, int mode)
4079{
4080 struct job *jp;
4081
Denys Vlasenko883cea42009-07-11 15:31:59 +02004082 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004083
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004084 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004085 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004086 continue;
4087
4088 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004089 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004090 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004091 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004092 }
4093}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004094
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004095static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004096jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004097{
4098 int mode, m;
4099
4100 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004101 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004102 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004103 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004104 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004105 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004106 }
4107
4108 argv = argptr;
4109 if (*argv) {
4110 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004111 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004112 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004113 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004114 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004115 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004116
4117 return 0;
4118}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004119#endif /* JOBS */
4120
Michael Abbott359da5e2009-12-04 23:03:29 +01004121/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004122static int
4123getstatus(struct job *job)
4124{
4125 int status;
4126 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004127 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004128
Michael Abbott359da5e2009-12-04 23:03:29 +01004129 /* Fetch last member's status */
4130 ps = job->ps + job->nprocs - 1;
4131 status = ps->ps_status;
4132 if (pipefail) {
4133 /* "set -o pipefail" mode: use last _nonzero_ status */
4134 while (status == 0 && --ps >= job->ps)
4135 status = ps->ps_status;
4136 }
4137
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004138 retval = WEXITSTATUS(status);
4139 if (!WIFEXITED(status)) {
4140#if JOBS
4141 retval = WSTOPSIG(status);
4142 if (!WIFSTOPPED(status))
4143#endif
4144 {
4145 /* XXX: limits number of signals */
4146 retval = WTERMSIG(status);
4147#if JOBS
4148 if (retval == SIGINT)
4149 job->sigint = 1;
4150#endif
4151 }
4152 retval += 128;
4153 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004154 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004155 jobno(job), job->nprocs, status, retval));
4156 return retval;
4157}
4158
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004159static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004160waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004161{
4162 struct job *job;
4163 int retval;
4164 struct job *jp;
4165
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004166 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004167 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004168
4169 nextopt(nullstr);
4170 retval = 0;
4171
4172 argv = argptr;
4173 if (!*argv) {
4174 /* wait for all jobs */
4175 for (;;) {
4176 jp = curjob;
4177 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004178 if (!jp) /* no running procs */
4179 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004180 if (jp->state == JOBRUNNING)
4181 break;
4182 jp->waited = 1;
4183 jp = jp->prev_job;
4184 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004185 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004186 /* man bash:
4187 * "When bash is waiting for an asynchronous command via
4188 * the wait builtin, the reception of a signal for which a trap
4189 * has been set will cause the wait builtin to return immediately
4190 * with an exit status greater than 128, immediately after which
4191 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004192 *
4193 * blocking_wait_with_raise_on_sig raises signal handlers
4194 * if it gets no pid (pid < 0). However,
4195 * if child sends us a signal *and immediately exits*,
4196 * blocking_wait_with_raise_on_sig gets pid > 0
4197 * and does not handle pending_sig. Check this case: */
4198 if (pending_sig)
4199 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004200 }
4201 }
4202
4203 retval = 127;
4204 do {
4205 if (**argv != '%') {
4206 pid_t pid = number(*argv);
4207 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004208 while (1) {
4209 if (!job)
4210 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004211 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004212 break;
4213 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004214 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004215 } else
4216 job = getjob(*argv, 0);
4217 /* loop until process terminated or stopped */
4218 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004219 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 job->waited = 1;
4221 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004222 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223 } while (*++argv);
4224
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004225 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004226 return retval;
4227}
4228
4229static struct job *
4230growjobtab(void)
4231{
4232 size_t len;
4233 ptrdiff_t offset;
4234 struct job *jp, *jq;
4235
4236 len = njobs * sizeof(*jp);
4237 jq = jobtab;
4238 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4239
4240 offset = (char *)jp - (char *)jq;
4241 if (offset) {
4242 /* Relocate pointers */
4243 size_t l = len;
4244
4245 jq = (struct job *)((char *)jq + l);
4246 while (l) {
4247 l -= sizeof(*jp);
4248 jq--;
4249#define joff(p) ((struct job *)((char *)(p) + l))
4250#define jmove(p) (p) = (void *)((char *)(p) + offset)
4251 if (joff(jp)->ps == &jq->ps0)
4252 jmove(joff(jp)->ps);
4253 if (joff(jp)->prev_job)
4254 jmove(joff(jp)->prev_job);
4255 }
4256 if (curjob)
4257 jmove(curjob);
4258#undef joff
4259#undef jmove
4260 }
4261
4262 njobs += 4;
4263 jobtab = jp;
4264 jp = (struct job *)((char *)jp + len);
4265 jq = jp + 3;
4266 do {
4267 jq->used = 0;
4268 } while (--jq >= jp);
4269 return jp;
4270}
4271
4272/*
4273 * Return a new job structure.
4274 * Called with interrupts off.
4275 */
4276static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004277makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004278{
4279 int i;
4280 struct job *jp;
4281
4282 for (i = njobs, jp = jobtab; ; jp++) {
4283 if (--i < 0) {
4284 jp = growjobtab();
4285 break;
4286 }
4287 if (jp->used == 0)
4288 break;
4289 if (jp->state != JOBDONE || !jp->waited)
4290 continue;
4291#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004292 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004293 continue;
4294#endif
4295 freejob(jp);
4296 break;
4297 }
4298 memset(jp, 0, sizeof(*jp));
4299#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004300 /* jp->jobctl is a bitfield.
4301 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004302 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004303 jp->jobctl = 1;
4304#endif
4305 jp->prev_job = curjob;
4306 curjob = jp;
4307 jp->used = 1;
4308 jp->ps = &jp->ps0;
4309 if (nprocs > 1) {
4310 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4311 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004312 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004313 jobno(jp)));
4314 return jp;
4315}
4316
4317#if JOBS
4318/*
4319 * Return a string identifying a command (to be printed by the
4320 * jobs command).
4321 */
4322static char *cmdnextc;
4323
4324static void
4325cmdputs(const char *s)
4326{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004327 static const char vstype[VSTYPE + 1][3] = {
4328 "", "}", "-", "+", "?", "=",
4329 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004330 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004331 };
4332
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004333 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004334 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004335 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004336 unsigned char c;
4337 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004338 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004339
Denys Vlasenko46a14772009-12-10 21:27:13 +01004340 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004341 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4342 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004343 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004344 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004345 switch (c) {
4346 case CTLESC:
4347 c = *p++;
4348 break;
4349 case CTLVAR:
4350 subtype = *p++;
4351 if ((subtype & VSTYPE) == VSLENGTH)
4352 str = "${#";
4353 else
4354 str = "${";
4355 if (!(subtype & VSQUOTE) == !(quoted & 1))
4356 goto dostr;
4357 quoted ^= 1;
4358 c = '"';
4359 break;
4360 case CTLENDVAR:
4361 str = "\"}" + !(quoted & 1);
4362 quoted >>= 1;
4363 subtype = 0;
4364 goto dostr;
4365 case CTLBACKQ:
4366 str = "$(...)";
4367 goto dostr;
4368 case CTLBACKQ+CTLQUOTE:
4369 str = "\"$(...)\"";
4370 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004371#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004372 case CTLARI:
4373 str = "$((";
4374 goto dostr;
4375 case CTLENDARI:
4376 str = "))";
4377 goto dostr;
4378#endif
4379 case CTLQUOTEMARK:
4380 quoted ^= 1;
4381 c = '"';
4382 break;
4383 case '=':
4384 if (subtype == 0)
4385 break;
4386 if ((subtype & VSTYPE) != VSNORMAL)
4387 quoted <<= 1;
4388 str = vstype[subtype & VSTYPE];
4389 if (subtype & VSNUL)
4390 c = ':';
4391 else
4392 goto checkstr;
4393 break;
4394 case '\'':
4395 case '\\':
4396 case '"':
4397 case '$':
4398 /* These can only happen inside quotes */
4399 cc[0] = c;
4400 str = cc;
4401 c = '\\';
4402 break;
4403 default:
4404 break;
4405 }
4406 USTPUTC(c, nextc);
4407 checkstr:
4408 if (!str)
4409 continue;
4410 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004411 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004412 USTPUTC(c, nextc);
4413 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004414 } /* while *p++ not NUL */
4415
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004416 if (quoted & 1) {
4417 USTPUTC('"', nextc);
4418 }
4419 *nextc = 0;
4420 cmdnextc = nextc;
4421}
4422
4423/* cmdtxt() and cmdlist() call each other */
4424static void cmdtxt(union node *n);
4425
4426static void
4427cmdlist(union node *np, int sep)
4428{
4429 for (; np; np = np->narg.next) {
4430 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004431 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004432 cmdtxt(np);
4433 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004434 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004435 }
4436}
4437
4438static void
4439cmdtxt(union node *n)
4440{
4441 union node *np;
4442 struct nodelist *lp;
4443 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004444
4445 if (!n)
4446 return;
4447 switch (n->type) {
4448 default:
4449#if DEBUG
4450 abort();
4451#endif
4452 case NPIPE:
4453 lp = n->npipe.cmdlist;
4454 for (;;) {
4455 cmdtxt(lp->n);
4456 lp = lp->next;
4457 if (!lp)
4458 break;
4459 cmdputs(" | ");
4460 }
4461 break;
4462 case NSEMI:
4463 p = "; ";
4464 goto binop;
4465 case NAND:
4466 p = " && ";
4467 goto binop;
4468 case NOR:
4469 p = " || ";
4470 binop:
4471 cmdtxt(n->nbinary.ch1);
4472 cmdputs(p);
4473 n = n->nbinary.ch2;
4474 goto donode;
4475 case NREDIR:
4476 case NBACKGND:
4477 n = n->nredir.n;
4478 goto donode;
4479 case NNOT:
4480 cmdputs("!");
4481 n = n->nnot.com;
4482 donode:
4483 cmdtxt(n);
4484 break;
4485 case NIF:
4486 cmdputs("if ");
4487 cmdtxt(n->nif.test);
4488 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004489 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004490 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004491 cmdputs("; else ");
4492 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004493 } else {
4494 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004495 }
4496 p = "; fi";
4497 goto dotail;
4498 case NSUBSHELL:
4499 cmdputs("(");
4500 n = n->nredir.n;
4501 p = ")";
4502 goto dotail;
4503 case NWHILE:
4504 p = "while ";
4505 goto until;
4506 case NUNTIL:
4507 p = "until ";
4508 until:
4509 cmdputs(p);
4510 cmdtxt(n->nbinary.ch1);
4511 n = n->nbinary.ch2;
4512 p = "; done";
4513 dodo:
4514 cmdputs("; do ");
4515 dotail:
4516 cmdtxt(n);
4517 goto dotail2;
4518 case NFOR:
4519 cmdputs("for ");
4520 cmdputs(n->nfor.var);
4521 cmdputs(" in ");
4522 cmdlist(n->nfor.args, 1);
4523 n = n->nfor.body;
4524 p = "; done";
4525 goto dodo;
4526 case NDEFUN:
4527 cmdputs(n->narg.text);
4528 p = "() { ... }";
4529 goto dotail2;
4530 case NCMD:
4531 cmdlist(n->ncmd.args, 1);
4532 cmdlist(n->ncmd.redirect, 0);
4533 break;
4534 case NARG:
4535 p = n->narg.text;
4536 dotail2:
4537 cmdputs(p);
4538 break;
4539 case NHERE:
4540 case NXHERE:
4541 p = "<<...";
4542 goto dotail2;
4543 case NCASE:
4544 cmdputs("case ");
4545 cmdputs(n->ncase.expr->narg.text);
4546 cmdputs(" in ");
4547 for (np = n->ncase.cases; np; np = np->nclist.next) {
4548 cmdtxt(np->nclist.pattern);
4549 cmdputs(") ");
4550 cmdtxt(np->nclist.body);
4551 cmdputs(";; ");
4552 }
4553 p = "esac";
4554 goto dotail2;
4555 case NTO:
4556 p = ">";
4557 goto redir;
4558 case NCLOBBER:
4559 p = ">|";
4560 goto redir;
4561 case NAPPEND:
4562 p = ">>";
4563 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004564#if ENABLE_ASH_BASH_COMPAT
4565 case NTO2:
4566#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004567 case NTOFD:
4568 p = ">&";
4569 goto redir;
4570 case NFROM:
4571 p = "<";
4572 goto redir;
4573 case NFROMFD:
4574 p = "<&";
4575 goto redir;
4576 case NFROMTO:
4577 p = "<>";
4578 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004579 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004580 cmdputs(p);
4581 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004582 cmdputs(utoa(n->ndup.dupfd));
4583 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004584 }
4585 n = n->nfile.fname;
4586 goto donode;
4587 }
4588}
4589
4590static char *
4591commandtext(union node *n)
4592{
4593 char *name;
4594
4595 STARTSTACKSTR(cmdnextc);
4596 cmdtxt(n);
4597 name = stackblock();
4598 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4599 name, cmdnextc, cmdnextc));
4600 return ckstrdup(name);
4601}
4602#endif /* JOBS */
4603
4604/*
4605 * Fork off a subshell. If we are doing job control, give the subshell its
4606 * own process group. Jp is a job structure that the job is to be added to.
4607 * N is the command that will be evaluated by the child. Both jp and n may
4608 * be NULL. The mode parameter can be one of the following:
4609 * FORK_FG - Fork off a foreground process.
4610 * FORK_BG - Fork off a background process.
4611 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4612 * process group even if job control is on.
4613 *
4614 * When job control is turned off, background processes have their standard
4615 * input redirected to /dev/null (except for the second and later processes
4616 * in a pipeline).
4617 *
4618 * Called with interrupts off.
4619 */
4620/*
4621 * Clear traps on a fork.
4622 */
4623static void
4624clear_traps(void)
4625{
4626 char **tp;
4627
4628 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004629 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004630 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004631 if (trap_ptr == trap)
4632 free(*tp);
4633 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004635 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004636 setsignal(tp - trap);
4637 INT_ON;
4638 }
4639 }
Alexander Shishkinccb97712010-07-25 13:07:39 +02004640 may_have_traps = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004641}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004642
4643/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004644static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004645
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004646/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004647static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004648forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004649{
4650 int oldlvl;
4651
4652 TRACE(("Child shell %d\n", getpid()));
4653 oldlvl = shlvl;
4654 shlvl++;
4655
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004656 /* man bash: "Non-builtin commands run by bash have signal handlers
4657 * set to the values inherited by the shell from its parent".
4658 * Do we do it correctly? */
4659
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004660 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004661
4662 if (mode == FORK_NOJOB /* is it `xxx` ? */
4663 && n && n->type == NCMD /* is it single cmd? */
4664 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004665 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004666 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4667 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4668 ) {
4669 TRACE(("Trap hack\n"));
4670 /* Awful hack for `trap` or $(trap).
4671 *
4672 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4673 * contains an example where "trap" is executed in a subshell:
4674 *
4675 * save_traps=$(trap)
4676 * ...
4677 * eval "$save_traps"
4678 *
4679 * Standard does not say that "trap" in subshell shall print
4680 * parent shell's traps. It only says that its output
4681 * must have suitable form, but then, in the above example
4682 * (which is not supposed to be normative), it implies that.
4683 *
4684 * bash (and probably other shell) does implement it
4685 * (traps are reset to defaults, but "trap" still shows them),
4686 * but as a result, "trap" logic is hopelessly messed up:
4687 *
4688 * # trap
4689 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4690 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4691 * # true | trap <--- trap is in subshell - no output (ditto)
4692 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4693 * trap -- 'echo Ho' SIGWINCH
4694 * # echo `(trap)` <--- in subshell in subshell - output
4695 * trap -- 'echo Ho' SIGWINCH
4696 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4697 * trap -- 'echo Ho' SIGWINCH
4698 *
4699 * The rules when to forget and when to not forget traps
4700 * get really complex and nonsensical.
4701 *
4702 * Our solution: ONLY bare $(trap) or `trap` is special.
4703 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004704 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004705 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004706 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004707 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004708 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004709#if JOBS
4710 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004711 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004712 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4713 pid_t pgrp;
4714
4715 if (jp->nprocs == 0)
4716 pgrp = getpid();
4717 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004718 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004719 /* this can fail because we are doing it in the parent also */
4720 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004721 if (mode == FORK_FG)
4722 xtcsetpgrp(ttyfd, pgrp);
4723 setsignal(SIGTSTP);
4724 setsignal(SIGTTOU);
4725 } else
4726#endif
4727 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004728 /* man bash: "When job control is not in effect,
4729 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004730 ignoresig(SIGINT);
4731 ignoresig(SIGQUIT);
4732 if (jp->nprocs == 0) {
4733 close(0);
4734 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004735 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004736 }
4737 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004738 if (!oldlvl) {
4739 if (iflag) { /* why if iflag only? */
4740 setsignal(SIGINT);
4741 setsignal(SIGTERM);
4742 }
4743 /* man bash:
4744 * "In all cases, bash ignores SIGQUIT. Non-builtin
4745 * commands run by bash have signal handlers
4746 * set to the values inherited by the shell
4747 * from its parent".
4748 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004749 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004750 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004751#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004752 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004753 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004754 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004755 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004756 /* "jobs": we do not want to clear job list for it,
4757 * instead we remove only _its_ own_ job from job list.
4758 * This makes "jobs .... | cat" more useful.
4759 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004760 freejob(curjob);
4761 return;
4762 }
4763#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004764 for (jp = curjob; jp; jp = jp->prev_job)
4765 freejob(jp);
4766 jobless = 0;
4767}
4768
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004769/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004770#if !JOBS
4771#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4772#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004773static void
4774forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4775{
4776 TRACE(("In parent shell: child = %d\n", pid));
4777 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004778 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4779 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004780 jobless++;
4781 return;
4782 }
4783#if JOBS
4784 if (mode != FORK_NOJOB && jp->jobctl) {
4785 int pgrp;
4786
4787 if (jp->nprocs == 0)
4788 pgrp = pid;
4789 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004790 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004791 /* This can fail because we are doing it in the child also */
4792 setpgid(pid, pgrp);
4793 }
4794#endif
4795 if (mode == FORK_BG) {
4796 backgndpid = pid; /* set $! */
4797 set_curjob(jp, CUR_RUNNING);
4798 }
4799 if (jp) {
4800 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004801 ps->ps_pid = pid;
4802 ps->ps_status = -1;
4803 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004804#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004805 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004806 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004807#endif
4808 }
4809}
4810
4811static int
4812forkshell(struct job *jp, union node *n, int mode)
4813{
4814 int pid;
4815
4816 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4817 pid = fork();
4818 if (pid < 0) {
4819 TRACE(("Fork failed, errno=%d", errno));
4820 if (jp)
4821 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004822 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004823 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004824 if (pid == 0) {
4825 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004826 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004827 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004828 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004829 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004830 return pid;
4831}
4832
4833/*
4834 * Wait for job to finish.
4835 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004836 * Under job control we have the problem that while a child process
4837 * is running interrupts generated by the user are sent to the child
4838 * but not to the shell. This means that an infinite loop started by
4839 * an interactive user may be hard to kill. With job control turned off,
4840 * an interactive user may place an interactive program inside a loop.
4841 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004842 * these interrupts to also abort the loop. The approach we take here
4843 * is to have the shell ignore interrupt signals while waiting for a
4844 * foreground process to terminate, and then send itself an interrupt
4845 * signal if the child process was terminated by an interrupt signal.
4846 * Unfortunately, some programs want to do a bit of cleanup and then
4847 * exit on interrupt; unless these processes terminate themselves by
4848 * sending a signal to themselves (instead of calling exit) they will
4849 * confuse this approach.
4850 *
4851 * Called with interrupts off.
4852 */
4853static int
4854waitforjob(struct job *jp)
4855{
4856 int st;
4857
4858 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004859
4860 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004861 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004862 /* In non-interactive shells, we _can_ get
4863 * a keyboard signal here and be EINTRed,
4864 * but we just loop back, waiting for command to complete.
4865 *
4866 * man bash:
4867 * "If bash is waiting for a command to complete and receives
4868 * a signal for which a trap has been set, the trap
4869 * will not be executed until the command completes."
4870 *
4871 * Reality is that even if trap is not set, bash
4872 * will not act on the signal until command completes.
4873 * Try this. sleep5intoff.c:
4874 * #include <signal.h>
4875 * #include <unistd.h>
4876 * int main() {
4877 * sigset_t set;
4878 * sigemptyset(&set);
4879 * sigaddset(&set, SIGINT);
4880 * sigaddset(&set, SIGQUIT);
4881 * sigprocmask(SIG_BLOCK, &set, NULL);
4882 * sleep(5);
4883 * return 0;
4884 * }
4885 * $ bash -c './sleep5intoff; echo hi'
4886 * ^C^C^C^C <--- pressing ^C once a second
4887 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004888 * $ bash -c './sleep5intoff; echo hi'
4889 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4890 * $ _
4891 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004892 dowait(DOWAIT_BLOCK, jp);
4893 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004894 INT_ON;
4895
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004896 st = getstatus(jp);
4897#if JOBS
4898 if (jp->jobctl) {
4899 xtcsetpgrp(ttyfd, rootpid);
4900 /*
4901 * This is truly gross.
4902 * If we're doing job control, then we did a TIOCSPGRP which
4903 * caused us (the shell) to no longer be in the controlling
4904 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4905 * intuit from the subprocess exit status whether a SIGINT
4906 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4907 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004908 if (jp->sigint) /* TODO: do the same with all signals */
4909 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004910 }
4911 if (jp->state == JOBDONE)
4912#endif
4913 freejob(jp);
4914 return st;
4915}
4916
4917/*
4918 * return 1 if there are stopped jobs, otherwise 0
4919 */
4920static int
4921stoppedjobs(void)
4922{
4923 struct job *jp;
4924 int retval;
4925
4926 retval = 0;
4927 if (job_warning)
4928 goto out;
4929 jp = curjob;
4930 if (jp && jp->state == JOBSTOPPED) {
4931 out2str("You have stopped jobs.\n");
4932 job_warning = 2;
4933 retval++;
4934 }
4935 out:
4936 return retval;
4937}
4938
4939
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004940/* ============ redir.c
4941 *
4942 * Code for dealing with input/output redirection.
4943 */
4944
4945#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004946#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004947
4948/*
4949 * Open a file in noclobber mode.
4950 * The code was copied from bash.
4951 */
4952static int
4953noclobberopen(const char *fname)
4954{
4955 int r, fd;
4956 struct stat finfo, finfo2;
4957
4958 /*
4959 * If the file exists and is a regular file, return an error
4960 * immediately.
4961 */
4962 r = stat(fname, &finfo);
4963 if (r == 0 && S_ISREG(finfo.st_mode)) {
4964 errno = EEXIST;
4965 return -1;
4966 }
4967
4968 /*
4969 * If the file was not present (r != 0), make sure we open it
4970 * exclusively so that if it is created before we open it, our open
4971 * will fail. Make sure that we do not truncate an existing file.
4972 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4973 * file was not a regular file, we leave O_EXCL off.
4974 */
4975 if (r != 0)
4976 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4977 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4978
4979 /* If the open failed, return the file descriptor right away. */
4980 if (fd < 0)
4981 return fd;
4982
4983 /*
4984 * OK, the open succeeded, but the file may have been changed from a
4985 * non-regular file to a regular file between the stat and the open.
4986 * We are assuming that the O_EXCL open handles the case where FILENAME
4987 * did not exist and is symlinked to an existing file between the stat
4988 * and open.
4989 */
4990
4991 /*
4992 * If we can open it and fstat the file descriptor, and neither check
4993 * revealed that it was a regular file, and the file has not been
4994 * replaced, return the file descriptor.
4995 */
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02004996 if (fstat(fd, &finfo2) == 0
4997 && !S_ISREG(finfo2.st_mode)
4998 && finfo.st_dev == finfo2.st_dev
4999 && finfo.st_ino == finfo2.st_ino
5000 ) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005001 return fd;
Denys Vlasenko8d3e2252010-08-31 12:42:06 +02005002 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003
5004 /* The file has been replaced. badness. */
5005 close(fd);
5006 errno = EEXIST;
5007 return -1;
5008}
5009
5010/*
5011 * Handle here documents. Normally we fork off a process to write the
5012 * data to a pipe. If the document is short, we can stuff the data in
5013 * the pipe without forking.
5014 */
5015/* openhere needs this forward reference */
5016static void expandhere(union node *arg, int fd);
5017static int
5018openhere(union node *redir)
5019{
5020 int pip[2];
5021 size_t len = 0;
5022
5023 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005024 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005025 if (redir->type == NHERE) {
5026 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005027 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005028 full_write(pip[1], redir->nhere.doc->narg.text, len);
5029 goto out;
5030 }
5031 }
5032 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005033 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005034 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00005035 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5036 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5037 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5038 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005039 signal(SIGPIPE, SIG_DFL);
5040 if (redir->type == NHERE)
5041 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00005042 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005043 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00005044 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005045 }
5046 out:
5047 close(pip[1]);
5048 return pip[0];
5049}
5050
5051static int
5052openredirect(union node *redir)
5053{
5054 char *fname;
5055 int f;
5056
5057 switch (redir->nfile.type) {
5058 case NFROM:
5059 fname = redir->nfile.expfname;
5060 f = open(fname, O_RDONLY);
5061 if (f < 0)
5062 goto eopen;
5063 break;
5064 case NFROMTO:
5065 fname = redir->nfile.expfname;
Andreas Bühmannda75f442010-06-24 04:32:37 +02005066 f = open(fname, O_RDWR|O_CREAT, 0666);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005067 if (f < 0)
5068 goto ecreate;
5069 break;
5070 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00005071#if ENABLE_ASH_BASH_COMPAT
5072 case NTO2:
5073#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005074 /* Take care of noclobber mode. */
5075 if (Cflag) {
5076 fname = redir->nfile.expfname;
5077 f = noclobberopen(fname);
5078 if (f < 0)
5079 goto ecreate;
5080 break;
5081 }
5082 /* FALLTHROUGH */
5083 case NCLOBBER:
5084 fname = redir->nfile.expfname;
5085 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5086 if (f < 0)
5087 goto ecreate;
5088 break;
5089 case NAPPEND:
5090 fname = redir->nfile.expfname;
5091 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5092 if (f < 0)
5093 goto ecreate;
5094 break;
5095 default:
5096#if DEBUG
5097 abort();
5098#endif
5099 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005100/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00005101// case NTOFD:
5102// case NFROMFD:
5103// f = -1;
5104// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005105 case NHERE:
5106 case NXHERE:
5107 f = openhere(redir);
5108 break;
5109 }
5110
5111 return f;
5112 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005113 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005114 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005115 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005116}
5117
5118/*
5119 * Copy a file descriptor to be >= to. Returns -1
5120 * if the source file descriptor is closed, EMPTY if there are no unused
5121 * file descriptors left.
5122 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005123/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5124 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005125enum {
5126 COPYFD_EXACT = (int)~(INT_MAX),
5127 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5128};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129static int
5130copyfd(int from, int to)
5131{
5132 int newfd;
5133
Denis Vlasenko5a867312008-07-24 19:46:38 +00005134 if (to & COPYFD_EXACT) {
5135 to &= ~COPYFD_EXACT;
5136 /*if (from != to)*/
5137 newfd = dup2(from, to);
5138 } else {
5139 newfd = fcntl(from, F_DUPFD, to);
5140 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005141 if (newfd < 0) {
5142 if (errno == EMFILE)
5143 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005144 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005145 ash_msg_and_raise_error("%d: %m", from);
5146 }
5147 return newfd;
5148}
5149
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005150/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005151struct two_fd_t {
5152 int orig, copy;
5153};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005154struct redirtab {
5155 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005156 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005157 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005158 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005159};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005160#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005161
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005162static int need_to_remember(struct redirtab *rp, int fd)
5163{
5164 int i;
5165
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005166 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005167 return 0;
5168
5169 for (i = 0; i < rp->pair_count; i++) {
5170 if (rp->two_fd[i].orig == fd) {
5171 /* already remembered */
5172 return 0;
5173 }
5174 }
5175 return 1;
5176}
5177
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005178/* "hidden" fd is a fd used to read scripts, or a copy of such */
5179static int is_hidden_fd(struct redirtab *rp, int fd)
5180{
5181 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005182 struct parsefile *pf;
5183
5184 if (fd == -1)
5185 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005186 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005187 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005188 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005189 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005190 * $ ash # running ash interactively
5191 * $ . ./script.sh
5192 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005193 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005194 * it's still ok to use it: "read" builtin uses it,
5195 * why should we cripple "exec" builtin?
5196 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005197 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005198 return 1;
5199 }
5200 pf = pf->prev;
5201 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005202
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005203 if (!rp)
5204 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005205 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005206 fd |= COPYFD_RESTORE;
5207 for (i = 0; i < rp->pair_count; i++) {
5208 if (rp->two_fd[i].copy == fd) {
5209 return 1;
5210 }
5211 }
5212 return 0;
5213}
5214
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005215/*
5216 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5217 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005218 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005219 */
5220/* flags passed to redirect */
5221#define REDIR_PUSH 01 /* save previous values of file descriptors */
5222#define REDIR_SAVEFD2 03 /* set preverrout */
5223static void
5224redirect(union node *redir, int flags)
5225{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005226 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005227 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005228 int i;
5229 int fd;
5230 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005231 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005232
Denis Vlasenko01631112007-12-16 17:20:38 +00005233 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005234 if (!redir) {
5235 return;
5236 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005237
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005238 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005239 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005240 INT_OFF;
5241 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005242 union node *tmp = redir;
5243 do {
5244 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005245#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005246 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005247 sv_pos++;
5248#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005249 tmp = tmp->nfile.next;
5250 } while (tmp);
5251 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005252 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005253 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005254 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005255 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005256 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005257 while (sv_pos > 0) {
5258 sv_pos--;
5259 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5260 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005261 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005262
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005263 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005264 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005265 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005266 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005267 right_fd = redir->ndup.dupfd;
5268 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005269 /* redirect from/to same file descriptor? */
5270 if (right_fd == fd)
5271 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005272 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005273 if (is_hidden_fd(sv, right_fd)) {
5274 errno = EBADF; /* as if it is closed */
5275 ash_msg_and_raise_error("%d: %m", right_fd);
5276 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005277 newfd = -1;
5278 } else {
5279 newfd = openredirect(redir); /* always >= 0 */
5280 if (fd == newfd) {
5281 /* Descriptor wasn't open before redirect.
5282 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005283 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005284 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005285 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005286 continue;
5287 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005288 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005289#if ENABLE_ASH_BASH_COMPAT
5290 redirect_more:
5291#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005292 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005293 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005294 /* Careful to not accidentally "save"
5295 * to the same fd as right side fd in N>&M */
5296 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5297 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005298/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5299 * are closed in popredir() in the child, preventing them from leaking
5300 * into child. (popredir() also cleans up the mess in case of failures)
5301 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005302 if (i == -1) {
5303 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005304 if (i != EBADF) {
5305 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005306 if (newfd >= 0)
5307 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005308 errno = i;
5309 ash_msg_and_raise_error("%d: %m", fd);
5310 /* NOTREACHED */
5311 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005312 /* EBADF: it is not open - good, remember to close it */
5313 remember_to_close:
5314 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005315 } else { /* fd is open, save its copy */
5316 /* "exec fd>&-" should not close fds
5317 * which point to script file(s).
5318 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005319 if (is_hidden_fd(sv, fd))
5320 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005321 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005322 if (fd == 2)
5323 copied_fd2 = i;
5324 sv->two_fd[sv_pos].orig = fd;
5325 sv->two_fd[sv_pos].copy = i;
5326 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005327 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005328 if (newfd < 0) {
5329 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005330 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005331 /* Don't want to trigger debugging */
5332 if (fd != -1)
5333 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005334 } else {
5335 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005336 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005337 } else if (fd != newfd) { /* move newfd to fd */
5338 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005339#if ENABLE_ASH_BASH_COMPAT
5340 if (!(redir->nfile.type == NTO2 && fd == 2))
5341#endif
5342 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005343 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005344#if ENABLE_ASH_BASH_COMPAT
5345 if (redir->nfile.type == NTO2 && fd == 1) {
5346 /* We already redirected it to fd 1, now copy it to 2 */
5347 newfd = 1;
5348 fd = 2;
5349 goto redirect_more;
5350 }
5351#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005352 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005353
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005354 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005355 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5356 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005357}
5358
5359/*
5360 * Undo the effects of the last redirection.
5361 */
5362static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005363popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005364{
5365 struct redirtab *rp;
5366 int i;
5367
Denis Vlasenko01631112007-12-16 17:20:38 +00005368 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005369 return;
5370 INT_OFF;
5371 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005372 for (i = 0; i < rp->pair_count; i++) {
5373 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005374 int copy = rp->two_fd[i].copy;
5375 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005376 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005377 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005378 continue;
5379 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005380 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005381 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005382 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005383 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005384 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005385 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005386 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005387 }
5388 }
5389 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005390 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005391 free(rp);
5392 INT_ON;
5393}
5394
5395/*
5396 * Undo all redirections. Called on error or interrupt.
5397 */
5398
5399/*
5400 * Discard all saved file descriptors.
5401 */
5402static void
5403clearredir(int drop)
5404{
5405 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005406 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005407 if (!redirlist)
5408 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005409 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005410 }
5411}
5412
5413static int
5414redirectsafe(union node *redir, int flags)
5415{
5416 int err;
5417 volatile int saveint;
5418 struct jmploc *volatile savehandler = exception_handler;
5419 struct jmploc jmploc;
5420
5421 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005422 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5423 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005424 if (!err) {
5425 exception_handler = &jmploc;
5426 redirect(redir, flags);
5427 }
5428 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005429 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005430 longjmp(exception_handler->loc, 1);
5431 RESTORE_INT(saveint);
5432 return err;
5433}
5434
5435
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436/* ============ Routines to expand arguments to commands
5437 *
5438 * We have to deal with backquotes, shell variables, and file metacharacters.
5439 */
5440
Mike Frysinger98c52642009-04-02 10:02:37 +00005441#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005442static arith_t
5443ash_arith(const char *s)
5444{
5445 arith_eval_hooks_t math_hooks;
5446 arith_t result;
5447 int errcode = 0;
5448
5449 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005450 math_hooks.setvar = setvar2;
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02005451 //math_hooks.endofname = endofname;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005452
5453 INT_OFF;
5454 result = arith(s, &errcode, &math_hooks);
5455 if (errcode < 0) {
5456 if (errcode == -3)
5457 ash_msg_and_raise_error("exponent less than 0");
5458 if (errcode == -2)
5459 ash_msg_and_raise_error("divide by zero");
5460 if (errcode == -5)
5461 ash_msg_and_raise_error("expression recursion loop detected");
5462 raise_error_syntax(s);
5463 }
5464 INT_ON;
5465
5466 return result;
5467}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005468#endif
5469
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470/*
5471 * expandarg flags
5472 */
5473#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5474#define EXP_TILDE 0x2 /* do normal tilde expansion */
5475#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5476#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5477#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5478#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5479#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5480#define EXP_WORD 0x80 /* expand word in parameter expansion */
5481#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5482/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005483 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 */
5485#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5486#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5487#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5488#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5489#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5490
5491/*
5492 * Structure specifying which parts of the string should be searched
5493 * for IFS characters.
5494 */
5495struct ifsregion {
5496 struct ifsregion *next; /* next region in list */
5497 int begoff; /* offset of start of region */
5498 int endoff; /* offset of end of region */
5499 int nulonly; /* search for nul bytes only */
5500};
5501
5502struct arglist {
5503 struct strlist *list;
5504 struct strlist **lastp;
5505};
5506
5507/* output of current string */
5508static char *expdest;
5509/* list of back quote expressions */
5510static struct nodelist *argbackq;
5511/* first struct in list of ifs regions */
5512static struct ifsregion ifsfirst;
5513/* last struct in list */
5514static struct ifsregion *ifslastp;
5515/* holds expanded arg list */
5516static struct arglist exparg;
5517
5518/*
5519 * Our own itoa().
5520 */
5521static int
5522cvtnum(arith_t num)
5523{
5524 int len;
5525
5526 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005527 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005528 STADJUST(len, expdest);
5529 return len;
5530}
5531
5532static size_t
5533esclen(const char *start, const char *p)
5534{
5535 size_t esc = 0;
5536
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005537 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005538 esc++;
5539 }
5540 return esc;
5541}
5542
5543/*
5544 * Remove any CTLESC characters from a string.
5545 */
5546static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005547rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005548{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005549 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005550
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005551 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005552 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005553 unsigned protect_against_glob;
5554 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005555
5556 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005557 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005558 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005559
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005560 q = p;
5561 r = str;
5562 if (flag & RMESCAPE_ALLOC) {
5563 size_t len = p - str;
5564 size_t fulllen = len + strlen(p) + 1;
5565
5566 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005567 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005568 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005569 /* p and str may be invalidated by makestrspace */
5570 str = (char *)stackblock() + strloc;
5571 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005572 } else if (flag & RMESCAPE_HEAP) {
5573 r = ckmalloc(fulllen);
5574 } else {
5575 r = stalloc(fulllen);
5576 }
5577 q = r;
5578 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005579 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005580 }
5581 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005582
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005583 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5584 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005585 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005586 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005587 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005588// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5589// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5590// Note: both inquotes and protect_against_glob only affect whether
5591// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005592 inquotes = ~inquotes;
5593 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005594 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005595 continue;
5596 }
5597 if (*p == '\\') {
5598 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005599 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005600 goto copy;
5601 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005602 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005603 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005604 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005605 *q++ = '\\';
5606 }
5607 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005608 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005609 copy:
5610 *q++ = *p++;
5611 }
5612 *q = '\0';
5613 if (flag & RMESCAPE_GROW) {
5614 expdest = r;
5615 STADJUST(q - r + 1, expdest);
5616 }
5617 return r;
5618}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005619#define pmatch(a, b) !fnmatch((a), (b), 0)
5620
5621/*
5622 * Prepare a pattern for a expmeta (internal glob(3)) call.
5623 *
5624 * Returns an stalloced string.
5625 */
5626static char *
5627preglob(const char *pattern, int quoted, int flag)
5628{
5629 flag |= RMESCAPE_GLOB;
5630 if (quoted) {
5631 flag |= RMESCAPE_QUOTED;
5632 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005633 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005634}
5635
5636/*
5637 * Put a string on the stack.
5638 */
5639static void
5640memtodest(const char *p, size_t len, int syntax, int quotes)
5641{
5642 char *q = expdest;
5643
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005644 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005645
5646 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005647 unsigned char c = *p++;
5648 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005649 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005650 if (quotes) {
5651 int n = SIT(c, syntax);
5652 if (n == CCTL || n == CBACK)
5653 USTPUTC(CTLESC, q);
5654 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005655 USTPUTC(c, q);
5656 }
5657
5658 expdest = q;
5659}
5660
5661static void
5662strtodest(const char *p, int syntax, int quotes)
5663{
5664 memtodest(p, strlen(p), syntax, quotes);
5665}
5666
5667/*
5668 * Record the fact that we have to scan this region of the
5669 * string for IFS characters.
5670 */
5671static void
5672recordregion(int start, int end, int nulonly)
5673{
5674 struct ifsregion *ifsp;
5675
5676 if (ifslastp == NULL) {
5677 ifsp = &ifsfirst;
5678 } else {
5679 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005680 ifsp = ckzalloc(sizeof(*ifsp));
5681 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682 ifslastp->next = ifsp;
5683 INT_ON;
5684 }
5685 ifslastp = ifsp;
5686 ifslastp->begoff = start;
5687 ifslastp->endoff = end;
5688 ifslastp->nulonly = nulonly;
5689}
5690
5691static void
5692removerecordregions(int endoff)
5693{
5694 if (ifslastp == NULL)
5695 return;
5696
5697 if (ifsfirst.endoff > endoff) {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005698 while (ifsfirst.next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005699 struct ifsregion *ifsp;
5700 INT_OFF;
5701 ifsp = ifsfirst.next->next;
5702 free(ifsfirst.next);
5703 ifsfirst.next = ifsp;
5704 INT_ON;
5705 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005706 if (ifsfirst.begoff > endoff) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005707 ifslastp = NULL;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005708 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005709 ifslastp = &ifsfirst;
5710 ifsfirst.endoff = endoff;
5711 }
5712 return;
5713 }
5714
5715 ifslastp = &ifsfirst;
5716 while (ifslastp->next && ifslastp->next->begoff < endoff)
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005717 ifslastp = ifslastp->next;
5718 while (ifslastp->next) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005719 struct ifsregion *ifsp;
5720 INT_OFF;
5721 ifsp = ifslastp->next->next;
5722 free(ifslastp->next);
5723 ifslastp->next = ifsp;
5724 INT_ON;
5725 }
5726 if (ifslastp->endoff > endoff)
5727 ifslastp->endoff = endoff;
5728}
5729
5730static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005731exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005732{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005733 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005734 char *name;
5735 struct passwd *pw;
5736 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005737 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005738 int startloc;
5739
5740 name = p + 1;
5741
5742 while ((c = *++p) != '\0') {
5743 switch (c) {
5744 case CTLESC:
5745 return startp;
5746 case CTLQUOTEMARK:
5747 return startp;
5748 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005749 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005750 goto done;
5751 break;
5752 case '/':
5753 case CTLENDVAR:
5754 goto done;
5755 }
5756 }
5757 done:
5758 *p = '\0';
5759 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005760 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005761 } else {
5762 pw = getpwnam(name);
5763 if (pw == NULL)
5764 goto lose;
5765 home = pw->pw_dir;
5766 }
5767 if (!home || !*home)
5768 goto lose;
5769 *p = c;
5770 startloc = expdest - (char *)stackblock();
5771 strtodest(home, SQSYNTAX, quotes);
5772 recordregion(startloc, expdest - (char *)stackblock(), 0);
5773 return p;
5774 lose:
5775 *p = c;
5776 return startp;
5777}
5778
5779/*
5780 * Execute a command inside back quotes. If it's a builtin command, we
5781 * want to save its output in a block obtained from malloc. Otherwise
5782 * we fork off a subprocess and get the output of the command via a pipe.
5783 * Should be called with interrupts off.
5784 */
5785struct backcmd { /* result of evalbackcmd */
5786 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005787 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005788 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005789 struct job *jp; /* job structure for command */
5790};
5791
5792/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005793static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005794#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005795static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005797static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005798evalbackcmd(union node *n, struct backcmd *result)
5799{
5800 int saveherefd;
5801
5802 result->fd = -1;
5803 result->buf = NULL;
5804 result->nleft = 0;
5805 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005806 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005807 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005808
5809 saveherefd = herefd;
5810 herefd = -1;
5811
5812 {
5813 int pip[2];
5814 struct job *jp;
5815
5816 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005817 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005818 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005819 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5820 FORCE_INT_ON;
5821 close(pip[0]);
5822 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005823 /*close(1);*/
5824 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005825 close(pip[1]);
5826 }
5827 eflag = 0;
5828 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5829 /* NOTREACHED */
5830 }
5831 close(pip[1]);
5832 result->fd = pip[0];
5833 result->jp = jp;
5834 }
5835 herefd = saveherefd;
5836 out:
5837 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5838 result->fd, result->buf, result->nleft, result->jp));
5839}
5840
5841/*
5842 * Expand stuff in backwards quotes.
5843 */
5844static void
5845expbackq(union node *cmd, int quoted, int quotes)
5846{
5847 struct backcmd in;
5848 int i;
5849 char buf[128];
5850 char *p;
5851 char *dest;
5852 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005853 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 struct stackmark smark;
5855
5856 INT_OFF;
5857 setstackmark(&smark);
5858 dest = expdest;
5859 startloc = dest - (char *)stackblock();
5860 grabstackstr(dest);
5861 evalbackcmd(cmd, &in);
5862 popstackmark(&smark);
5863
5864 p = in.buf;
5865 i = in.nleft;
5866 if (i == 0)
5867 goto read;
5868 for (;;) {
5869 memtodest(p, i, syntax, quotes);
5870 read:
5871 if (in.fd < 0)
5872 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005873 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005874 TRACE(("expbackq: read returns %d\n", i));
5875 if (i <= 0)
5876 break;
5877 p = buf;
5878 }
5879
Denis Vlasenko60818682007-09-28 22:07:23 +00005880 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 if (in.fd >= 0) {
5882 close(in.fd);
5883 back_exitstatus = waitforjob(in.jp);
5884 }
5885 INT_ON;
5886
5887 /* Eat all trailing newlines */
5888 dest = expdest;
5889 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5890 STUNPUTC(dest);
5891 expdest = dest;
5892
5893 if (quoted == 0)
5894 recordregion(startloc, dest - (char *)stackblock(), 0);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02005895 TRACE(("evalbackq: size:%d:'%.*s'\n",
5896 (int)((dest - (char *)stackblock()) - startloc),
5897 (int)((dest - (char *)stackblock()) - startloc),
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005898 stackblock() + startloc));
5899}
5900
Mike Frysinger98c52642009-04-02 10:02:37 +00005901#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005902/*
5903 * Expand arithmetic expression. Backup to start of expression,
5904 * evaluate, place result in (backed up) result, adjust string position.
5905 */
5906static void
5907expari(int quotes)
5908{
5909 char *p, *start;
5910 int begoff;
5911 int flag;
5912 int len;
5913
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005914 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005915
5916 /*
5917 * This routine is slightly over-complicated for
5918 * efficiency. Next we scan backwards looking for the
5919 * start of arithmetic.
5920 */
5921 start = stackblock();
5922 p = expdest - 1;
5923 *p = '\0';
5924 p--;
5925 do {
5926 int esc;
5927
Denys Vlasenkocd716832009-11-28 22:14:02 +01005928 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 p--;
5930#if DEBUG
5931 if (p < start) {
5932 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5933 }
5934#endif
5935 }
5936
5937 esc = esclen(start, p);
5938 if (!(esc % 2)) {
5939 break;
5940 }
5941
5942 p -= esc + 1;
5943 } while (1);
5944
5945 begoff = p - start;
5946
5947 removerecordregions(begoff);
5948
5949 flag = p[1];
5950
5951 expdest = p;
5952
5953 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005954 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005955
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005956 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005957
5958 if (flag != '"')
5959 recordregion(begoff, begoff + len, 0);
5960}
5961#endif
5962
5963/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005964static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005965
5966/*
5967 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5968 * characters to allow for further processing. Otherwise treat
5969 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005970 *
5971 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5972 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5973 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005974 */
5975static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005976argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005977{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005978 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005979 '=',
5980 ':',
5981 CTLQUOTEMARK,
5982 CTLENDVAR,
5983 CTLESC,
5984 CTLVAR,
5985 CTLBACKQ,
5986 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005987#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005988 CTLENDARI,
5989#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005990 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005991 };
5992 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005993 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5994 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005995 int inquotes;
5996 size_t length;
5997 int startloc;
5998
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005999 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006000 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006001 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006002 reject++;
6003 }
6004 inquotes = 0;
6005 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006006 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006007 char *q;
6008
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006009 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006010 tilde:
6011 q = p;
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006012 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006013 q++;
6014 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006015 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006016 }
6017 start:
6018 startloc = expdest - (char *)stackblock();
6019 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006020 unsigned char c;
6021
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006022 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006023 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006024 if (c) {
6025 if (!(c & 0x80)
Denys Vlasenko958581a2010-09-12 15:04:27 +02006026 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006027 ) {
6028 /* c == '=' || c == ':' || c == CTLENDARI */
6029 length++;
6030 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006031 }
6032 if (length > 0) {
6033 int newloc;
6034 expdest = stack_nputstr(p, length, expdest);
6035 newloc = expdest - (char *)stackblock();
6036 if (breakall && !inquotes && newloc > startloc) {
6037 recordregion(startloc, newloc, 0);
6038 }
6039 startloc = newloc;
6040 }
6041 p += length + 1;
6042 length = 0;
6043
6044 switch (c) {
6045 case '\0':
6046 goto breakloop;
6047 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006048 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006049 p--;
6050 continue;
6051 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006052 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006053 reject++;
6054 /* fall through */
6055 case ':':
6056 /*
6057 * sort of a hack - expand tildes in variable
6058 * assignments (after the first '=' and after ':'s).
6059 */
6060 if (*--p == '~') {
6061 goto tilde;
6062 }
6063 continue;
6064 }
6065
6066 switch (c) {
6067 case CTLENDVAR: /* ??? */
6068 goto breakloop;
6069 case CTLQUOTEMARK:
6070 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006071 if (!inquotes
6072 && memcmp(p, dolatstr, 4) == 0
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006073 && ( p[4] == (char)CTLQUOTEMARK
6074 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006075 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006076 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006077 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006078 goto start;
6079 }
6080 inquotes = !inquotes;
6081 addquote:
6082 if (quotes) {
6083 p--;
6084 length++;
6085 startloc++;
6086 }
6087 break;
6088 case CTLESC:
6089 startloc++;
6090 length++;
6091 goto addquote;
6092 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006093 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006094 goto start;
6095 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006096 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006097 case CTLBACKQ|CTLQUOTE:
6098 expbackq(argbackq->n, c, quotes);
6099 argbackq = argbackq->next;
6100 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00006101#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006102 case CTLENDARI:
6103 p--;
6104 expari(quotes);
6105 goto start;
6106#endif
6107 }
6108 }
Denys Vlasenko958581a2010-09-12 15:04:27 +02006109 breakloop: ;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006110}
6111
6112static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006113scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6114 char *pattern, int quotes, int zero)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006115{
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006116 char *loc, *loc2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006117 char c;
6118
6119 loc = startp;
6120 loc2 = rmesc;
6121 do {
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006122 int match;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006124
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006125 c = *loc2;
6126 if (zero) {
6127 *loc2 = '\0';
6128 s = rmesc;
6129 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006130 match = pmatch(pattern, s);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006131
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006132 *loc2 = c;
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006133 if (match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006134 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006135 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006136 loc++;
6137 loc++;
6138 loc2++;
6139 } while (c);
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006140 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006141}
6142
6143static char *
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006144scanright(char *startp, char *rmesc, char *rmescend,
6145 char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006146{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006147#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6148 int try2optimize = match_at_start;
6149#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006150 int esc = 0;
6151 char *loc;
6152 char *loc2;
6153
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006154 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6155 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6156 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6157 * Logic:
6158 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6159 * and on each iteration they go back two/one char until they reach the beginning.
6160 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6161 */
6162 /* TODO: document in what other circumstances we are called. */
6163
6164 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006165 int match;
6166 char c = *loc2;
6167 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006168 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006169 *loc2 = '\0';
6170 s = rmesc;
6171 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006172 match = pmatch(pattern, s);
6173 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006174 *loc2 = c;
6175 if (match)
6176 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006177#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6178 if (try2optimize) {
6179 /* Maybe we can optimize this:
6180 * if pattern ends with unescaped *, we can avoid checking
6181 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6182 * it wont match truncated "raw_value_of_" strings too.
6183 */
6184 unsigned plen = strlen(pattern);
6185 /* Does it end with "*"? */
6186 if (plen != 0 && pattern[--plen] == '*') {
6187 /* "xxxx*" is not escaped */
6188 /* "xxx\*" is escaped */
6189 /* "xx\\*" is not escaped */
6190 /* "x\\\*" is escaped */
6191 int slashes = 0;
6192 while (plen != 0 && pattern[--plen] == '\\')
6193 slashes++;
6194 if (!(slashes & 1))
6195 break; /* ends with unescaped "*" */
6196 }
6197 try2optimize = 0;
6198 }
6199#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006200 loc--;
6201 if (quotes) {
6202 if (--esc < 0) {
6203 esc = esclen(startp, loc);
6204 }
6205 if (esc % 2) {
6206 esc--;
6207 loc--;
6208 }
6209 }
6210 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006211 return NULL;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006212}
6213
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006214static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006215static void
6216varunset(const char *end, const char *var, const char *umsg, int varflags)
6217{
6218 const char *msg;
6219 const char *tail;
6220
6221 tail = nullstr;
6222 msg = "parameter not set";
6223 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006224 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006225 if (varflags & VSNUL)
6226 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006227 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006228 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006229 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006230 }
Denys Vlasenko09dd6ec2010-08-07 02:44:33 +02006231 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006232}
6233
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006234#if ENABLE_ASH_BASH_COMPAT
6235static char *
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006236parse_sub_pattern(char *arg, int varflags)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006237{
6238 char *idx, *repl = NULL;
6239 unsigned char c;
6240
Denys Vlasenko16149002010-08-06 22:06:21 +02006241 //char *org_arg = arg;
Denys Vlasenko33bbb272010-08-07 22:24:36 +02006242 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
Denis Vlasenko2659c632008-06-14 06:04:59 +00006243 idx = arg;
6244 while (1) {
6245 c = *arg;
6246 if (!c)
6247 break;
6248 if (c == '/') {
6249 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006250 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006251 repl = idx + 1;
6252 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006253 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006254 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006255 *idx++ = c;
Denis Vlasenko2659c632008-06-14 06:04:59 +00006256 arg++;
Denys Vlasenko33bbb272010-08-07 22:24:36 +02006257 /*
6258 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6259 * The result is a_\_z_c (not a\_\_z_c)!
6260 *
6261 * Enable debug prints in this function and you'll see:
6262 * ash: arg:'\\b/_\\_z_' varflags:d
6263 * ash: pattern:'\\b' repl:'_\_z_'
6264 * That is, \\b is interpreted as \\b, but \\_ as \_!
6265 * IOW: search pattern and replace string treat backslashes
6266 * differently! That is the reason why we check repl below:
6267 */
6268 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6269 arg++; /* skip both '\', not just first one */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006271 *idx = c; /* NUL */
Denys Vlasenko16149002010-08-06 22:06:21 +02006272 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006273
6274 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006275}
6276#endif /* ENABLE_ASH_BASH_COMPAT */
6277
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006278static const char *
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006279subevalvar(char *p, char *varname, int strloc, int subtype,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006280 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006281{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006282 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006283 char *startp;
6284 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006285 char *rmesc, *rmescend;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006286 char *str;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006287 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006288 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006289 int saveherefd = herefd;
6290 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006291 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006292 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006293
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006294 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6295 // p, varname, strloc, subtype, startloc, varflags, quotes);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006296
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006297 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006298 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6299 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006300 STPUTC('\0', expdest);
6301 herefd = saveherefd;
6302 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006303 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006304
6305 switch (subtype) {
6306 case VSASSIGN:
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006307 setvar(varname, startp, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006308 amount = startp - expdest;
6309 STADJUST(amount, expdest);
6310 return startp;
6311
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006312 case VSQUESTION:
6313 varunset(p, varname, startp, varflags);
6314 /* NOTREACHED */
6315
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006316#if ENABLE_ASH_BASH_COMPAT
6317 case VSSUBSTR:
6318 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006319 /* Read POS in ${var:POS:LEN} */
6320 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006321 len = str - startp - 1;
6322
6323 /* *loc != '\0', guaranteed by parser */
6324 if (quotes) {
6325 char *ptr;
6326
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006327 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006328 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006329 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006330 len--;
6331 ptr++;
6332 }
6333 }
6334 }
6335 orig_len = len;
6336
6337 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006338 /* ${var::LEN} */
6339 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006340 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006341 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006342 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006343 while (*loc && *loc != ':') {
6344 /* TODO?
6345 * bash complains on: var=qwe; echo ${var:1a:123}
6346 if (!isdigit(*loc))
6347 ash_msg_and_raise_error(msg_illnum, str);
6348 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006349 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006350 }
6351 if (*loc++ == ':') {
6352 len = number(loc);
6353 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006354 }
6355 if (pos >= orig_len) {
6356 pos = 0;
6357 len = 0;
6358 }
6359 if (len > (orig_len - pos))
6360 len = orig_len - pos;
6361
6362 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006363 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006364 str++;
6365 }
6366 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006367 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006368 *loc++ = *str++;
6369 *loc++ = *str++;
6370 }
6371 *loc = '\0';
6372 amount = loc - expdest;
6373 STADJUST(amount, expdest);
6374 return loc;
6375#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006376 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006377
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006378 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006379
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006380 /* We'll comeback here if we grow the stack while handling
6381 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6382 * stack will need rebasing, and we'll need to remove our work
6383 * areas each time
6384 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006385 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006386
6387 amount = expdest - ((char *)stackblock() + resetloc);
6388 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006389 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006390
6391 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006392 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006394 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006395 if (rmesc != startp) {
6396 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006397 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006398 }
6399 }
6400 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006401 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006402 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006403 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006404
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006405#if ENABLE_ASH_BASH_COMPAT
6406 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006407 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006408
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006409 if (!repl) {
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006410 repl = parse_sub_pattern(str, varflags);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006411 //bb_error_msg("repl:'%s'", repl);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006412 if (!repl)
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006413 repl = nullstr;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006414 }
6415
6416 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006417 if (str[0] == '\0')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006418 return NULL;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006419
6420 len = 0;
6421 idx = startp;
6422 end = str - 1;
6423 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006424 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006425 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006426 //bb_error_msg("scanright('%s'):'%s'", str, loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006427 if (!loc) {
6428 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006429 char *restart_detect = stackblock();
6430 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006431 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006432 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006433 idx++;
6434 len++;
6435 STPUTC(*idx, expdest);
6436 }
6437 if (stackblock() != restart_detect)
6438 goto restart;
6439 idx++;
6440 len++;
6441 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006442 /* continue; - prone to quadratic behavior, smarter code: */
6443 if (idx >= end)
6444 break;
6445 if (str[0] == '*') {
6446 /* Pattern is "*foo". If "*foo" does not match "long_string",
6447 * it would never match "ong_string" etc, no point in trying.
6448 */
6449 goto skip_matching;
6450 }
6451 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006452 }
6453
6454 if (subtype == VSREPLACEALL) {
6455 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006456 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006457 idx++;
6458 idx++;
6459 rmesc++;
6460 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006461 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006462 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006463 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006464
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006465 //bb_error_msg("repl:'%s'", repl);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006466 for (loc = (char*)repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006467 char *restart_detect = stackblock();
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006468 if (quotes && *loc == '\\') {
6469 STPUTC(CTLESC, expdest);
6470 len++;
6471 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006472 STPUTC(*loc, expdest);
6473 if (stackblock() != restart_detect)
6474 goto restart;
6475 len++;
6476 }
6477
6478 if (subtype == VSREPLACE) {
Denys Vlasenkof02c82f2010-08-06 19:14:47 +02006479 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006480 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006481 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006482 STPUTC(*idx, expdest);
6483 if (stackblock() != restart_detect)
6484 goto restart;
6485 len++;
6486 idx++;
6487 }
6488 break;
6489 }
6490 }
6491
6492 /* We've put the replaced text into a buffer at workloc, now
6493 * move it to the right place and adjust the stack.
6494 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006495 STPUTC('\0', expdest);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006496 startp = (char *)stackblock() + startloc;
6497 memmove(startp, (char *)stackblock() + workloc, len + 1);
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006498 //bb_error_msg("startp:'%s'", startp);
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006499 amount = expdest - (startp + len);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006500 STADJUST(-amount, expdest);
6501 return startp;
6502 }
6503#endif /* ENABLE_ASH_BASH_COMPAT */
6504
6505 subtype -= VSTRIMRIGHT;
6506#if DEBUG
6507 if (subtype < 0 || subtype > 7)
6508 abort();
6509#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006510 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006511 zero = subtype >> 1;
6512 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6513 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6514
6515 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6516 if (loc) {
6517 if (zero) {
6518 memmove(startp, loc, str - loc);
6519 loc = startp + (str - loc) - 1;
6520 }
6521 *loc = '\0';
6522 amount = loc - expdest;
6523 STADJUST(amount, expdest);
6524 }
6525 return loc;
6526}
6527
6528/*
6529 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006530 * name parameter (examples):
6531 * ash -c 'echo $1' name:'1='
6532 * ash -c 'echo $qwe' name:'qwe='
6533 * ash -c 'echo $$' name:'$='
6534 * ash -c 'echo ${$}' name:'$='
6535 * ash -c 'echo ${$##q}' name:'$=q'
6536 * ash -c 'echo ${#$}' name:'$='
6537 * note: examples with bad shell syntax:
6538 * ash -c 'echo ${#$1}' name:'$=1'
6539 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006540 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006541static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006542varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006543{
Mike Frysinger98c52642009-04-02 10:02:37 +00006544 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006545 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006547 int sepq = 0;
6548 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006549 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006550 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006551 int quoted = varflags & VSQUOTE;
6552 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006553
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006554 switch (*name) {
6555 case '$':
6556 num = rootpid;
6557 goto numvar;
6558 case '?':
6559 num = exitstatus;
6560 goto numvar;
6561 case '#':
6562 num = shellparam.nparam;
6563 goto numvar;
6564 case '!':
6565 num = backgndpid;
6566 if (num == 0)
6567 return -1;
6568 numvar:
6569 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006570 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006572 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006573 for (i = NOPTS - 1; i >= 0; i--) {
6574 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006575 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006576 len++;
6577 }
6578 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006579 check_1char_name:
6580#if 0
6581 /* handles cases similar to ${#$1} */
6582 if (name[2] != '\0')
6583 raise_error_syntax("bad substitution");
6584#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006585 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006586 case '@': {
6587 char **ap;
6588 int sep;
6589
6590 if (quoted && (flags & EXP_FULL)) {
6591 /* note: this is not meant as PEOF value */
6592 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006593 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006594 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006595 /* fall through */
6596 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006597 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006598 i = SIT(sep, syntax);
6599 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006600 sepq = 1;
6601 param:
6602 ap = shellparam.p;
6603 if (!ap)
6604 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006605 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006606 size_t partlen;
6607
6608 partlen = strlen(p);
6609 len += partlen;
6610
6611 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6612 memtodest(p, partlen, syntax, quotes);
6613
6614 if (*ap && sep) {
6615 char *q;
6616
6617 len++;
6618 if (subtype == VSPLUS || subtype == VSLENGTH) {
6619 continue;
6620 }
6621 q = expdest;
6622 if (sepq)
6623 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006624 /* note: may put NUL despite sep != 0
6625 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006626 STPUTC(sep, q);
6627 expdest = q;
6628 }
6629 }
6630 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006631 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006632 case '0':
6633 case '1':
6634 case '2':
6635 case '3':
6636 case '4':
6637 case '5':
6638 case '6':
6639 case '7':
6640 case '8':
6641 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006642 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 if (num < 0 || num > shellparam.nparam)
6644 return -1;
6645 p = num ? shellparam.p[num - 1] : arg0;
6646 goto value;
6647 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006648 /* NB: name has form "VAR=..." */
6649
6650 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6651 * which should be considered before we check variables. */
6652 if (var_str_list) {
6653 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6654 p = NULL;
6655 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006656 char *str, *eq;
6657 str = var_str_list->text;
6658 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006659 if (!eq) /* stop at first non-assignment */
6660 break;
6661 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006662 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006663 && strncmp(str, name, name_len) == 0
6664 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006665 p = eq;
6666 /* goto value; - WRONG! */
6667 /* think "A=1 A=2 B=$A" */
6668 }
6669 var_str_list = var_str_list->next;
6670 } while (var_str_list);
6671 if (p)
6672 goto value;
6673 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006674 p = lookupvar(name);
6675 value:
6676 if (!p)
6677 return -1;
6678
6679 len = strlen(p);
6680 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6681 memtodest(p, len, syntax, quotes);
6682 return len;
6683 }
6684
6685 if (subtype == VSPLUS || subtype == VSLENGTH)
6686 STADJUST(-len, expdest);
6687 return len;
6688}
6689
6690/*
6691 * Expand a variable, and return a pointer to the next character in the
6692 * input string.
6693 */
6694static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006695evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006696{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006697 char varflags;
6698 char subtype;
6699 char quoted;
6700 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006701 char *var;
6702 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006703 int startloc;
6704 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006705
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006706 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006707 subtype = varflags & VSTYPE;
6708 quoted = varflags & VSQUOTE;
6709 var = p;
6710 easy = (!quoted || (*var == '@' && shellparam.nparam));
6711 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006712 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006713
6714 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006715 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006716 if (varflags & VSNUL)
6717 varlen--;
6718
6719 if (subtype == VSPLUS) {
6720 varlen = -1 - varlen;
6721 goto vsplus;
6722 }
6723
6724 if (subtype == VSMINUS) {
6725 vsplus:
6726 if (varlen < 0) {
6727 argstr(
Denys Vlasenko6040fe82010-09-12 15:03:16 +02006728 p,
6729 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006730 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006731 );
6732 goto end;
6733 }
6734 if (easy)
6735 goto record;
6736 goto end;
6737 }
6738
6739 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6740 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006741 if (subevalvar(p, var, /* strloc: */ 0,
6742 subtype, startloc, varflags,
6743 /* quotes: */ 0,
6744 var_str_list)
6745 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006746 varflags &= ~VSNUL;
6747 /*
6748 * Remove any recorded regions beyond
6749 * start of variable
6750 */
6751 removerecordregions(startloc);
6752 goto again;
6753 }
6754 goto end;
6755 }
6756 if (easy)
6757 goto record;
6758 goto end;
6759 }
6760
6761 if (varlen < 0 && uflag)
6762 varunset(p, var, 0, 0);
6763
6764 if (subtype == VSLENGTH) {
6765 cvtnum(varlen > 0 ? varlen : 0);
6766 goto record;
6767 }
6768
6769 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006770 if (easy)
6771 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006772 goto end;
6773 }
6774
6775#if DEBUG
6776 switch (subtype) {
6777 case VSTRIMLEFT:
6778 case VSTRIMLEFTMAX:
6779 case VSTRIMRIGHT:
6780 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006781#if ENABLE_ASH_BASH_COMPAT
6782 case VSSUBSTR:
6783 case VSREPLACE:
6784 case VSREPLACEALL:
6785#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006786 break;
6787 default:
6788 abort();
6789 }
6790#endif
6791
6792 if (varlen >= 0) {
6793 /*
6794 * Terminate the string and start recording the pattern
6795 * right after it
6796 */
6797 STPUTC('\0', expdest);
6798 patloc = expdest - (char *)stackblock();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +02006799 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006800 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006801//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006802 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006803 var_str_list)
6804 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006805 int amount = expdest - (
6806 (char *)stackblock() + patloc - 1
6807 );
6808 STADJUST(-amount, expdest);
6809 }
6810 /* Remove any recorded regions beyond start of variable */
6811 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006812 record:
6813 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006814 }
6815
6816 end:
6817 if (subtype != VSNORMAL) { /* skip to end of alternative */
6818 int nesting = 1;
6819 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006820 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006821 if (c == CTLESC)
6822 p++;
6823 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6824 if (varlen >= 0)
6825 argbackq = argbackq->next;
6826 } else if (c == CTLVAR) {
6827 if ((*p++ & VSTYPE) != VSNORMAL)
6828 nesting++;
6829 } else if (c == CTLENDVAR) {
6830 if (--nesting == 0)
6831 break;
6832 }
6833 }
6834 }
6835 return p;
6836}
6837
6838/*
6839 * Break the argument string into pieces based upon IFS and add the
6840 * strings to the argument list. The regions of the string to be
6841 * searched for IFS characters have been stored by recordregion.
6842 */
6843static void
6844ifsbreakup(char *string, struct arglist *arglist)
6845{
6846 struct ifsregion *ifsp;
6847 struct strlist *sp;
6848 char *start;
6849 char *p;
6850 char *q;
6851 const char *ifs, *realifs;
6852 int ifsspc;
6853 int nulonly;
6854
6855 start = string;
6856 if (ifslastp != NULL) {
6857 ifsspc = 0;
6858 nulonly = 0;
6859 realifs = ifsset() ? ifsval() : defifs;
6860 ifsp = &ifsfirst;
6861 do {
6862 p = string + ifsp->begoff;
6863 nulonly = ifsp->nulonly;
6864 ifs = nulonly ? nullstr : realifs;
6865 ifsspc = 0;
6866 while (p < string + ifsp->endoff) {
6867 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006868 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006869 p++;
6870 if (!strchr(ifs, *p)) {
6871 p++;
6872 continue;
6873 }
6874 if (!nulonly)
6875 ifsspc = (strchr(defifs, *p) != NULL);
6876 /* Ignore IFS whitespace at start */
6877 if (q == start && ifsspc) {
6878 p++;
6879 start = p;
6880 continue;
6881 }
6882 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006883 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006884 sp->text = start;
6885 *arglist->lastp = sp;
6886 arglist->lastp = &sp->next;
6887 p++;
6888 if (!nulonly) {
6889 for (;;) {
6890 if (p >= string + ifsp->endoff) {
6891 break;
6892 }
6893 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006894 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006895 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006896 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006897 p = q;
6898 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006899 }
6900 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901 if (ifsspc) {
6902 p++;
6903 ifsspc = 0;
6904 } else {
6905 p = q;
6906 break;
6907 }
6908 } else
6909 p++;
6910 }
6911 }
6912 start = p;
6913 } /* while */
6914 ifsp = ifsp->next;
6915 } while (ifsp != NULL);
6916 if (nulonly)
6917 goto add;
6918 }
6919
6920 if (!*start)
6921 return;
6922
6923 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006924 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006925 sp->text = start;
6926 *arglist->lastp = sp;
6927 arglist->lastp = &sp->next;
6928}
6929
6930static void
6931ifsfree(void)
6932{
6933 struct ifsregion *p;
6934
6935 INT_OFF;
6936 p = ifsfirst.next;
6937 do {
6938 struct ifsregion *ifsp;
6939 ifsp = p->next;
6940 free(p);
6941 p = ifsp;
6942 } while (p);
6943 ifslastp = NULL;
6944 ifsfirst.next = NULL;
6945 INT_ON;
6946}
6947
6948/*
6949 * Add a file name to the list.
6950 */
6951static void
6952addfname(const char *name)
6953{
6954 struct strlist *sp;
6955
Denis Vlasenko597906c2008-02-20 16:38:54 +00006956 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006957 sp->text = ststrdup(name);
6958 *exparg.lastp = sp;
6959 exparg.lastp = &sp->next;
6960}
6961
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006962/*
6963 * Do metacharacter (i.e. *, ?, [...]) expansion.
6964 */
6965static void
Denys Vlasenkofd33e172010-06-26 22:55:44 +02006966expmeta(char *expdir, char *enddir, char *name)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006967{
6968 char *p;
6969 const char *cp;
6970 char *start;
6971 char *endname;
6972 int metaflag;
6973 struct stat statb;
6974 DIR *dirp;
6975 struct dirent *dp;
6976 int atend;
6977 int matchdot;
6978
6979 metaflag = 0;
6980 start = name;
6981 for (p = name; *p; p++) {
6982 if (*p == '*' || *p == '?')
6983 metaflag = 1;
6984 else if (*p == '[') {
6985 char *q = p + 1;
6986 if (*q == '!')
6987 q++;
6988 for (;;) {
6989 if (*q == '\\')
6990 q++;
6991 if (*q == '/' || *q == '\0')
6992 break;
6993 if (*++q == ']') {
6994 metaflag = 1;
6995 break;
6996 }
6997 }
6998 } else if (*p == '\\')
6999 p++;
7000 else if (*p == '/') {
7001 if (metaflag)
7002 goto out;
7003 start = p + 1;
7004 }
7005 }
7006 out:
7007 if (metaflag == 0) { /* we've reached the end of the file name */
7008 if (enddir != expdir)
7009 metaflag++;
7010 p = name;
7011 do {
7012 if (*p == '\\')
7013 p++;
7014 *enddir++ = *p;
7015 } while (*p++);
7016 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7017 addfname(expdir);
7018 return;
7019 }
7020 endname = p;
7021 if (name < start) {
7022 p = name;
7023 do {
7024 if (*p == '\\')
7025 p++;
7026 *enddir++ = *p++;
7027 } while (p < start);
7028 }
7029 if (enddir == expdir) {
7030 cp = ".";
7031 } else if (enddir == expdir + 1 && *expdir == '/') {
7032 cp = "/";
7033 } else {
7034 cp = expdir;
7035 enddir[-1] = '\0';
7036 }
7037 dirp = opendir(cp);
7038 if (dirp == NULL)
7039 return;
7040 if (enddir != expdir)
7041 enddir[-1] = '/';
7042 if (*endname == 0) {
7043 atend = 1;
7044 } else {
7045 atend = 0;
7046 *endname++ = '\0';
7047 }
7048 matchdot = 0;
7049 p = start;
7050 if (*p == '\\')
7051 p++;
7052 if (*p == '.')
7053 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007054 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007055 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007056 continue;
7057 if (pmatch(start, dp->d_name)) {
7058 if (atend) {
7059 strcpy(enddir, dp->d_name);
7060 addfname(expdir);
7061 } else {
7062 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7063 continue;
7064 p[-1] = '/';
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007065 expmeta(expdir, p, endname);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007066 }
7067 }
7068 }
7069 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007070 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007071 endname[-1] = '/';
7072}
7073
7074static struct strlist *
7075msort(struct strlist *list, int len)
7076{
7077 struct strlist *p, *q = NULL;
7078 struct strlist **lpp;
7079 int half;
7080 int n;
7081
7082 if (len <= 1)
7083 return list;
7084 half = len >> 1;
7085 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007086 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007087 q = p;
7088 p = p->next;
7089 }
7090 q->next = NULL; /* terminate first half of list */
7091 q = msort(list, half); /* sort first half of list */
7092 p = msort(p, len - half); /* sort second half */
7093 lpp = &list;
7094 for (;;) {
7095#if ENABLE_LOCALE_SUPPORT
7096 if (strcoll(p->text, q->text) < 0)
7097#else
7098 if (strcmp(p->text, q->text) < 0)
7099#endif
7100 {
7101 *lpp = p;
7102 lpp = &p->next;
7103 p = *lpp;
7104 if (p == NULL) {
7105 *lpp = q;
7106 break;
7107 }
7108 } else {
7109 *lpp = q;
7110 lpp = &q->next;
7111 q = *lpp;
7112 if (q == NULL) {
7113 *lpp = p;
7114 break;
7115 }
7116 }
7117 }
7118 return list;
7119}
7120
7121/*
7122 * Sort the results of file name expansion. It calculates the number of
7123 * strings to sort and then calls msort (short for merge sort) to do the
7124 * work.
7125 */
7126static struct strlist *
7127expsort(struct strlist *str)
7128{
7129 int len;
7130 struct strlist *sp;
7131
7132 len = 0;
7133 for (sp = str; sp; sp = sp->next)
7134 len++;
7135 return msort(str, len);
7136}
7137
7138static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007139expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007140{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007141 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007142 '*', '?', '[', 0
7143 };
7144 /* TODO - EXP_REDIR */
7145
7146 while (str) {
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007147 char *expdir;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007148 struct strlist **savelastp;
7149 struct strlist *sp;
7150 char *p;
7151
7152 if (fflag)
7153 goto nometa;
7154 if (!strpbrk(str->text, metachars))
7155 goto nometa;
7156 savelastp = exparg.lastp;
7157
7158 INT_OFF;
7159 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7160 {
7161 int i = strlen(str->text);
7162 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7163 }
Denys Vlasenkofd33e172010-06-26 22:55:44 +02007164 expmeta(expdir, expdir, p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007165 free(expdir);
7166 if (p != str->text)
7167 free(p);
7168 INT_ON;
7169 if (exparg.lastp == savelastp) {
7170 /*
7171 * no matches
7172 */
7173 nometa:
7174 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007175 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007176 exparg.lastp = &str->next;
7177 } else {
7178 *exparg.lastp = NULL;
7179 *savelastp = sp = expsort(*savelastp);
7180 while (sp->next != NULL)
7181 sp = sp->next;
7182 exparg.lastp = &sp->next;
7183 }
7184 str = str->next;
7185 }
7186}
7187
7188/*
7189 * Perform variable substitution and command substitution on an argument,
7190 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7191 * perform splitting and file name expansion. When arglist is NULL, perform
7192 * here document expansion.
7193 */
7194static void
7195expandarg(union node *arg, struct arglist *arglist, int flag)
7196{
7197 struct strlist *sp;
7198 char *p;
7199
7200 argbackq = arg->narg.backquote;
7201 STARTSTACKSTR(expdest);
7202 ifsfirst.next = NULL;
7203 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007204 argstr(arg->narg.text, flag,
7205 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007206 p = _STPUTC('\0', expdest);
7207 expdest = p - 1;
7208 if (arglist == NULL) {
7209 return; /* here document expanded */
7210 }
7211 p = grabstackstr(p);
7212 exparg.lastp = &exparg.list;
7213 /*
7214 * TODO - EXP_REDIR
7215 */
7216 if (flag & EXP_FULL) {
7217 ifsbreakup(p, &exparg);
7218 *exparg.lastp = NULL;
7219 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007220 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007221 } else {
7222 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007223 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007224 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007225 sp->text = p;
7226 *exparg.lastp = sp;
7227 exparg.lastp = &sp->next;
7228 }
7229 if (ifsfirst.next)
7230 ifsfree();
7231 *exparg.lastp = NULL;
7232 if (exparg.list) {
7233 *arglist->lastp = exparg.list;
7234 arglist->lastp = exparg.lastp;
7235 }
7236}
7237
7238/*
7239 * Expand shell variables and backquotes inside a here document.
7240 */
7241static void
7242expandhere(union node *arg, int fd)
7243{
7244 herefd = fd;
7245 expandarg(arg, (struct arglist *)NULL, 0);
7246 full_write(fd, stackblock(), expdest - (char *)stackblock());
7247}
7248
7249/*
7250 * Returns true if the pattern matches the string.
7251 */
7252static int
7253patmatch(char *pattern, const char *string)
7254{
7255 return pmatch(preglob(pattern, 0, 0), string);
7256}
7257
7258/*
7259 * See if a pattern matches in a case statement.
7260 */
7261static int
7262casematch(union node *pattern, char *val)
7263{
7264 struct stackmark smark;
7265 int result;
7266
7267 setstackmark(&smark);
7268 argbackq = pattern->narg.backquote;
7269 STARTSTACKSTR(expdest);
7270 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007271 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7272 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007273 STACKSTRNUL(expdest);
7274 result = patmatch(stackblock(), val);
7275 popstackmark(&smark);
7276 return result;
7277}
7278
7279
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280/* ============ find_command */
7281
7282struct builtincmd {
7283 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007284 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007285 /* unsigned flags; */
7286};
7287#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007288/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007289 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007290#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007291#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007292
7293struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007294 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007295 union param {
7296 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007297 /* index >= 0 for commands without path (slashes) */
7298 /* (TODO: what exactly does the value mean? PATH position?) */
7299 /* index == -1 for commands with slashes */
7300 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007301 const struct builtincmd *cmd;
7302 struct funcnode *func;
7303 } u;
7304};
7305/* values of cmdtype */
7306#define CMDUNKNOWN -1 /* no entry in table for command */
7307#define CMDNORMAL 0 /* command is an executable program */
7308#define CMDFUNCTION 1 /* command is a shell function */
7309#define CMDBUILTIN 2 /* command is a shell builtin */
7310
7311/* action to find_command() */
7312#define DO_ERR 0x01 /* prints errors */
7313#define DO_ABS 0x02 /* checks absolute paths */
7314#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7315#define DO_ALTPATH 0x08 /* using alternate path */
7316#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7317
7318static void find_command(char *, struct cmdentry *, int, const char *);
7319
7320
7321/* ============ Hashing commands */
7322
7323/*
7324 * When commands are first encountered, they are entered in a hash table.
7325 * This ensures that a full path search will not have to be done for them
7326 * on each invocation.
7327 *
7328 * We should investigate converting to a linear search, even though that
7329 * would make the command name "hash" a misnomer.
7330 */
7331
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007332struct tblentry {
7333 struct tblentry *next; /* next entry in hash chain */
7334 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007335 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007336 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007337 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007338};
7339
Denis Vlasenko01631112007-12-16 17:20:38 +00007340static struct tblentry **cmdtable;
7341#define INIT_G_cmdtable() do { \
7342 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7343} while (0)
7344
7345static int builtinloc = -1; /* index in path of %builtin, or -1 */
7346
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007347
7348static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007349tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007350{
7351 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007352
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007353#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007354 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007355 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007356 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007357 while (*envp)
7358 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007359 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007360 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007361 /* re-exec ourselves with the new arguments */
7362 execve(bb_busybox_exec_path, argv, envp);
7363 /* If they called chroot or otherwise made the binary no longer
7364 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007365 }
7366#endif
7367
7368 repeat:
7369#ifdef SYSV
7370 do {
7371 execve(cmd, argv, envp);
7372 } while (errno == EINTR);
7373#else
7374 execve(cmd, argv, envp);
7375#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007376 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007377 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007378 return;
7379 }
7380 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007381 char **ap;
7382 char **new;
7383
7384 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007385 continue;
7386 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007387 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007388 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007389 ap += 2;
7390 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007391 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007392 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007393 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007394 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007395 goto repeat;
7396 }
7397}
7398
7399/*
7400 * Exec a program. Never returns. If you change this routine, you may
7401 * have to change the find_command routine as well.
7402 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007403static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007404static void
7405shellexec(char **argv, const char *path, int idx)
7406{
7407 char *cmdname;
7408 int e;
7409 char **envp;
7410 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007411#if ENABLE_FEATURE_SH_STANDALONE
7412 int applet_no = -1;
7413#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007414
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007415 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007416 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007417 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007418#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007419 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007420#endif
7421 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007422 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007423 e = errno;
7424 } else {
7425 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007426 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007427 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007428 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007429 if (errno != ENOENT && errno != ENOTDIR)
7430 e = errno;
7431 }
7432 stunalloc(cmdname);
7433 }
7434 }
7435
7436 /* Map to POSIX errors */
7437 switch (e) {
7438 case EACCES:
7439 exerrno = 126;
7440 break;
7441 case ENOENT:
7442 exerrno = 127;
7443 break;
7444 default:
7445 exerrno = 2;
7446 break;
7447 }
7448 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007449 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7450 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007451 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7452 /* NOTREACHED */
7453}
7454
7455static void
7456printentry(struct tblentry *cmdp)
7457{
7458 int idx;
7459 const char *path;
7460 char *name;
7461
7462 idx = cmdp->param.index;
7463 path = pathval();
7464 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007465 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007466 stunalloc(name);
7467 } while (--idx >= 0);
7468 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7469}
7470
7471/*
7472 * Clear out command entries. The argument specifies the first entry in
7473 * PATH which has changed.
7474 */
7475static void
7476clearcmdentry(int firstchange)
7477{
7478 struct tblentry **tblp;
7479 struct tblentry **pp;
7480 struct tblentry *cmdp;
7481
7482 INT_OFF;
7483 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7484 pp = tblp;
7485 while ((cmdp = *pp) != NULL) {
7486 if ((cmdp->cmdtype == CMDNORMAL &&
7487 cmdp->param.index >= firstchange)
7488 || (cmdp->cmdtype == CMDBUILTIN &&
7489 builtinloc >= firstchange)
7490 ) {
7491 *pp = cmdp->next;
7492 free(cmdp);
7493 } else {
7494 pp = &cmdp->next;
7495 }
7496 }
7497 }
7498 INT_ON;
7499}
7500
7501/*
7502 * Locate a command in the command hash table. If "add" is nonzero,
7503 * add the command to the table if it is not already present. The
7504 * variable "lastcmdentry" is set to point to the address of the link
7505 * pointing to the entry, so that delete_cmd_entry can delete the
7506 * entry.
7507 *
7508 * Interrupts must be off if called with add != 0.
7509 */
7510static struct tblentry **lastcmdentry;
7511
7512static struct tblentry *
7513cmdlookup(const char *name, int add)
7514{
7515 unsigned int hashval;
7516 const char *p;
7517 struct tblentry *cmdp;
7518 struct tblentry **pp;
7519
7520 p = name;
7521 hashval = (unsigned char)*p << 4;
7522 while (*p)
7523 hashval += (unsigned char)*p++;
7524 hashval &= 0x7FFF;
7525 pp = &cmdtable[hashval % CMDTABLESIZE];
7526 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7527 if (strcmp(cmdp->cmdname, name) == 0)
7528 break;
7529 pp = &cmdp->next;
7530 }
7531 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007532 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7533 + strlen(name)
7534 /* + 1 - already done because
7535 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007536 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007537 cmdp->cmdtype = CMDUNKNOWN;
7538 strcpy(cmdp->cmdname, name);
7539 }
7540 lastcmdentry = pp;
7541 return cmdp;
7542}
7543
7544/*
7545 * Delete the command entry returned on the last lookup.
7546 */
7547static void
7548delete_cmd_entry(void)
7549{
7550 struct tblentry *cmdp;
7551
7552 INT_OFF;
7553 cmdp = *lastcmdentry;
7554 *lastcmdentry = cmdp->next;
7555 if (cmdp->cmdtype == CMDFUNCTION)
7556 freefunc(cmdp->param.func);
7557 free(cmdp);
7558 INT_ON;
7559}
7560
7561/*
7562 * Add a new command entry, replacing any existing command entry for
7563 * the same name - except special builtins.
7564 */
7565static void
7566addcmdentry(char *name, struct cmdentry *entry)
7567{
7568 struct tblentry *cmdp;
7569
7570 cmdp = cmdlookup(name, 1);
7571 if (cmdp->cmdtype == CMDFUNCTION) {
7572 freefunc(cmdp->param.func);
7573 }
7574 cmdp->cmdtype = entry->cmdtype;
7575 cmdp->param = entry->u;
7576 cmdp->rehash = 0;
7577}
7578
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007579static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007580hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007581{
7582 struct tblentry **pp;
7583 struct tblentry *cmdp;
7584 int c;
7585 struct cmdentry entry;
7586 char *name;
7587
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007588 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007589 clearcmdentry(0);
7590 return 0;
7591 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007592
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007593 if (*argptr == NULL) {
7594 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7595 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7596 if (cmdp->cmdtype == CMDNORMAL)
7597 printentry(cmdp);
7598 }
7599 }
7600 return 0;
7601 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007602
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007603 c = 0;
7604 while ((name = *argptr) != NULL) {
7605 cmdp = cmdlookup(name, 0);
7606 if (cmdp != NULL
7607 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007608 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7609 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007610 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007611 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007612 find_command(name, &entry, DO_ERR, pathval());
7613 if (entry.cmdtype == CMDUNKNOWN)
7614 c = 1;
7615 argptr++;
7616 }
7617 return c;
7618}
7619
7620/*
7621 * Called when a cd is done. Marks all commands so the next time they
7622 * are executed they will be rehashed.
7623 */
7624static void
7625hashcd(void)
7626{
7627 struct tblentry **pp;
7628 struct tblentry *cmdp;
7629
7630 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7631 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007632 if (cmdp->cmdtype == CMDNORMAL
7633 || (cmdp->cmdtype == CMDBUILTIN
7634 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7635 && builtinloc > 0)
7636 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007637 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007638 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007639 }
7640 }
7641}
7642
7643/*
7644 * Fix command hash table when PATH changed.
7645 * Called before PATH is changed. The argument is the new value of PATH;
7646 * pathval() still returns the old value at this point.
7647 * Called with interrupts off.
7648 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007649static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007650changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007651{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007652 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007653 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007654 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 int idx_bltin;
7656
7657 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007658 firstchange = 9999; /* assume no change */
7659 idx = 0;
7660 idx_bltin = -1;
7661 for (;;) {
7662 if (*old != *new) {
7663 firstchange = idx;
7664 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007665 || (*old == ':' && *new == '\0')
7666 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007667 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007668 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007669 old = new; /* ignore subsequent differences */
7670 }
7671 if (*new == '\0')
7672 break;
7673 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7674 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007675 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007676 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007677 new++;
7678 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007679 }
7680 if (builtinloc < 0 && idx_bltin >= 0)
7681 builtinloc = idx_bltin; /* zap builtins */
7682 if (builtinloc >= 0 && idx_bltin < 0)
7683 firstchange = 0;
7684 clearcmdentry(firstchange);
7685 builtinloc = idx_bltin;
7686}
7687
7688#define TEOF 0
7689#define TNL 1
7690#define TREDIR 2
7691#define TWORD 3
7692#define TSEMI 4
7693#define TBACKGND 5
7694#define TAND 6
7695#define TOR 7
7696#define TPIPE 8
7697#define TLP 9
7698#define TRP 10
7699#define TENDCASE 11
7700#define TENDBQUOTE 12
7701#define TNOT 13
7702#define TCASE 14
7703#define TDO 15
7704#define TDONE 16
7705#define TELIF 17
7706#define TELSE 18
7707#define TESAC 19
7708#define TFI 20
7709#define TFOR 21
7710#define TIF 22
7711#define TIN 23
7712#define TTHEN 24
7713#define TUNTIL 25
7714#define TWHILE 26
7715#define TBEGIN 27
7716#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007717typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007718
7719/* first char is indicating which tokens mark the end of a list */
7720static const char *const tokname_array[] = {
7721 "\1end of file",
7722 "\0newline",
7723 "\0redirection",
7724 "\0word",
7725 "\0;",
7726 "\0&",
7727 "\0&&",
7728 "\0||",
7729 "\0|",
7730 "\0(",
7731 "\1)",
7732 "\1;;",
7733 "\1`",
7734#define KWDOFFSET 13
7735 /* the following are keywords */
7736 "\0!",
7737 "\0case",
7738 "\1do",
7739 "\1done",
7740 "\1elif",
7741 "\1else",
7742 "\1esac",
7743 "\1fi",
7744 "\0for",
7745 "\0if",
7746 "\0in",
7747 "\1then",
7748 "\0until",
7749 "\0while",
7750 "\0{",
7751 "\1}",
7752};
7753
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007754/* Wrapper around strcmp for qsort/bsearch/... */
7755static int
7756pstrcmp(const void *a, const void *b)
7757{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007758 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007759}
7760
7761static const char *const *
7762findkwd(const char *s)
7763{
7764 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007765 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7766 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007767}
7768
7769/*
7770 * Locate and print what a word is...
7771 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007772static int
7773describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007774{
7775 struct cmdentry entry;
7776 struct tblentry *cmdp;
7777#if ENABLE_ASH_ALIAS
7778 const struct alias *ap;
7779#endif
7780 const char *path = pathval();
7781
7782 if (describe_command_verbose) {
7783 out1str(command);
7784 }
7785
7786 /* First look at the keywords */
7787 if (findkwd(command)) {
7788 out1str(describe_command_verbose ? " is a shell keyword" : command);
7789 goto out;
7790 }
7791
7792#if ENABLE_ASH_ALIAS
7793 /* Then look at the aliases */
7794 ap = lookupalias(command, 0);
7795 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007796 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007797 out1str("alias ");
7798 printalias(ap);
7799 return 0;
7800 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007801 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007802 goto out;
7803 }
7804#endif
7805 /* Then check if it is a tracked alias */
7806 cmdp = cmdlookup(command, 0);
7807 if (cmdp != NULL) {
7808 entry.cmdtype = cmdp->cmdtype;
7809 entry.u = cmdp->param;
7810 } else {
7811 /* Finally use brute force */
7812 find_command(command, &entry, DO_ABS, path);
7813 }
7814
7815 switch (entry.cmdtype) {
7816 case CMDNORMAL: {
7817 int j = entry.u.index;
7818 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007819 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007820 p = command;
7821 } else {
7822 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007823 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007824 stunalloc(p);
7825 } while (--j >= 0);
7826 }
7827 if (describe_command_verbose) {
7828 out1fmt(" is%s %s",
7829 (cmdp ? " a tracked alias for" : nullstr), p
7830 );
7831 } else {
7832 out1str(p);
7833 }
7834 break;
7835 }
7836
7837 case CMDFUNCTION:
7838 if (describe_command_verbose) {
7839 out1str(" is a shell function");
7840 } else {
7841 out1str(command);
7842 }
7843 break;
7844
7845 case CMDBUILTIN:
7846 if (describe_command_verbose) {
7847 out1fmt(" is a %sshell builtin",
7848 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7849 "special " : nullstr
7850 );
7851 } else {
7852 out1str(command);
7853 }
7854 break;
7855
7856 default:
7857 if (describe_command_verbose) {
7858 out1str(": not found\n");
7859 }
7860 return 127;
7861 }
7862 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007863 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007864 return 0;
7865}
7866
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007867static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007868typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007869{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007870 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007871 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007872 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007873
Denis Vlasenko46846e22007-05-20 13:08:31 +00007874 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007875 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007876 i++;
7877 verbose = 0;
7878 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007879 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007880 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007881 }
7882 return err;
7883}
7884
7885#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007886static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007887commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007888{
7889 int c;
7890 enum {
7891 VERIFY_BRIEF = 1,
7892 VERIFY_VERBOSE = 2,
7893 } verify = 0;
7894
7895 while ((c = nextopt("pvV")) != '\0')
7896 if (c == 'V')
7897 verify |= VERIFY_VERBOSE;
7898 else if (c == 'v')
7899 verify |= VERIFY_BRIEF;
7900#if DEBUG
7901 else if (c != 'p')
7902 abort();
7903#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007904 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7905 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007906 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007907 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007908
7909 return 0;
7910}
7911#endif
7912
7913
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007914/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007915
Denis Vlasenko340299a2008-11-21 10:36:36 +00007916static int funcblocksize; /* size of structures in function */
7917static int funcstringsize; /* size of strings in node */
7918static void *funcblock; /* block to allocate function from */
7919static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007920
Eric Andersencb57d552001-06-28 07:25:16 +00007921/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007922#define EV_EXIT 01 /* exit after evaluating tree */
7923#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007924#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007925
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007926static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007927 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7928 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7929 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7930 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7931 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7932 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7933 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7934 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7935 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7936 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7937 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7938 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7939 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7940 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7941 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7942 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7943 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007944#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007945 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007946#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007947 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7948 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7949 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7950 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7951 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7952 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7953 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7954 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7955 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007956};
7957
7958static void calcsize(union node *n);
7959
7960static void
7961sizenodelist(struct nodelist *lp)
7962{
7963 while (lp) {
7964 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7965 calcsize(lp->n);
7966 lp = lp->next;
7967 }
7968}
7969
7970static void
7971calcsize(union node *n)
7972{
7973 if (n == NULL)
7974 return;
7975 funcblocksize += nodesize[n->type];
7976 switch (n->type) {
7977 case NCMD:
7978 calcsize(n->ncmd.redirect);
7979 calcsize(n->ncmd.args);
7980 calcsize(n->ncmd.assign);
7981 break;
7982 case NPIPE:
7983 sizenodelist(n->npipe.cmdlist);
7984 break;
7985 case NREDIR:
7986 case NBACKGND:
7987 case NSUBSHELL:
7988 calcsize(n->nredir.redirect);
7989 calcsize(n->nredir.n);
7990 break;
7991 case NAND:
7992 case NOR:
7993 case NSEMI:
7994 case NWHILE:
7995 case NUNTIL:
7996 calcsize(n->nbinary.ch2);
7997 calcsize(n->nbinary.ch1);
7998 break;
7999 case NIF:
8000 calcsize(n->nif.elsepart);
8001 calcsize(n->nif.ifpart);
8002 calcsize(n->nif.test);
8003 break;
8004 case NFOR:
8005 funcstringsize += strlen(n->nfor.var) + 1;
8006 calcsize(n->nfor.body);
8007 calcsize(n->nfor.args);
8008 break;
8009 case NCASE:
8010 calcsize(n->ncase.cases);
8011 calcsize(n->ncase.expr);
8012 break;
8013 case NCLIST:
8014 calcsize(n->nclist.body);
8015 calcsize(n->nclist.pattern);
8016 calcsize(n->nclist.next);
8017 break;
8018 case NDEFUN:
8019 case NARG:
8020 sizenodelist(n->narg.backquote);
8021 funcstringsize += strlen(n->narg.text) + 1;
8022 calcsize(n->narg.next);
8023 break;
8024 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008025#if ENABLE_ASH_BASH_COMPAT
8026 case NTO2:
8027#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008028 case NCLOBBER:
8029 case NFROM:
8030 case NFROMTO:
8031 case NAPPEND:
8032 calcsize(n->nfile.fname);
8033 calcsize(n->nfile.next);
8034 break;
8035 case NTOFD:
8036 case NFROMFD:
8037 calcsize(n->ndup.vname);
8038 calcsize(n->ndup.next);
8039 break;
8040 case NHERE:
8041 case NXHERE:
8042 calcsize(n->nhere.doc);
8043 calcsize(n->nhere.next);
8044 break;
8045 case NNOT:
8046 calcsize(n->nnot.com);
8047 break;
8048 };
8049}
8050
8051static char *
8052nodeckstrdup(char *s)
8053{
8054 char *rtn = funcstring;
8055
8056 strcpy(funcstring, s);
8057 funcstring += strlen(s) + 1;
8058 return rtn;
8059}
8060
8061static union node *copynode(union node *);
8062
8063static struct nodelist *
8064copynodelist(struct nodelist *lp)
8065{
8066 struct nodelist *start;
8067 struct nodelist **lpp;
8068
8069 lpp = &start;
8070 while (lp) {
8071 *lpp = funcblock;
8072 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8073 (*lpp)->n = copynode(lp->n);
8074 lp = lp->next;
8075 lpp = &(*lpp)->next;
8076 }
8077 *lpp = NULL;
8078 return start;
8079}
8080
8081static union node *
8082copynode(union node *n)
8083{
8084 union node *new;
8085
8086 if (n == NULL)
8087 return NULL;
8088 new = funcblock;
8089 funcblock = (char *) funcblock + nodesize[n->type];
8090
8091 switch (n->type) {
8092 case NCMD:
8093 new->ncmd.redirect = copynode(n->ncmd.redirect);
8094 new->ncmd.args = copynode(n->ncmd.args);
8095 new->ncmd.assign = copynode(n->ncmd.assign);
8096 break;
8097 case NPIPE:
8098 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008099 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008100 break;
8101 case NREDIR:
8102 case NBACKGND:
8103 case NSUBSHELL:
8104 new->nredir.redirect = copynode(n->nredir.redirect);
8105 new->nredir.n = copynode(n->nredir.n);
8106 break;
8107 case NAND:
8108 case NOR:
8109 case NSEMI:
8110 case NWHILE:
8111 case NUNTIL:
8112 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8113 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8114 break;
8115 case NIF:
8116 new->nif.elsepart = copynode(n->nif.elsepart);
8117 new->nif.ifpart = copynode(n->nif.ifpart);
8118 new->nif.test = copynode(n->nif.test);
8119 break;
8120 case NFOR:
8121 new->nfor.var = nodeckstrdup(n->nfor.var);
8122 new->nfor.body = copynode(n->nfor.body);
8123 new->nfor.args = copynode(n->nfor.args);
8124 break;
8125 case NCASE:
8126 new->ncase.cases = copynode(n->ncase.cases);
8127 new->ncase.expr = copynode(n->ncase.expr);
8128 break;
8129 case NCLIST:
8130 new->nclist.body = copynode(n->nclist.body);
8131 new->nclist.pattern = copynode(n->nclist.pattern);
8132 new->nclist.next = copynode(n->nclist.next);
8133 break;
8134 case NDEFUN:
8135 case NARG:
8136 new->narg.backquote = copynodelist(n->narg.backquote);
8137 new->narg.text = nodeckstrdup(n->narg.text);
8138 new->narg.next = copynode(n->narg.next);
8139 break;
8140 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008141#if ENABLE_ASH_BASH_COMPAT
8142 case NTO2:
8143#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008144 case NCLOBBER:
8145 case NFROM:
8146 case NFROMTO:
8147 case NAPPEND:
8148 new->nfile.fname = copynode(n->nfile.fname);
8149 new->nfile.fd = n->nfile.fd;
8150 new->nfile.next = copynode(n->nfile.next);
8151 break;
8152 case NTOFD:
8153 case NFROMFD:
8154 new->ndup.vname = copynode(n->ndup.vname);
8155 new->ndup.dupfd = n->ndup.dupfd;
8156 new->ndup.fd = n->ndup.fd;
8157 new->ndup.next = copynode(n->ndup.next);
8158 break;
8159 case NHERE:
8160 case NXHERE:
8161 new->nhere.doc = copynode(n->nhere.doc);
8162 new->nhere.fd = n->nhere.fd;
8163 new->nhere.next = copynode(n->nhere.next);
8164 break;
8165 case NNOT:
8166 new->nnot.com = copynode(n->nnot.com);
8167 break;
8168 };
8169 new->type = n->type;
8170 return new;
8171}
8172
8173/*
8174 * Make a copy of a parse tree.
8175 */
8176static struct funcnode *
8177copyfunc(union node *n)
8178{
8179 struct funcnode *f;
8180 size_t blocksize;
8181
8182 funcblocksize = offsetof(struct funcnode, n);
8183 funcstringsize = 0;
8184 calcsize(n);
8185 blocksize = funcblocksize;
8186 f = ckmalloc(blocksize + funcstringsize);
8187 funcblock = (char *) f + offsetof(struct funcnode, n);
8188 funcstring = (char *) f + blocksize;
8189 copynode(n);
8190 f->count = 0;
8191 return f;
8192}
8193
8194/*
8195 * Define a shell function.
8196 */
8197static void
8198defun(char *name, union node *func)
8199{
8200 struct cmdentry entry;
8201
8202 INT_OFF;
8203 entry.cmdtype = CMDFUNCTION;
8204 entry.u.func = copyfunc(func);
8205 addcmdentry(name, &entry);
8206 INT_ON;
8207}
8208
Denis Vlasenko4b875702009-03-19 13:30:04 +00008209/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008210#define SKIPBREAK (1 << 0)
8211#define SKIPCONT (1 << 1)
8212#define SKIPFUNC (1 << 2)
8213#define SKIPFILE (1 << 3)
8214#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008215static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008216static int skipcount; /* number of levels to skip */
8217static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008218static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008219
Denis Vlasenko4b875702009-03-19 13:30:04 +00008220/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008221static int evalstring(char *s, int mask);
8222
Denis Vlasenko4b875702009-03-19 13:30:04 +00008223/* Called to execute a trap.
8224 * Single callsite - at the end of evaltree().
8225 * If we return non-zero, exaltree raises EXEXIT exception.
8226 *
8227 * Perhaps we should avoid entering new trap handlers
8228 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008229 */
8230static int
8231dotrap(void)
8232{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008233 uint8_t *g;
8234 int sig;
8235 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008236
8237 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008238 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008239 xbarrier();
8240
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008241 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008242 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8243 int want_exexit;
8244 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008245
Denis Vlasenko4b875702009-03-19 13:30:04 +00008246 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008247 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008248 t = trap[sig];
8249 /* non-trapped SIGINT is handled separately by raise_interrupt,
8250 * don't upset it by resetting gotsig[SIGINT-1] */
8251 if (sig == SIGINT && !t)
8252 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008253
8254 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008255 *g = 0;
8256 if (!t)
8257 continue;
8258 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008259 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008260 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008261 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008262 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008263 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008264 }
8265
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008266 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008267 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008268}
8269
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008270/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008271static void evalloop(union node *, int);
8272static void evalfor(union node *, int);
8273static void evalcase(union node *, int);
8274static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008275static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008276static void evalpipe(union node *, int);
8277static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008278static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008279static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008280
Eric Andersen62483552001-07-10 06:09:16 +00008281/*
Eric Andersenc470f442003-07-28 09:56:35 +00008282 * Evaluate a parse tree. The value is left in the global variable
8283 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008284 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008285static void
Eric Andersenc470f442003-07-28 09:56:35 +00008286evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008287{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008288 struct jmploc *volatile savehandler = exception_handler;
8289 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008290 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008291 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008292 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008293 int int_level;
8294
8295 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008296
Eric Andersenc470f442003-07-28 09:56:35 +00008297 if (n == NULL) {
8298 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008299 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008300 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008301 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008302
8303 exception_handler = &jmploc;
8304 {
8305 int err = setjmp(jmploc.loc);
8306 if (err) {
8307 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008308 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008309 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8310 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008311 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008312 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008313 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008314 TRACE(("exception %d in evaltree, propagating err=%d\n",
8315 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008316 exception_handler = savehandler;
8317 longjmp(exception_handler->loc, err);
8318 }
8319 }
8320
Eric Andersenc470f442003-07-28 09:56:35 +00008321 switch (n->type) {
8322 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008323#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008324 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008325 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008326 break;
8327#endif
8328 case NNOT:
8329 evaltree(n->nnot.com, EV_TESTED);
8330 status = !exitstatus;
8331 goto setstatus;
8332 case NREDIR:
8333 expredir(n->nredir.redirect);
8334 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8335 if (!status) {
8336 evaltree(n->nredir.n, flags & EV_TESTED);
8337 status = exitstatus;
8338 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008339 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008340 goto setstatus;
8341 case NCMD:
8342 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008343 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008344 if (eflag && !(flags & EV_TESTED))
8345 checkexit = ~0;
8346 goto calleval;
8347 case NFOR:
8348 evalfn = evalfor;
8349 goto calleval;
8350 case NWHILE:
8351 case NUNTIL:
8352 evalfn = evalloop;
8353 goto calleval;
8354 case NSUBSHELL:
8355 case NBACKGND:
8356 evalfn = evalsubshell;
8357 goto calleval;
8358 case NPIPE:
8359 evalfn = evalpipe;
8360 goto checkexit;
8361 case NCASE:
8362 evalfn = evalcase;
8363 goto calleval;
8364 case NAND:
8365 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008366 case NSEMI: {
8367
Eric Andersenc470f442003-07-28 09:56:35 +00008368#if NAND + 1 != NOR
8369#error NAND + 1 != NOR
8370#endif
8371#if NOR + 1 != NSEMI
8372#error NOR + 1 != NSEMI
8373#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008374 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008375 evaltree(
8376 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008377 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008378 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008379 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008380 break;
8381 if (!evalskip) {
8382 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008383 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008384 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008385 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008386 evalfn(n, flags);
8387 break;
8388 }
8389 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008390 }
Eric Andersenc470f442003-07-28 09:56:35 +00008391 case NIF:
8392 evaltree(n->nif.test, EV_TESTED);
8393 if (evalskip)
8394 break;
8395 if (exitstatus == 0) {
8396 n = n->nif.ifpart;
8397 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008398 }
8399 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008400 n = n->nif.elsepart;
8401 goto evaln;
8402 }
8403 goto success;
8404 case NDEFUN:
8405 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008406 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008407 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008408 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008409 exitstatus = status;
8410 break;
8411 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008412
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008413 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008414 exception_handler = savehandler;
8415 out1:
8416 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008417 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008418 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008419 goto exexit;
8420
8421 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008422 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008423 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008424 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008425
8426 RESTORE_INT(int_level);
8427 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008428}
8429
Eric Andersenc470f442003-07-28 09:56:35 +00008430#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8431static
8432#endif
8433void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8434
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008435static void
Eric Andersenc470f442003-07-28 09:56:35 +00008436evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008437{
8438 int status;
8439
8440 loopnest++;
8441 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008442 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008443 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008444 int i;
8445
Eric Andersencb57d552001-06-28 07:25:16 +00008446 evaltree(n->nbinary.ch1, EV_TESTED);
8447 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008448 skipping:
8449 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008450 evalskip = 0;
8451 continue;
8452 }
8453 if (evalskip == SKIPBREAK && --skipcount <= 0)
8454 evalskip = 0;
8455 break;
8456 }
Eric Andersenc470f442003-07-28 09:56:35 +00008457 i = exitstatus;
8458 if (n->type != NWHILE)
8459 i = !i;
8460 if (i != 0)
8461 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008462 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008463 status = exitstatus;
8464 if (evalskip)
8465 goto skipping;
8466 }
8467 loopnest--;
8468 exitstatus = status;
8469}
8470
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008471static void
Eric Andersenc470f442003-07-28 09:56:35 +00008472evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008473{
8474 struct arglist arglist;
8475 union node *argp;
8476 struct strlist *sp;
8477 struct stackmark smark;
8478
8479 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008480 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008481 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008482 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008483 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008484 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008485 if (evalskip)
8486 goto out;
8487 }
8488 *arglist.lastp = NULL;
8489
8490 exitstatus = 0;
8491 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008492 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008493 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008494 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008495 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008496 if (evalskip) {
8497 if (evalskip == SKIPCONT && --skipcount <= 0) {
8498 evalskip = 0;
8499 continue;
8500 }
8501 if (evalskip == SKIPBREAK && --skipcount <= 0)
8502 evalskip = 0;
8503 break;
8504 }
8505 }
8506 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008507 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008508 popstackmark(&smark);
8509}
8510
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008511static void
Eric Andersenc470f442003-07-28 09:56:35 +00008512evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008513{
8514 union node *cp;
8515 union node *patp;
8516 struct arglist arglist;
8517 struct stackmark smark;
8518
8519 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008520 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008521 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008522 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008523 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008524 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8525 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008526 if (casematch(patp, arglist.list->text)) {
8527 if (evalskip == 0) {
8528 evaltree(cp->nclist.body, flags);
8529 }
8530 goto out;
8531 }
8532 }
8533 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008534 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008535 popstackmark(&smark);
8536}
8537
Eric Andersenc470f442003-07-28 09:56:35 +00008538/*
8539 * Kick off a subshell to evaluate a tree.
8540 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008541static void
Eric Andersenc470f442003-07-28 09:56:35 +00008542evalsubshell(union node *n, int flags)
8543{
8544 struct job *jp;
8545 int backgnd = (n->type == NBACKGND);
8546 int status;
8547
8548 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008549 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008550 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008551 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008552 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008553 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008554 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008555 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008556 flags |= EV_EXIT;
8557 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008558 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008559 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008560 redirect(n->nredir.redirect, 0);
8561 evaltreenr(n->nredir.n, flags);
8562 /* never returns */
8563 }
8564 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008565 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008566 status = waitforjob(jp);
8567 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008568 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008569}
8570
Eric Andersenc470f442003-07-28 09:56:35 +00008571/*
8572 * Compute the names of the files in a redirection list.
8573 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008574static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008575static void
8576expredir(union node *n)
8577{
8578 union node *redir;
8579
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008580 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008581 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008582
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008583 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008584 fn.lastp = &fn.list;
8585 switch (redir->type) {
8586 case NFROMTO:
8587 case NFROM:
8588 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008589#if ENABLE_ASH_BASH_COMPAT
8590 case NTO2:
8591#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008592 case NCLOBBER:
8593 case NAPPEND:
8594 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008595#if ENABLE_ASH_BASH_COMPAT
8596 store_expfname:
8597#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008598 redir->nfile.expfname = fn.list->text;
8599 break;
8600 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008601 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008602 if (redir->ndup.vname) {
8603 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008604 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008605 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008606#if ENABLE_ASH_BASH_COMPAT
8607//FIXME: we used expandarg with different args!
8608 if (!isdigit_str9(fn.list->text)) {
8609 /* >&file, not >&fd */
8610 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8611 ash_msg_and_raise_error("redir error");
8612 redir->type = NTO2;
8613 goto store_expfname;
8614 }
8615#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008616 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008617 }
8618 break;
8619 }
8620 }
8621}
8622
Eric Andersencb57d552001-06-28 07:25:16 +00008623/*
Eric Andersencb57d552001-06-28 07:25:16 +00008624 * Evaluate a pipeline. All the processes in the pipeline are children
8625 * of the process creating the pipeline. (This differs from some versions
8626 * of the shell, which make the last process in a pipeline the parent
8627 * of all the rest.)
8628 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008629static void
Eric Andersenc470f442003-07-28 09:56:35 +00008630evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008631{
8632 struct job *jp;
8633 struct nodelist *lp;
8634 int pipelen;
8635 int prevfd;
8636 int pip[2];
8637
Eric Andersenc470f442003-07-28 09:56:35 +00008638 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008639 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008640 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008641 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008642 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008643 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008644 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008645 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008646 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008647 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008648 pip[1] = -1;
8649 if (lp->next) {
8650 if (pipe(pip) < 0) {
8651 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008652 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008653 }
8654 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008655 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008656 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008657 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008658 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008659 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008660 if (prevfd > 0) {
8661 dup2(prevfd, 0);
8662 close(prevfd);
8663 }
8664 if (pip[1] > 1) {
8665 dup2(pip[1], 1);
8666 close(pip[1]);
8667 }
Eric Andersenc470f442003-07-28 09:56:35 +00008668 evaltreenr(lp->n, flags);
8669 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008670 }
8671 if (prevfd >= 0)
8672 close(prevfd);
8673 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008674 /* Don't want to trigger debugging */
8675 if (pip[1] != -1)
8676 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008677 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008678 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008679 exitstatus = waitforjob(jp);
8680 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008681 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008682 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008683}
8684
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008685/*
8686 * Controls whether the shell is interactive or not.
8687 */
8688static void
8689setinteractive(int on)
8690{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008691 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008692
8693 if (++on == is_interactive)
8694 return;
8695 is_interactive = on;
8696 setsignal(SIGINT);
8697 setsignal(SIGQUIT);
8698 setsignal(SIGTERM);
8699#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8700 if (is_interactive > 1) {
8701 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008702 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008703
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008704 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008705 /* note: ash and hush share this string */
8706 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008707 "Enter 'help' for a list of built-in commands."
8708 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008709 bb_banner,
8710 "built-in shell (ash)"
8711 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008712 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008713 }
8714 }
8715#endif
8716}
8717
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008718static void
8719optschanged(void)
8720{
8721#if DEBUG
8722 opentrace();
8723#endif
8724 setinteractive(iflag);
8725 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008726#if ENABLE_FEATURE_EDITING_VI
8727 if (viflag)
8728 line_input_state->flags |= VI_MODE;
8729 else
8730 line_input_state->flags &= ~VI_MODE;
8731#else
8732 viflag = 0; /* forcibly keep the option off */
8733#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008734}
8735
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008736static struct localvar *localvars;
8737
8738/*
8739 * Called after a function returns.
8740 * Interrupts must be off.
8741 */
8742static void
8743poplocalvars(void)
8744{
8745 struct localvar *lvp;
8746 struct var *vp;
8747
8748 while ((lvp = localvars) != NULL) {
8749 localvars = lvp->next;
8750 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008751 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008752 if (vp == NULL) { /* $- saved */
8753 memcpy(optlist, lvp->text, sizeof(optlist));
8754 free((char*)lvp->text);
8755 optschanged();
8756 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008757 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008758 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008759 if (vp->var_func)
8760 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008761 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008762 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008763 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008764 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008765 }
8766 free(lvp);
8767 }
8768}
8769
8770static int
8771evalfun(struct funcnode *func, int argc, char **argv, int flags)
8772{
8773 volatile struct shparam saveparam;
8774 struct localvar *volatile savelocalvars;
8775 struct jmploc *volatile savehandler;
8776 struct jmploc jmploc;
8777 int e;
8778
8779 saveparam = shellparam;
8780 savelocalvars = localvars;
8781 e = setjmp(jmploc.loc);
8782 if (e) {
8783 goto funcdone;
8784 }
8785 INT_OFF;
8786 savehandler = exception_handler;
8787 exception_handler = &jmploc;
8788 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008789 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008790 func->count++;
8791 funcnest++;
8792 INT_ON;
8793 shellparam.nparam = argc - 1;
8794 shellparam.p = argv + 1;
8795#if ENABLE_ASH_GETOPTS
8796 shellparam.optind = 1;
8797 shellparam.optoff = -1;
8798#endif
8799 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008800 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008801 INT_OFF;
8802 funcnest--;
8803 freefunc(func);
8804 poplocalvars();
8805 localvars = savelocalvars;
8806 freeparam(&shellparam);
8807 shellparam = saveparam;
8808 exception_handler = savehandler;
8809 INT_ON;
8810 evalskip &= ~SKIPFUNC;
8811 return e;
8812}
8813
Denis Vlasenko131ae172007-02-18 13:00:19 +00008814#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008815static char **
8816parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008817{
8818 char *cp, c;
8819
8820 for (;;) {
8821 cp = *++argv;
8822 if (!cp)
8823 return 0;
8824 if (*cp++ != '-')
8825 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008826 c = *cp++;
8827 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008828 break;
8829 if (c == '-' && !*cp) {
8830 argv++;
8831 break;
8832 }
8833 do {
8834 switch (c) {
8835 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008836 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008837 break;
8838 default:
8839 /* run 'typecmd' for other options */
8840 return 0;
8841 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008842 c = *cp++;
8843 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008844 }
8845 return argv;
8846}
8847#endif
8848
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008849/*
8850 * Make a variable a local variable. When a variable is made local, it's
8851 * value and flags are saved in a localvar structure. The saved values
8852 * will be restored when the shell function returns. We handle the name
8853 * "-" as a special case.
8854 */
8855static void
8856mklocal(char *name)
8857{
8858 struct localvar *lvp;
8859 struct var **vpp;
8860 struct var *vp;
8861
8862 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008863 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008864 if (LONE_DASH(name)) {
8865 char *p;
8866 p = ckmalloc(sizeof(optlist));
8867 lvp->text = memcpy(p, optlist, sizeof(optlist));
8868 vp = NULL;
8869 } else {
8870 char *eq;
8871
8872 vpp = hashvar(name);
8873 vp = *findvar(vpp, name);
8874 eq = strchr(name, '=');
8875 if (vp == NULL) {
8876 if (eq)
8877 setvareq(name, VSTRFIXED);
8878 else
8879 setvar(name, NULL, VSTRFIXED);
8880 vp = *vpp; /* the new variable */
8881 lvp->flags = VUNSET;
8882 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008883 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008884 lvp->flags = vp->flags;
8885 vp->flags |= VSTRFIXED|VTEXTFIXED;
8886 if (eq)
8887 setvareq(name, 0);
8888 }
8889 }
8890 lvp->vp = vp;
8891 lvp->next = localvars;
8892 localvars = lvp;
8893 INT_ON;
8894}
8895
8896/*
8897 * The "local" command.
8898 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008899static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008900localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008901{
8902 char *name;
8903
8904 argv = argptr;
8905 while ((name = *argv++) != NULL) {
8906 mklocal(name);
8907 }
8908 return 0;
8909}
8910
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008911static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008912falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008913{
8914 return 1;
8915}
8916
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008917static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008918truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008919{
8920 return 0;
8921}
8922
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008923static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008924execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008925{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008926 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008927 iflag = 0; /* exit on error */
8928 mflag = 0;
8929 optschanged();
8930 shellexec(argv + 1, pathval(), 0);
8931 }
8932 return 0;
8933}
8934
8935/*
8936 * The return command.
8937 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008938static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008939returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008940{
8941 /*
8942 * If called outside a function, do what ksh does;
8943 * skip the rest of the file.
8944 */
8945 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8946 return argv[1] ? number(argv[1]) : exitstatus;
8947}
8948
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008949/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008950static int breakcmd(int, char **) FAST_FUNC;
8951static int dotcmd(int, char **) FAST_FUNC;
8952static int evalcmd(int, char **) FAST_FUNC;
8953static int exitcmd(int, char **) FAST_FUNC;
8954static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008955#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008956static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008957#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008958#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008959static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008960#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008961#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008962static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008963#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008964static int readcmd(int, char **) FAST_FUNC;
8965static int setcmd(int, char **) FAST_FUNC;
8966static int shiftcmd(int, char **) FAST_FUNC;
8967static int timescmd(int, char **) FAST_FUNC;
8968static int trapcmd(int, char **) FAST_FUNC;
8969static int umaskcmd(int, char **) FAST_FUNC;
8970static int unsetcmd(int, char **) FAST_FUNC;
8971static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008972
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008973#define BUILTIN_NOSPEC "0"
8974#define BUILTIN_SPECIAL "1"
8975#define BUILTIN_REGULAR "2"
8976#define BUILTIN_SPEC_REG "3"
8977#define BUILTIN_ASSIGN "4"
8978#define BUILTIN_SPEC_ASSG "5"
8979#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008980#define BUILTIN_SPEC_REG_ASSG "7"
8981
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008982/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008983#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008984static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008985#endif
8986#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008987static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008988#endif
8989#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008990static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008991#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008992
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008993/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008994static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008995 { BUILTIN_SPEC_REG "." , dotcmd },
8996 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008997#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008998 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008999#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009000 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009001#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00009002#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009003#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009004 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009005#endif
9006#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009007 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009008#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009009 { BUILTIN_SPEC_REG "break" , breakcmd },
9010 { BUILTIN_REGULAR "cd" , cdcmd },
9011 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009012#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009013 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009014#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009015 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009016#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009017 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009018#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009019 { BUILTIN_SPEC_REG "eval" , evalcmd },
9020 { BUILTIN_SPEC_REG "exec" , execcmd },
9021 { BUILTIN_SPEC_REG "exit" , exitcmd },
9022 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9023 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009024#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009025 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009026#endif
9027#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009028 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009029#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009030 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009031#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009032 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009033#endif
9034#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009035 { BUILTIN_REGULAR "jobs" , jobscmd },
9036 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009037#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00009038#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009039 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009040#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009041 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009042#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009043 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00009044#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009045 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9046 { BUILTIN_REGULAR "read" , readcmd },
9047 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9048 { BUILTIN_SPEC_REG "return" , returncmd },
9049 { BUILTIN_SPEC_REG "set" , setcmd },
9050 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009051#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009052 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02009053#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009054#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009055 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009056#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009057 { BUILTIN_SPEC_REG "times" , timescmd },
9058 { BUILTIN_SPEC_REG "trap" , trapcmd },
9059 { BUILTIN_REGULAR "true" , truecmd },
9060 { BUILTIN_NOSPEC "type" , typecmd },
9061 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9062 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009063#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009064 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009065#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01009066 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9067 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009068};
9069
Denis Vlasenko80591b02008-03-25 07:49:43 +00009070/* Should match the above table! */
9071#define COMMANDCMD (builtintab + \
9072 2 + \
9073 1 * ENABLE_ASH_BUILTIN_TEST + \
9074 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9075 1 * ENABLE_ASH_ALIAS + \
9076 1 * ENABLE_ASH_JOB_CONTROL + \
9077 3)
9078#define EXECCMD (builtintab + \
9079 2 + \
9080 1 * ENABLE_ASH_BUILTIN_TEST + \
9081 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9082 1 * ENABLE_ASH_ALIAS + \
9083 1 * ENABLE_ASH_JOB_CONTROL + \
9084 3 + \
9085 1 * ENABLE_ASH_CMDCMD + \
9086 1 + \
9087 ENABLE_ASH_BUILTIN_ECHO + \
9088 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009089
9090/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009091 * Search the table of builtin commands.
9092 */
9093static struct builtincmd *
9094find_builtin(const char *name)
9095{
9096 struct builtincmd *bp;
9097
9098 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00009099 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00009100 pstrcmp
9101 );
9102 return bp;
9103}
9104
9105/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009106 * Execute a simple command.
9107 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009108static int
9109isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009110{
9111 const char *q = endofname(p);
9112 if (p == q)
9113 return 0;
9114 return *q == '=';
9115}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009116static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009117bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009118{
9119 /* Preserve exitstatus of a previous possible redirection
9120 * as POSIX mandates */
9121 return back_exitstatus;
9122}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009123static void
Eric Andersenc470f442003-07-28 09:56:35 +00009124evalcommand(union node *cmd, int flags)
9125{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009126 static const struct builtincmd null_bltin = {
9127 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009128 };
Eric Andersenc470f442003-07-28 09:56:35 +00009129 struct stackmark smark;
9130 union node *argp;
9131 struct arglist arglist;
9132 struct arglist varlist;
9133 char **argv;
9134 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009135 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009136 struct cmdentry cmdentry;
9137 struct job *jp;
9138 char *lastarg;
9139 const char *path;
9140 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009141 int status;
9142 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009143 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009144 smallint cmd_is_exec;
9145 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009146
9147 /* First expand the arguments. */
9148 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9149 setstackmark(&smark);
9150 back_exitstatus = 0;
9151
9152 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009153 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009154 varlist.lastp = &varlist.list;
9155 *varlist.lastp = NULL;
9156 arglist.lastp = &arglist.list;
9157 *arglist.lastp = NULL;
9158
9159 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009160 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009161 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9162 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9163 }
9164
Eric Andersenc470f442003-07-28 09:56:35 +00009165 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9166 struct strlist **spp;
9167
9168 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009169 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009170 expandarg(argp, &arglist, EXP_VARTILDE);
9171 else
9172 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9173
Eric Andersenc470f442003-07-28 09:56:35 +00009174 for (sp = *spp; sp; sp = sp->next)
9175 argc++;
9176 }
9177
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009178 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009179 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009180 TRACE(("evalcommand arg: %s\n", sp->text));
9181 *nargv++ = sp->text;
9182 }
9183 *nargv = NULL;
9184
9185 lastarg = NULL;
9186 if (iflag && funcnest == 0 && argc > 0)
9187 lastarg = nargv[-1];
9188
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009189 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009190 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009191 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009192
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009193 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009194 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9195 struct strlist **spp;
9196 char *p;
9197
9198 spp = varlist.lastp;
9199 expandarg(argp, &varlist, EXP_VARTILDE);
9200
9201 /*
9202 * Modify the command lookup path, if a PATH= assignment
9203 * is present
9204 */
9205 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009206 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009207 path = p;
9208 }
9209
9210 /* Print the command if xflag is set. */
9211 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009212 int n;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009213 const char *p = " %s" + 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009214
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009215 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009216 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009217 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009218 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009219 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009220 sp = sp->next;
Denys Vlasenkofd33e172010-06-26 22:55:44 +02009221 p = " %s";
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009222 }
9223 sp = arglist.list;
9224 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009225 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009226 }
9227
9228 cmd_is_exec = 0;
9229 spclbltin = -1;
9230
9231 /* Now locate the command. */
9232 if (argc) {
9233 const char *oldpath;
9234 int cmd_flag = DO_ERR;
9235
9236 path += 5;
9237 oldpath = path;
9238 for (;;) {
9239 find_command(argv[0], &cmdentry, cmd_flag, path);
9240 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009241 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009242 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009243 goto bail;
9244 }
9245
9246 /* implement bltin and command here */
9247 if (cmdentry.cmdtype != CMDBUILTIN)
9248 break;
9249 if (spclbltin < 0)
9250 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9251 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009252 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009253#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009254 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009255 path = oldpath;
9256 nargv = parse_command_args(argv, &path);
9257 if (!nargv)
9258 break;
9259 argc -= nargv - argv;
9260 argv = nargv;
9261 cmd_flag |= DO_NOFUNC;
9262 } else
9263#endif
9264 break;
9265 }
9266 }
9267
9268 if (status) {
9269 /* We have a redirection error. */
9270 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009271 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009272 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009273 exitstatus = status;
9274 goto out;
9275 }
9276
9277 /* Execute the command. */
9278 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009279 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009280
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009281#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009282/* (1) BUG: if variables are set, we need to fork, or save/restore them
9283 * around run_nofork_applet() call.
9284 * (2) Should this check also be done in forkshell()?
9285 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9286 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009287 /* find_command() encodes applet_no as (-2 - applet_no) */
9288 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009289 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009290 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009291 /* run <applet>_main() */
9292 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009293 break;
9294 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009295#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009296 /* Can we avoid forking off? For example, very last command
9297 * in a script or a subshell does not need forking,
9298 * we can just exec it.
9299 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009300 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009301 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009302 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009303 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009304 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009305 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009306 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009307 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009308 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009309 break;
9310 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009311 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009312 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009313 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009314 }
9315 listsetvar(varlist.list, VEXPORT|VSTACK);
9316 shellexec(argv, path, cmdentry.u.index);
9317 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009318 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009319 case CMDBUILTIN:
9320 cmdenviron = varlist.list;
9321 if (cmdenviron) {
9322 struct strlist *list = cmdenviron;
9323 int i = VNOSET;
9324 if (spclbltin > 0 || argc == 0) {
9325 i = 0;
9326 if (cmd_is_exec && argc > 1)
9327 i = VEXPORT;
9328 }
9329 listsetvar(list, i);
9330 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009331 /* Tight loop with builtins only:
9332 * "while kill -0 $child; do true; done"
9333 * will never exit even if $child died, unless we do this
9334 * to reap the zombie and make kill detect that it's gone: */
9335 dowait(DOWAIT_NONBLOCK, NULL);
9336
Eric Andersenc470f442003-07-28 09:56:35 +00009337 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9338 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009339 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009340 if (i == EXEXIT)
9341 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009342 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009343 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009344 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009345 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009346 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009347 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009348 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009349 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009350 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009351 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009352 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009353 }
9354 break;
9355
9356 case CMDFUNCTION:
9357 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009358 /* See above for the rationale */
9359 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009360 if (evalfun(cmdentry.u.func, argc, argv, flags))
9361 goto raise;
9362 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009363
9364 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009365
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009366 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009367 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009368 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009369 /* dsl: I think this is intended to be used to support
9370 * '_' in 'vi' command mode during line editing...
9371 * However I implemented that within libedit itself.
9372 */
9373 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009374 }
Eric Andersenc470f442003-07-28 09:56:35 +00009375 popstackmark(&smark);
9376}
9377
9378static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009379evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9380{
Eric Andersenc470f442003-07-28 09:56:35 +00009381 char *volatile savecmdname;
9382 struct jmploc *volatile savehandler;
9383 struct jmploc jmploc;
9384 int i;
9385
9386 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009387 i = setjmp(jmploc.loc);
9388 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009389 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009390 savehandler = exception_handler;
9391 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009392 commandname = argv[0];
9393 argptr = argv + 1;
9394 optptr = NULL; /* initialize nextopt */
9395 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009396 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009397 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009398 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009399 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009400 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009401 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009402
9403 return i;
9404}
9405
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009406static int
9407goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009408{
Denys Vlasenko8b2f13d2010-09-07 12:19:33 +02009409 return endofname(p)[0] == '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009410}
9411
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009412
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009413/*
9414 * Search for a command. This is called before we fork so that the
9415 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009416 * the child. The check for "goodname" is an overly conservative
9417 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009418 */
Eric Andersenc470f442003-07-28 09:56:35 +00009419static void
9420prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009421{
9422 struct cmdentry entry;
9423
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009424 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9425 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009426}
9427
Eric Andersencb57d552001-06-28 07:25:16 +00009428
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009429/* ============ Builtin commands
9430 *
9431 * Builtin commands whose functions are closely tied to evaluation
9432 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009433 */
9434
9435/*
Eric Andersencb57d552001-06-28 07:25:16 +00009436 * Handle break and continue commands. Break, continue, and return are
9437 * all handled by setting the evalskip flag. The evaluation routines
9438 * above all check this flag, and if it is set they start skipping
9439 * commands rather than executing them. The variable skipcount is
9440 * the number of loops to break/continue, or the number of function
9441 * levels to return. (The latter is always 1.) It should probably
9442 * be an error to break out of more loops than exist, but it isn't
9443 * in the standard shell so we don't make it one here.
9444 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009445static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009446breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009447{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009448 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009449
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009450 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009451 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009452 if (n > loopnest)
9453 n = loopnest;
9454 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009455 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009456 skipcount = n;
9457 }
9458 return 0;
9459}
9460
Eric Andersenc470f442003-07-28 09:56:35 +00009461
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009462/* ============ input.c
9463 *
Eric Andersen90898442003-08-06 11:20:52 +00009464 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009465 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009466
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009467enum {
9468 INPUT_PUSH_FILE = 1,
9469 INPUT_NOFILE_OK = 2,
9470};
Eric Andersencb57d552001-06-28 07:25:16 +00009471
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009472static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009473/* values of checkkwd variable */
9474#define CHKALIAS 0x1
9475#define CHKKWD 0x2
9476#define CHKNL 0x4
9477
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009478/*
9479 * Push a string back onto the input at this current parsefile level.
9480 * We handle aliases this way.
9481 */
9482#if !ENABLE_ASH_ALIAS
9483#define pushstring(s, ap) pushstring(s)
9484#endif
9485static void
9486pushstring(char *s, struct alias *ap)
9487{
9488 struct strpush *sp;
9489 int len;
9490
9491 len = strlen(s);
9492 INT_OFF;
9493 if (g_parsefile->strpush) {
9494 sp = ckzalloc(sizeof(*sp));
9495 sp->prev = g_parsefile->strpush;
9496 } else {
9497 sp = &(g_parsefile->basestrpush);
9498 }
9499 g_parsefile->strpush = sp;
9500 sp->prev_string = g_parsefile->next_to_pgetc;
9501 sp->prev_left_in_line = g_parsefile->left_in_line;
9502#if ENABLE_ASH_ALIAS
9503 sp->ap = ap;
9504 if (ap) {
9505 ap->flag |= ALIASINUSE;
9506 sp->string = s;
9507 }
9508#endif
9509 g_parsefile->next_to_pgetc = s;
9510 g_parsefile->left_in_line = len;
9511 INT_ON;
9512}
9513
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009514static void
9515popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009516{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009517 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009518
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009519 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009520#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009521 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009522 if (g_parsefile->next_to_pgetc[-1] == ' '
9523 || g_parsefile->next_to_pgetc[-1] == '\t'
9524 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009525 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009526 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009527 if (sp->string != sp->ap->val) {
9528 free(sp->string);
9529 }
9530 sp->ap->flag &= ~ALIASINUSE;
9531 if (sp->ap->flag & ALIASDEAD) {
9532 unalias(sp->ap->name);
9533 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009534 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009535#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009536 g_parsefile->next_to_pgetc = sp->prev_string;
9537 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009538 g_parsefile->strpush = sp->prev;
9539 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009540 free(sp);
9541 INT_ON;
9542}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009543
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009544//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9545//it peeks whether it is &>, and then pushes back both chars.
9546//This function needs to save last *next_to_pgetc to buf[0]
9547//to make two pungetc() reliable. Currently,
9548// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009549static int
9550preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009551{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009552 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009553 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009554
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009556#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009557 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009558 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9559 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009560 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009561#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009562 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009563#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009564 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009565 if (nr == 0) {
9566 /* Ctrl+C pressed */
9567 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009568 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009569 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009570 raise(SIGINT);
9571 return 1;
9572 }
Eric Andersenc470f442003-07-28 09:56:35 +00009573 goto retry;
9574 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009575 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009576 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009577 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009578 }
Eric Andersencb57d552001-06-28 07:25:16 +00009579 }
9580#else
Denys Vlasenko161bb8f2010-06-06 05:07:11 +02009581 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009582#endif
9583
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009584#if 0
9585/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009586 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009587 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009588 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009589 if (flags >= 0 && (flags & O_NONBLOCK)) {
9590 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009591 if (fcntl(0, F_SETFL, flags) >= 0) {
9592 out2str("sh: turning off NDELAY mode\n");
9593 goto retry;
9594 }
9595 }
9596 }
9597 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009598#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009599 return nr;
9600}
9601
9602/*
9603 * Refill the input buffer and return the next input character:
9604 *
9605 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009606 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9607 * or we are reading from a string so we can't refill the buffer,
9608 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009609 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009610 * 4) Process input up to the next newline, deleting nul characters.
9611 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009612//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9613#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009614static int
Eric Andersenc470f442003-07-28 09:56:35 +00009615preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009616{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009617 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009618 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009619
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009620 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009621#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009622 if (g_parsefile->left_in_line == -1
9623 && g_parsefile->strpush->ap
9624 && g_parsefile->next_to_pgetc[-1] != ' '
9625 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009626 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009627 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009628 return PEOA;
9629 }
Eric Andersen2870d962001-07-02 17:27:21 +00009630#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009631 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009632 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009633 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9634 g_parsefile->left_in_line,
9635 g_parsefile->next_to_pgetc,
9636 g_parsefile->next_to_pgetc);
9637 if (--g_parsefile->left_in_line >= 0)
9638 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009639 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009640 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009641 * "pgetc" needs refilling.
9642 */
9643
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009644 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009645 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009646 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009647 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009648 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009649 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009650 /* even in failure keep left_in_line and next_to_pgetc
9651 * in lock step, for correct multi-layer pungetc.
9652 * left_in_line was decremented before preadbuffer(),
9653 * must inc next_to_pgetc: */
9654 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009655 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009656 }
Eric Andersencb57d552001-06-28 07:25:16 +00009657
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009658 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009659 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009660 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009661 again:
9662 more = preadfd();
9663 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009664 /* don't try reading again */
9665 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009666 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009667 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009668 return PEOF;
9669 }
9670 }
9671
Denis Vlasenko727752d2008-11-28 03:41:47 +00009672 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009673 * Set g_parsefile->left_in_line
9674 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009675 * NUL chars are deleted.
9676 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009677 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009678 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009679 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009680
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009681 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009682
Denis Vlasenko727752d2008-11-28 03:41:47 +00009683 c = *q;
9684 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009685 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009686 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009687 q++;
9688 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009689 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009690 break;
9691 }
Eric Andersencb57d552001-06-28 07:25:16 +00009692 }
9693
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009694 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009695 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9696 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009697 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009698 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009699 }
9700 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009701 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009702
Eric Andersencb57d552001-06-28 07:25:16 +00009703 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009704 char save = *q;
9705 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009706 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009707 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009708 }
9709
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009710 pgetc_debug("preadbuffer at %d:%p'%s'",
9711 g_parsefile->left_in_line,
9712 g_parsefile->next_to_pgetc,
9713 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009714 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009715}
9716
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009717#define pgetc_as_macro() \
9718 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009719 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009720 : preadbuffer() \
9721 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009722
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009723static int
9724pgetc(void)
9725{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009726 pgetc_debug("pgetc_fast at %d:%p'%s'",
9727 g_parsefile->left_in_line,
9728 g_parsefile->next_to_pgetc,
9729 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009730 return pgetc_as_macro();
9731}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009732
9733#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009734# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009735#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009736# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009737#endif
9738
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009739#if ENABLE_ASH_ALIAS
9740static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009741pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009742{
9743 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009744 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009745 pgetc_debug("pgetc_fast at %d:%p'%s'",
9746 g_parsefile->left_in_line,
9747 g_parsefile->next_to_pgetc,
9748 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009749 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009750 } while (c == PEOA);
9751 return c;
9752}
9753#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009754# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009755#endif
9756
9757/*
9758 * Read a line from the script.
9759 */
9760static char *
9761pfgets(char *line, int len)
9762{
9763 char *p = line;
9764 int nleft = len;
9765 int c;
9766
9767 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009768 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009769 if (c == PEOF) {
9770 if (p == line)
9771 return NULL;
9772 break;
9773 }
9774 *p++ = c;
9775 if (c == '\n')
9776 break;
9777 }
9778 *p = '\0';
9779 return line;
9780}
9781
Eric Andersenc470f442003-07-28 09:56:35 +00009782/*
9783 * Undo the last call to pgetc. Only one character may be pushed back.
9784 * PEOF may be pushed back.
9785 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009786static void
Eric Andersenc470f442003-07-28 09:56:35 +00009787pungetc(void)
9788{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009789 g_parsefile->left_in_line++;
9790 g_parsefile->next_to_pgetc--;
9791 pgetc_debug("pushed back to %d:%p'%s'",
9792 g_parsefile->left_in_line,
9793 g_parsefile->next_to_pgetc,
9794 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009795}
9796
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009797/*
9798 * To handle the "." command, a stack of input files is used. Pushfile
9799 * adds a new entry to the stack and popfile restores the previous level.
9800 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009801static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009802pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009803{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009804 struct parsefile *pf;
9805
Denis Vlasenko597906c2008-02-20 16:38:54 +00009806 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009807 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009808 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009809 /*pf->strpush = NULL; - ckzalloc did it */
9810 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009811 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009812}
9813
9814static void
9815popfile(void)
9816{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009817 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009818
Denis Vlasenkob012b102007-02-19 22:43:01 +00009819 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009820 if (pf->pf_fd >= 0)
9821 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009822 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009823 while (pf->strpush)
9824 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009825 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009826 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009827 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009828}
9829
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009830/*
9831 * Return to top level.
9832 */
9833static void
9834popallfiles(void)
9835{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009836 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009837 popfile();
9838}
9839
9840/*
9841 * Close the file(s) that the shell is reading commands from. Called
9842 * after a fork is done.
9843 */
9844static void
9845closescript(void)
9846{
9847 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009848 if (g_parsefile->pf_fd > 0) {
9849 close(g_parsefile->pf_fd);
9850 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009851 }
9852}
9853
9854/*
9855 * Like setinputfile, but takes an open file descriptor. Call this with
9856 * interrupts off.
9857 */
9858static void
9859setinputfd(int fd, int push)
9860{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009861 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009862 if (push) {
9863 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009864 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009865 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009866 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009867 if (g_parsefile->buf == NULL)
9868 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009869 g_parsefile->left_in_buffer = 0;
9870 g_parsefile->left_in_line = 0;
9871 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009872}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009873
Eric Andersenc470f442003-07-28 09:56:35 +00009874/*
9875 * Set the input to take input from a file. If push is set, push the
9876 * old input onto the stack first.
9877 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009878static int
9879setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009880{
9881 int fd;
9882 int fd2;
9883
Denis Vlasenkob012b102007-02-19 22:43:01 +00009884 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009885 fd = open(fname, O_RDONLY);
9886 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009887 if (flags & INPUT_NOFILE_OK)
9888 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009889 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009890 }
Eric Andersenc470f442003-07-28 09:56:35 +00009891 if (fd < 10) {
9892 fd2 = copyfd(fd, 10);
9893 close(fd);
9894 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009895 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009896 fd = fd2;
9897 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009898 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009899 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009900 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009901 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009902}
9903
Eric Andersencb57d552001-06-28 07:25:16 +00009904/*
9905 * Like setinputfile, but takes input from a string.
9906 */
Eric Andersenc470f442003-07-28 09:56:35 +00009907static void
9908setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009909{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009910 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009911 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009912 g_parsefile->next_to_pgetc = string;
9913 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009914 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009915 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009916 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009917}
9918
9919
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009920/* ============ mail.c
9921 *
9922 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009923 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009924
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009925#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009926
Eric Andersencb57d552001-06-28 07:25:16 +00009927#define MAXMBOXES 10
9928
Eric Andersenc470f442003-07-28 09:56:35 +00009929/* times of mailboxes */
9930static time_t mailtime[MAXMBOXES];
9931/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009932static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009933
Eric Andersencb57d552001-06-28 07:25:16 +00009934/*
Eric Andersenc470f442003-07-28 09:56:35 +00009935 * Print appropriate message(s) if mail has arrived.
9936 * If mail_var_path_changed is set,
9937 * then the value of MAIL has mail_var_path_changed,
9938 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009939 */
Eric Andersenc470f442003-07-28 09:56:35 +00009940static void
9941chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009942{
Eric Andersencb57d552001-06-28 07:25:16 +00009943 const char *mpath;
9944 char *p;
9945 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009946 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009947 struct stackmark smark;
9948 struct stat statb;
9949
Eric Andersencb57d552001-06-28 07:25:16 +00009950 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009951 mpath = mpathset() ? mpathval() : mailval();
9952 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009953 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009954 if (p == NULL)
9955 break;
9956 if (*p == '\0')
9957 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009958 for (q = p; *q; q++)
9959 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009960#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009961 if (q[-1] != '/')
9962 abort();
9963#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009964 q[-1] = '\0'; /* delete trailing '/' */
9965 if (stat(p, &statb) < 0) {
9966 *mtp = 0;
9967 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009968 }
Eric Andersenc470f442003-07-28 09:56:35 +00009969 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9970 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009971 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009972 pathopt ? pathopt : "you have mail"
9973 );
9974 }
9975 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009976 }
Eric Andersenc470f442003-07-28 09:56:35 +00009977 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009978 popstackmark(&smark);
9979}
Eric Andersencb57d552001-06-28 07:25:16 +00009980
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009981static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009982changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009983{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009984 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009985}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009986
Denis Vlasenko131ae172007-02-18 13:00:19 +00009987#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009988
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009989
9990/* ============ ??? */
9991
Eric Andersencb57d552001-06-28 07:25:16 +00009992/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009993 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009994 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009995static void
9996setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009997{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009998 char **newparam;
9999 char **ap;
10000 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +000010001
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010002 for (nparam = 0; argv[nparam]; nparam++)
10003 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010004 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10005 while (*argv) {
10006 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +000010007 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010008 *ap = NULL;
10009 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +000010010 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010011 shellparam.nparam = nparam;
10012 shellparam.p = newparam;
10013#if ENABLE_ASH_GETOPTS
10014 shellparam.optind = 1;
10015 shellparam.optoff = -1;
10016#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010017}
10018
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010019/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000010020 * Process shell options. The global variable argptr contains a pointer
10021 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010022 *
10023 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10024 * For a non-interactive shell, an error condition encountered
10025 * by a special built-in ... shall cause the shell to write a diagnostic message
10026 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +000010027 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +000010028 * ...
10029 * Utility syntax error (option or operand error) Shall exit
10030 * ...
10031 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10032 * we see that bash does not do that (set "finishes" with error code 1 instead,
10033 * and shell continues), and people rely on this behavior!
10034 * Testcase:
10035 * set -o barfoo 2>/dev/null
10036 * echo $?
10037 *
10038 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000010039 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010040static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010041plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +000010042{
10043 int i;
10044
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010045 if (name) {
10046 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010047 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000010048 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010049 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010050 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010051 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010052 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010053 return 1;
Eric Andersen62483552001-07-10 06:09:16 +000010054 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010055 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010056 if (val) {
10057 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10058 } else {
10059 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10060 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010061 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010062 return 0;
Eric Andersen62483552001-07-10 06:09:16 +000010063}
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010064static void
10065setoption(int flag, int val)
10066{
10067 int i;
10068
10069 for (i = 0; i < NOPTS; i++) {
10070 if (optletters(i) == flag) {
10071 optlist[i] = val;
10072 return;
10073 }
10074 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010075 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010076 /* NOTREACHED */
10077}
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010078static int
Eric Andersenc470f442003-07-28 09:56:35 +000010079options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +000010080{
10081 char *p;
10082 int val;
10083 int c;
10084
10085 if (cmdline)
10086 minusc = NULL;
10087 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010088 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010089 if (c != '-' && c != '+')
10090 break;
10091 argptr++;
10092 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010093 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +000010094 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010095 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +000010096 if (!cmdline) {
10097 /* "-" means turn off -x and -v */
10098 if (p[0] == '\0')
10099 xflag = vflag = 0;
10100 /* "--" means reset params */
10101 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +000010102 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010103 }
Eric Andersenc470f442003-07-28 09:56:35 +000010104 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010105 }
Eric Andersencb57d552001-06-28 07:25:16 +000010106 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010107 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010108 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010109 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010110 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010111 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010112 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010113 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010114 /* it already printed err message */
10115 return 1; /* error */
10116 }
Eric Andersencb57d552001-06-28 07:25:16 +000010117 if (*argptr)
10118 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010119 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10120 isloginsh = 1;
10121 /* bash does not accept +-login, we also won't */
10122 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010123 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010124 isloginsh = 1;
10125 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010126 } else {
10127 setoption(c, val);
10128 }
10129 }
10130 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010131 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010132}
10133
Eric Andersencb57d552001-06-28 07:25:16 +000010134/*
Eric Andersencb57d552001-06-28 07:25:16 +000010135 * The shift builtin command.
10136 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010137static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010138shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010139{
10140 int n;
10141 char **ap1, **ap2;
10142
10143 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010144 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010145 n = number(argv[1]);
10146 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010147 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010148 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010149 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010150 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010151 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010152 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010153 }
10154 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010155 while ((*ap2++ = *ap1++) != NULL)
10156 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010157#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010158 shellparam.optind = 1;
10159 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010160#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010161 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010162 return 0;
10163}
10164
Eric Andersencb57d552001-06-28 07:25:16 +000010165/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010166 * POSIX requires that 'set' (but not export or readonly) output the
10167 * variables in lexicographic order - by the locale's collating order (sigh).
10168 * Maybe we could keep them in an ordered balanced binary tree
10169 * instead of hashed lists.
10170 * For now just roll 'em through qsort for printing...
10171 */
10172static int
10173showvars(const char *sep_prefix, int on, int off)
10174{
10175 const char *sep;
10176 char **ep, **epend;
10177
10178 ep = listvars(on, off, &epend);
10179 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10180
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010181 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010182
10183 for (; ep < epend; ep++) {
10184 const char *p;
10185 const char *q;
10186
10187 p = strchrnul(*ep, '=');
10188 q = nullstr;
10189 if (*p)
10190 q = single_quote(++p);
10191 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10192 }
10193 return 0;
10194}
10195
10196/*
Eric Andersencb57d552001-06-28 07:25:16 +000010197 * The set command builtin.
10198 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010199static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010200setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010201{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010202 int retval;
10203
Denis Vlasenko68404f12008-03-17 09:00:54 +000010204 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010205 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010206 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010207 retval = 1;
10208 if (!options(0)) { /* if no parse error... */
10209 retval = 0;
10210 optschanged();
10211 if (*argptr != NULL) {
10212 setparam(argptr);
10213 }
Eric Andersencb57d552001-06-28 07:25:16 +000010214 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010215 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010216 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010217}
10218
Denis Vlasenko131ae172007-02-18 13:00:19 +000010219#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010220static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010221change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010222{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010223 uint32_t t;
10224
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010225 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010226 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010227 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010228 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010229 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010230 vrandom.flags &= ~VNOFUNC;
10231 } else {
10232 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010233 t = strtoul(value, NULL, 10);
10234 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010235 }
Eric Andersenef02f822004-03-11 13:34:24 +000010236}
Eric Andersen16767e22004-03-16 05:14:10 +000010237#endif
10238
Denis Vlasenko131ae172007-02-18 13:00:19 +000010239#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010240static int
Eric Andersenc470f442003-07-28 09:56:35 +000010241getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010242{
10243 char *p, *q;
10244 char c = '?';
10245 int done = 0;
10246 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010247 char s[12];
10248 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010249
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010250 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010251 return 1;
10252 optnext = optfirst + *param_optind - 1;
10253
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010254 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010255 p = NULL;
10256 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010257 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010258 if (p == NULL || *p == '\0') {
10259 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010260 p = *optnext;
10261 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010262 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010263 p = NULL;
10264 done = 1;
10265 goto out;
10266 }
10267 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010268 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010269 goto atend;
10270 }
10271
10272 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010273 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010274 if (*q == '\0') {
10275 if (optstr[0] == ':') {
10276 s[0] = c;
10277 s[1] = '\0';
10278 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010279 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010280 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010281 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010282 }
10283 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010284 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010285 }
10286 if (*++q == ':')
10287 q++;
10288 }
10289
10290 if (*++q == ':') {
10291 if (*p == '\0' && (p = *optnext) == NULL) {
10292 if (optstr[0] == ':') {
10293 s[0] = c;
10294 s[1] = '\0';
10295 err |= setvarsafe("OPTARG", s, 0);
10296 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010297 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010298 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010299 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010300 c = '?';
10301 }
Eric Andersenc470f442003-07-28 09:56:35 +000010302 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010303 }
10304
10305 if (p == *optnext)
10306 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010307 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010308 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010309 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010310 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010311 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010312 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010313 *param_optind = optnext - optfirst + 1;
10314 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010315 err |= setvarsafe("OPTIND", s, VNOFUNC);
10316 s[0] = c;
10317 s[1] = '\0';
10318 err |= setvarsafe(optvar, s, 0);
10319 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010320 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010321 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010322 flush_stdout_stderr();
10323 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010324 }
10325 return done;
10326}
Eric Andersenc470f442003-07-28 09:56:35 +000010327
10328/*
10329 * The getopts builtin. Shellparam.optnext points to the next argument
10330 * to be processed. Shellparam.optptr points to the next character to
10331 * be processed in the current argument. If shellparam.optnext is NULL,
10332 * then it's the first time getopts has been called.
10333 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010334static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010335getoptscmd(int argc, char **argv)
10336{
10337 char **optbase;
10338
10339 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010340 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010341 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010342 optbase = shellparam.p;
10343 if (shellparam.optind > shellparam.nparam + 1) {
10344 shellparam.optind = 1;
10345 shellparam.optoff = -1;
10346 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010347 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010348 optbase = &argv[3];
10349 if (shellparam.optind > argc - 2) {
10350 shellparam.optind = 1;
10351 shellparam.optoff = -1;
10352 }
10353 }
10354
10355 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010356 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010357}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010358#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010359
Eric Andersencb57d552001-06-28 07:25:16 +000010360
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010361/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010362
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010363struct heredoc {
10364 struct heredoc *next; /* next here document in list */
10365 union node *here; /* redirection node */
10366 char *eofmark; /* string indicating end of input */
10367 smallint striptabs; /* if set, strip leading tabs */
10368};
10369
10370static smallint tokpushback; /* last token pushed back */
10371static smallint parsebackquote; /* nonzero if we are inside backquotes */
10372static smallint quoteflag; /* set if (part of) last token was quoted */
10373static token_id_t lasttoken; /* last token read (integer id Txxx) */
10374static struct heredoc *heredoclist; /* list of here documents to read */
10375static char *wordtext; /* text of last word returned by readtoken */
10376static struct nodelist *backquotelist;
10377static union node *redirnode;
10378static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010379
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010380static const char *
10381tokname(char *buf, int tok)
10382{
10383 if (tok < TSEMI)
10384 return tokname_array[tok] + 1;
10385 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10386 return buf;
10387}
10388
10389/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010390 * Called when an unexpected token is read during the parse. The argument
10391 * is the token that is expected, or -1 if more than one type of token can
10392 * occur at this point.
10393 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010394static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010395static void
10396raise_error_unexpected_syntax(int token)
10397{
10398 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010399 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010400 int l;
10401
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010402 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010403 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010404 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010405 raise_error_syntax(msg);
10406 /* NOTREACHED */
10407}
Eric Andersencb57d552001-06-28 07:25:16 +000010408
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010409#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010410
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010411/* parsing is heavily cross-recursive, need these forward decls */
10412static union node *andor(void);
10413static union node *pipeline(void);
10414static union node *parse_command(void);
10415static void parseheredoc(void);
10416static char peektoken(void);
10417static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010418
Eric Andersenc470f442003-07-28 09:56:35 +000010419static union node *
10420list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010421{
10422 union node *n1, *n2, *n3;
10423 int tok;
10424
Eric Andersenc470f442003-07-28 09:56:35 +000010425 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10426 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010427 return NULL;
10428 n1 = NULL;
10429 for (;;) {
10430 n2 = andor();
10431 tok = readtoken();
10432 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010433 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010434 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010435 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010436 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010437 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010438 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010439 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010440 n2 = n3;
10441 }
10442 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010443 }
10444 }
10445 if (n1 == NULL) {
10446 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010447 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010448 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010449 n3->type = NSEMI;
10450 n3->nbinary.ch1 = n1;
10451 n3->nbinary.ch2 = n2;
10452 n1 = n3;
10453 }
10454 switch (tok) {
10455 case TBACKGND:
10456 case TSEMI:
10457 tok = readtoken();
10458 /* fall through */
10459 case TNL:
10460 if (tok == TNL) {
10461 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010462 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010463 return n1;
10464 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010465 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010466 }
Eric Andersenc470f442003-07-28 09:56:35 +000010467 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010468 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010469 return n1;
10470 break;
10471 case TEOF:
10472 if (heredoclist)
10473 parseheredoc();
10474 else
Eric Andersenc470f442003-07-28 09:56:35 +000010475 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010476 return n1;
10477 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010478 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010479 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010480 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010481 return n1;
10482 }
10483 }
10484}
10485
Eric Andersenc470f442003-07-28 09:56:35 +000010486static union node *
10487andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010488{
Eric Andersencb57d552001-06-28 07:25:16 +000010489 union node *n1, *n2, *n3;
10490 int t;
10491
Eric Andersencb57d552001-06-28 07:25:16 +000010492 n1 = pipeline();
10493 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010494 t = readtoken();
10495 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010496 t = NAND;
10497 } else if (t == TOR) {
10498 t = NOR;
10499 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010500 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010501 return n1;
10502 }
Eric Andersenc470f442003-07-28 09:56:35 +000010503 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010504 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010505 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010506 n3->type = t;
10507 n3->nbinary.ch1 = n1;
10508 n3->nbinary.ch2 = n2;
10509 n1 = n3;
10510 }
10511}
10512
Eric Andersenc470f442003-07-28 09:56:35 +000010513static union node *
10514pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010515{
Eric Andersencb57d552001-06-28 07:25:16 +000010516 union node *n1, *n2, *pipenode;
10517 struct nodelist *lp, *prev;
10518 int negate;
10519
10520 negate = 0;
10521 TRACE(("pipeline: entered\n"));
10522 if (readtoken() == TNOT) {
10523 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010524 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010525 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010526 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010527 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010528 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010529 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010530 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010531 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010532 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010533 pipenode->npipe.cmdlist = lp;
10534 lp->n = n1;
10535 do {
10536 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010537 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010538 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010539 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010540 prev->next = lp;
10541 } while (readtoken() == TPIPE);
10542 lp->next = NULL;
10543 n1 = pipenode;
10544 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010545 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010546 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010547 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010548 n2->type = NNOT;
10549 n2->nnot.com = n1;
10550 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010551 }
10552 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010553}
10554
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010555static union node *
10556makename(void)
10557{
10558 union node *n;
10559
Denis Vlasenko597906c2008-02-20 16:38:54 +000010560 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010561 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010562 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010563 n->narg.text = wordtext;
10564 n->narg.backquote = backquotelist;
10565 return n;
10566}
10567
10568static void
10569fixredir(union node *n, const char *text, int err)
10570{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010571 int fd;
10572
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010573 TRACE(("Fix redir %s %d\n", text, err));
10574 if (!err)
10575 n->ndup.vname = NULL;
10576
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010577 fd = bb_strtou(text, NULL, 10);
10578 if (!errno && fd >= 0)
10579 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010580 else if (LONE_DASH(text))
10581 n->ndup.dupfd = -1;
10582 else {
10583 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010584 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010585 n->ndup.vname = makename();
10586 }
10587}
10588
10589/*
10590 * Returns true if the text contains nothing to expand (no dollar signs
10591 * or backquotes).
10592 */
10593static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010594noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010595{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010596 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010597
Denys Vlasenkocd716832009-11-28 22:14:02 +010010598 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010599 if (c == CTLQUOTEMARK)
10600 continue;
10601 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010602 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010603 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010604 return 0;
10605 }
10606 return 1;
10607}
10608
10609static void
10610parsefname(void)
10611{
10612 union node *n = redirnode;
10613
10614 if (readtoken() != TWORD)
10615 raise_error_unexpected_syntax(-1);
10616 if (n->type == NHERE) {
10617 struct heredoc *here = heredoc;
10618 struct heredoc *p;
10619 int i;
10620
10621 if (quoteflag == 0)
10622 n->type = NXHERE;
10623 TRACE(("Here document %d\n", n->type));
10624 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010625 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010626 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010627 here->eofmark = wordtext;
10628 here->next = NULL;
10629 if (heredoclist == NULL)
10630 heredoclist = here;
10631 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010632 for (p = heredoclist; p->next; p = p->next)
10633 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010634 p->next = here;
10635 }
10636 } else if (n->type == NTOFD || n->type == NFROMFD) {
10637 fixredir(n, wordtext, 0);
10638 } else {
10639 n->nfile.fname = makename();
10640 }
10641}
Eric Andersencb57d552001-06-28 07:25:16 +000010642
Eric Andersenc470f442003-07-28 09:56:35 +000010643static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010644simplecmd(void)
10645{
10646 union node *args, **app;
10647 union node *n = NULL;
10648 union node *vars, **vpp;
10649 union node **rpp, *redir;
10650 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010651#if ENABLE_ASH_BASH_COMPAT
10652 smallint double_brackets_flag = 0;
10653#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010654
10655 args = NULL;
10656 app = &args;
10657 vars = NULL;
10658 vpp = &vars;
10659 redir = NULL;
10660 rpp = &redir;
10661
10662 savecheckkwd = CHKALIAS;
10663 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010664 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010665 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010666 t = readtoken();
10667 switch (t) {
10668#if ENABLE_ASH_BASH_COMPAT
10669 case TAND: /* "&&" */
10670 case TOR: /* "||" */
10671 if (!double_brackets_flag) {
10672 tokpushback = 1;
10673 goto out;
10674 }
10675 wordtext = (char *) (t == TAND ? "-a" : "-o");
10676#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010677 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010678 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010679 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010681 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010682#if ENABLE_ASH_BASH_COMPAT
10683 if (strcmp("[[", wordtext) == 0)
10684 double_brackets_flag = 1;
10685 else if (strcmp("]]", wordtext) == 0)
10686 double_brackets_flag = 0;
10687#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010688 n->narg.backquote = backquotelist;
10689 if (savecheckkwd && isassignment(wordtext)) {
10690 *vpp = n;
10691 vpp = &n->narg.next;
10692 } else {
10693 *app = n;
10694 app = &n->narg.next;
10695 savecheckkwd = 0;
10696 }
10697 break;
10698 case TREDIR:
10699 *rpp = n = redirnode;
10700 rpp = &n->nfile.next;
10701 parsefname(); /* read name of redirection file */
10702 break;
10703 case TLP:
10704 if (args && app == &args->narg.next
10705 && !vars && !redir
10706 ) {
10707 struct builtincmd *bcmd;
10708 const char *name;
10709
10710 /* We have a function */
10711 if (readtoken() != TRP)
10712 raise_error_unexpected_syntax(TRP);
10713 name = n->narg.text;
10714 if (!goodname(name)
10715 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10716 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010717 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010718 }
10719 n->type = NDEFUN;
10720 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10721 n->narg.next = parse_command();
10722 return n;
10723 }
10724 /* fall through */
10725 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010726 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010727 goto out;
10728 }
10729 }
10730 out:
10731 *app = NULL;
10732 *vpp = NULL;
10733 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010734 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010735 n->type = NCMD;
10736 n->ncmd.args = args;
10737 n->ncmd.assign = vars;
10738 n->ncmd.redirect = redir;
10739 return n;
10740}
10741
10742static union node *
10743parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010744{
Eric Andersencb57d552001-06-28 07:25:16 +000010745 union node *n1, *n2;
10746 union node *ap, **app;
10747 union node *cp, **cpp;
10748 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010749 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010750 int t;
10751
10752 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010753 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010754
Eric Andersencb57d552001-06-28 07:25:16 +000010755 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010756 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010757 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010758 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010759 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010760 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010761 n1->type = NIF;
10762 n1->nif.test = list(0);
10763 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010764 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010765 n1->nif.ifpart = list(0);
10766 n2 = n1;
10767 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010768 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010769 n2 = n2->nif.elsepart;
10770 n2->type = NIF;
10771 n2->nif.test = list(0);
10772 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010773 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010774 n2->nif.ifpart = list(0);
10775 }
10776 if (lasttoken == TELSE)
10777 n2->nif.elsepart = list(0);
10778 else {
10779 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010780 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010781 }
Eric Andersenc470f442003-07-28 09:56:35 +000010782 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010783 break;
10784 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010785 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010786 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010787 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010788 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010789 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010790 got = readtoken();
10791 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010792 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010793 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010794 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010795 }
10796 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010797 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010798 break;
10799 }
10800 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010801 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010802 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010803 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010804 n1->type = NFOR;
10805 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010806 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010807 if (readtoken() == TIN) {
10808 app = &ap;
10809 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010810 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010811 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010812 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010813 n2->narg.text = wordtext;
10814 n2->narg.backquote = backquotelist;
10815 *app = n2;
10816 app = &n2->narg.next;
10817 }
10818 *app = NULL;
10819 n1->nfor.args = ap;
10820 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010821 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010822 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010823 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010824 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010825 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010826 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010827 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010828 n1->nfor.args = n2;
10829 /*
10830 * Newline or semicolon here is optional (but note
10831 * that the original Bourne shell only allowed NL).
10832 */
10833 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010834 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010835 }
Eric Andersenc470f442003-07-28 09:56:35 +000010836 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010837 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010838 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010839 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010840 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010841 break;
10842 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010843 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010844 n1->type = NCASE;
10845 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010846 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010847 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010848 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010849 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010850 n2->narg.text = wordtext;
10851 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010852 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010853 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010854 } while (readtoken() == TNL);
10855 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010856 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010857 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010858 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010859 checkkwd = CHKNL | CHKKWD;
10860 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010861 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010862 if (lasttoken == TLP)
10863 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010864 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010865 cp->type = NCLIST;
10866 app = &cp->nclist.pattern;
10867 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010868 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010869 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010870 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010871 ap->narg.text = wordtext;
10872 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010873 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010874 break;
10875 app = &ap->narg.next;
10876 readtoken();
10877 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010878 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010879 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010880 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010881 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010882
Eric Andersenc470f442003-07-28 09:56:35 +000010883 cpp = &cp->nclist.next;
10884
10885 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010886 t = readtoken();
10887 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010888 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010889 raise_error_unexpected_syntax(TENDCASE);
10890 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010891 }
Eric Andersenc470f442003-07-28 09:56:35 +000010892 }
Eric Andersencb57d552001-06-28 07:25:16 +000010893 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010894 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010895 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010896 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010897 n1->type = NSUBSHELL;
10898 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010899 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010900 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010901 break;
10902 case TBEGIN:
10903 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010904 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010905 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010906 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010907 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010908 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010909 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010910 }
10911
Eric Andersenc470f442003-07-28 09:56:35 +000010912 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010913 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010914
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010915 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010916 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010917 checkkwd = CHKKWD | CHKALIAS;
10918 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010919 while (readtoken() == TREDIR) {
10920 *rpp = n2 = redirnode;
10921 rpp = &n2->nfile.next;
10922 parsefname();
10923 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010924 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010925 *rpp = NULL;
10926 if (redir) {
10927 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010928 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010929 n2->type = NREDIR;
10930 n2->nredir.n = n1;
10931 n1 = n2;
10932 }
10933 n1->nredir.redirect = redir;
10934 }
Eric Andersencb57d552001-06-28 07:25:16 +000010935 return n1;
10936}
10937
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010938#if ENABLE_ASH_BASH_COMPAT
10939static int decode_dollar_squote(void)
10940{
10941 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10942 int c, cnt;
10943 char *p;
10944 char buf[4];
10945
10946 c = pgetc();
10947 p = strchr(C_escapes, c);
10948 if (p) {
10949 buf[0] = c;
10950 p = buf;
10951 cnt = 3;
10952 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10953 do {
10954 c = pgetc();
10955 *++p = c;
10956 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10957 pungetc();
10958 } else if (c == 'x') { /* \xHH */
10959 do {
10960 c = pgetc();
10961 *++p = c;
10962 } while (isxdigit(c) && --cnt);
10963 pungetc();
10964 if (cnt == 3) { /* \x but next char is "bad" */
10965 c = 'x';
10966 goto unrecognized;
10967 }
10968 } else { /* simple seq like \\ or \t */
10969 p++;
10970 }
10971 *p = '\0';
10972 p = buf;
10973 c = bb_process_escape_sequence((void*)&p);
10974 } else { /* unrecognized "\z": print both chars unless ' or " */
10975 if (c != '\'' && c != '"') {
10976 unrecognized:
10977 c |= 0x100; /* "please encode \, then me" */
10978 }
10979 }
10980 return c;
10981}
10982#endif
10983
Eric Andersencb57d552001-06-28 07:25:16 +000010984/*
10985 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10986 * is not NULL, read a here document. In the latter case, eofmark is the
10987 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010988 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010989 * is the first character of the input token or document.
10990 *
10991 * Because C does not have internal subroutines, I have simulated them
10992 * using goto's to implement the subroutine linkage. The following macros
10993 * will run code that appears at the end of readtoken1.
10994 */
Eric Andersen2870d962001-07-02 17:27:21 +000010995#define CHECKEND() {goto checkend; checkend_return:;}
10996#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10997#define PARSESUB() {goto parsesub; parsesub_return:;}
10998#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10999#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11000#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000011001static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010011002readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000011003{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011004 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010011005 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000011006 char *out;
11007 int len;
11008 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011009 struct nodelist *bqlist;
11010 smallint quotef;
11011 smallint dblquote;
11012 smallint oldstyle;
11013 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000011014#if ENABLE_ASH_EXPAND_PRMT
11015 smallint pssyntax; /* we are expanding a prompt string */
11016#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011017 int varnest; /* levels of variables expansion */
11018 int arinest; /* levels of arithmetic expansion */
11019 int parenlevel; /* levels of parens in arithmetic */
11020 int dqvarnest; /* levels of variables expansion within double quotes */
11021
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011022 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011023
Eric Andersencb57d552001-06-28 07:25:16 +000011024#if __GNUC__
11025 /* Avoid longjmp clobbering */
11026 (void) &out;
11027 (void) &quotef;
11028 (void) &dblquote;
11029 (void) &varnest;
11030 (void) &arinest;
11031 (void) &parenlevel;
11032 (void) &dqvarnest;
11033 (void) &oldstyle;
11034 (void) &prevsyntax;
11035 (void) &syntax;
11036#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011037 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000011038 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011039 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011040 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000011041#if ENABLE_ASH_EXPAND_PRMT
11042 pssyntax = (syntax == PSSYNTAX);
11043 if (pssyntax)
11044 syntax = DQSYNTAX;
11045#endif
11046 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011047 varnest = 0;
11048 arinest = 0;
11049 parenlevel = 0;
11050 dqvarnest = 0;
11051
11052 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011053 loop:
11054 /* For each line, until end of word */
Denys Vlasenko958581a2010-09-12 15:04:27 +020011055 CHECKEND(); /* set c to PEOF if at end of here document */
11056 for (;;) { /* until end of line or end of word */
11057 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11058 switch (SIT(c, syntax)) {
11059 case CNL: /* '\n' */
11060 if (syntax == BASESYNTAX)
11061 goto endword; /* exit outer loop */
11062 USTPUTC(c, out);
11063 g_parsefile->linno++;
11064 setprompt_if(doprompt, 2);
11065 c = pgetc();
11066 goto loop; /* continue outer loop */
11067 case CWORD:
11068 USTPUTC(c, out);
11069 break;
11070 case CCTL:
11071 if (eofmark == NULL || dblquote)
11072 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011073#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko958581a2010-09-12 15:04:27 +020011074 if (c == '\\' && bash_dollar_squote) {
11075 c = decode_dollar_squote();
11076 if (c & 0x100) {
11077 USTPUTC('\\', out);
11078 c = (unsigned char)c;
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011079 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011080 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011081#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011082 USTPUTC(c, out);
11083 break;
11084 case CBACK: /* backslash */
11085 c = pgetc_without_PEOA();
11086 if (c == PEOF) {
11087 USTPUTC(CTLESC, out);
11088 USTPUTC('\\', out);
11089 pungetc();
11090 } else if (c == '\n') {
11091 setprompt_if(doprompt, 2);
11092 } else {
11093#if ENABLE_ASH_EXPAND_PRMT
11094 if (c == '$' && pssyntax) {
Eric Andersenc470f442003-07-28 09:56:35 +000011095 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011096 USTPUTC('\\', out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011097 }
Denis Vlasenko46a53062007-09-24 18:30:02 +000011098#endif
Denys Vlasenko958581a2010-09-12 15:04:27 +020011099 /* Backslash is retained if we are in "str" and next char isn't special */
11100 if (dblquote
11101 && c != '\\'
11102 && c != '`'
11103 && c != '$'
11104 && (c != '"' || eofmark != NULL)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011105 ) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011106 USTPUTC(CTLESC, out);
11107 USTPUTC('\\', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011108 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011109 if (SIT(c, SQSYNTAX) == CCTL)
11110 USTPUTC(CTLESC, out);
Denys Vlasenko0ff78a02010-08-30 15:20:07 +020011111 USTPUTC(c, out);
Denys Vlasenko958581a2010-09-12 15:04:27 +020011112 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011113 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011114 break;
11115 case CSQUOTE:
11116 syntax = SQSYNTAX;
11117 quotemark:
11118 if (eofmark == NULL) {
11119 USTPUTC(CTLQUOTEMARK, out);
11120 }
11121 break;
11122 case CDQUOTE:
11123 syntax = DQSYNTAX;
11124 dblquote = 1;
11125 goto quotemark;
11126 case CENDQUOTE:
11127 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11128 if (eofmark != NULL && arinest == 0
11129 && varnest == 0
11130 ) {
11131 USTPUTC(c, out);
11132 } else {
11133 if (dqvarnest == 0) {
11134 syntax = BASESYNTAX;
11135 dblquote = 0;
11136 }
11137 quotef = 1;
11138 goto quotemark;
11139 }
11140 break;
11141 case CVAR: /* '$' */
11142 PARSESUB(); /* parse substitution */
11143 break;
11144 case CENDVAR: /* '}' */
11145 if (varnest > 0) {
11146 varnest--;
11147 if (dqvarnest > 0) {
11148 dqvarnest--;
11149 }
11150 c = CTLENDVAR;
11151 }
11152 USTPUTC(c, out);
11153 break;
11154#if ENABLE_SH_MATH_SUPPORT
11155 case CLP: /* '(' in arithmetic */
11156 parenlevel++;
11157 USTPUTC(c, out);
11158 break;
11159 case CRP: /* ')' in arithmetic */
11160 if (parenlevel > 0) {
11161 parenlevel--;
11162 } else {
11163 if (pgetc() == ')') {
11164 if (--arinest == 0) {
11165 syntax = prevsyntax;
11166 dblquote = (syntax == DQSYNTAX);
11167 c = CTLENDARI;
11168 }
11169 } else {
11170 /*
11171 * unbalanced parens
11172 * (don't 2nd guess - no error)
11173 */
11174 pungetc();
11175 }
11176 }
11177 USTPUTC(c, out);
11178 break;
11179#endif
11180 case CBQUOTE: /* '`' */
11181 PARSEBACKQOLD();
11182 break;
11183 case CENDFILE:
11184 goto endword; /* exit outer loop */
11185 case CIGN:
11186 break;
11187 default:
11188 if (varnest == 0) {
11189#if ENABLE_ASH_BASH_COMPAT
11190 if (c == '&') {
11191 if (pgetc() == '>')
11192 c = 0x100 + '>'; /* flag &> */
11193 pungetc();
11194 }
11195#endif
11196 goto endword; /* exit outer loop */
11197 }
11198 IF_ASH_ALIAS(if (c != PEOA))
11199 USTPUTC(c, out);
11200 }
11201 c = pgetc_fast();
11202 } /* for (;;) */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011203 endword:
Denys Vlasenko958581a2010-09-12 15:04:27 +020011204
Mike Frysinger98c52642009-04-02 10:02:37 +000011205#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011206 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011207 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011208#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011209 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011210 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011211 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011212 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011213 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011214 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011215 }
11216 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011217 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011218 out = stackblock();
11219 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011220 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011221 && quotef == 0
11222 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011223 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011224 PARSEREDIR(); /* passed as params: out, c */
11225 lasttoken = TREDIR;
11226 return lasttoken;
11227 }
11228 /* else: non-number X seen, interpret it
11229 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011230 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011231 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011232 }
11233 quoteflag = quotef;
11234 backquotelist = bqlist;
11235 grabstackblock(len);
11236 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011237 lasttoken = TWORD;
11238 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011239/* end of readtoken routine */
11240
Eric Andersencb57d552001-06-28 07:25:16 +000011241/*
11242 * Check to see whether we are at the end of the here document. When this
11243 * is called, c is set to the first character of the next input line. If
11244 * we are at the end of the here document, this routine sets the c to PEOF.
11245 */
Eric Andersenc470f442003-07-28 09:56:35 +000011246checkend: {
11247 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011248#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011249 if (c == PEOA)
11250 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011251#endif
11252 if (striptabs) {
11253 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011254 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011255 }
Eric Andersenc470f442003-07-28 09:56:35 +000011256 }
11257 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011258 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011259 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011260
Eric Andersenc470f442003-07-28 09:56:35 +000011261 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011262 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11263 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011264 if (*p == '\n' && *q == '\0') {
11265 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011266 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011267 needprompt = doprompt;
11268 } else {
11269 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011270 }
11271 }
11272 }
11273 }
Eric Andersenc470f442003-07-28 09:56:35 +000011274 goto checkend_return;
11275}
Eric Andersencb57d552001-06-28 07:25:16 +000011276
Eric Andersencb57d552001-06-28 07:25:16 +000011277/*
11278 * Parse a redirection operator. The variable "out" points to a string
11279 * specifying the fd to be redirected. The variable "c" contains the
11280 * first character of the redirection operator.
11281 */
Eric Andersenc470f442003-07-28 09:56:35 +000011282parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011283 /* out is already checked to be a valid number or "" */
11284 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011285 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011286
Denis Vlasenko597906c2008-02-20 16:38:54 +000011287 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011288 if (c == '>') {
11289 np->nfile.fd = 1;
11290 c = pgetc();
11291 if (c == '>')
11292 np->type = NAPPEND;
11293 else if (c == '|')
11294 np->type = NCLOBBER;
11295 else if (c == '&')
11296 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011297 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011298 else {
11299 np->type = NTO;
11300 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011301 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011302 }
11303#if ENABLE_ASH_BASH_COMPAT
11304 else if (c == 0x100 + '>') { /* this flags &> redirection */
11305 np->nfile.fd = 1;
11306 pgetc(); /* this is '>', no need to check */
11307 np->type = NTO2;
11308 }
11309#endif
11310 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011311 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011312 c = pgetc();
11313 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011314 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011315 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011316 np = stzalloc(sizeof(struct nhere));
11317 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011318 }
11319 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011320 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011321 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011322 c = pgetc();
11323 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011324 heredoc->striptabs = 1;
11325 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011326 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011327 pungetc();
11328 }
11329 break;
11330
11331 case '&':
11332 np->type = NFROMFD;
11333 break;
11334
11335 case '>':
11336 np->type = NFROMTO;
11337 break;
11338
11339 default:
11340 np->type = NFROM;
11341 pungetc();
11342 break;
11343 }
Eric Andersencb57d552001-06-28 07:25:16 +000011344 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011345 if (fd >= 0)
11346 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011347 redirnode = np;
11348 goto parseredir_return;
11349}
Eric Andersencb57d552001-06-28 07:25:16 +000011350
Eric Andersencb57d552001-06-28 07:25:16 +000011351/*
11352 * Parse a substitution. At this point, we have read the dollar sign
11353 * and nothing else.
11354 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011355
11356/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11357 * (assuming ascii char codes, as the original implementation did) */
11358#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011359 (((unsigned)(c) - 33 < 32) \
11360 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011361parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011362 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011363 int typeloc;
11364 int flags;
Eric Andersencb57d552001-06-28 07:25:16 +000011365
Eric Andersenc470f442003-07-28 09:56:35 +000011366 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011367 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011368 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011369 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011370#if ENABLE_ASH_BASH_COMPAT
11371 if (c == '\'')
11372 bash_dollar_squote = 1;
11373 else
11374#endif
11375 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011376 pungetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011377 } else if (c == '(') {
11378 /* $(command) or $((arith)) */
Eric Andersenc470f442003-07-28 09:56:35 +000011379 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011380#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011381 PARSEARITH();
11382#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011383 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011384#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011385 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011386 pungetc();
11387 PARSEBACKQNEW();
11388 }
11389 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011390 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
Eric Andersenc470f442003-07-28 09:56:35 +000011391 USTPUTC(CTLVAR, out);
11392 typeloc = out - (char *)stackblock();
11393 USTPUTC(VSNORMAL, out);
11394 subtype = VSNORMAL;
11395 if (c == '{') {
11396 c = pgetc();
11397 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011398 c = pgetc();
11399 if (c == '}')
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011400 c = '#'; /* ${#} - same as $# */
Eric Andersenc470f442003-07-28 09:56:35 +000011401 else
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011402 subtype = VSLENGTH; /* ${#VAR} */
11403 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011404 subtype = 0;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011405 }
Eric Andersenc470f442003-07-28 09:56:35 +000011406 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011407 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011408 /* $[{[#]]NAME[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011409 do {
11410 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011411 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011412 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011413 } else if (isdigit(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011414 /* $[{[#]]NUM[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011415 do {
11416 STPUTC(c, out);
11417 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011418 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011419 } else if (is_special(c)) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011420 /* $[{[#]]<specialchar>[}] */
Eric Andersenc470f442003-07-28 09:56:35 +000011421 USTPUTC(c, out);
11422 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011423 } else {
11424 badsub:
11425 raise_error_syntax("bad substitution");
11426 }
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011427 if (c != '}' && subtype == VSLENGTH) {
11428 /* ${#VAR didn't end with } */
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011429 goto badsub;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011430 }
Eric Andersencb57d552001-06-28 07:25:16 +000011431
Eric Andersenc470f442003-07-28 09:56:35 +000011432 STPUTC('=', out);
11433 flags = 0;
11434 if (subtype == 0) {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011435 /* ${VAR...} but not $VAR or ${#VAR} */
11436 /* c == first char after VAR */
Eric Andersenc470f442003-07-28 09:56:35 +000011437 switch (c) {
11438 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011439 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011440#if ENABLE_ASH_BASH_COMPAT
11441 if (c == ':' || c == '$' || isdigit(c)) {
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011442//TODO: support more general format ${v:EXPR:EXPR},
11443// where EXPR follows $(()) rules
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011444 subtype = VSSUBSTR;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011445 pungetc();
11446 break; /* "goto do_pungetc" is bigger (!) */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011447 }
11448#endif
11449 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011450 /*FALLTHROUGH*/
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011451 default: {
11452 static const char types[] ALIGN1 = "}-+?=";
11453 const char *p = strchr(types, c);
Eric Andersenc470f442003-07-28 09:56:35 +000011454 if (p == NULL)
11455 goto badsub;
11456 subtype = p - types + VSNORMAL;
11457 break;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011458 }
Eric Andersenc470f442003-07-28 09:56:35 +000011459 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011460 case '#': {
11461 int cc = c;
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011462 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011463 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011464 if (c != cc)
11465 goto do_pungetc;
11466 subtype++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011467 break;
11468 }
11469#if ENABLE_ASH_BASH_COMPAT
11470 case '/':
Denys Vlasenko6040fe82010-09-12 15:03:16 +020011471 /* ${v/[/]pattern/repl} */
11472//TODO: encode pattern and repl separately.
11473// Currently ${v/$var_with_slash/repl} is horribly broken
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011474 subtype = VSREPLACE;
11475 c = pgetc();
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011476 if (c != '/')
11477 goto do_pungetc;
11478 subtype++; /* VSREPLACEALL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011479 break;
11480#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011481 }
Eric Andersenc470f442003-07-28 09:56:35 +000011482 } else {
Denys Vlasenkob0fbe4b2010-08-05 17:19:27 +020011483 do_pungetc:
Eric Andersenc470f442003-07-28 09:56:35 +000011484 pungetc();
11485 }
11486 if (dblquote || arinest)
11487 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011488 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011489 if (subtype != VSNORMAL) {
11490 varnest++;
11491 if (dblquote || arinest) {
11492 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011493 }
11494 }
11495 }
Eric Andersenc470f442003-07-28 09:56:35 +000011496 goto parsesub_return;
11497}
Eric Andersencb57d552001-06-28 07:25:16 +000011498
Eric Andersencb57d552001-06-28 07:25:16 +000011499/*
11500 * Called to parse command substitutions. Newstyle is set if the command
11501 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11502 * list of commands (passed by reference), and savelen is the number of
11503 * characters on the top of the stack which must be preserved.
11504 */
Eric Andersenc470f442003-07-28 09:56:35 +000011505parsebackq: {
11506 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011507 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011508 union node *n;
11509 char *volatile str;
11510 struct jmploc jmploc;
11511 struct jmploc *volatile savehandler;
11512 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011513 smallint saveprompt = 0;
11514
Eric Andersencb57d552001-06-28 07:25:16 +000011515#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011516 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011517#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011518 savepbq = parsebackquote;
11519 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011520 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011521 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011522 exception_handler = savehandler;
11523 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011524 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011525 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011526 str = NULL;
11527 savelen = out - (char *)stackblock();
11528 if (savelen > 0) {
11529 str = ckmalloc(savelen);
11530 memcpy(str, stackblock(), savelen);
11531 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011532 savehandler = exception_handler;
11533 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011534 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011535 if (oldstyle) {
11536 /* We must read until the closing backquote, giving special
11537 treatment to some slashes, and then push the string and
11538 reread it as input, interpreting it normally. */
11539 char *pout;
Eric Andersenc470f442003-07-28 09:56:35 +000011540 size_t psavelen;
11541 char *pstr;
11542
Eric Andersenc470f442003-07-28 09:56:35 +000011543 STARTSTACKSTR(pout);
11544 for (;;) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011545 int pc;
11546
11547 setprompt_if(needprompt, 2);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011548 pc = pgetc();
11549 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011550 case '`':
11551 goto done;
11552
11553 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011554 pc = pgetc();
11555 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011556 g_parsefile->linno++;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011557 setprompt_if(doprompt, 2);
Eric Andersenc470f442003-07-28 09:56:35 +000011558 /*
11559 * If eating a newline, avoid putting
11560 * the newline into the new character
11561 * stream (via the STPUTC after the
11562 * switch).
11563 */
11564 continue;
11565 }
11566 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011567 && (!dblquote || pc != '"')
11568 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011569 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011570 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011571 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011572 break;
11573 }
11574 /* fall through */
11575
11576 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011577 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011578 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011579 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011580
11581 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011582 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011583 needprompt = doprompt;
11584 break;
11585
11586 default:
11587 break;
11588 }
11589 STPUTC(pc, pout);
11590 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011591 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011592 STPUTC('\0', pout);
11593 psavelen = pout - (char *)stackblock();
11594 if (psavelen > 0) {
11595 pstr = grabstackstr(pout);
11596 setinputstring(pstr);
11597 }
11598 }
11599 nlpp = &bqlist;
11600 while (*nlpp)
11601 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011602 *nlpp = stzalloc(sizeof(**nlpp));
11603 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011604 parsebackquote = oldstyle;
11605
11606 if (oldstyle) {
11607 saveprompt = doprompt;
11608 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011609 }
11610
Eric Andersenc470f442003-07-28 09:56:35 +000011611 n = list(2);
11612
11613 if (oldstyle)
11614 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011615 else if (readtoken() != TRP)
11616 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011617
11618 (*nlpp)->n = n;
11619 if (oldstyle) {
11620 /*
11621 * Start reading from old file again, ignoring any pushed back
11622 * tokens left from the backquote parsing
11623 */
11624 popfile();
11625 tokpushback = 0;
11626 }
11627 while (stackblocksize() <= savelen)
11628 growstackblock();
11629 STARTSTACKSTR(out);
11630 if (str) {
11631 memcpy(out, str, savelen);
11632 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011633 INT_OFF;
11634 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011635 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011636 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011637 }
11638 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011639 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011640 if (arinest || dblquote)
11641 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11642 else
11643 USTPUTC(CTLBACKQ, out);
11644 if (oldstyle)
11645 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011646 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011647}
11648
Mike Frysinger98c52642009-04-02 10:02:37 +000011649#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011650/*
11651 * Parse an arithmetic expansion (indicate start of one and set state)
11652 */
Eric Andersenc470f442003-07-28 09:56:35 +000011653parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011654 if (++arinest == 1) {
11655 prevsyntax = syntax;
11656 syntax = ARISYNTAX;
11657 USTPUTC(CTLARI, out);
11658 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011659 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011660 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011661 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011662 } else {
11663 /*
11664 * we collapse embedded arithmetic expansion to
11665 * parenthesis, which should be equivalent
11666 */
11667 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011668 }
Eric Andersenc470f442003-07-28 09:56:35 +000011669 goto parsearith_return;
11670}
11671#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011672
Eric Andersenc470f442003-07-28 09:56:35 +000011673} /* end of readtoken */
11674
Eric Andersencb57d552001-06-28 07:25:16 +000011675/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011676 * Read the next input token.
11677 * If the token is a word, we set backquotelist to the list of cmds in
11678 * backquotes. We set quoteflag to true if any part of the word was
11679 * quoted.
11680 * If the token is TREDIR, then we set redirnode to a structure containing
11681 * the redirection.
11682 * In all cases, the variable startlinno is set to the number of the line
11683 * on which the token starts.
11684 *
11685 * [Change comment: here documents and internal procedures]
11686 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11687 * word parsing code into a separate routine. In this case, readtoken
11688 * doesn't need to have any internal procedures, but parseword does.
11689 * We could also make parseoperator in essence the main routine, and
11690 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011691 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011692#define NEW_xxreadtoken
11693#ifdef NEW_xxreadtoken
11694/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011695static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011696 '\n', '(', ')', /* singles */
11697 '&', '|', ';', /* doubles */
11698 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011699};
Eric Andersencb57d552001-06-28 07:25:16 +000011700
Denis Vlasenko834dee72008-10-07 09:18:30 +000011701#define xxreadtoken_singles 3
11702#define xxreadtoken_doubles 3
11703
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011704static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011705 TNL, TLP, TRP, /* only single occurrence allowed */
11706 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11707 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011708 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011709};
11710
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011711static int
11712xxreadtoken(void)
11713{
11714 int c;
11715
11716 if (tokpushback) {
11717 tokpushback = 0;
11718 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011719 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011720 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011721 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011722 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011723 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011724 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011725 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011726
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011727 if (c == '#') {
11728 while ((c = pgetc()) != '\n' && c != PEOF)
11729 continue;
11730 pungetc();
11731 } else if (c == '\\') {
11732 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011733 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011734 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011735 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011736 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011737 setprompt_if(doprompt, 2);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011738 } else {
11739 const char *p;
11740
11741 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11742 if (c != PEOF) {
11743 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011744 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011745 needprompt = doprompt;
11746 }
11747
11748 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011749 if (p == NULL)
11750 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011751
Denis Vlasenko834dee72008-10-07 09:18:30 +000011752 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11753 int cc = pgetc();
11754 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011755 p += xxreadtoken_doubles + 1;
11756 } else {
11757 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011758#if ENABLE_ASH_BASH_COMPAT
11759 if (c == '&' && cc == '>') /* &> */
11760 break; /* return readtoken1(...) */
11761#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011762 }
11763 }
11764 }
11765 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11766 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011767 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011768 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011769
11770 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011771}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011772#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773#define RETURN(token) return lasttoken = token
11774static int
11775xxreadtoken(void)
11776{
11777 int c;
11778
11779 if (tokpushback) {
11780 tokpushback = 0;
11781 return lasttoken;
11782 }
Denys Vlasenko958581a2010-09-12 15:04:27 +020011783 setprompt_if(needprompt, 2);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011784 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011786 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011787 switch (c) {
11788 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011789 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011790 continue;
11791 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011792 while ((c = pgetc()) != '\n' && c != PEOF)
11793 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011794 pungetc();
11795 continue;
11796 case '\\':
11797 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011798 startlinno = ++g_parsefile->linno;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011799 setprompt_if(doprompt, 2);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011800 continue;
11801 }
11802 pungetc();
11803 goto breakloop;
11804 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011805 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011806 needprompt = doprompt;
11807 RETURN(TNL);
11808 case PEOF:
11809 RETURN(TEOF);
11810 case '&':
11811 if (pgetc() == '&')
11812 RETURN(TAND);
11813 pungetc();
11814 RETURN(TBACKGND);
11815 case '|':
11816 if (pgetc() == '|')
11817 RETURN(TOR);
11818 pungetc();
11819 RETURN(TPIPE);
11820 case ';':
11821 if (pgetc() == ';')
11822 RETURN(TENDCASE);
11823 pungetc();
11824 RETURN(TSEMI);
11825 case '(':
11826 RETURN(TLP);
11827 case ')':
11828 RETURN(TRP);
11829 default:
11830 goto breakloop;
11831 }
11832 }
11833 breakloop:
11834 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11835#undef RETURN
11836}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011837#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011838
11839static int
11840readtoken(void)
11841{
11842 int t;
11843#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011844 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011845#endif
11846
11847#if ENABLE_ASH_ALIAS
11848 top:
11849#endif
11850
11851 t = xxreadtoken();
11852
11853 /*
11854 * eat newlines
11855 */
11856 if (checkkwd & CHKNL) {
11857 while (t == TNL) {
11858 parseheredoc();
11859 t = xxreadtoken();
11860 }
11861 }
11862
11863 if (t != TWORD || quoteflag) {
11864 goto out;
11865 }
11866
11867 /*
11868 * check for keywords
11869 */
11870 if (checkkwd & CHKKWD) {
11871 const char *const *pp;
11872
11873 pp = findkwd(wordtext);
11874 if (pp) {
11875 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011876 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011877 goto out;
11878 }
11879 }
11880
11881 if (checkkwd & CHKALIAS) {
11882#if ENABLE_ASH_ALIAS
11883 struct alias *ap;
11884 ap = lookupalias(wordtext, 1);
11885 if (ap != NULL) {
11886 if (*ap->val) {
11887 pushstring(ap->val, ap);
11888 }
11889 goto top;
11890 }
11891#endif
11892 }
11893 out:
11894 checkkwd = 0;
11895#if DEBUG
11896 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011897 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011898 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011899 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011900#endif
11901 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011902}
11903
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011904static char
11905peektoken(void)
11906{
11907 int t;
11908
11909 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011910 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011911 return tokname_array[t][0];
11912}
Eric Andersencb57d552001-06-28 07:25:16 +000011913
11914/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011915 * Read and parse a command. Returns NODE_EOF on end of file.
11916 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011917 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011918static union node *
11919parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011920{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011921 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011922
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011923 tokpushback = 0;
11924 doprompt = interact;
Denys Vlasenko958581a2010-09-12 15:04:27 +020011925 setprompt_if(doprompt, doprompt);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011926 needprompt = 0;
11927 t = readtoken();
11928 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011929 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011930 if (t == TNL)
11931 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011932 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011933 return list(1);
11934}
11935
11936/*
11937 * Input any here documents.
11938 */
11939static void
11940parseheredoc(void)
11941{
11942 struct heredoc *here;
11943 union node *n;
11944
11945 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011946 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011947
11948 while (here) {
Denys Vlasenko958581a2010-09-12 15:04:27 +020011949 setprompt_if(needprompt, 2);
11950 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011951 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011952 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011953 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011954 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011955 n->narg.text = wordtext;
11956 n->narg.backquote = backquotelist;
11957 here->here->nhere.doc = n;
11958 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011959 }
Eric Andersencb57d552001-06-28 07:25:16 +000011960}
11961
11962
11963/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011964 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011965 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011966#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011967static const char *
11968expandstr(const char *ps)
11969{
11970 union node n;
11971
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011972 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11973 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011974 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011975 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011976 popfile();
11977
11978 n.narg.type = NARG;
11979 n.narg.next = NULL;
11980 n.narg.text = wordtext;
11981 n.narg.backquote = backquotelist;
11982
11983 expandarg(&n, NULL, 0);
11984 return stackblock();
11985}
11986#endif
11987
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011988/*
11989 * Execute a command or commands contained in a string.
11990 */
11991static int
11992evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011993{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011994 union node *n;
11995 struct stackmark smark;
11996 int skip;
11997
11998 setinputstring(s);
11999 setstackmark(&smark);
12000
12001 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012002 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012003 evaltree(n, 0);
12004 popstackmark(&smark);
12005 skip = evalskip;
12006 if (skip)
12007 break;
12008 }
12009 popfile();
12010
12011 skip &= mask;
12012 evalskip = skip;
12013 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000012014}
12015
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012016/*
12017 * The eval command.
12018 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012019static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012020evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012021{
12022 char *p;
12023 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012024
Denis Vlasenko68404f12008-03-17 09:00:54 +000012025 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012026 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012027 argv += 2;
12028 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012029 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012030 for (;;) {
12031 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012032 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012033 if (p == NULL)
12034 break;
12035 STPUTC(' ', concat);
12036 }
12037 STPUTC('\0', concat);
12038 p = grabstackstr(concat);
12039 }
12040 evalstring(p, ~SKIPEVAL);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012041 }
12042 return exitstatus;
12043}
12044
12045/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010012046 * Read and execute commands.
12047 * "Top" is nonzero for the top level command loop;
12048 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012049 */
12050static int
12051cmdloop(int top)
12052{
12053 union node *n;
12054 struct stackmark smark;
12055 int inter;
12056 int numeof = 0;
12057
12058 TRACE(("cmdloop(%d) called\n", top));
12059 for (;;) {
12060 int skip;
12061
12062 setstackmark(&smark);
12063#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000012064 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012065 showjobs(stderr, SHOW_CHANGED);
12066#endif
12067 inter = 0;
12068 if (iflag && top) {
12069 inter++;
12070#if ENABLE_ASH_MAIL
12071 chkmail();
12072#endif
12073 }
12074 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020012075#if DEBUG
12076 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020012077 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000012078#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020012079 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012080 if (!top || numeof >= 50)
12081 break;
12082 if (!stoppedjobs()) {
12083 if (!Iflag)
12084 break;
12085 out2str("\nUse \"exit\" to leave shell.\n");
12086 }
12087 numeof++;
12088 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000012089 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12090 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012091 numeof = 0;
12092 evaltree(n, 0);
12093 }
12094 popstackmark(&smark);
12095 skip = evalskip;
12096
12097 if (skip) {
12098 evalskip = 0;
12099 return skip & SKIPEVAL;
12100 }
12101 }
12102 return 0;
12103}
12104
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012105/*
12106 * Take commands from a file. To be compatible we should do a path
12107 * search for the file, which is necessary to find sub-commands.
12108 */
12109static char *
12110find_dot_file(char *name)
12111{
12112 char *fullname;
12113 const char *path = pathval();
12114 struct stat statb;
12115
12116 /* don't try this for absolute or relative paths */
12117 if (strchr(name, '/'))
12118 return name;
12119
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012120 /* IIRC standards do not say whether . is to be searched.
12121 * And it is even smaller this way, making it unconditional for now:
12122 */
12123 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12124 fullname = name;
12125 goto try_cur_dir;
12126 }
12127
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012128 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012129 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012130 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12131 /*
12132 * Don't bother freeing here, since it will
12133 * be freed by the caller.
12134 */
12135 return fullname;
12136 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012137 if (fullname != name)
12138 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012139 }
12140
12141 /* not found in the PATH */
12142 ash_msg_and_raise_error("%s: not found", name);
12143 /* NOTREACHED */
12144}
12145
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012146static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012147dotcmd(int argc, char **argv)
12148{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012149 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012150 struct strlist *sp;
12151 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012152
12153 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012154 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012155
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012156 if (!argv[1]) {
12157 /* bash says: "bash: .: filename argument required" */
12158 return 2; /* bash compat */
12159 }
12160
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012161 /* "false; . empty_file; echo $?" should print 0, not 1: */
12162 exitstatus = 0;
12163
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012164 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012165
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012166 argv += 2;
12167 argc -= 2;
12168 if (argc) { /* argc > 0, argv[0] != NULL */
12169 saveparam = shellparam;
12170 shellparam.malloced = 0;
12171 shellparam.nparam = argc;
12172 shellparam.p = argv;
12173 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012174
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012175 setinputfile(fullname, INPUT_PUSH_FILE);
12176 commandname = fullname;
12177 cmdloop(0);
12178 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012179
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012180 if (argc) {
12181 freeparam(&shellparam);
12182 shellparam = saveparam;
12183 };
12184
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012185 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012186}
12187
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012188static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012189exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012190{
12191 if (stoppedjobs())
12192 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012193 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012194 exitstatus = number(argv[1]);
12195 raise_exception(EXEXIT);
12196 /* NOTREACHED */
12197}
12198
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012199/*
12200 * Read a file containing shell functions.
12201 */
12202static void
12203readcmdfile(char *name)
12204{
12205 setinputfile(name, INPUT_PUSH_FILE);
12206 cmdloop(0);
12207 popfile();
12208}
12209
12210
Denis Vlasenkocc571512007-02-23 21:10:35 +000012211/* ============ find_command inplementation */
12212
12213/*
12214 * Resolve a command name. If you change this routine, you may have to
12215 * change the shellexec routine as well.
12216 */
12217static void
12218find_command(char *name, struct cmdentry *entry, int act, const char *path)
12219{
12220 struct tblentry *cmdp;
12221 int idx;
12222 int prev;
12223 char *fullname;
12224 struct stat statb;
12225 int e;
12226 int updatetbl;
12227 struct builtincmd *bcmd;
12228
12229 /* If name contains a slash, don't use PATH or hash table */
12230 if (strchr(name, '/') != NULL) {
12231 entry->u.index = -1;
12232 if (act & DO_ABS) {
12233 while (stat(name, &statb) < 0) {
12234#ifdef SYSV
12235 if (errno == EINTR)
12236 continue;
12237#endif
12238 entry->cmdtype = CMDUNKNOWN;
12239 return;
12240 }
12241 }
12242 entry->cmdtype = CMDNORMAL;
12243 return;
12244 }
12245
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012246/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012247
12248 updatetbl = (path == pathval());
12249 if (!updatetbl) {
12250 act |= DO_ALTPATH;
12251 if (strstr(path, "%builtin") != NULL)
12252 act |= DO_ALTBLTIN;
12253 }
12254
12255 /* If name is in the table, check answer will be ok */
12256 cmdp = cmdlookup(name, 0);
12257 if (cmdp != NULL) {
12258 int bit;
12259
12260 switch (cmdp->cmdtype) {
12261 default:
12262#if DEBUG
12263 abort();
12264#endif
12265 case CMDNORMAL:
12266 bit = DO_ALTPATH;
12267 break;
12268 case CMDFUNCTION:
12269 bit = DO_NOFUNC;
12270 break;
12271 case CMDBUILTIN:
12272 bit = DO_ALTBLTIN;
12273 break;
12274 }
12275 if (act & bit) {
12276 updatetbl = 0;
12277 cmdp = NULL;
12278 } else if (cmdp->rehash == 0)
12279 /* if not invalidated by cd, we're done */
12280 goto success;
12281 }
12282
12283 /* If %builtin not in path, check for builtin next */
12284 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012285 if (bcmd) {
12286 if (IS_BUILTIN_REGULAR(bcmd))
12287 goto builtin_success;
12288 if (act & DO_ALTPATH) {
12289 if (!(act & DO_ALTBLTIN))
12290 goto builtin_success;
12291 } else if (builtinloc <= 0) {
12292 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012293 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012294 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012295
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012296#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012297 {
12298 int applet_no = find_applet_by_name(name);
12299 if (applet_no >= 0) {
12300 entry->cmdtype = CMDNORMAL;
12301 entry->u.index = -2 - applet_no;
12302 return;
12303 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012304 }
12305#endif
12306
Denis Vlasenkocc571512007-02-23 21:10:35 +000012307 /* We have to search path. */
12308 prev = -1; /* where to start */
12309 if (cmdp && cmdp->rehash) { /* doing a rehash */
12310 if (cmdp->cmdtype == CMDBUILTIN)
12311 prev = builtinloc;
12312 else
12313 prev = cmdp->param.index;
12314 }
12315
12316 e = ENOENT;
12317 idx = -1;
12318 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012319 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012320 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012321 /* NB: code below will still use fullname
12322 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012323 idx++;
12324 if (pathopt) {
12325 if (prefix(pathopt, "builtin")) {
12326 if (bcmd)
12327 goto builtin_success;
12328 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012329 }
12330 if ((act & DO_NOFUNC)
12331 || !prefix(pathopt, "func")
12332 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012333 continue;
12334 }
12335 }
12336 /* if rehash, don't redo absolute path names */
12337 if (fullname[0] == '/' && idx <= prev) {
12338 if (idx < prev)
12339 continue;
12340 TRACE(("searchexec \"%s\": no change\n", name));
12341 goto success;
12342 }
12343 while (stat(fullname, &statb) < 0) {
12344#ifdef SYSV
12345 if (errno == EINTR)
12346 continue;
12347#endif
12348 if (errno != ENOENT && errno != ENOTDIR)
12349 e = errno;
12350 goto loop;
12351 }
12352 e = EACCES; /* if we fail, this will be the error */
12353 if (!S_ISREG(statb.st_mode))
12354 continue;
12355 if (pathopt) { /* this is a %func directory */
12356 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012357 /* NB: stalloc will return space pointed by fullname
12358 * (because we don't have any intervening allocations
12359 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012360 readcmdfile(fullname);
12361 cmdp = cmdlookup(name, 0);
12362 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12363 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12364 stunalloc(fullname);
12365 goto success;
12366 }
12367 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12368 if (!updatetbl) {
12369 entry->cmdtype = CMDNORMAL;
12370 entry->u.index = idx;
12371 return;
12372 }
12373 INT_OFF;
12374 cmdp = cmdlookup(name, 1);
12375 cmdp->cmdtype = CMDNORMAL;
12376 cmdp->param.index = idx;
12377 INT_ON;
12378 goto success;
12379 }
12380
12381 /* We failed. If there was an entry for this command, delete it */
12382 if (cmdp && updatetbl)
12383 delete_cmd_entry();
12384 if (act & DO_ERR)
12385 ash_msg("%s: %s", name, errmsg(e, "not found"));
12386 entry->cmdtype = CMDUNKNOWN;
12387 return;
12388
12389 builtin_success:
12390 if (!updatetbl) {
12391 entry->cmdtype = CMDBUILTIN;
12392 entry->u.cmd = bcmd;
12393 return;
12394 }
12395 INT_OFF;
12396 cmdp = cmdlookup(name, 1);
12397 cmdp->cmdtype = CMDBUILTIN;
12398 cmdp->param.cmd = bcmd;
12399 INT_ON;
12400 success:
12401 cmdp->rehash = 0;
12402 entry->cmdtype = cmdp->cmdtype;
12403 entry->u = cmdp->param;
12404}
12405
12406
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012407/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012408
Eric Andersencb57d552001-06-28 07:25:16 +000012409/*
Eric Andersencb57d552001-06-28 07:25:16 +000012410 * The trap builtin.
12411 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012412static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012413trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012414{
12415 char *action;
12416 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012417 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012418
Eric Andersenc470f442003-07-28 09:56:35 +000012419 nextopt(nullstr);
12420 ap = argptr;
12421 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012422 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012423 char *tr = trap_ptr[signo];
12424 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012425 /* note: bash adds "SIG", but only if invoked
12426 * as "bash". If called as "sh", or if set -o posix,
12427 * then it prints short signal names.
12428 * We are printing short names: */
12429 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012430 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012431 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012432 /* trap_ptr != trap only if we are in special-cased `trap` code.
12433 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012434 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012435 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012436 }
12437 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012438 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012439 if (trap_ptr != trap) {
12440 free(trap_ptr);
12441 trap_ptr = trap;
12442 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012443 */
Eric Andersencb57d552001-06-28 07:25:16 +000012444 return 0;
12445 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012446
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012447 action = NULL;
12448 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012449 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012450 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012451 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012452 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012453 if (signo < 0) {
12454 /* Mimic bash message exactly */
12455 ash_msg("%s: invalid signal specification", *ap);
12456 exitcode = 1;
12457 goto next;
12458 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012459 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012460 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012461 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012462 action = NULL;
12463 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012464 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012465 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012466 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012467 if (action)
12468 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012469 trap[signo] = action;
12470 if (signo != 0)
12471 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012472 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012473 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012474 ap++;
12475 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012476 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012477}
12478
Eric Andersenc470f442003-07-28 09:56:35 +000012479
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012480/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012481
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012482#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012483/*
12484 * Lists available builtins
12485 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012486static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012487helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012488{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012489 unsigned col;
12490 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012491
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012492 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012493 "Built-in commands:\n"
12494 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012495 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012496 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012497 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012498 if (col > 60) {
12499 out1fmt("\n");
12500 col = 0;
12501 }
12502 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012503#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012504 {
12505 const char *a = applet_names;
12506 while (*a) {
12507 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12508 if (col > 60) {
12509 out1fmt("\n");
12510 col = 0;
12511 }
12512 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012513 }
12514 }
12515#endif
12516 out1fmt("\n\n");
12517 return EXIT_SUCCESS;
12518}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012519#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012520
Eric Andersencb57d552001-06-28 07:25:16 +000012521/*
Eric Andersencb57d552001-06-28 07:25:16 +000012522 * The export and readonly commands.
12523 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012524static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012525exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012526{
12527 struct var *vp;
12528 char *name;
12529 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012530 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012531 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012532
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012533 if (nextopt("p") != 'p') {
12534 aptr = argptr;
12535 name = *aptr;
12536 if (name) {
12537 do {
12538 p = strchr(name, '=');
12539 if (p != NULL) {
12540 p++;
12541 } else {
12542 vp = *findvar(hashvar(name), name);
12543 if (vp) {
12544 vp->flags |= flag;
12545 continue;
12546 }
Eric Andersencb57d552001-06-28 07:25:16 +000012547 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012548 setvar(name, p, flag);
12549 } while ((name = *++aptr) != NULL);
12550 return 0;
12551 }
Eric Andersencb57d552001-06-28 07:25:16 +000012552 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012553 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012554 return 0;
12555}
12556
Eric Andersencb57d552001-06-28 07:25:16 +000012557/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012558 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012559 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012560static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012561unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012562{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012563 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012564
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012565 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012566 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012567 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012568}
12569
Eric Andersencb57d552001-06-28 07:25:16 +000012570/*
Eric Andersencb57d552001-06-28 07:25:16 +000012571 * The unset builtin command. We unset the function before we unset the
12572 * variable to allow a function to be unset when there is a readonly variable
12573 * with the same name.
12574 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012575static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012576unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012577{
12578 char **ap;
12579 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012580 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012581 int ret = 0;
12582
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012583 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012584 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012585 }
Eric Andersencb57d552001-06-28 07:25:16 +000012586
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012587 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012588 if (flag != 'f') {
12589 i = unsetvar(*ap);
12590 ret |= i;
12591 if (!(i & 2))
12592 continue;
12593 }
12594 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012595 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012596 }
Eric Andersenc470f442003-07-28 09:56:35 +000012597 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012598}
12599
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012600static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012601 ' ', offsetof(struct tms, tms_utime),
12602 '\n', offsetof(struct tms, tms_stime),
12603 ' ', offsetof(struct tms, tms_cutime),
12604 '\n', offsetof(struct tms, tms_cstime),
12605 0
12606};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012607static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012608timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012609{
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012610 unsigned long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012611 const unsigned char *p;
12612 struct tms buf;
12613
12614 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012615 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012616
12617 p = timescmd_str;
12618 do {
12619 t = *(clock_t *)(((char *) &buf) + p[1]);
12620 s = t / clk_tck;
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012621 t = t % clk_tck;
12622 out1fmt("%lum%lu.%03lus%c",
12623 s / 60, s % 60,
12624 (t * 1000) / clk_tck,
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012625 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012626 p += 2;
12627 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012628
Eric Andersencb57d552001-06-28 07:25:16 +000012629 return 0;
12630}
12631
Mike Frysinger98c52642009-04-02 10:02:37 +000012632#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012633/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012634 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012635 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012636 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012637 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012638 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012639static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012640letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012641{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012642 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012643
Denis Vlasenko68404f12008-03-17 09:00:54 +000012644 argv++;
12645 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012646 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012647 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012648 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012649 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012650
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012651 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012652}
Eric Andersenc470f442003-07-28 09:56:35 +000012653#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012654
Eric Andersenc470f442003-07-28 09:56:35 +000012655/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012656 * The read builtin. Options:
12657 * -r Do not interpret '\' specially
12658 * -s Turn off echo (tty only)
12659 * -n NCHARS Read NCHARS max
12660 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12661 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12662 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012663 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012664 * TODO: bash also has:
12665 * -a ARRAY Read into array[0],[1],etc
12666 * -d DELIM End on DELIM char, not newline
12667 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012668 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012669static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012670readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012671{
Denys Vlasenko73067272010-01-12 22:11:24 +010012672 char *opt_n = NULL;
12673 char *opt_p = NULL;
12674 char *opt_t = NULL;
12675 char *opt_u = NULL;
12676 int read_flags = 0;
12677 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012678 int i;
12679
Denys Vlasenko73067272010-01-12 22:11:24 +010012680 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012681 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012682 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012683 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012684 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012685 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012686 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012687 break;
12688 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012689 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012690 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012691 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012692 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012693 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012694 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012695 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012696 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012697 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012698 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012699 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012700 default:
12701 break;
12702 }
Eric Andersenc470f442003-07-28 09:56:35 +000012703 }
Paul Fox02eb9342005-09-07 16:56:02 +000012704
Denys Vlasenko03dad222010-01-12 23:29:57 +010012705 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012706 argptr,
12707 bltinlookup("IFS"), /* can be NULL */
12708 read_flags,
12709 opt_n,
12710 opt_p,
12711 opt_t,
12712 opt_u
12713 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012714
Denys Vlasenko73067272010-01-12 22:11:24 +010012715 if ((uintptr_t)r > 1)
12716 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012717
Denys Vlasenko73067272010-01-12 22:11:24 +010012718 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012719}
12720
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012721static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012722umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012723{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012724 static const char permuser[3] ALIGN1 = "ugo";
12725 static const char permmode[3] ALIGN1 = "rwx";
12726 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012727 S_IRUSR, S_IWUSR, S_IXUSR,
12728 S_IRGRP, S_IWGRP, S_IXGRP,
12729 S_IROTH, S_IWOTH, S_IXOTH
12730 };
12731
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012732 /* TODO: use bb_parse_mode() instead */
12733
Eric Andersenc470f442003-07-28 09:56:35 +000012734 char *ap;
12735 mode_t mask;
12736 int i;
12737 int symbolic_mode = 0;
12738
12739 while (nextopt("S") != '\0') {
12740 symbolic_mode = 1;
12741 }
12742
Denis Vlasenkob012b102007-02-19 22:43:01 +000012743 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012744 mask = umask(0);
12745 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012746 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012747
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012748 ap = *argptr;
12749 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012750 if (symbolic_mode) {
12751 char buf[18];
12752 char *p = buf;
12753
12754 for (i = 0; i < 3; i++) {
12755 int j;
12756
12757 *p++ = permuser[i];
12758 *p++ = '=';
12759 for (j = 0; j < 3; j++) {
12760 if ((mask & permmask[3 * i + j]) == 0) {
12761 *p++ = permmode[j];
12762 }
12763 }
12764 *p++ = ',';
12765 }
12766 *--p = 0;
12767 puts(buf);
12768 } else {
12769 out1fmt("%.4o\n", mask);
12770 }
12771 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012772 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012773 mask = 0;
12774 do {
12775 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012776 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012777 mask = (mask << 3) + (*ap - '0');
12778 } while (*++ap != '\0');
12779 umask(mask);
12780 } else {
12781 mask = ~mask & 0777;
12782 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012783 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012784 }
12785 umask(~mask & 0777);
12786 }
12787 }
12788 return 0;
12789}
12790
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012791static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012792ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012793{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012794 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012795}
12796
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012797/* ============ main() and helpers */
12798
12799/*
12800 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012801 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012802static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012803static void
12804exitshell(void)
12805{
12806 struct jmploc loc;
12807 char *p;
12808 int status;
12809
12810 status = exitstatus;
12811 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12812 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012813 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012814/* dash bug: it just does _exit(exitstatus) here
12815 * but we have to do setjobctl(0) first!
12816 * (bug is still not fixed in dash-0.5.3 - if you run dash
12817 * under Midnight Commander, on exit from dash MC is backgrounded) */
12818 status = exitstatus;
12819 goto out;
12820 }
12821 exception_handler = &loc;
12822 p = trap[0];
12823 if (p) {
12824 trap[0] = NULL;
12825 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012826 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012827 }
12828 flush_stdout_stderr();
12829 out:
12830 setjobctl(0);
12831 _exit(status);
12832 /* NOTREACHED */
12833}
12834
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012835static void
12836init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012837{
12838 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012839 /* we will never free this */
12840 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012841
12842 /* from trap.c: */
12843 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012844 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12845 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12846 */
12847 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012848
12849 /* from var.c: */
12850 {
12851 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012852 const char *p;
12853 struct stat st1, st2;
12854
12855 initvar();
12856 for (envp = environ; envp && *envp; envp++) {
12857 if (strchr(*envp, '=')) {
12858 setvareq(*envp, VEXPORT|VTEXTFIXED);
12859 }
12860 }
12861
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012862 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012863
12864 p = lookupvar("PWD");
12865 if (p)
12866 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12867 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12868 p = '\0';
12869 setpwd(p, 0);
12870 }
12871}
12872
12873/*
12874 * Process the shell command line arguments.
12875 */
12876static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012877procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012878{
12879 int i;
12880 const char *xminusc;
12881 char **xargv;
12882
12883 xargv = argv;
12884 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012885 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012886 xargv++;
12887 for (i = 0; i < NOPTS; i++)
12888 optlist[i] = 2;
12889 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012890 if (options(1)) {
12891 /* it already printed err message */
12892 raise_exception(EXERROR);
12893 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012894 xargv = argptr;
12895 xminusc = minusc;
12896 if (*xargv == NULL) {
12897 if (xminusc)
12898 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12899 sflag = 1;
12900 }
12901 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12902 iflag = 1;
12903 if (mflag == 2)
12904 mflag = iflag;
12905 for (i = 0; i < NOPTS; i++)
12906 if (optlist[i] == 2)
12907 optlist[i] = 0;
12908#if DEBUG == 2
12909 debug = 1;
12910#endif
12911 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12912 if (xminusc) {
12913 minusc = *xargv++;
12914 if (*xargv)
12915 goto setarg0;
12916 } else if (!sflag) {
12917 setinputfile(*xargv, 0);
12918 setarg0:
12919 arg0 = *xargv++;
12920 commandname = arg0;
12921 }
12922
12923 shellparam.p = xargv;
12924#if ENABLE_ASH_GETOPTS
12925 shellparam.optind = 1;
12926 shellparam.optoff = -1;
12927#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012928 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012929 while (*xargv) {
12930 shellparam.nparam++;
12931 xargv++;
12932 }
12933 optschanged();
12934}
12935
12936/*
12937 * Read /etc/profile or .profile.
12938 */
12939static void
12940read_profile(const char *name)
12941{
12942 int skip;
12943
12944 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12945 return;
12946 skip = cmdloop(0);
12947 popfile();
12948 if (skip)
12949 exitshell();
12950}
12951
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012952/*
12953 * This routine is called when an error or an interrupt occurs in an
12954 * interactive shell and control is returned to the main command loop.
12955 */
12956static void
12957reset(void)
12958{
12959 /* from eval.c: */
12960 evalskip = 0;
12961 loopnest = 0;
12962 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012963 g_parsefile->left_in_buffer = 0;
12964 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012965 popallfiles();
12966 /* from parser.c: */
12967 tokpushback = 0;
12968 checkkwd = 0;
12969 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012970 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012971}
12972
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012973#if PROFILE
12974static short profile_buf[16384];
12975extern int etext();
12976#endif
12977
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012978/*
12979 * Main routine. We initialize things, parse the arguments, execute
12980 * profiles if we're a login shell, and then call cmdloop to execute
12981 * commands. The setjmp call sets up the location to jump to when an
12982 * exception occurs. When an exception occurs the variable "state"
12983 * is used to figure out how far we had gotten.
12984 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012985int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012986int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012987{
Mike Frysinger98c52642009-04-02 10:02:37 +000012988 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012989 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012990 struct jmploc jmploc;
12991 struct stackmark smark;
12992
Denis Vlasenko01631112007-12-16 17:20:38 +000012993 /* Initialize global data */
12994 INIT_G_misc();
12995 INIT_G_memstack();
12996 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012997#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012998 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012999#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013000 INIT_G_cmdtable();
13001
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013002#if PROFILE
13003 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13004#endif
13005
13006#if ENABLE_FEATURE_EDITING
13007 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13008#endif
13009 state = 0;
13010 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013011 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013012 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013013
13014 reset();
13015
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013016 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013017 if (e == EXERROR)
13018 exitstatus = 2;
13019 s = state;
13020 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13021 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013022 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013023 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013024
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013025 popstackmark(&smark);
13026 FORCE_INT_ON; /* enable interrupts */
13027 if (s == 1)
13028 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013029 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013030 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013031 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013032 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013033 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013034 }
13035 exception_handler = &jmploc;
13036#if DEBUG
13037 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013038 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013039 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013040#endif
13041 rootpid = getpid();
13042
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013043 init();
13044 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013045 procargs(argv);
13046
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013047#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13048 if (iflag) {
13049 const char *hp = lookupvar("HISTFILE");
13050
13051 if (hp == NULL) {
13052 hp = lookupvar("HOME");
13053 if (hp != NULL) {
13054 char *defhp = concat_path_file(hp, ".ash_history");
13055 setvar("HISTFILE", defhp, 0);
13056 free(defhp);
13057 }
13058 }
13059 }
13060#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013061 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013062 isloginsh = 1;
13063 if (isloginsh) {
13064 state = 1;
13065 read_profile("/etc/profile");
13066 state1:
13067 state = 2;
13068 read_profile(".profile");
13069 }
13070 state2:
13071 state = 3;
13072 if (
13073#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013074 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013075#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013076 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013077 ) {
13078 shinit = lookupvar("ENV");
13079 if (shinit != NULL && *shinit != '\0') {
13080 read_profile(shinit);
13081 }
13082 }
13083 state3:
13084 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013085 if (minusc) {
13086 /* evalstring pushes parsefile stack.
13087 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013088 * is one of stacked source fds.
13089 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020013090 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020013091 // ^^ not necessary since now we special-case fd 0
13092 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013093 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013094 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013095
13096 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013097#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013098 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013099 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013100 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013101 line_input_state->hist_file = hp;
13102 }
13103#endif
13104 state4: /* XXX ??? - why isn't this before the "if" statement */
13105 cmdloop(1);
13106 }
13107#if PROFILE
13108 monitor(0);
13109#endif
13110#ifdef GPROF
13111 {
13112 extern void _mcleanup(void);
13113 _mcleanup();
13114 }
13115#endif
13116 exitshell();
13117 /* NOTREACHED */
13118}
13119
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013120
Eric Andersendf82f612001-06-28 07:46:40 +000013121/*-
13122 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013123 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013124 *
13125 * This code is derived from software contributed to Berkeley by
13126 * Kenneth Almquist.
13127 *
13128 * Redistribution and use in source and binary forms, with or without
13129 * modification, are permitted provided that the following conditions
13130 * are met:
13131 * 1. Redistributions of source code must retain the above copyright
13132 * notice, this list of conditions and the following disclaimer.
13133 * 2. Redistributions in binary form must reproduce the above copyright
13134 * notice, this list of conditions and the following disclaimer in the
13135 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013136 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013137 * may be used to endorse or promote products derived from this software
13138 * without specific prior written permission.
13139 *
13140 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13141 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13142 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13143 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13144 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13145 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13146 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13147 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13148 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13149 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13150 * SUCH DAMAGE.
13151 */