1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * 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.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
43 #include <sys/times.h>
44 #include <sys/utsname.h> /* for setting $HOSTNAME */
46 #include "busybox.h" /* for applet_names */
49 #include "shell_common.h"
50 #if ENABLE_SH_MATH_SUPPORT
53 #if ENABLE_ASH_RANDOM_SUPPORT
56 # define CLEAR_RANDOM_T(rnd) ((void)0)
59 #include "NUM_APPLETS.h"
61 /* STANDALONE does not make sense, and won't compile */
62 # undef CONFIG_FEATURE_SH_STANDALONE
63 # undef ENABLE_FEATURE_SH_STANDALONE
64 # undef IF_FEATURE_SH_STANDALONE
65 # undef IF_NOT_FEATURE_SH_STANDALONE
66 # define ENABLE_FEATURE_SH_STANDALONE 0
67 # define IF_FEATURE_SH_STANDALONE(...)
68 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
72 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
76 # error "Do not even bother, ash will not run on NOMMU machine"
82 //config: depends on !NOMMU
84 //config: Tha 'ash' shell adds about 60k in the default configuration and is
85 //config: the most complete and most pedantically correct shell included with
86 //config: busybox. This shell is actually a derivative of the Debian 'dash'
87 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
88 //config: (written by Kenneth Almquist) from NetBSD.
90 //config:config ASH_BASH_COMPAT
91 //config: bool "bash-compatible extensions"
93 //config: depends on ASH
95 //config: Enable bash-compatible extensions.
97 //config:config ASH_IDLE_TIMEOUT
98 //config: bool "Idle timeout variable"
100 //config: depends on ASH
102 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
104 //config:config ASH_JOB_CONTROL
105 //config: bool "Job control"
107 //config: depends on ASH
109 //config: Enable job control in the ash shell.
111 //config:config ASH_ALIAS
112 //config: bool "Alias support"
114 //config: depends on ASH
116 //config: Enable alias support in the ash shell.
118 //config:config ASH_GETOPTS
119 //config: bool "Builtin getopt to parse positional parameters"
121 //config: depends on ASH
123 //config: Enable support for getopts builtin in ash.
125 //config:config ASH_BUILTIN_ECHO
126 //config: bool "Builtin version of 'echo'"
128 //config: depends on ASH
130 //config: Enable support for echo builtin in ash.
132 //config:config ASH_BUILTIN_PRINTF
133 //config: bool "Builtin version of 'printf'"
135 //config: depends on ASH
137 //config: Enable support for printf builtin in ash.
139 //config:config ASH_BUILTIN_TEST
140 //config: bool "Builtin version of 'test'"
142 //config: depends on ASH
144 //config: Enable support for test builtin in ash.
146 //config:config ASH_HELP
147 //config: bool "help builtin"
149 //config: depends on ASH
151 //config: Enable help builtin in ash.
153 //config:config ASH_CMDCMD
154 //config: bool "'command' command to override shell builtins"
156 //config: depends on ASH
158 //config: Enable support for the ash 'command' builtin, which allows
159 //config: you to run the specified command with the specified arguments,
160 //config: even when there is an ash builtin command with the same name.
162 //config:config ASH_MAIL
163 //config: bool "Check for new mail on interactive shells"
165 //config: depends on ASH
167 //config: Enable "check for new mail" function in the ash shell.
169 //config:config ASH_OPTIMIZE_FOR_SIZE
170 //config: bool "Optimize for size instead of speed"
172 //config: depends on ASH
174 //config: Compile ash for reduced size at the price of speed.
176 //config:config ASH_RANDOM_SUPPORT
177 //config: bool "Pseudorandom generator and $RANDOM variable"
179 //config: depends on ASH
181 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
182 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
183 //config: You can reset the generator by using a specified start value.
184 //config: After "unset RANDOM" the generator will switch off and this
185 //config: variable will no longer have special treatment.
187 //config:config ASH_EXPAND_PRMT
188 //config: bool "Expand prompt string"
190 //config: depends on ASH
192 //config: "PS#" may contain volatile content, such as backquote commands.
193 //config: This option recreates the prompt string from the environment
194 //config: variable each time it is displayed.
197 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
198 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
199 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
201 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
202 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
205 /* ============ Hash table sizes. Configurable. */
209 #define CMDTABLESIZE 31 /* should be prime */
212 /* ============ Shell options */
214 static const char *const optletters_optnames[] = {
229 #if ENABLE_ASH_BASH_COMPAT
238 #define optletters(n) optletters_optnames[n][0]
239 #define optnames(n) (optletters_optnames[n] + 1)
241 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
244 /* ============ Misc data */
246 #define msg_illnum "Illegal number: %s"
249 * We enclose jmp_buf in a structure so that we can declare pointers to
250 * jump locations. The global variable handler contains the location to
251 * jump to when an exception occurs, and the global variable exception_type
252 * contains a code identifying the exception. To implement nested
253 * exception handlers, the user should save the value of handler on entry
254 * to an inner scope, set handler to point to a jmploc structure for the
255 * inner scope, and restore handler on exit from the scope.
261 struct globals_misc {
262 /* pid of main shell */
264 /* shell level: 0 for the main shell, 1 for its children, and so on */
266 #define rootshell (!shlvl)
267 char *minusc; /* argument to -c option */
269 char *curdir; // = nullstr; /* current working directory */
270 char *physdir; // = nullstr; /* physical working directory */
272 char *arg0; /* value of $0 */
274 struct jmploc *exception_handler;
276 volatile int suppress_int; /* counter */
277 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
278 /* last pending signal */
279 volatile /*sig_atomic_t*/ smallint pending_sig;
280 smallint exception_type; /* kind of exception (0..5) */
282 #define EXINT 0 /* SIGINT received */
283 #define EXERROR 1 /* a generic error */
284 #define EXSHELLPROC 2 /* execute a shell procedure */
285 #define EXEXEC 3 /* command execution failed */
286 #define EXEXIT 4 /* exit the shell */
287 #define EXSIG 5 /* trapped signal in wait(1) */
290 char nullstr[1]; /* zero length string */
293 #define eflag optlist[0]
294 #define fflag optlist[1]
295 #define Iflag optlist[2]
296 #define iflag optlist[3]
297 #define mflag optlist[4]
298 #define nflag optlist[5]
299 #define sflag optlist[6]
300 #define xflag optlist[7]
301 #define vflag optlist[8]
302 #define Cflag optlist[9]
303 #define aflag optlist[10]
304 #define bflag optlist[11]
305 #define uflag optlist[12]
306 #define viflag optlist[13]
307 #if ENABLE_ASH_BASH_COMPAT
308 # define pipefail optlist[14]
313 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
314 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
317 /* trap handler commands */
319 * Sigmode records the current value of the signal handlers for the various
320 * modes. A value of zero means that the current handler is not known.
321 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
323 char sigmode[NSIG - 1];
324 #define S_DFL 1 /* default signal handling (SIG_DFL) */
325 #define S_CATCH 2 /* signal is caught */
326 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
327 #define S_HARD_IGN 4 /* signal is ignored permenantly */
329 /* indicates specified signal received */
330 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
331 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
333 char **trap_ptr; /* used only by "trap hack" */
335 /* Rarely referenced stuff */
336 #if ENABLE_ASH_RANDOM_SUPPORT
339 pid_t backgndpid; /* pid of last background process */
340 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
342 extern struct globals_misc *const ash_ptr_to_globals_misc;
343 #define G_misc (*ash_ptr_to_globals_misc)
344 #define rootpid (G_misc.rootpid )
345 #define shlvl (G_misc.shlvl )
346 #define minusc (G_misc.minusc )
347 #define curdir (G_misc.curdir )
348 #define physdir (G_misc.physdir )
349 #define arg0 (G_misc.arg0 )
350 #define exception_handler (G_misc.exception_handler)
351 #define exception_type (G_misc.exception_type )
352 #define suppress_int (G_misc.suppress_int )
353 #define pending_int (G_misc.pending_int )
354 #define pending_sig (G_misc.pending_sig )
355 #define isloginsh (G_misc.isloginsh )
356 #define nullstr (G_misc.nullstr )
357 #define optlist (G_misc.optlist )
358 #define sigmode (G_misc.sigmode )
359 #define gotsig (G_misc.gotsig )
360 #define may_have_traps (G_misc.may_have_traps )
361 #define trap (G_misc.trap )
362 #define trap_ptr (G_misc.trap_ptr )
363 #define random_gen (G_misc.random_gen )
364 #define backgndpid (G_misc.backgndpid )
365 #define job_warning (G_misc.job_warning)
366 #define INIT_G_misc() do { \
367 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
375 /* ============ DEBUG */
377 static void trace_printf(const char *fmt, ...);
378 static void trace_vprintf(const char *fmt, va_list va);
379 # define TRACE(param) trace_printf param
380 # define TRACEV(param) trace_vprintf param
381 # define close(fd) do { \
383 if (close(dfd) < 0) \
384 bb_error_msg("bug on %d: closing %d(0x%x)", \
385 __LINE__, dfd, dfd); \
388 # define TRACE(param)
389 # define TRACEV(param)
393 /* ============ Utility functions */
394 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
396 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
397 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
399 static int isdigit_str9(const char *str)
401 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
402 while (--maxlen && isdigit(*str))
404 return (*str == '\0');
407 static const char *var_end(const char *var)
416 /* ============ Interrupts / exceptions */
418 static void exitshell(void) NORETURN;
421 * These macros allow the user to suspend the handling of interrupt signals
422 * over a period of time. This is similar to SIGHOLD or to sigblock, but
423 * much more efficient and portable. (But hacking the kernel is so much
424 * more fun than worrying about efficiency and portability. :-))
426 #define INT_OFF do { \
432 * Called to raise an exception. Since C doesn't include exceptions, we
433 * just do a longjmp to the exception handler. The type of exception is
434 * stored in the global variable "exception_type".
436 static void raise_exception(int) NORETURN;
438 raise_exception(int e)
441 if (exception_handler == NULL)
446 longjmp(exception_handler->loc, 1);
449 #define raise_exception(e) do { \
450 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
451 raise_exception(e); \
456 * Called from trap.c when a SIGINT is received. (If the user specifies
457 * that SIGINT is to be trapped or ignored using the trap builtin, then
458 * this routine is not called.) Suppressint is nonzero when interrupts
459 * are held using the INT_OFF macro. (The test for iflag is just
460 * defensive programming.)
462 static void raise_interrupt(void) NORETURN;
464 raise_interrupt(void)
469 /* Signal is not automatically unmasked after it is raised,
470 * do it ourself - unmask all signals */
471 sigprocmask_allsigs(SIG_UNBLOCK);
472 /* pending_sig = 0; - now done in signal_handler() */
475 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
476 if (!(rootshell && iflag)) {
477 /* Kill ourself with SIGINT */
478 signal(SIGINT, SIG_DFL);
483 raise_exception(ex_type);
487 #define raise_interrupt() do { \
488 TRACE(("raising interrupt on line %d\n", __LINE__)); \
493 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
497 if (--suppress_int == 0 && pending_int) {
501 #define INT_ON int_on()
502 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
510 #define FORCE_INT_ON force_int_on()
512 #define SAVE_INT(v) ((v) = suppress_int)
514 #define RESTORE_INT(v) do { \
516 suppress_int = (v); \
517 if (suppress_int == 0 && pending_int) \
522 /* ============ Stdout/stderr output */
525 outstr(const char *p, FILE *file)
533 flush_stdout_stderr(void)
541 outcslow(int c, FILE *dest)
549 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
551 out1fmt(const char *fmt, ...)
558 r = vprintf(fmt, ap);
564 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
566 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
573 ret = vsnprintf(outbuf, length, fmt, ap);
580 out1str(const char *p)
586 out2str(const char *p)
589 flush_stdout_stderr();
593 /* ============ Parser structures */
595 /* control characters in argument strings */
596 #define CTL_FIRST CTLESC
597 #define CTLESC ((unsigned char)'\201') /* escape next character */
598 #define CTLVAR ((unsigned char)'\202') /* variable defn */
599 #define CTLENDVAR ((unsigned char)'\203')
600 #define CTLBACKQ ((unsigned char)'\204')
601 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
602 #define CTLENDARI ((unsigned char)'\207')
603 #define CTLQUOTEMARK ((unsigned char)'\210')
604 #define CTL_LAST CTLQUOTEMARK
606 /* variable substitution byte (follows CTLVAR) */
607 #define VSTYPE 0x0f /* type of variable substitution */
608 #define VSNUL 0x10 /* colon--treat the empty string as unset */
610 /* values of VSTYPE field */
611 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
612 #define VSMINUS 0x2 /* ${var-text} */
613 #define VSPLUS 0x3 /* ${var+text} */
614 #define VSQUESTION 0x4 /* ${var?message} */
615 #define VSASSIGN 0x5 /* ${var=text} */
616 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
617 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
618 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
619 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
620 #define VSLENGTH 0xa /* ${#var} */
621 #if ENABLE_ASH_BASH_COMPAT
622 #define VSSUBSTR 0xc /* ${var:position:length} */
623 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
624 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
627 static const char dolatstr[] ALIGN1 = {
628 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
630 #define DOLATSTRLEN 6
649 #if ENABLE_ASH_BASH_COMPAT
666 smallint type; /* Nxxxx */
669 union node *redirect;
674 smallint pipe_backgnd;
675 struct nodelist *cmdlist;
681 union node *redirect;
694 union node *elsepart;
721 struct nodelist *backquote;
724 /* nfile and ndup layout must match!
725 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
726 * that it is actually NTO2 (>&file), and change its type.
743 char *_unused_expfname;
762 struct nredir nredir;
763 struct nbinary nbinary;
767 struct nclist nclist;
776 * NODE_EOF is returned by parsecmd when it encounters an end of file.
777 * It must be distinct from NULL.
779 #define NODE_EOF ((union node *) -1L)
782 struct nodelist *next;
795 freefunc(struct funcnode *f)
797 if (f && --f->count < 0)
802 /* ============ Debugging output */
806 static FILE *tracefile;
809 trace_printf(const char *fmt, ...)
816 fprintf(tracefile, "%u ", (int) time(NULL));
818 fprintf(tracefile, "[%u] ", (int) getpid());
820 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
822 vfprintf(tracefile, fmt, va);
827 trace_vprintf(const char *fmt, va_list va)
832 fprintf(tracefile, "%u ", (int) time(NULL));
834 fprintf(tracefile, "[%u] ", (int) getpid());
836 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
837 vfprintf(tracefile, fmt, va);
841 trace_puts(const char *s)
849 trace_puts_quoted(char *s)
856 putc('"', tracefile);
857 for (p = s; *p; p++) {
858 switch ((unsigned char)*p) {
859 case '\n': c = 'n'; goto backslash;
860 case '\t': c = 't'; goto backslash;
861 case '\r': c = 'r'; goto backslash;
862 case '\"': c = '\"'; goto backslash;
863 case '\\': c = '\\'; goto backslash;
864 case CTLESC: c = 'e'; goto backslash;
865 case CTLVAR: c = 'v'; goto backslash;
866 case CTLBACKQ: c = 'q'; goto backslash;
868 putc('\\', tracefile);
872 if (*p >= ' ' && *p <= '~')
875 putc('\\', tracefile);
876 putc((*p >> 6) & 03, tracefile);
877 putc((*p >> 3) & 07, tracefile);
878 putc(*p & 07, tracefile);
883 putc('"', tracefile);
887 trace_puts_args(char **ap)
894 trace_puts_quoted(*ap);
896 putc('\n', tracefile);
899 putc(' ', tracefile);
914 /* leave open because libedit might be using it */
917 strcpy(s, "./trace");
919 if (!freopen(s, "a", tracefile)) {
920 fprintf(stderr, "Can't re-open %s\n", s);
925 tracefile = fopen(s, "a");
926 if (tracefile == NULL) {
927 fprintf(stderr, "Can't open %s\n", s);
933 flags = fcntl(fileno(tracefile), F_GETFL);
935 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
937 setlinebuf(tracefile);
938 fputs("\nTracing started.\n", tracefile);
942 indent(int amount, char *pfx, FILE *fp)
946 for (i = 0; i < amount; i++) {
947 if (pfx && i == amount - 1)
953 /* little circular references here... */
954 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
957 sharg(union node *arg, FILE *fp)
960 struct nodelist *bqlist;
961 unsigned char subtype;
963 if (arg->type != NARG) {
964 out1fmt("<node type %d>\n", arg->type);
967 bqlist = arg->narg.backquote;
968 for (p = arg->narg.text; *p; p++) {
969 switch ((unsigned char)*p) {
978 if (subtype == VSLENGTH)
989 switch (subtype & VSTYPE) {
1015 case VSTRIMRIGHTMAX:
1022 out1fmt("<subtype %d>", subtype);
1031 shtree(bqlist->n, -1, NULL, fp);
1042 shcmd(union node *cmd, FILE *fp)
1050 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1056 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1060 switch (np->nfile.type) {
1061 case NTO: s = ">>"+1; dftfd = 1; break;
1062 case NCLOBBER: s = ">|"; dftfd = 1; break;
1063 case NAPPEND: s = ">>"; dftfd = 1; break;
1064 #if ENABLE_ASH_BASH_COMPAT
1067 case NTOFD: s = ">&"; dftfd = 1; break;
1068 case NFROM: s = "<"; break;
1069 case NFROMFD: s = "<&"; break;
1070 case NFROMTO: s = "<>"; break;
1071 default: s = "*error*"; break;
1073 if (np->nfile.fd != dftfd)
1074 fprintf(fp, "%d", np->nfile.fd);
1076 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1077 fprintf(fp, "%d", np->ndup.dupfd);
1079 sharg(np->nfile.fname, fp);
1086 shtree(union node *n, int ind, char *pfx, FILE *fp)
1088 struct nodelist *lp;
1094 indent(ind, pfx, fp);
1096 if (n == NODE_EOF) {
1111 shtree(n->nbinary.ch1, ind, NULL, fp);
1114 shtree(n->nbinary.ch2, ind, NULL, fp);
1122 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1123 shtree(lp->n, 0, NULL, fp);
1127 if (n->npipe.pipe_backgnd)
1133 fprintf(fp, "<node type %d>", n->type);
1141 showtree(union node *n)
1143 trace_puts("showtree called\n");
1144 shtree(n, 1, NULL, stderr);
1150 /* ============ Parser data */
1153 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1156 struct strlist *next;
1163 struct strpush *prev; /* preceding string on stack */
1165 int prev_left_in_line;
1166 #if ENABLE_ASH_ALIAS
1167 struct alias *ap; /* if push was associated with an alias */
1169 char *string; /* remember the string since it may change */
1173 struct parsefile *prev; /* preceding file on stack */
1174 int linno; /* current line */
1175 int pf_fd; /* file descriptor (or -1 if string) */
1176 int left_in_line; /* number of chars left in this line */
1177 int left_in_buffer; /* number of chars left in this buffer past the line */
1178 char *next_to_pgetc; /* next char in buffer */
1179 char *buf; /* input buffer */
1180 struct strpush *strpush; /* for pushing strings at this level */
1181 struct strpush basestrpush; /* so pushing one is fast */
1184 static struct parsefile basepf; /* top level input file */
1185 static struct parsefile *g_parsefile = &basepf; /* current input file */
1186 static int startlinno; /* line # where last token started */
1187 static char *commandname; /* currently executing command */
1188 static struct strlist *cmdenviron; /* environment for builtin command */
1189 static uint8_t exitstatus; /* exit status of last command */
1192 /* ============ Message printing */
1195 ash_vmsg(const char *msg, va_list ap)
1197 fprintf(stderr, "%s: ", arg0);
1199 if (strcmp(arg0, commandname))
1200 fprintf(stderr, "%s: ", commandname);
1201 if (!iflag || g_parsefile->pf_fd > 0)
1202 fprintf(stderr, "line %d: ", startlinno);
1204 vfprintf(stderr, msg, ap);
1205 outcslow('\n', stderr);
1209 * Exverror is called to raise the error exception. If the second argument
1210 * is not NULL then error prints an error message using printf style
1211 * formatting. It then raises the error exception.
1213 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1215 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1219 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1221 TRACE(("\") pid=%d\n", getpid()));
1223 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1228 flush_stdout_stderr();
1229 raise_exception(cond);
1233 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1235 ash_msg_and_raise_error(const char *msg, ...)
1240 ash_vmsg_and_raise(EXERROR, msg, ap);
1245 static void raise_error_syntax(const char *) NORETURN;
1247 raise_error_syntax(const char *msg)
1249 ash_msg_and_raise_error("syntax error: %s", msg);
1253 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1255 ash_msg_and_raise(int cond, const char *msg, ...)
1260 ash_vmsg_and_raise(cond, msg, ap);
1266 * error/warning routines for external builtins
1269 ash_msg(const char *fmt, ...)
1279 * Return a string describing an error. The returned string may be a
1280 * pointer to a static buffer that will be overwritten on the next call.
1281 * Action describes the operation that got the error.
1284 errmsg(int e, const char *em)
1286 if (e == ENOENT || e == ENOTDIR) {
1293 /* ============ Memory allocation */
1296 /* I consider these wrappers nearly useless:
1297 * ok, they return you to nearest exception handler, but
1298 * how much memory do you leak in the process, making
1299 * memory starvation worse?
1302 ckrealloc(void * p, size_t nbytes)
1304 p = realloc(p, nbytes);
1306 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1311 ckmalloc(size_t nbytes)
1313 return ckrealloc(NULL, nbytes);
1317 ckzalloc(size_t nbytes)
1319 return memset(ckmalloc(nbytes), 0, nbytes);
1323 ckstrdup(const char *s)
1325 char *p = strdup(s);
1327 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1331 /* Using bbox equivalents. They exit if out of memory */
1332 # define ckrealloc xrealloc
1333 # define ckmalloc xmalloc
1334 # define ckzalloc xzalloc
1335 # define ckstrdup xstrdup
1339 * It appears that grabstackstr() will barf with such alignments
1340 * because stalloc() will return a string allocated in a new stackblock.
1342 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1344 /* Most machines require the value returned from malloc to be aligned
1345 * in some way. The following macro will get this right
1346 * on many machines. */
1347 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1348 /* Minimum size of a block */
1349 MINSIZE = SHELL_ALIGN(504),
1352 struct stack_block {
1353 struct stack_block *prev;
1354 char space[MINSIZE];
1358 struct stack_block *stackp;
1361 struct stackmark *marknext;
1365 struct globals_memstack {
1366 struct stack_block *g_stackp; // = &stackbase;
1367 struct stackmark *markp;
1368 char *g_stacknxt; // = stackbase.space;
1369 char *sstrend; // = stackbase.space + MINSIZE;
1370 size_t g_stacknleft; // = MINSIZE;
1371 int herefd; // = -1;
1372 struct stack_block stackbase;
1374 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1375 #define G_memstack (*ash_ptr_to_globals_memstack)
1376 #define g_stackp (G_memstack.g_stackp )
1377 #define markp (G_memstack.markp )
1378 #define g_stacknxt (G_memstack.g_stacknxt )
1379 #define sstrend (G_memstack.sstrend )
1380 #define g_stacknleft (G_memstack.g_stacknleft)
1381 #define herefd (G_memstack.herefd )
1382 #define stackbase (G_memstack.stackbase )
1383 #define INIT_G_memstack() do { \
1384 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1386 g_stackp = &stackbase; \
1387 g_stacknxt = stackbase.space; \
1388 g_stacknleft = MINSIZE; \
1389 sstrend = stackbase.space + MINSIZE; \
1394 #define stackblock() ((void *)g_stacknxt)
1395 #define stackblocksize() g_stacknleft
1398 * Parse trees for commands are allocated in lifo order, so we use a stack
1399 * to make this more efficient, and also to avoid all sorts of exception
1400 * handling code to handle interrupts in the middle of a parse.
1402 * The size 504 was chosen because the Ultrix malloc handles that size
1406 stalloc(size_t nbytes)
1411 aligned = SHELL_ALIGN(nbytes);
1412 if (aligned > g_stacknleft) {
1415 struct stack_block *sp;
1417 blocksize = aligned;
1418 if (blocksize < MINSIZE)
1419 blocksize = MINSIZE;
1420 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1421 if (len < blocksize)
1422 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1425 sp->prev = g_stackp;
1426 g_stacknxt = sp->space;
1427 g_stacknleft = blocksize;
1428 sstrend = g_stacknxt + blocksize;
1433 g_stacknxt += aligned;
1434 g_stacknleft -= aligned;
1439 stzalloc(size_t nbytes)
1441 return memset(stalloc(nbytes), 0, nbytes);
1448 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1449 write(STDERR_FILENO, "stunalloc\n", 10);
1453 g_stacknleft += g_stacknxt - (char *)p;
1458 * Like strdup but works with the ash stack.
1461 ststrdup(const char *p)
1463 size_t len = strlen(p) + 1;
1464 return memcpy(stalloc(len), p, len);
1468 setstackmark(struct stackmark *mark)
1470 mark->stackp = g_stackp;
1471 mark->stacknxt = g_stacknxt;
1472 mark->stacknleft = g_stacknleft;
1473 mark->marknext = markp;
1478 popstackmark(struct stackmark *mark)
1480 struct stack_block *sp;
1486 markp = mark->marknext;
1487 while (g_stackp != mark->stackp) {
1489 g_stackp = sp->prev;
1492 g_stacknxt = mark->stacknxt;
1493 g_stacknleft = mark->stacknleft;
1494 sstrend = mark->stacknxt + mark->stacknleft;
1499 * When the parser reads in a string, it wants to stick the string on the
1500 * stack and only adjust the stack pointer when it knows how big the
1501 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1502 * of space on top of the stack and stackblocklen returns the length of
1503 * this block. Growstackblock will grow this space by at least one byte,
1504 * possibly moving it (like realloc). Grabstackblock actually allocates the
1505 * part of the block that has been used.
1508 growstackblock(void)
1512 newlen = g_stacknleft * 2;
1513 if (newlen < g_stacknleft)
1514 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1518 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1519 struct stack_block *oldstackp;
1520 struct stackmark *xmark;
1521 struct stack_block *sp;
1522 struct stack_block *prevstackp;
1526 oldstackp = g_stackp;
1528 prevstackp = sp->prev;
1529 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1530 sp = ckrealloc(sp, grosslen);
1531 sp->prev = prevstackp;
1533 g_stacknxt = sp->space;
1534 g_stacknleft = newlen;
1535 sstrend = sp->space + newlen;
1538 * Stack marks pointing to the start of the old block
1539 * must be relocated to point to the new block
1542 while (xmark != NULL && xmark->stackp == oldstackp) {
1543 xmark->stackp = g_stackp;
1544 xmark->stacknxt = g_stacknxt;
1545 xmark->stacknleft = g_stacknleft;
1546 xmark = xmark->marknext;
1550 char *oldspace = g_stacknxt;
1551 size_t oldlen = g_stacknleft;
1552 char *p = stalloc(newlen);
1554 /* free the space we just allocated */
1555 g_stacknxt = memcpy(p, oldspace, oldlen);
1556 g_stacknleft += newlen;
1561 grabstackblock(size_t len)
1563 len = SHELL_ALIGN(len);
1565 g_stacknleft -= len;
1569 * The following routines are somewhat easier to use than the above.
1570 * The user declares a variable of type STACKSTR, which may be declared
1571 * to be a register. The macro STARTSTACKSTR initializes things. Then
1572 * the user uses the macro STPUTC to add characters to the string. In
1573 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1574 * grown as necessary. When the user is done, she can just leave the
1575 * string there and refer to it using stackblock(). Or she can allocate
1576 * the space for it using grabstackstr(). If it is necessary to allow
1577 * someone else to use the stack temporarily and then continue to grow
1578 * the string, the user should use grabstack to allocate the space, and
1579 * then call ungrabstr(p) to return to the previous mode of operation.
1581 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1582 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1583 * is space for at least one character.
1588 size_t len = stackblocksize();
1589 if (herefd >= 0 && len >= 1024) {
1590 full_write(herefd, stackblock(), len);
1591 return stackblock();
1594 return (char *)stackblock() + len;
1598 * Called from CHECKSTRSPACE.
1601 makestrspace(size_t newlen, char *p)
1603 size_t len = p - g_stacknxt;
1604 size_t size = stackblocksize();
1609 size = stackblocksize();
1611 if (nleft >= newlen)
1615 return (char *)stackblock() + len;
1619 stack_nputstr(const char *s, size_t n, char *p)
1621 p = makestrspace(n, p);
1622 p = (char *)memcpy(p, s, n) + n;
1627 stack_putstr(const char *s, char *p)
1629 return stack_nputstr(s, strlen(s), p);
1633 _STPUTC(int c, char *p)
1641 #define STARTSTACKSTR(p) ((p) = stackblock())
1642 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1643 #define CHECKSTRSPACE(n, p) do { \
1646 size_t m = sstrend - q; \
1648 (p) = makestrspace(l, q); \
1650 #define USTPUTC(c, p) (*(p)++ = (c))
1651 #define STACKSTRNUL(p) do { \
1652 if ((p) == sstrend) \
1653 (p) = growstackstr(); \
1656 #define STUNPUTC(p) (--(p))
1657 #define STTOPC(p) ((p)[-1])
1658 #define STADJUST(amount, p) ((p) += (amount))
1660 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1661 #define ungrabstackstr(s, p) stunalloc(s)
1662 #define stackstrend() ((void *)sstrend)
1665 /* ============ String helpers */
1668 * prefix -- see if pfx is a prefix of string.
1671 prefix(const char *string, const char *pfx)
1674 if (*pfx++ != *string++)
1677 return (char *) string;
1681 * Check for a valid number. This should be elsewhere.
1684 is_number(const char *p)
1689 } while (*++p != '\0');
1694 * Convert a string of digits to an integer, printing an error message on
1698 number(const char *s)
1701 ash_msg_and_raise_error(msg_illnum, s);
1706 * Produce a possibly single quoted string suitable as input to the shell.
1707 * The return string is allocated on the stack.
1710 single_quote(const char *s)
1720 len = strchrnul(s, '\'') - s;
1722 q = p = makestrspace(len + 3, p);
1725 q = (char *)memcpy(q, s, len) + len;
1734 do len++; while (*++s == '\'');
1736 q = p = makestrspace(len + 3, p);
1739 q = (char *)memcpy(q, s - len, len) + len;
1747 return stackblock();
1751 /* ============ nextopt */
1753 static char **argptr; /* argument list for builtin commands */
1754 static char *optionarg; /* set by nextopt (like getopt) */
1755 static char *optptr; /* used by nextopt */
1758 * XXX - should get rid of. Have all builtins use getopt(3).
1759 * The library getopt must have the BSD extension static variable
1760 * "optreset", otherwise it can't be used within the shell safely.
1762 * Standard option processing (a la getopt) for builtin routines.
1763 * The only argument that is passed to nextopt is the option string;
1764 * the other arguments are unnecessary. It returns the character,
1765 * or '\0' on end of input.
1768 nextopt(const char *optstring)
1775 if (p == NULL || *p == '\0') {
1776 /* We ate entire "-param", take next one */
1782 if (*++p == '\0') /* just "-" ? */
1785 if (LONE_DASH(p)) /* "--" ? */
1787 /* p => next "-param" */
1789 /* p => some option char in the middle of a "-param" */
1791 for (q = optstring; *q != c;) {
1793 ash_msg_and_raise_error("illegal option -%c", c);
1801 ash_msg_and_raise_error("no arg for -%c option", c);
1811 /* ============ Shell variables */
1814 * The parsefile structure pointed to by the global variable parsefile
1815 * contains information about the current file being read.
1818 int nparam; /* # of positional parameters (without $0) */
1819 #if ENABLE_ASH_GETOPTS
1820 int optind; /* next parameter to be processed by getopts */
1821 int optoff; /* used by getopts */
1823 unsigned char malloced; /* if parameter list dynamically allocated */
1824 char **p; /* parameter list */
1828 * Free the list of positional parameters.
1831 freeparam(volatile struct shparam *param)
1833 if (param->malloced) {
1835 ap = ap1 = param->p;
1842 #if ENABLE_ASH_GETOPTS
1843 static void FAST_FUNC getoptsreset(const char *value);
1847 struct var *next; /* next entry in hash list */
1848 int flags; /* flags are defined above */
1849 const char *var_text; /* name=value */
1850 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1851 /* the variable gets set/unset */
1855 struct localvar *next; /* next local variable in list */
1856 struct var *vp; /* the variable that was made local */
1857 int flags; /* saved flags */
1858 const char *text; /* saved text */
1862 #define VEXPORT 0x01 /* variable is exported */
1863 #define VREADONLY 0x02 /* variable cannot be modified */
1864 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1865 #define VTEXTFIXED 0x08 /* text is statically allocated */
1866 #define VSTACK 0x10 /* text is allocated on the stack */
1867 #define VUNSET 0x20 /* the variable is not set */
1868 #define VNOFUNC 0x40 /* don't call the callback function */
1869 #define VNOSET 0x80 /* do not set variable - just readonly test */
1870 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1871 #if ENABLE_ASH_RANDOM_SUPPORT
1872 # define VDYNAMIC 0x200 /* dynamic variable */
1878 /* Need to be before varinit_data[] */
1879 #if ENABLE_LOCALE_SUPPORT
1880 static void FAST_FUNC
1881 change_lc_all(const char *value)
1883 if (value && *value != '\0')
1884 setlocale(LC_ALL, value);
1886 static void FAST_FUNC
1887 change_lc_ctype(const char *value)
1889 if (value && *value != '\0')
1890 setlocale(LC_CTYPE, value);
1894 static void chkmail(void);
1895 static void changemail(const char *var_value) FAST_FUNC;
1897 # define chkmail() ((void)0)
1899 static void changepath(const char *) FAST_FUNC;
1900 #if ENABLE_ASH_RANDOM_SUPPORT
1901 static void change_random(const char *) FAST_FUNC;
1904 static const struct {
1906 const char *var_text;
1907 void (*var_func)(const char *) FAST_FUNC;
1908 } varinit_data[] = {
1910 * Note: VEXPORT would not work correctly here for NOFORK applets:
1911 * some environment strings may be constant.
1913 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1915 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1916 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1918 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1919 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1920 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1921 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1922 #if ENABLE_ASH_GETOPTS
1923 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1925 #if ENABLE_ASH_RANDOM_SUPPORT
1926 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1928 #if ENABLE_LOCALE_SUPPORT
1929 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1932 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1933 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1939 struct globals_var {
1940 struct shparam shellparam; /* $@ current positional parameters */
1941 struct redirtab *redirlist;
1943 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1944 struct var *vartab[VTABSIZE];
1945 struct var varinit[ARRAY_SIZE(varinit_data)];
1947 extern struct globals_var *const ash_ptr_to_globals_var;
1948 #define G_var (*ash_ptr_to_globals_var)
1949 #define shellparam (G_var.shellparam )
1950 //#define redirlist (G_var.redirlist )
1951 #define g_nullredirs (G_var.g_nullredirs )
1952 #define preverrout_fd (G_var.preverrout_fd)
1953 #define vartab (G_var.vartab )
1954 #define varinit (G_var.varinit )
1955 #define INIT_G_var() do { \
1957 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1959 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1960 varinit[i].flags = varinit_data[i].flags; \
1961 varinit[i].var_text = varinit_data[i].var_text; \
1962 varinit[i].var_func = varinit_data[i].var_func; \
1966 #define vifs varinit[0]
1968 # define vmail (&vifs)[1]
1969 # define vmpath (&vmail)[1]
1970 # define vpath (&vmpath)[1]
1972 # define vpath (&vifs)[1]
1974 #define vps1 (&vpath)[1]
1975 #define vps2 (&vps1)[1]
1976 #define vps4 (&vps2)[1]
1977 #if ENABLE_ASH_GETOPTS
1978 # define voptind (&vps4)[1]
1979 # if ENABLE_ASH_RANDOM_SUPPORT
1980 # define vrandom (&voptind)[1]
1983 # if ENABLE_ASH_RANDOM_SUPPORT
1984 # define vrandom (&vps4)[1]
1989 * The following macros access the values of the above variables.
1990 * They have to skip over the name. They return the null string
1991 * for unset variables.
1993 #define ifsval() (vifs.var_text + 4)
1994 #define ifsset() ((vifs.flags & VUNSET) == 0)
1996 # define mailval() (vmail.var_text + 5)
1997 # define mpathval() (vmpath.var_text + 9)
1998 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2000 #define pathval() (vpath.var_text + 5)
2001 #define ps1val() (vps1.var_text + 4)
2002 #define ps2val() (vps2.var_text + 4)
2003 #define ps4val() (vps4.var_text + 4)
2004 #if ENABLE_ASH_GETOPTS
2005 # define optindval() (voptind.var_text + 7)
2008 #if ENABLE_ASH_GETOPTS
2009 static void FAST_FUNC
2010 getoptsreset(const char *value)
2012 shellparam.optind = number(value);
2013 shellparam.optoff = -1;
2018 * Compares two strings up to the first = or '\0'. The first
2019 * string must be terminated by '='; the second may be terminated by
2020 * either '=' or '\0'.
2023 varcmp(const char *p, const char *q)
2027 while ((c = *p) == (d = *q)) {
2028 if (c == '\0' || c == '=')
2042 * Find the appropriate entry in the hash table from the name.
2044 static struct var **
2045 hashvar(const char *p)
2049 hashval = ((unsigned char) *p) << 4;
2050 while (*p && *p != '=')
2051 hashval += (unsigned char) *p++;
2052 return &vartab[hashval % VTABSIZE];
2056 vpcmp(const void *a, const void *b)
2058 return varcmp(*(const char **)a, *(const char **)b);
2062 * This routine initializes the builtin variables.
2072 * PS1 depends on uid
2074 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2075 vps1.var_text = "PS1=\\w \\$ ";
2078 vps1.var_text = "PS1=# ";
2081 end = vp + ARRAY_SIZE(varinit);
2083 vpp = hashvar(vp->var_text);
2086 } while (++vp < end);
2089 static struct var **
2090 findvar(struct var **vpp, const char *name)
2092 for (; *vpp; vpp = &(*vpp)->next) {
2093 if (varcmp((*vpp)->var_text, name) == 0) {
2101 * Find the value of a variable. Returns NULL if not set.
2103 static const char* FAST_FUNC
2104 lookupvar(const char *name)
2108 v = *findvar(hashvar(name), name);
2110 #if ENABLE_ASH_RANDOM_SUPPORT
2112 * Dynamic variables are implemented roughly the same way they are
2113 * in bash. Namely, they're "special" so long as they aren't unset.
2114 * As soon as they're unset, they're no longer dynamic, and dynamic
2115 * lookup will no longer happen at that point. -- PFM.
2117 if (v->flags & VDYNAMIC)
2120 if (!(v->flags & VUNSET))
2121 return var_end(v->var_text);
2126 static void reinit_unicode_for_ash(void)
2128 /* Unicode support should be activated even if LANG is set
2129 * _during_ shell execution, not only if it was set when
2130 * shell was started. Therefore, re-check LANG every time:
2132 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2133 || ENABLE_UNICODE_USING_LOCALE
2135 const char *s = lookupvar("LC_ALL");
2136 if (!s) s = lookupvar("LC_CTYPE");
2137 if (!s) s = lookupvar("LANG");
2143 * Search the environment of a builtin command.
2146 bltinlookup(const char *name)
2150 for (sp = cmdenviron; sp; sp = sp->next) {
2151 if (varcmp(sp->text, name) == 0)
2152 return var_end(sp->text);
2154 return lookupvar(name);
2158 * Same as setvar except that the variable and value are passed in
2159 * the first argument as name=value. Since the first argument will
2160 * be actually stored in the table, it should not be a string that
2162 * Called with interrupts off.
2165 setvareq(char *s, int flags)
2167 struct var *vp, **vpp;
2170 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2171 vp = *findvar(vpp, s);
2173 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2176 if (flags & VNOSAVE)
2179 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2185 if (vp->var_func && !(flags & VNOFUNC))
2186 vp->var_func(var_end(s));
2188 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2189 free((char*)vp->var_text);
2191 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2193 /* variable s is not found */
2196 vp = ckzalloc(sizeof(*vp));
2198 /*vp->func = NULL; - ckzalloc did it */
2201 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2208 * Set the value of a variable. The flags argument is ored with the
2209 * flags of the variable. If val is NULL, the variable is unset.
2212 setvar(const char *name, const char *val, int flags)
2220 q = endofname(name);
2221 p = strchrnul(q, '=');
2223 if (!namelen || p != q)
2224 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2229 vallen = strlen(val);
2233 nameeq = ckmalloc(namelen + vallen + 2);
2234 p = memcpy(nameeq, name, namelen) + namelen;
2237 p = memcpy(p, val, vallen) + vallen;
2240 setvareq(nameeq, flags | VNOSAVE);
2244 static void FAST_FUNC
2245 setvar0(const char *name, const char *val)
2247 setvar(name, val, 0);
2250 #if ENABLE_ASH_GETOPTS
2252 * Safe version of setvar, returns 1 on success 0 on failure.
2255 setvarsafe(const char *name, const char *val, int flags)
2258 volatile int saveint;
2259 struct jmploc *volatile savehandler = exception_handler;
2260 struct jmploc jmploc;
2263 if (setjmp(jmploc.loc))
2266 exception_handler = &jmploc;
2267 setvar(name, val, flags);
2270 exception_handler = savehandler;
2271 RESTORE_INT(saveint);
2277 * Unset the specified variable.
2280 unsetvar(const char *s)
2286 vpp = findvar(hashvar(s), s);
2290 int flags = vp->flags;
2293 if (flags & VREADONLY)
2295 #if ENABLE_ASH_RANDOM_SUPPORT
2296 vp->flags &= ~VDYNAMIC;
2300 if ((flags & VSTRFIXED) == 0) {
2302 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2303 free((char*)vp->var_text);
2309 vp->flags &= ~VEXPORT;
2319 * Process a linked list of variable assignments.
2322 listsetvar(struct strlist *list_set_var, int flags)
2324 struct strlist *lp = list_set_var;
2330 setvareq(lp->text, flags);
2337 * Generate a list of variables satisfying the given conditions.
2340 listvars(int on, int off, char ***end)
2351 for (vp = *vpp; vp; vp = vp->next) {
2352 if ((vp->flags & mask) == on) {
2353 if (ep == stackstrend())
2354 ep = growstackstr();
2355 *ep++ = (char*)vp->var_text;
2358 } while (++vpp < vartab + VTABSIZE);
2359 if (ep == stackstrend())
2360 ep = growstackstr();
2364 return grabstackstr(ep);
2368 /* ============ Path search helper
2370 * The variable path (passed by reference) should be set to the start
2371 * of the path before the first call; path_advance will update
2372 * this value as it proceeds. Successive calls to path_advance will return
2373 * the possible path expansions in sequence. If an option (indicated by
2374 * a percent sign) appears in the path entry then the global variable
2375 * pathopt will be set to point to it; otherwise pathopt will be set to
2378 static const char *pathopt; /* set by path_advance */
2381 path_advance(const char **path, const char *name)
2391 for (p = start; *p && *p != ':' && *p != '%'; p++)
2393 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2394 while (stackblocksize() < len)
2398 memcpy(q, start, p - start);
2406 while (*p && *p != ':')
2413 return stalloc(len);
2417 /* ============ Prompt */
2419 static smallint doprompt; /* if set, prompt the user */
2420 static smallint needprompt; /* true if interactive and at start of line */
2422 #if ENABLE_FEATURE_EDITING
2423 static line_input_t *line_input_state;
2424 static const char *cmdedit_prompt;
2426 putprompt(const char *s)
2428 if (ENABLE_ASH_EXPAND_PRMT) {
2429 free((char*)cmdedit_prompt);
2430 cmdedit_prompt = ckstrdup(s);
2437 putprompt(const char *s)
2443 #if ENABLE_ASH_EXPAND_PRMT
2444 /* expandstr() needs parsing machinery, so it is far away ahead... */
2445 static const char *expandstr(const char *ps);
2447 #define expandstr(s) s
2451 setprompt_if(smallint do_set, int whichprompt)
2454 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2461 switch (whichprompt) {
2471 #if ENABLE_ASH_EXPAND_PRMT
2472 setstackmark(&smark);
2473 stalloc(stackblocksize());
2475 putprompt(expandstr(prompt));
2476 #if ENABLE_ASH_EXPAND_PRMT
2477 popstackmark(&smark);
2482 /* ============ The cd and pwd commands */
2484 #define CD_PHYSICAL 1
2494 while ((i = nextopt("LP")) != '\0') {
2496 flags ^= CD_PHYSICAL;
2505 * Update curdir (the name of the current directory) in response to a
2509 updatepwd(const char *dir)
2516 cdcomppath = ststrdup(dir);
2519 if (curdir == nullstr)
2521 new = stack_putstr(curdir, new);
2523 new = makestrspace(strlen(dir) + 2, new);
2524 lim = (char *)stackblock() + 1;
2528 if (new > lim && *lim == '/')
2533 if (dir[1] == '/' && dir[2] != '/') {
2539 p = strtok(cdcomppath, "/");
2543 if (p[1] == '.' && p[2] == '\0') {
2555 new = stack_putstr(p, new);
2563 return stackblock();
2567 * Find out what the current directory is. If we already know the current
2568 * directory, this routine returns immediately.
2573 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2574 return dir ? dir : nullstr;
2578 setpwd(const char *val, int setold)
2582 oldcur = dir = curdir;
2585 setvar("OLDPWD", oldcur, VEXPORT);
2588 if (physdir != nullstr) {
2589 if (physdir != oldcur)
2593 if (oldcur == val || !val) {
2599 dir = ckstrdup(val);
2600 if (oldcur != dir && oldcur != nullstr) {
2605 setvar("PWD", dir, VEXPORT);
2608 static void hashcd(void);
2611 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2612 * know that the current directory has changed.
2615 docd(const char *dest, int flags)
2617 const char *dir = NULL;
2620 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2623 if (!(flags & CD_PHYSICAL)) {
2624 dir = updatepwd(dest);
2638 static int FAST_FUNC
2639 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2651 dest = bltinlookup("HOME");
2652 else if (LONE_DASH(dest)) {
2653 dest = bltinlookup("OLDPWD");
2675 path = bltinlookup("CDPATH");
2684 p = path_advance(&path, dest);
2685 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2689 if (!docd(p, flags))
2694 ash_msg_and_raise_error("can't cd to %s", dest);
2697 if (flags & CD_PRINT)
2698 out1fmt("%s\n", curdir);
2702 static int FAST_FUNC
2703 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2706 const char *dir = curdir;
2710 if (physdir == nullstr)
2714 out1fmt("%s\n", dir);
2719 /* ============ ... */
2722 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2724 /* Syntax classes */
2725 #define CWORD 0 /* character is nothing special */
2726 #define CNL 1 /* newline character */
2727 #define CBACK 2 /* a backslash character */
2728 #define CSQUOTE 3 /* single quote */
2729 #define CDQUOTE 4 /* double quote */
2730 #define CENDQUOTE 5 /* a terminating quote */
2731 #define CBQUOTE 6 /* backwards single quote */
2732 #define CVAR 7 /* a dollar sign */
2733 #define CENDVAR 8 /* a '}' character */
2734 #define CLP 9 /* a left paren in arithmetic */
2735 #define CRP 10 /* a right paren in arithmetic */
2736 #define CENDFILE 11 /* end of file */
2737 #define CCTL 12 /* like CWORD, except it must be escaped */
2738 #define CSPCL 13 /* these terminate a word */
2739 #define CIGN 14 /* character should be ignored */
2742 #if ENABLE_ASH_ALIAS
2746 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2748 #if ENABLE_SH_MATH_SUPPORT
2749 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2751 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2753 static const uint16_t S_I_T[] = {
2754 #if ENABLE_ASH_ALIAS
2755 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2757 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2758 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2759 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2760 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2761 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2762 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2763 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2764 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2765 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2766 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2767 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2768 #if !USE_SIT_FUNCTION
2769 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2770 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2771 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2775 /* Constants below must match table above */
2777 #if ENABLE_ASH_ALIAS
2778 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2780 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2781 CNL_CNL_CNL_CNL , /* 2 */
2782 CWORD_CCTL_CCTL_CWORD , /* 3 */
2783 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2784 CVAR_CVAR_CWORD_CVAR , /* 5 */
2785 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2786 CSPCL_CWORD_CWORD_CLP , /* 7 */
2787 CSPCL_CWORD_CWORD_CRP , /* 8 */
2788 CBACK_CBACK_CCTL_CBACK , /* 9 */
2789 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2790 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2791 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2792 CWORD_CWORD_CWORD_CWORD , /* 13 */
2793 CCTL_CCTL_CCTL_CCTL , /* 14 */
2796 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2797 * caller must ensure proper cast on it if c is *char_ptr!
2799 /* Values for syntax param */
2800 #define BASESYNTAX 0 /* not in quotes */
2801 #define DQSYNTAX 1 /* in double quotes */
2802 #define SQSYNTAX 2 /* in single quotes */
2803 #define ARISYNTAX 3 /* in arithmetic */
2804 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2806 #if USE_SIT_FUNCTION
2809 SIT(int c, int syntax)
2811 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2812 # if ENABLE_ASH_ALIAS
2813 static const uint8_t syntax_index_table[] ALIGN1 = {
2814 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2815 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2816 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
2821 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2822 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2823 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2832 # if ENABLE_ASH_ALIAS
2838 /* Cast is purely for paranoia here,
2839 * just in case someone passed signed char to us */
2840 if ((unsigned char)c >= CTL_FIRST
2841 && (unsigned char)c <= CTL_LAST
2845 s = strchrnul(spec_symbls, c);
2848 indx = syntax_index_table[s - spec_symbls];
2850 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2853 #else /* !USE_SIT_FUNCTION */
2855 static const uint8_t syntax_index_table[] = {
2856 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2857 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2867 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2868 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2890 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2892 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2894 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2896 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2897 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2898 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2899 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2902 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2904 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2919 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2949 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2950 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2954 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2982 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2983 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2985 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2987 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2988 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2989 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2990 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2991 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2992 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2993 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2994 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3113 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3114 # if ENABLE_ASH_ALIAS
3115 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3119 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3121 #endif /* !USE_SIT_FUNCTION */
3124 /* ============ Alias handling */
3126 #if ENABLE_ASH_ALIAS
3128 #define ALIASINUSE 1
3139 static struct alias **atab; // [ATABSIZE];
3140 #define INIT_G_alias() do { \
3141 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3145 static struct alias **
3146 __lookupalias(const char *name) {
3147 unsigned int hashval;
3154 ch = (unsigned char)*p;
3158 ch = (unsigned char)*++p;
3160 app = &atab[hashval % ATABSIZE];
3162 for (; *app; app = &(*app)->next) {
3163 if (strcmp(name, (*app)->name) == 0) {
3171 static struct alias *
3172 lookupalias(const char *name, int check)
3174 struct alias *ap = *__lookupalias(name);
3176 if (check && ap && (ap->flag & ALIASINUSE))
3181 static struct alias *
3182 freealias(struct alias *ap)
3186 if (ap->flag & ALIASINUSE) {
3187 ap->flag |= ALIASDEAD;
3199 setalias(const char *name, const char *val)
3201 struct alias *ap, **app;
3203 app = __lookupalias(name);
3207 if (!(ap->flag & ALIASINUSE)) {
3210 ap->val = ckstrdup(val);
3211 ap->flag &= ~ALIASDEAD;
3214 ap = ckzalloc(sizeof(struct alias));
3215 ap->name = ckstrdup(name);
3216 ap->val = ckstrdup(val);
3217 /*ap->flag = 0; - ckzalloc did it */
3218 /*ap->next = NULL;*/
3225 unalias(const char *name)
3229 app = __lookupalias(name);
3233 *app = freealias(*app);
3244 struct alias *ap, **app;
3248 for (i = 0; i < ATABSIZE; i++) {
3250 for (ap = *app; ap; ap = *app) {
3251 *app = freealias(*app);
3261 printalias(const struct alias *ap)
3263 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3267 * TODO - sort output
3269 static int FAST_FUNC
3270 aliascmd(int argc UNUSED_PARAM, char **argv)
3279 for (i = 0; i < ATABSIZE; i++) {
3280 for (ap = atab[i]; ap; ap = ap->next) {
3286 while ((n = *++argv) != NULL) {
3287 v = strchr(n+1, '=');
3288 if (v == NULL) { /* n+1: funny ksh stuff */
3289 ap = *__lookupalias(n);
3291 fprintf(stderr, "%s: %s not found\n", "alias", n);
3304 static int FAST_FUNC
3305 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3309 while ((i = nextopt("a")) != '\0') {
3315 for (i = 0; *argptr; argptr++) {
3316 if (unalias(*argptr)) {
3317 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3325 #endif /* ASH_ALIAS */
3328 /* ============ jobs.c */
3330 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3333 #define FORK_NOJOB 2
3335 /* mode flags for showjob(s) */
3336 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3337 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3338 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3341 * A job structure contains information about a job. A job is either a
3342 * single process or a set of processes contained in a pipeline. In the
3343 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3347 pid_t ps_pid; /* process id */
3348 int ps_status; /* last process status from wait() */
3349 char *ps_cmd; /* text of command being run */
3353 struct procstat ps0; /* status of process */
3354 struct procstat *ps; /* status or processes when more than one */
3356 int stopstatus; /* status of a stopped job */
3359 nprocs: 16, /* number of processes */
3361 #define JOBRUNNING 0 /* at least one proc running */
3362 #define JOBSTOPPED 1 /* all procs are stopped */
3363 #define JOBDONE 2 /* all procs are completed */
3365 sigint: 1, /* job was killed by SIGINT */
3366 jobctl: 1, /* job running under job control */
3368 waited: 1, /* true if this entry has been waited for */
3369 used: 1, /* true if this entry is in used */
3370 changed: 1; /* true if status has changed */
3371 struct job *prev_job; /* previous job */
3374 static struct job *makejob(/*union node *,*/ int);
3375 static int forkshell(struct job *, union node *, int);
3376 static int waitforjob(struct job *);
3379 enum { doing_jobctl = 0 };
3380 #define setjobctl(on) do {} while (0)
3382 static smallint doing_jobctl; //references:8
3383 static void setjobctl(int);
3390 ignoresig(int signo)
3392 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3393 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3394 /* No, need to do it */
3395 signal(signo, SIG_IGN);
3397 sigmode[signo - 1] = S_HARD_IGN;
3401 * Only one usage site - in setsignal()
3404 signal_handler(int signo)
3406 gotsig[signo - 1] = 1;
3408 if (signo == SIGINT && !trap[SIGINT]) {
3409 if (!suppress_int) {
3411 raise_interrupt(); /* does not return */
3415 pending_sig = signo;
3420 * Set the signal handler for the specified signal. The routine figures
3421 * out what it should be set to.
3424 setsignal(int signo)
3427 char cur_act, new_act;
3428 struct sigaction act;
3432 if (t != NULL) { /* trap for this sig is set */
3434 if (t[0] == '\0') /* trap is "": ignore this sig */
3438 if (rootshell && new_act == S_DFL) {
3441 if (iflag || minusc || sflag == 0)
3450 * "In all cases, bash ignores SIGQUIT. Non-builtin
3451 * commands run by bash have signal handlers
3452 * set to the values inherited by the shell
3453 * from its parent". */
3469 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3470 //whereas we have to restore it to what shell got on entry
3471 //from the parent. See comment above
3473 t = &sigmode[signo - 1];
3476 /* current setting is not yet known */
3477 if (sigaction(signo, NULL, &act)) {
3478 /* pretend it worked; maybe we should give a warning,
3479 * but other shells don't. We don't alter sigmode,
3480 * so we retry every time.
3481 * btw, in Linux it never fails. --vda */
3484 if (act.sa_handler == SIG_IGN) {
3485 cur_act = S_HARD_IGN;
3487 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3489 cur_act = S_IGN; /* don't hard ignore these */
3493 if (cur_act == S_HARD_IGN || cur_act == new_act)
3496 act.sa_handler = SIG_DFL;
3499 act.sa_handler = signal_handler;
3502 act.sa_handler = SIG_IGN;
3506 /* flags and mask matter only if !DFL and !IGN, but we do it
3507 * for all cases for more deterministic behavior:
3510 sigfillset(&act.sa_mask);
3512 sigaction_set(signo, &act);
3517 /* mode flags for set_curjob */
3518 #define CUR_DELETE 2
3519 #define CUR_RUNNING 1
3520 #define CUR_STOPPED 0
3522 /* mode flags for dowait */
3523 #define DOWAIT_NONBLOCK WNOHANG
3524 #define DOWAIT_BLOCK 0
3527 /* pgrp of shell on invocation */
3528 static int initialpgrp; //references:2
3529 static int ttyfd = -1; //5
3532 static struct job *jobtab; //5
3534 static unsigned njobs; //4
3536 static struct job *curjob; //lots
3537 /* number of presumed living untracked jobs */
3538 static int jobless; //4
3541 set_curjob(struct job *jp, unsigned mode)
3544 struct job **jpp, **curp;
3546 /* first remove from list */
3547 jpp = curp = &curjob;
3552 jpp = &jp1->prev_job;
3554 *jpp = jp1->prev_job;
3556 /* Then re-insert in correct position */
3564 /* job being deleted */
3567 /* newly created job or backgrounded job,
3568 * put after all stopped jobs.
3573 if (!jp1 || jp1->state != JOBSTOPPED)
3576 jpp = &jp1->prev_job;
3582 /* newly stopped job - becomes curjob */
3583 jp->prev_job = *jpp;
3591 jobno(const struct job *jp)
3593 return jp - jobtab + 1;
3598 * Convert a job name to a job structure.
3601 #define getjob(name, getctl) getjob(name)
3604 getjob(const char *name, int getctl)
3608 const char *err_msg = "%s: no such job";
3612 char *(*match)(const char *, const char *);
3627 if (c == '+' || c == '%') {
3629 err_msg = "No current job";
3635 err_msg = "No previous job";
3646 jp = jobtab + num - 1;
3661 if (match(jp->ps[0].ps_cmd, p)) {
3665 err_msg = "%s: ambiguous";
3675 err_msg = "job %s not created under job control";
3676 if (getctl && jp->jobctl == 0)
3681 ash_msg_and_raise_error(err_msg, name);
3685 * Mark a job structure as unused.
3688 freejob(struct job *jp)
3690 struct procstat *ps;
3694 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3695 if (ps->ps_cmd != nullstr)
3698 if (jp->ps != &jp->ps0)
3701 set_curjob(jp, CUR_DELETE);
3707 xtcsetpgrp(int fd, pid_t pgrp)
3709 if (tcsetpgrp(fd, pgrp))
3710 ash_msg_and_raise_error("can't set tty process group (%m)");
3714 * Turn job control on and off.
3716 * Note: This code assumes that the third arg to ioctl is a character
3717 * pointer, which is true on Berkeley systems but not System V. Since
3718 * System V doesn't have job control yet, this isn't a problem now.
3720 * Called with interrupts off.
3728 if (on == doing_jobctl || rootshell == 0)
3732 ofd = fd = open(_PATH_TTY, O_RDWR);
3734 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3735 * That sometimes helps to acquire controlling tty.
3736 * Obviously, a workaround for bugs when someone
3737 * failed to provide a controlling tty to bash! :) */
3743 fd = fcntl(fd, F_DUPFD, 10);
3748 /* fd is a tty at this point */
3749 close_on_exec_on(fd);
3750 while (1) { /* while we are in the background */
3751 pgrp = tcgetpgrp(fd);
3754 ash_msg("can't access tty; job control turned off");
3758 if (pgrp == getpgrp())
3769 xtcsetpgrp(fd, pgrp);
3771 /* turning job control off */
3774 /* was xtcsetpgrp, but this can make exiting ash
3775 * loop forever if pty is already deleted */
3776 tcsetpgrp(fd, pgrp);
3790 static int FAST_FUNC
3791 killcmd(int argc, char **argv)
3793 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3796 if (argv[i][0] == '%') {
3798 * "kill %N" - job kill
3799 * Converting to pgrp / pid kill
3805 jp = getjob(argv[i], 0);
3807 * In jobs started under job control, we signal
3808 * entire process group by kill -PGRP_ID.
3809 * This happens, f.e., in interactive shell.
3811 * Otherwise, we signal each child via
3812 * kill PID1 PID2 PID3.
3814 * sh -c 'sleep 1|sleep 1 & kill %1'
3815 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3816 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3818 n = jp->nprocs; /* can't be 0 (I hope) */
3821 dst = alloca(n * sizeof(int)*4);
3823 for (j = 0; j < n; j++) {
3824 struct procstat *ps = &jp->ps[j];
3825 /* Skip non-running and not-stopped members
3826 * (i.e. dead members) of the job
3828 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3831 * kill_main has matching code to expect
3832 * leading space. Needed to not confuse
3833 * negative pids with "kill -SIGNAL_NO" syntax
3835 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3839 } while (argv[++i]);
3841 return kill_main(argc, argv);
3845 showpipe(struct job *jp /*, FILE *out*/)
3847 struct procstat *ps;
3848 struct procstat *psend;
3850 psend = jp->ps + jp->nprocs;
3851 for (ps = jp->ps + 1; ps < psend; ps++)
3852 printf(" | %s", ps->ps_cmd);
3853 outcslow('\n', stdout);
3854 flush_stdout_stderr();
3859 restartjob(struct job *jp, int mode)
3861 struct procstat *ps;
3867 if (jp->state == JOBDONE)
3869 jp->state = JOBRUNNING;
3870 pgid = jp->ps[0].ps_pid;
3871 if (mode == FORK_FG)
3872 xtcsetpgrp(ttyfd, pgid);
3873 killpg(pgid, SIGCONT);
3877 if (WIFSTOPPED(ps->ps_status)) {
3883 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3888 static int FAST_FUNC
3889 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3895 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3899 jp = getjob(*argv, 1);
3900 if (mode == FORK_BG) {
3901 set_curjob(jp, CUR_RUNNING);
3902 printf("[%d] ", jobno(jp));
3904 out1str(jp->ps[0].ps_cmd);
3905 showpipe(jp /*, stdout*/);
3906 retval = restartjob(jp, mode);
3907 } while (*argv && *++argv);
3913 sprint_status(char *s, int status, int sigonly)
3919 if (!WIFEXITED(status)) {
3921 if (WIFSTOPPED(status))
3922 st = WSTOPSIG(status);
3925 st = WTERMSIG(status);
3927 if (st == SIGINT || st == SIGPIPE)
3930 if (WIFSTOPPED(status))
3935 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3936 col = fmtstr(s, 32, strsignal(st));
3937 if (WCOREDUMP(status)) {
3938 col += fmtstr(s + col, 16, " (core dumped)");
3940 } else if (!sigonly) {
3941 st = WEXITSTATUS(status);
3943 col = fmtstr(s, 16, "Done(%d)", st);
3945 col = fmtstr(s, 16, "Done");
3952 dowait(int wait_flags, struct job *job)
3957 struct job *thisjob;
3960 TRACE(("dowait(0x%x) called\n", wait_flags));
3962 /* Do a wait system call. If job control is compiled in, we accept
3963 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3964 * NB: _not_ safe_waitpid, we need to detect EINTR */
3966 wait_flags |= WUNTRACED;
3967 pid = waitpid(-1, &status, wait_flags);
3968 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3969 pid, status, errno, strerror(errno)));
3975 for (jp = curjob; jp; jp = jp->prev_job) {
3976 struct procstat *ps;
3977 struct procstat *psend;
3978 if (jp->state == JOBDONE)
3982 psend = ps + jp->nprocs;
3984 if (ps->ps_pid == pid) {
3985 TRACE(("Job %d: changing status of proc %d "
3986 "from 0x%x to 0x%x\n",
3987 jobno(jp), pid, ps->ps_status, status));
3988 ps->ps_status = status;
3991 if (ps->ps_status == -1)
3994 if (state == JOBRUNNING)
3996 if (WIFSTOPPED(ps->ps_status)) {
3997 jp->stopstatus = ps->ps_status;
4001 } while (++ps < psend);
4006 if (!WIFSTOPPED(status))
4012 if (state != JOBRUNNING) {
4013 thisjob->changed = 1;
4015 if (thisjob->state != state) {
4016 TRACE(("Job %d: changing state from %d to %d\n",
4017 jobno(thisjob), thisjob->state, state));
4018 thisjob->state = state;
4020 if (state == JOBSTOPPED) {
4021 set_curjob(thisjob, CUR_STOPPED);
4030 if (thisjob && thisjob == job) {
4034 len = sprint_status(s, status, 1);
4045 blocking_wait_with_raise_on_sig(void)
4047 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4048 if (pid <= 0 && pending_sig)
4049 raise_exception(EXSIG);
4055 showjob(FILE *out, struct job *jp, int mode)
4057 struct procstat *ps;
4058 struct procstat *psend;
4065 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4066 /* just output process (group) id of pipeline */
4067 fprintf(out, "%d\n", ps->ps_pid);
4071 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4076 else if (curjob && jp == curjob->prev_job)
4079 if (mode & SHOW_PIDS)
4080 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4082 psend = ps + jp->nprocs;
4084 if (jp->state == JOBRUNNING) {
4085 strcpy(s + col, "Running");
4086 col += sizeof("Running") - 1;
4088 int status = psend[-1].ps_status;
4089 if (jp->state == JOBSTOPPED)
4090 status = jp->stopstatus;
4091 col += sprint_status(s + col, status, 0);
4093 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4095 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4096 * or prints several "PID | <cmdN>" lines,
4097 * depending on SHOW_PIDS bit.
4098 * We do not print status of individual processes
4099 * between PID and <cmdN>. bash does it, but not very well:
4100 * first line shows overall job status, not process status,
4101 * making it impossible to know 1st process status.
4105 /* for each process */
4108 if (mode & SHOW_PIDS)
4109 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4111 fprintf(out, "%s%*c%s%s",
4113 33 - col >= 0 ? 33 - col : 0, ' ',
4114 ps == jp->ps ? "" : "| ",
4117 } while (++ps != psend);
4118 outcslow('\n', out);
4122 if (jp->state == JOBDONE) {
4123 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4129 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4130 * statuses have changed since the last call to showjobs.
4133 showjobs(FILE *out, int mode)
4137 TRACE(("showjobs(0x%x) called\n", mode));
4139 /* Handle all finished jobs */
4140 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4143 for (jp = curjob; jp; jp = jp->prev_job) {
4144 if (!(mode & SHOW_CHANGED) || jp->changed) {
4145 showjob(out, jp, mode);
4150 static int FAST_FUNC
4151 jobscmd(int argc UNUSED_PARAM, char **argv)
4156 while ((m = nextopt("lp")) != '\0') {
4160 mode |= SHOW_ONLY_PGID;
4166 showjob(stdout, getjob(*argv, 0), mode);
4169 showjobs(stdout, mode);
4176 /* Called only on finished or stopped jobs (no members are running) */
4178 getstatus(struct job *job)
4182 struct procstat *ps;
4184 /* Fetch last member's status */
4185 ps = job->ps + job->nprocs - 1;
4186 status = ps->ps_status;
4188 /* "set -o pipefail" mode: use last _nonzero_ status */
4189 while (status == 0 && --ps >= job->ps)
4190 status = ps->ps_status;
4193 retval = WEXITSTATUS(status);
4194 if (!WIFEXITED(status)) {
4196 retval = WSTOPSIG(status);
4197 if (!WIFSTOPPED(status))
4200 /* XXX: limits number of signals */
4201 retval = WTERMSIG(status);
4203 if (retval == SIGINT)
4209 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4210 jobno(job), job->nprocs, status, retval));
4214 static int FAST_FUNC
4215 waitcmd(int argc UNUSED_PARAM, char **argv)
4222 raise_exception(EXSIG);
4229 /* wait for all jobs */
4233 if (!jp) /* no running procs */
4235 if (jp->state == JOBRUNNING)
4240 blocking_wait_with_raise_on_sig();
4242 * "When bash is waiting for an asynchronous command via
4243 * the wait builtin, the reception of a signal for which a trap
4244 * has been set will cause the wait builtin to return immediately
4245 * with an exit status greater than 128, immediately after which
4246 * the trap is executed."
4248 * blocking_wait_with_raise_on_sig raises signal handlers
4249 * if it gets no pid (pid < 0). However,
4250 * if child sends us a signal *and immediately exits*,
4251 * blocking_wait_with_raise_on_sig gets pid > 0
4252 * and does not handle pending_sig. Check this case: */
4254 raise_exception(EXSIG);
4260 if (**argv != '%') {
4261 pid_t pid = number(*argv);
4266 if (job->ps[job->nprocs - 1].ps_pid == pid)
4268 job = job->prev_job;
4271 job = getjob(*argv, 0);
4273 /* loop until process terminated or stopped */
4274 while (job->state == JOBRUNNING)
4275 blocking_wait_with_raise_on_sig();
4277 retval = getstatus(job);
4290 struct job *jp, *jq;
4292 len = njobs * sizeof(*jp);
4294 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4296 offset = (char *)jp - (char *)jq;
4298 /* Relocate pointers */
4301 jq = (struct job *)((char *)jq + l);
4305 #define joff(p) ((struct job *)((char *)(p) + l))
4306 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4307 if (joff(jp)->ps == &jq->ps0)
4308 jmove(joff(jp)->ps);
4309 if (joff(jp)->prev_job)
4310 jmove(joff(jp)->prev_job);
4320 jp = (struct job *)((char *)jp + len);
4324 } while (--jq >= jp);
4329 * Return a new job structure.
4330 * Called with interrupts off.
4333 makejob(/*union node *node,*/ int nprocs)
4338 for (i = njobs, jp = jobtab; ; jp++) {
4345 if (jp->state != JOBDONE || !jp->waited)
4354 memset(jp, 0, sizeof(*jp));
4356 /* jp->jobctl is a bitfield.
4357 * "jp->jobctl |= jobctl" likely to give awful code */
4361 jp->prev_job = curjob;
4366 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4368 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4375 * Return a string identifying a command (to be printed by the
4378 static char *cmdnextc;
4381 cmdputs(const char *s)
4383 static const char vstype[VSTYPE + 1][3] = {
4384 "", "}", "-", "+", "?", "=",
4385 "%", "%%", "#", "##"
4386 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4389 const char *p, *str;
4393 unsigned char subtype = 0;
4397 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4399 while ((c = *p++) != '\0') {
4407 if ((subtype & VSTYPE) == VSLENGTH)
4413 str = "\"}" + !(quoted & 1);
4420 #if ENABLE_SH_MATH_SUPPORT
4435 if ((subtype & VSTYPE) != VSNORMAL)
4437 str = vstype[subtype & VSTYPE];
4438 if (subtype & VSNUL)
4447 /* These can only happen inside quotes */
4460 while ((c = *str++) != '\0') {
4463 } /* while *p++ not NUL */
4466 USTPUTC('"', nextc);
4472 /* cmdtxt() and cmdlist() call each other */
4473 static void cmdtxt(union node *n);
4476 cmdlist(union node *np, int sep)
4478 for (; np; np = np->narg.next) {
4482 if (sep && np->narg.next)
4488 cmdtxt(union node *n)
4491 struct nodelist *lp;
4502 lp = n->npipe.cmdlist;
4520 cmdtxt(n->nbinary.ch1);
4536 cmdtxt(n->nif.test);
4538 if (n->nif.elsepart) {
4539 cmdtxt(n->nif.ifpart);
4541 n = n->nif.elsepart;
4559 cmdtxt(n->nbinary.ch1);
4569 cmdputs(n->nfor.var);
4571 cmdlist(n->nfor.args, 1);
4576 cmdputs(n->narg.text);
4580 cmdlist(n->ncmd.args, 1);
4581 cmdlist(n->ncmd.redirect, 0);
4594 cmdputs(n->ncase.expr->narg.text);
4596 for (np = n->ncase.cases; np; np = np->nclist.next) {
4597 cmdtxt(np->nclist.pattern);
4599 cmdtxt(np->nclist.body);
4613 #if ENABLE_ASH_BASH_COMPAT
4628 cmdputs(utoa(n->nfile.fd));
4630 if (n->type == NTOFD || n->type == NFROMFD) {
4631 cmdputs(utoa(n->ndup.dupfd));
4640 commandtext(union node *n)
4644 STARTSTACKSTR(cmdnextc);
4646 name = stackblock();
4647 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4648 name, cmdnextc, cmdnextc));
4649 return ckstrdup(name);
4654 * Fork off a subshell. If we are doing job control, give the subshell its
4655 * own process group. Jp is a job structure that the job is to be added to.
4656 * N is the command that will be evaluated by the child. Both jp and n may
4657 * be NULL. The mode parameter can be one of the following:
4658 * FORK_FG - Fork off a foreground process.
4659 * FORK_BG - Fork off a background process.
4660 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4661 * process group even if job control is on.
4663 * When job control is turned off, background processes have their standard
4664 * input redirected to /dev/null (except for the second and later processes
4667 * Called with interrupts off.
4670 * Clear traps on a fork.
4677 for (tp = trap; tp < &trap[NSIG]; tp++) {
4678 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4680 if (trap_ptr == trap)
4682 /* else: it "belongs" to trap_ptr vector, don't free */
4684 if ((tp - trap) != 0)
4685 setsignal(tp - trap);
4692 /* Lives far away from here, needed for forkchild */
4693 static void closescript(void);
4695 /* Called after fork(), in child */
4696 static NOINLINE void
4697 forkchild(struct job *jp, union node *n, int mode)
4701 TRACE(("Child shell %d\n", getpid()));
4705 /* man bash: "Non-builtin commands run by bash have signal handlers
4706 * set to the values inherited by the shell from its parent".
4707 * Do we do it correctly? */
4711 if (mode == FORK_NOJOB /* is it `xxx` ? */
4712 && n && n->type == NCMD /* is it single cmd? */
4713 /* && n->ncmd.args->type == NARG - always true? */
4714 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4715 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4716 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4718 TRACE(("Trap hack\n"));
4719 /* Awful hack for `trap` or $(trap).
4721 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4722 * contains an example where "trap" is executed in a subshell:
4724 * save_traps=$(trap)
4726 * eval "$save_traps"
4728 * Standard does not say that "trap" in subshell shall print
4729 * parent shell's traps. It only says that its output
4730 * must have suitable form, but then, in the above example
4731 * (which is not supposed to be normative), it implies that.
4733 * bash (and probably other shell) does implement it
4734 * (traps are reset to defaults, but "trap" still shows them),
4735 * but as a result, "trap" logic is hopelessly messed up:
4738 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4739 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4740 * # true | trap <--- trap is in subshell - no output (ditto)
4741 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4742 * trap -- 'echo Ho' SIGWINCH
4743 * # echo `(trap)` <--- in subshell in subshell - output
4744 * trap -- 'echo Ho' SIGWINCH
4745 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4746 * trap -- 'echo Ho' SIGWINCH
4748 * The rules when to forget and when to not forget traps
4749 * get really complex and nonsensical.
4751 * Our solution: ONLY bare $(trap) or `trap` is special.
4753 /* Save trap handler strings for trap builtin to print */
4754 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4755 /* Fall through into clearing traps */
4759 /* do job control only in root shell */
4761 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4764 if (jp->nprocs == 0)
4767 pgrp = jp->ps[0].ps_pid;
4768 /* this can fail because we are doing it in the parent also */
4770 if (mode == FORK_FG)
4771 xtcsetpgrp(ttyfd, pgrp);
4776 if (mode == FORK_BG) {
4777 /* man bash: "When job control is not in effect,
4778 * asynchronous commands ignore SIGINT and SIGQUIT" */
4781 if (jp->nprocs == 0) {
4783 if (open(bb_dev_null, O_RDONLY) != 0)
4784 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4788 if (iflag) { /* why if iflag only? */
4793 * "In all cases, bash ignores SIGQUIT. Non-builtin
4794 * commands run by bash have signal handlers
4795 * set to the values inherited by the shell
4797 * Take care of the second rule: */
4801 if (n && n->type == NCMD
4802 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4804 TRACE(("Job hack\n"));
4805 /* "jobs": we do not want to clear job list for it,
4806 * instead we remove only _its_ own_ job from job list.
4807 * This makes "jobs .... | cat" more useful.
4813 for (jp = curjob; jp; jp = jp->prev_job)
4818 /* Called after fork(), in parent */
4820 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4823 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4825 TRACE(("In parent shell: child = %d\n", pid));
4827 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4833 if (mode != FORK_NOJOB && jp->jobctl) {
4836 if (jp->nprocs == 0)
4839 pgrp = jp->ps[0].ps_pid;
4840 /* This can fail because we are doing it in the child also */
4844 if (mode == FORK_BG) {
4845 backgndpid = pid; /* set $! */
4846 set_curjob(jp, CUR_RUNNING);
4849 struct procstat *ps = &jp->ps[jp->nprocs++];
4852 ps->ps_cmd = nullstr;
4854 if (doing_jobctl && n)
4855 ps->ps_cmd = commandtext(n);
4861 forkshell(struct job *jp, union node *n, int mode)
4865 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4868 TRACE(("Fork failed, errno=%d", errno));
4871 ash_msg_and_raise_error("can't fork");
4874 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4875 forkchild(jp, n, mode);
4877 forkparent(jp, n, mode, pid);
4883 * Wait for job to finish.
4885 * Under job control we have the problem that while a child process
4886 * is running interrupts generated by the user are sent to the child
4887 * but not to the shell. This means that an infinite loop started by
4888 * an interactive user may be hard to kill. With job control turned off,
4889 * an interactive user may place an interactive program inside a loop.
4890 * If the interactive program catches interrupts, the user doesn't want
4891 * these interrupts to also abort the loop. The approach we take here
4892 * is to have the shell ignore interrupt signals while waiting for a
4893 * foreground process to terminate, and then send itself an interrupt
4894 * signal if the child process was terminated by an interrupt signal.
4895 * Unfortunately, some programs want to do a bit of cleanup and then
4896 * exit on interrupt; unless these processes terminate themselves by
4897 * sending a signal to themselves (instead of calling exit) they will
4898 * confuse this approach.
4900 * Called with interrupts off.
4903 waitforjob(struct job *jp)
4907 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4910 while (jp->state == JOBRUNNING) {
4911 /* In non-interactive shells, we _can_ get
4912 * a keyboard signal here and be EINTRed,
4913 * but we just loop back, waiting for command to complete.
4916 * "If bash is waiting for a command to complete and receives
4917 * a signal for which a trap has been set, the trap
4918 * will not be executed until the command completes."
4920 * Reality is that even if trap is not set, bash
4921 * will not act on the signal until command completes.
4922 * Try this. sleep5intoff.c:
4923 * #include <signal.h>
4924 * #include <unistd.h>
4927 * sigemptyset(&set);
4928 * sigaddset(&set, SIGINT);
4929 * sigaddset(&set, SIGQUIT);
4930 * sigprocmask(SIG_BLOCK, &set, NULL);
4934 * $ bash -c './sleep5intoff; echo hi'
4935 * ^C^C^C^C <--- pressing ^C once a second
4937 * $ bash -c './sleep5intoff; echo hi'
4938 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4941 dowait(DOWAIT_BLOCK, jp);
4948 xtcsetpgrp(ttyfd, rootpid);
4950 * This is truly gross.
4951 * If we're doing job control, then we did a TIOCSPGRP which
4952 * caused us (the shell) to no longer be in the controlling
4953 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4954 * intuit from the subprocess exit status whether a SIGINT
4955 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4957 if (jp->sigint) /* TODO: do the same with all signals */
4958 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4960 if (jp->state == JOBDONE)
4967 * return 1 if there are stopped jobs, otherwise 0
4979 if (jp && jp->state == JOBSTOPPED) {
4980 out2str("You have stopped jobs.\n");
4989 /* ============ redir.c
4991 * Code for dealing with input/output redirection.
4996 #define EMPTY -2 /* marks an unused slot in redirtab */
4997 #define CLOSED -3 /* marks a slot of previously-closed fd */
5000 * Open a file in noclobber mode.
5001 * The code was copied from bash.
5004 noclobberopen(const char *fname)
5007 struct stat finfo, finfo2;
5010 * If the file exists and is a regular file, return an error
5013 r = stat(fname, &finfo);
5014 if (r == 0 && S_ISREG(finfo.st_mode)) {
5020 * If the file was not present (r != 0), make sure we open it
5021 * exclusively so that if it is created before we open it, our open
5022 * will fail. Make sure that we do not truncate an existing file.
5023 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5024 * file was not a regular file, we leave O_EXCL off.
5027 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5028 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5030 /* If the open failed, return the file descriptor right away. */
5035 * OK, the open succeeded, but the file may have been changed from a
5036 * non-regular file to a regular file between the stat and the open.
5037 * We are assuming that the O_EXCL open handles the case where FILENAME
5038 * did not exist and is symlinked to an existing file between the stat
5043 * If we can open it and fstat the file descriptor, and neither check
5044 * revealed that it was a regular file, and the file has not been
5045 * replaced, return the file descriptor.
5047 if (fstat(fd, &finfo2) == 0
5048 && !S_ISREG(finfo2.st_mode)
5049 && finfo.st_dev == finfo2.st_dev
5050 && finfo.st_ino == finfo2.st_ino
5055 /* The file has been replaced. badness. */
5062 * Handle here documents. Normally we fork off a process to write the
5063 * data to a pipe. If the document is short, we can stuff the data in
5064 * the pipe without forking.
5066 /* openhere needs this forward reference */
5067 static void expandhere(union node *arg, int fd);
5069 openhere(union node *redir)
5075 ash_msg_and_raise_error("pipe call failed");
5076 if (redir->type == NHERE) {
5077 len = strlen(redir->nhere.doc->narg.text);
5078 if (len <= PIPE_BUF) {
5079 full_write(pip[1], redir->nhere.doc->narg.text, len);
5083 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5086 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5087 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5088 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5089 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5090 signal(SIGPIPE, SIG_DFL);
5091 if (redir->type == NHERE)
5092 full_write(pip[1], redir->nhere.doc->narg.text, len);
5094 expandhere(redir->nhere.doc, pip[1]);
5095 _exit(EXIT_SUCCESS);
5103 openredirect(union node *redir)
5108 fname = redir->nfile.expfname;
5109 switch (redir->nfile.type) {
5111 f = open(fname, O_RDONLY);
5116 f = open(fname, O_RDWR|O_CREAT, 0666);
5121 #if ENABLE_ASH_BASH_COMPAT
5124 /* Take care of noclobber mode. */
5126 f = noclobberopen(fname);
5133 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5138 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5146 /* Fall through to eliminate warning. */
5147 /* Our single caller does this itself */
5154 f = openhere(redir);
5160 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5162 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5166 * Copy a file descriptor to be >= to. Returns -1
5167 * if the source file descriptor is closed, EMPTY if there are no unused
5168 * file descriptors left.
5170 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5171 * old code was doing close(to) prior to copyfd() to achieve the same */
5173 COPYFD_EXACT = (int)~(INT_MAX),
5174 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5177 copyfd(int from, int to)
5181 if (to & COPYFD_EXACT) {
5182 to &= ~COPYFD_EXACT;
5184 newfd = dup2(from, to);
5186 newfd = fcntl(from, F_DUPFD, to);
5189 if (errno == EMFILE)
5191 /* Happens when source fd is not open: try "echo >&99" */
5192 ash_msg_and_raise_error("%d: %m", from);
5197 /* Struct def and variable are moved down to the first usage site */
5202 struct redirtab *next;
5205 struct two_fd_t two_fd[];
5207 #define redirlist (G_var.redirlist)
5209 static int need_to_remember(struct redirtab *rp, int fd)
5213 if (!rp) /* remembering was not requested */
5216 for (i = 0; i < rp->pair_count; i++) {
5217 if (rp->two_fd[i].orig == fd) {
5218 /* already remembered */
5225 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5226 static int is_hidden_fd(struct redirtab *rp, int fd)
5229 struct parsefile *pf;
5233 /* Check open scripts' fds */
5236 /* We skip pf_fd == 0 case because of the following case:
5237 * $ ash # running ash interactively
5239 * and in script.sh: "exec 9>&0".
5240 * Even though top-level pf_fd _is_ 0,
5241 * it's still ok to use it: "read" builtin uses it,
5242 * why should we cripple "exec" builtin?
5244 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5252 /* Check saved fds of redirects */
5253 fd |= COPYFD_RESTORE;
5254 for (i = 0; i < rp->pair_count; i++) {
5255 if (rp->two_fd[i].copy == fd) {
5263 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5264 * old file descriptors are stashed away so that the redirection can be
5265 * undone by calling popredir.
5267 /* flags passed to redirect */
5268 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5269 #define REDIR_SAVEFD2 03 /* set preverrout */
5271 redirect(union node *redir, int flags)
5273 struct redirtab *sv;
5278 int copied_fd2 = -1;
5288 if (flags & REDIR_PUSH) {
5289 union node *tmp = redir;
5292 #if ENABLE_ASH_BASH_COMPAT
5293 if (tmp->nfile.type == NTO2)
5296 tmp = tmp->nfile.next;
5298 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5299 sv->next = redirlist;
5300 sv->pair_count = sv_pos;
5302 sv->nullredirs = g_nullredirs - 1;
5304 while (sv_pos > 0) {
5306 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5312 fd = redir->nfile.fd;
5313 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5314 right_fd = redir->ndup.dupfd;
5315 //bb_error_msg("doing %d > %d", fd, right_fd);
5316 /* redirect from/to same file descriptor? */
5319 /* "echo >&10" and 10 is a fd opened to a sh script? */
5320 if (is_hidden_fd(sv, right_fd)) {
5321 errno = EBADF; /* as if it is closed */
5322 ash_msg_and_raise_error("%d: %m", right_fd);
5326 newfd = openredirect(redir); /* always >= 0 */
5328 /* Descriptor wasn't open before redirect.
5329 * Mark it for close in the future */
5330 if (need_to_remember(sv, fd)) {
5331 goto remember_to_close;
5336 #if ENABLE_ASH_BASH_COMPAT
5339 if (need_to_remember(sv, fd)) {
5340 /* Copy old descriptor */
5341 /* Careful to not accidentally "save"
5342 * to the same fd as right side fd in N>&M */
5343 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5344 i = fcntl(fd, F_DUPFD, minfd);
5345 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5346 * are closed in popredir() in the child, preventing them from leaking
5347 * into child. (popredir() also cleans up the mess in case of failures)
5352 /* Strange error (e.g. "too many files" EMFILE?) */
5356 ash_msg_and_raise_error("%d: %m", fd);
5359 /* EBADF: it is not open - good, remember to close it */
5362 } else { /* fd is open, save its copy */
5363 /* "exec fd>&-" should not close fds
5364 * which point to script file(s).
5365 * Force them to be restored afterwards */
5366 if (is_hidden_fd(sv, fd))
5367 i |= COPYFD_RESTORE;
5371 sv->two_fd[sv_pos].orig = fd;
5372 sv->two_fd[sv_pos].copy = i;
5376 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5377 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5378 /* Don't want to trigger debugging */
5382 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5384 } else if (fd != newfd) { /* move newfd to fd */
5385 copyfd(newfd, fd | COPYFD_EXACT);
5386 #if ENABLE_ASH_BASH_COMPAT
5387 if (!(redir->nfile.type == NTO2 && fd == 2))
5391 #if ENABLE_ASH_BASH_COMPAT
5392 if (redir->nfile.type == NTO2 && fd == 1) {
5393 /* We already redirected it to fd 1, now copy it to 2 */
5399 } while ((redir = redir->nfile.next) != NULL);
5402 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5403 preverrout_fd = copied_fd2;
5407 * Undo the effects of the last redirection.
5410 popredir(int drop, int restore)
5412 struct redirtab *rp;
5415 if (--g_nullredirs >= 0)
5419 for (i = 0; i < rp->pair_count; i++) {
5420 int fd = rp->two_fd[i].orig;
5421 int copy = rp->two_fd[i].copy;
5422 if (copy == CLOSED) {
5427 if (copy != EMPTY) {
5428 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5429 copy &= ~COPYFD_RESTORE;
5431 copyfd(copy, fd | COPYFD_EXACT);
5433 close(copy & ~COPYFD_RESTORE);
5436 redirlist = rp->next;
5437 g_nullredirs = rp->nullredirs;
5443 * Undo all redirections. Called on error or interrupt.
5447 * Discard all saved file descriptors.
5450 clearredir(int drop)
5456 popredir(drop, /*restore:*/ 0);
5461 redirectsafe(union node *redir, int flags)
5464 volatile int saveint;
5465 struct jmploc *volatile savehandler = exception_handler;
5466 struct jmploc jmploc;
5469 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5470 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5472 exception_handler = &jmploc;
5473 redirect(redir, flags);
5475 exception_handler = savehandler;
5476 if (err && exception_type != EXERROR)
5477 longjmp(exception_handler->loc, 1);
5478 RESTORE_INT(saveint);
5483 /* ============ Routines to expand arguments to commands
5485 * We have to deal with backquotes, shell variables, and file metacharacters.
5488 #if ENABLE_SH_MATH_SUPPORT
5490 ash_arith(const char *s)
5492 arith_state_t math_state;
5495 math_state.lookupvar = lookupvar;
5496 math_state.setvar = setvar0;
5497 //math_state.endofname = endofname;
5500 result = arith(&math_state, s);
5501 if (math_state.errmsg)
5502 ash_msg_and_raise_error(math_state.errmsg);
5512 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5513 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5514 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5515 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5516 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5517 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5518 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5519 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5520 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5524 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5525 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5526 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5527 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5528 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5530 /* Add CTLESC when necessary. */
5531 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5532 /* Do not skip NUL characters. */
5533 #define QUOTES_KEEPNUL EXP_TILDE
5536 * Structure specifying which parts of the string should be searched
5537 * for IFS characters.
5540 struct ifsregion *next; /* next region in list */
5541 int begoff; /* offset of start of region */
5542 int endoff; /* offset of end of region */
5543 int nulonly; /* search for nul bytes only */
5547 struct strlist *list;
5548 struct strlist **lastp;
5551 /* output of current string */
5552 static char *expdest;
5553 /* list of back quote expressions */
5554 static struct nodelist *argbackq;
5555 /* first struct in list of ifs regions */
5556 static struct ifsregion ifsfirst;
5557 /* last struct in list */
5558 static struct ifsregion *ifslastp;
5559 /* holds expanded arg list */
5560 static struct arglist exparg;
5565 #if !ENABLE_SH_MATH_SUPPORT
5566 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5567 typedef long arith_t;
5568 # define ARITH_FMT "%ld"
5575 expdest = makestrspace(32, expdest);
5576 len = fmtstr(expdest, 32, ARITH_FMT, num);
5577 STADJUST(len, expdest);
5582 esclen(const char *start, const char *p)
5586 while (p > start && (unsigned char)*--p == CTLESC) {
5593 * Remove any CTLESC characters from a string.
5596 rmescapes(char *str, int flag)
5598 static const char qchars[] ALIGN1 = {
5599 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5603 unsigned protect_against_glob;
5605 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5607 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5613 if (flag & RMESCAPE_ALLOC) {
5614 size_t len = p - str;
5615 size_t fulllen = len + strlen(p) + 1;
5617 if (flag & RMESCAPE_GROW) {
5618 int strloc = str - (char *)stackblock();
5619 r = makestrspace(fulllen, expdest);
5620 /* p and str may be invalidated by makestrspace */
5621 str = (char *)stackblock() + strloc;
5623 } else if (flag & RMESCAPE_HEAP) {
5624 r = ckmalloc(fulllen);
5626 r = stalloc(fulllen);
5630 q = (char *)memcpy(q, str, len) + len;
5635 globbing = flag & RMESCAPE_GLOB;
5636 protect_against_glob = globbing;
5638 if ((unsigned char)*p == CTLQUOTEMARK) {
5639 // Note: both inquotes and protect_against_glob only affect whether
5640 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5641 inquotes = ~inquotes;
5643 protect_against_glob = globbing;
5646 if ((unsigned char)*p == CTLESC) {
5648 if (protect_against_glob) {
5651 } else if (*p == '\\' && !inquotes) {
5652 /* naked back slash */
5653 protect_against_glob = 0;
5656 #if ENABLE_ASH_BASH_COMPAT
5657 else if (*p == '/' && slash) {
5658 /* stop handling globbing and mark location of slash */
5659 globbing = slash = 0;
5663 protect_against_glob = globbing;
5668 if (flag & RMESCAPE_GROW) {
5670 STADJUST(q - r + 1, expdest);
5674 #define pmatch(a, b) !fnmatch((a), (b), 0)
5677 * Prepare a pattern for a expmeta (internal glob(3)) call.
5679 * Returns an stalloced string.
5682 preglob(const char *pattern, int flag)
5684 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5688 * Put a string on the stack.
5691 memtodest(const char *p, size_t len, int syntax, int quotes)
5698 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5701 unsigned char c = *p++;
5703 int n = SIT(c, syntax);
5704 if ((quotes & QUOTES_ESC) &&
5706 (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
5709 } else if (!(quotes & QUOTES_KEEPNUL))
5718 strtodest(const char *p, int syntax, int quotes)
5720 size_t len = strlen(p);
5721 memtodest(p, len, syntax, quotes);
5726 * Record the fact that we have to scan this region of the
5727 * string for IFS characters.
5730 recordregion(int start, int end, int nulonly)
5732 struct ifsregion *ifsp;
5734 if (ifslastp == NULL) {
5738 ifsp = ckzalloc(sizeof(*ifsp));
5739 /*ifsp->next = NULL; - ckzalloc did it */
5740 ifslastp->next = ifsp;
5744 ifslastp->begoff = start;
5745 ifslastp->endoff = end;
5746 ifslastp->nulonly = nulonly;
5750 removerecordregions(int endoff)
5752 if (ifslastp == NULL)
5755 if (ifsfirst.endoff > endoff) {
5756 while (ifsfirst.next) {
5757 struct ifsregion *ifsp;
5759 ifsp = ifsfirst.next->next;
5760 free(ifsfirst.next);
5761 ifsfirst.next = ifsp;
5764 if (ifsfirst.begoff > endoff) {
5767 ifslastp = &ifsfirst;
5768 ifsfirst.endoff = endoff;
5773 ifslastp = &ifsfirst;
5774 while (ifslastp->next && ifslastp->next->begoff < endoff)
5775 ifslastp = ifslastp->next;
5776 while (ifslastp->next) {
5777 struct ifsregion *ifsp;
5779 ifsp = ifslastp->next->next;
5780 free(ifslastp->next);
5781 ifslastp->next = ifsp;
5784 if (ifslastp->endoff > endoff)
5785 ifslastp->endoff = endoff;
5789 exptilde(char *startp, char *p, int flags)
5795 int quotes = flags & QUOTES_ESC;
5799 while ((c = *++p) != '\0') {
5806 if (flags & EXP_VARTILDE)
5816 if (*name == '\0') {
5817 home = lookupvar("HOME");
5819 pw = getpwnam(name);
5824 if (!home || !*home)
5827 strtodest(home, SQSYNTAX, quotes);
5835 * Execute a command inside back quotes. If it's a builtin command, we
5836 * want to save its output in a block obtained from malloc. Otherwise
5837 * we fork off a subprocess and get the output of the command via a pipe.
5838 * Should be called with interrupts off.
5840 struct backcmd { /* result of evalbackcmd */
5841 int fd; /* file descriptor to read from */
5842 int nleft; /* number of chars in buffer */
5843 char *buf; /* buffer */
5844 struct job *jp; /* job structure for command */
5847 /* These forward decls are needed to use "eval" code for backticks handling: */
5848 static uint8_t back_exitstatus; /* exit status of backquoted command */
5849 #define EV_EXIT 01 /* exit after evaluating tree */
5850 static void evaltree(union node *, int);
5852 static void FAST_FUNC
5853 evalbackcmd(union node *n, struct backcmd *result)
5864 saveherefd = herefd;
5872 ash_msg_and_raise_error("pipe call failed");
5873 jp = makejob(/*n,*/ 1);
5874 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5879 copyfd(pip[1], 1 | COPYFD_EXACT);
5883 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5887 result->fd = pip[0];
5890 herefd = saveherefd;
5892 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5893 result->fd, result->buf, result->nleft, result->jp));
5897 * Expand stuff in backwards quotes.
5900 expbackq(union node *cmd, int flag)
5908 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5909 struct stackmark smark;
5912 setstackmark(&smark);
5914 startloc = dest - (char *)stackblock();
5916 evalbackcmd(cmd, &in);
5917 popstackmark(&smark);
5924 memtodest(p, i, syntax, flag & QUOTES_ESC);
5928 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5929 TRACE(("expbackq: read returns %d\n", i));
5938 back_exitstatus = waitforjob(in.jp);
5942 /* Eat all trailing newlines */
5944 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5948 if (!(flag & EXP_QUOTED))
5949 recordregion(startloc, dest - (char *)stackblock(), 0);
5950 TRACE(("evalbackq: size:%d:'%.*s'\n",
5951 (int)((dest - (char *)stackblock()) - startloc),
5952 (int)((dest - (char *)stackblock()) - startloc),
5953 stackblock() + startloc));
5956 #if ENABLE_SH_MATH_SUPPORT
5958 * Expand arithmetic expression. Backup to start of expression,
5959 * evaluate, place result in (backed up) result, adjust string position.
5971 * This routine is slightly over-complicated for
5972 * efficiency. Next we scan backwards looking for the
5973 * start of arithmetic.
5975 start = stackblock();
5982 while ((unsigned char)*p != CTLARI) {
5986 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5991 esc = esclen(start, p);
6001 removerecordregions(begoff);
6005 if (flag & QUOTES_ESC)
6006 rmescapes(p + 1, 0);
6008 len = cvtnum(ash_arith(p + 1));
6010 if (!(flag & EXP_QUOTED))
6011 recordregion(begoff, begoff + len, 0);
6015 /* argstr needs it */
6016 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6019 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6020 * characters to allow for further processing. Otherwise treat
6021 * $@ like $* since no splitting will be performed.
6023 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6024 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6025 * for correct expansion of "B=$A" word.
6028 argstr(char *p, int flags, struct strlist *var_str_list)
6030 static const char spclchars[] ALIGN1 = {
6038 #if ENABLE_SH_MATH_SUPPORT
6043 const char *reject = spclchars;
6044 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6049 if (!(flags & EXP_VARTILDE)) {
6051 } else if (flags & EXP_VARTILDE2) {
6056 if (flags & EXP_TILDE) {
6059 flags &= ~EXP_TILDE;
6063 p = exptilde(p, q, flags);
6066 startloc = expdest - (char *)stackblock();
6070 length += strcspn(p + length, reject);
6074 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6076 /* c == '=' || c == ':' || c == CTLENDARI */
6082 expdest = stack_nputstr(p, length, expdest);
6083 newloc = expdest - (char *)stackblock();
6084 if (breakall && !inquotes && newloc > startloc) {
6085 recordregion(startloc, newloc, 0);
6096 if (flags & EXP_VARTILDE2) {
6100 flags |= EXP_VARTILDE2;
6105 * sort of a hack - expand tildes in variable
6106 * assignments (after the first '=' and after ':'s).
6115 case CTLENDVAR: /* ??? */
6118 inquotes ^= EXP_QUOTED;
6119 /* "$@" syntax adherence hack */
6120 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6121 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6125 if (flags & QUOTES_ESC) {
6136 * Quoted parameter expansion pattern: remove quote
6137 * unless inside inner quotes or we have a literal
6140 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6141 EXP_QPAT && *p != '\\')
6146 TRACE(("argstr: evalvar('%s')\n", p));
6147 p = evalvar(p, flags | inquotes, var_str_list);
6148 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6151 expbackq(argbackq->n, flags | inquotes);
6152 argbackq = argbackq->next;
6154 #if ENABLE_SH_MATH_SUPPORT
6157 expari(flags | inquotes);
6166 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6167 char *pattern, int quotes, int zero)
6176 const char *s = loc2;
6183 match = pmatch(pattern, s);
6188 if (quotes && (unsigned char)*loc == CTLESC)
6197 scanright(char *startp, char *rmesc, char *rmescend,
6198 char *pattern, int quotes, int match_at_start)
6200 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6201 int try2optimize = match_at_start;
6207 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6208 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6209 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6211 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6212 * and on each iteration they go back two/one char until they reach the beginning.
6213 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6215 /* TODO: document in what other circumstances we are called. */
6217 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6220 const char *s = loc2;
6221 if (match_at_start) {
6225 match = pmatch(pattern, s);
6226 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6230 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6232 /* Maybe we can optimize this:
6233 * if pattern ends with unescaped *, we can avoid checking
6234 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6235 * it wont match truncated "raw_value_of_" strings too.
6237 unsigned plen = strlen(pattern);
6238 /* Does it end with "*"? */
6239 if (plen != 0 && pattern[--plen] == '*') {
6240 /* "xxxx*" is not escaped */
6241 /* "xxx\*" is escaped */
6242 /* "xx\\*" is not escaped */
6243 /* "x\\\*" is escaped */
6245 while (plen != 0 && pattern[--plen] == '\\')
6248 break; /* ends with unescaped "*" */
6256 esc = esclen(startp, loc);
6267 static void varunset(const char *, const char *, const char *, int) NORETURN;
6269 varunset(const char *end, const char *var, const char *umsg, int varflags)
6275 msg = "parameter not set";
6277 if ((unsigned char)*end == CTLENDVAR) {
6278 if (varflags & VSNUL)
6284 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6288 subevalvar(char *p, char *varname, int strloc, int subtype,
6289 int startloc, int varflags, int flag, struct strlist *var_str_list)
6291 struct nodelist *saveargbackq = argbackq;
6292 int quotes = flag & QUOTES_ESC;
6295 char *rmesc, *rmescend;
6297 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6298 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6299 int saveherefd = herefd;
6300 int amount, resetloc;
6301 IF_ASH_BASH_COMPAT(int workloc;)
6303 char *(*scan)(char*, char*, char*, char*, int, int);
6305 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6306 // p, varname, strloc, subtype, startloc, varflags, quotes);
6309 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6310 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6312 STPUTC('\0', expdest);
6313 herefd = saveherefd;
6314 argbackq = saveargbackq;
6315 startp = (char *)stackblock() + startloc;
6319 setvar0(varname, startp);
6320 amount = startp - expdest;
6321 STADJUST(amount, expdest);
6325 varunset(p, varname, startp, varflags);
6328 #if ENABLE_ASH_BASH_COMPAT
6330 loc = str = stackblock() + strloc;
6331 /* Read POS in ${var:POS:LEN} */
6332 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6333 len = str - startp - 1;
6335 /* *loc != '\0', guaranteed by parser */
6339 /* Adjust the length by the number of escapes */
6340 for (ptr = startp; ptr < (str - 1); ptr++) {
6341 if ((unsigned char)*ptr == CTLESC) {
6349 if (*loc++ == ':') {
6353 /* Skip POS in ${var:POS:LEN} */
6355 while (*loc && *loc != ':') {
6357 * bash complains on: var=qwe; echo ${var:1a:123}
6359 ash_msg_and_raise_error(msg_illnum, str);
6363 if (*loc++ == ':') {
6368 /* ${VAR:$((-n)):l} starts n chars from the end */
6369 pos = orig_len + pos;
6371 if ((unsigned)pos >= orig_len) {
6372 /* apart from obvious ${VAR:999999:l},
6373 * covers ${VAR:$((-9999999)):l} - result is ""
6379 if (len > (orig_len - pos))
6380 len = orig_len - pos;
6382 for (str = startp; pos; str++, pos--) {
6383 if (quotes && (unsigned char)*str == CTLESC)
6386 for (loc = startp; len; len--) {
6387 if (quotes && (unsigned char)*str == CTLESC)
6392 amount = loc - expdest;
6393 STADJUST(amount, expdest);
6398 resetloc = expdest - (char *)stackblock();
6400 /* We'll comeback here if we grow the stack while handling
6401 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6402 * stack will need rebasing, and we'll need to remove our work
6405 IF_ASH_BASH_COMPAT(restart:)
6407 amount = expdest - ((char *)stackblock() + resetloc);
6408 STADJUST(-amount, expdest);
6409 startp = (char *)stackblock() + startloc;
6412 rmescend = (char *)stackblock() + strloc;
6414 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6415 if (rmesc != startp) {
6417 startp = (char *)stackblock() + startloc;
6421 str = (char *)stackblock() + strloc;
6423 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6424 * The result is a_\_z_c (not a\_\_z_c)!
6426 * The search pattern and replace string treat backslashes differently!
6427 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6428 * and string. It's only used on the first call.
6430 preglob(str, IF_ASH_BASH_COMPAT(
6431 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6432 RMESCAPE_SLASH :) 0);
6434 #if ENABLE_ASH_BASH_COMPAT
6435 workloc = expdest - (char *)stackblock();
6436 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6440 if ((repl=strchr(str, CTLESC)))
6445 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6447 /* If there's no pattern to match, return the expansion unmolested */
6456 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6457 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6459 /* No match, advance */
6460 char *restart_detect = stackblock();
6462 STPUTC(*idx, expdest);
6463 if (quotes && (unsigned char)*idx == CTLESC) {
6466 STPUTC(*idx, expdest);
6468 if (stackblock() != restart_detect)
6473 /* continue; - prone to quadratic behavior, smarter code: */
6476 if (str[0] == '*') {
6477 /* Pattern is "*foo". If "*foo" does not match "long_string",
6478 * it would never match "ong_string" etc, no point in trying.
6485 if (subtype == VSREPLACEALL) {
6487 if (quotes && (unsigned char)*idx == CTLESC)
6496 //bb_error_msg("repl:'%s'", repl);
6497 for (loc = (char*)repl; *loc; loc++) {
6498 char *restart_detect = stackblock();
6499 if (quotes && *loc == '\\') {
6500 STPUTC(CTLESC, expdest);
6503 STPUTC(*loc, expdest);
6504 if (stackblock() != restart_detect)
6509 if (subtype == VSREPLACE) {
6510 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6512 char *restart_detect = stackblock();
6513 STPUTC(*idx, expdest);
6514 if (stackblock() != restart_detect)
6523 /* We've put the replaced text into a buffer at workloc, now
6524 * move it to the right place and adjust the stack.
6526 STPUTC('\0', expdest);
6527 startp = (char *)stackblock() + startloc;
6528 memmove(startp, (char *)stackblock() + workloc, len + 1);
6529 //bb_error_msg("startp:'%s'", startp);
6530 amount = expdest - (startp + len);
6531 STADJUST(-amount, expdest);
6534 #endif /* ENABLE_ASH_BASH_COMPAT */
6536 subtype -= VSTRIMRIGHT;
6538 if (subtype < 0 || subtype > 7)
6541 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6542 zero = subtype >> 1;
6543 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6544 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6546 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6549 memmove(startp, loc, str - loc);
6550 loc = startp + (str - loc) - 1;
6553 amount = loc - expdest;
6554 STADJUST(amount, expdest);
6560 * Add the value of a specialized variable to the stack string.
6561 * name parameter (examples):
6562 * ash -c 'echo $1' name:'1='
6563 * ash -c 'echo $qwe' name:'qwe='
6564 * ash -c 'echo $$' name:'$='
6565 * ash -c 'echo ${$}' name:'$='
6566 * ash -c 'echo ${$##q}' name:'$=q'
6567 * ash -c 'echo ${#$}' name:'$='
6568 * note: examples with bad shell syntax:
6569 * ash -c 'echo ${#$1}' name:'$=1'
6570 * ash -c 'echo ${#1#}' name:'1=#'
6572 static NOINLINE ssize_t
6573 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6580 int quoted = flags & EXP_QUOTED;
6581 int subtype = varflags & VSTYPE;
6582 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6583 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6584 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6586 sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
6596 num = shellparam.nparam;
6604 goto check_1char_name;
6606 expdest = makestrspace(NOPTS, expdest);
6607 for (i = NOPTS - 1; i >= 0; i--) {
6609 USTPUTC(optletters(i), expdest);
6615 /* handles cases similar to ${#$1} */
6616 if (name[2] != '\0')
6617 raise_error_syntax("bad substitution");
6624 if (quoted && (flags & EXP_FULL)) {
6625 /* note: this is not meant as PEOF value */
6626 sep = 1 << CHAR_BIT;
6631 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6637 while ((p = *ap++) != NULL) {
6638 len += strtodest(p, syntax, quotes);
6642 memtodest(&sepc, 1, syntax, quotes);
6646 } /* case '@' and '*' */
6657 num = atoi(name); /* number(name) fails on ${N#str} etc */
6658 if (num < 0 || num > shellparam.nparam)
6660 p = num ? shellparam.p[num - 1] : arg0;
6663 /* NB: name has form "VAR=..." */
6665 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6666 * which should be considered before we check variables. */
6668 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6672 str = var_str_list->text;
6673 eq = strchr(str, '=');
6674 if (!eq) /* stop at first non-assignment */
6677 if (name_len == (unsigned)(eq - str)
6678 && strncmp(str, name, name_len) == 0
6681 /* goto value; - WRONG! */
6682 /* think "A=1 A=2 B=$A" */
6684 var_str_list = var_str_list->next;
6685 } while (var_str_list);
6689 p = lookupvar(name);
6694 len = strtodest(p, syntax, quotes);
6695 #if ENABLE_UNICODE_SUPPORT
6696 if (subtype == VSLENGTH && len > 0) {
6697 reinit_unicode_for_ash();
6698 if (unicode_status == UNICODE_ON) {
6699 len = unicode_strlen(p);
6707 STADJUST(-len, expdest);
6712 * Expand a variable, and return a pointer to the next character in the
6716 evalvar(char *p, int flags, struct strlist *var_str_list)
6727 varflags = (unsigned char) *p++;
6728 subtype = varflags & VSTYPE;
6729 quoted = flags & EXP_QUOTED;
6731 easy = (!quoted || (*var == '@' && shellparam.nparam));
6732 startloc = expdest - (char *)stackblock();
6733 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6736 varlen = varvalue(var, varflags, flags, var_str_list);
6737 if (varflags & VSNUL)
6740 if (subtype == VSPLUS) {
6741 varlen = -1 - varlen;
6745 if (subtype == VSMINUS) {
6750 flags | EXP_TILDE | EXP_WORD,
6760 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6762 if (subevalvar(p, var, /* strloc: */ 0,
6763 subtype, startloc, varflags,
6764 /* quotes: */ flags & ~QUOTES_ESC,
6769 * Remove any recorded regions beyond
6772 removerecordregions(startloc);
6782 if (varlen < 0 && uflag)
6783 varunset(p, var, 0, 0);
6785 if (subtype == VSLENGTH) {
6786 cvtnum(varlen > 0 ? varlen : 0);
6790 if (subtype == VSNORMAL) {
6801 case VSTRIMRIGHTMAX:
6802 #if ENABLE_ASH_BASH_COMPAT
6815 * Terminate the string and start recording the pattern
6818 STPUTC('\0', expdest);
6819 patloc = expdest - (char *)stackblock();
6820 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6821 startloc, varflags, flags, var_str_list)) {
6822 int amount = expdest - (
6823 (char *)stackblock() + patloc - 1
6825 STADJUST(-amount, expdest);
6827 /* Remove any recorded regions beyond start of variable */
6828 removerecordregions(startloc);
6830 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6834 if (subtype != VSNORMAL) { /* skip to end of alternative */
6837 unsigned char c = *p++;
6840 else if (c == CTLBACKQ) {
6842 argbackq = argbackq->next;
6843 } else if (c == CTLVAR) {
6844 if ((*p++ & VSTYPE) != VSNORMAL)
6846 } else if (c == CTLENDVAR) {
6856 * Break the argument string into pieces based upon IFS and add the
6857 * strings to the argument list. The regions of the string to be
6858 * searched for IFS characters have been stored by recordregion.
6861 ifsbreakup(char *string, struct arglist *arglist)
6863 struct ifsregion *ifsp;
6868 const char *ifs, *realifs;
6873 if (ifslastp != NULL) {
6876 realifs = ifsset() ? ifsval() : defifs;
6879 p = string + ifsp->begoff;
6880 nulonly = ifsp->nulonly;
6881 ifs = nulonly ? nullstr : realifs;
6883 while (p < string + ifsp->endoff) {
6885 if ((unsigned char)*p == CTLESC)
6887 if (!strchr(ifs, *p)) {
6892 ifsspc = (strchr(defifs, *p) != NULL);
6893 /* Ignore IFS whitespace at start */
6894 if (q == start && ifsspc) {
6900 sp = stzalloc(sizeof(*sp));
6902 *arglist->lastp = sp;
6903 arglist->lastp = &sp->next;
6907 if (p >= string + ifsp->endoff) {
6911 if ((unsigned char)*p == CTLESC)
6913 if (strchr(ifs, *p) == NULL) {
6917 if (strchr(defifs, *p) == NULL) {
6932 } while (ifsp != NULL);
6941 sp = stzalloc(sizeof(*sp));
6943 *arglist->lastp = sp;
6944 arglist->lastp = &sp->next;
6950 struct ifsregion *p;
6955 struct ifsregion *ifsp;
6961 ifsfirst.next = NULL;
6966 * Add a file name to the list.
6969 addfname(const char *name)
6973 sp = stzalloc(sizeof(*sp));
6974 sp->text = ststrdup(name);
6976 exparg.lastp = &sp->next;
6980 * Do metacharacter (i.e. *, ?, [...]) expansion.
6983 expmeta(char *expdir, char *enddir, char *name)
6998 for (p = name; *p; p++) {
6999 if (*p == '*' || *p == '?')
7001 else if (*p == '[') {
7008 if (*q == '/' || *q == '\0')
7015 } else if (*p == '\\')
7017 else if (*p == '/') {
7024 if (metaflag == 0) { /* we've reached the end of the file name */
7025 if (enddir != expdir)
7033 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7044 } while (p < start);
7046 if (enddir == expdir) {
7048 } else if (enddir == expdir + 1 && *expdir == '/') {
7057 if (enddir != expdir)
7059 if (*endname == 0) {
7071 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7072 if (dp->d_name[0] == '.' && !matchdot)
7074 if (pmatch(start, dp->d_name)) {
7076 strcpy(enddir, dp->d_name);
7079 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7082 expmeta(expdir, p, endname);
7091 static struct strlist *
7092 msort(struct strlist *list, int len)
7094 struct strlist *p, *q = NULL;
7095 struct strlist **lpp;
7103 for (n = half; --n >= 0;) {
7107 q->next = NULL; /* terminate first half of list */
7108 q = msort(list, half); /* sort first half of list */
7109 p = msort(p, len - half); /* sort second half */
7112 #if ENABLE_LOCALE_SUPPORT
7113 if (strcoll(p->text, q->text) < 0)
7115 if (strcmp(p->text, q->text) < 0)
7139 * Sort the results of file name expansion. It calculates the number of
7140 * strings to sort and then calls msort (short for merge sort) to do the
7143 static struct strlist *
7144 expsort(struct strlist *str)
7150 for (sp = str; sp; sp = sp->next)
7152 return msort(str, len);
7156 expandmeta(struct strlist *str /*, int flag*/)
7158 static const char metachars[] ALIGN1 = {
7161 /* TODO - EXP_REDIR */
7165 struct strlist **savelastp;
7171 if (!strpbrk(str->text, metachars))
7173 savelastp = exparg.lastp;
7176 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7178 int i = strlen(str->text);
7179 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7181 expmeta(expdir, expdir, p);
7186 if (exparg.lastp == savelastp) {
7191 *exparg.lastp = str;
7192 rmescapes(str->text, 0);
7193 exparg.lastp = &str->next;
7195 *exparg.lastp = NULL;
7196 *savelastp = sp = expsort(*savelastp);
7197 while (sp->next != NULL)
7199 exparg.lastp = &sp->next;
7206 * Perform variable substitution and command substitution on an argument,
7207 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7208 * perform splitting and file name expansion. When arglist is NULL, perform
7209 * here document expansion.
7212 expandarg(union node *arg, struct arglist *arglist, int flag)
7217 argbackq = arg->narg.backquote;
7218 STARTSTACKSTR(expdest);
7219 ifsfirst.next = NULL;
7221 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7222 argstr(arg->narg.text, flag,
7223 /* var_str_list: */ arglist ? arglist->list : NULL);
7224 p = _STPUTC('\0', expdest);
7226 if (arglist == NULL) {
7227 return; /* here document expanded */
7229 p = grabstackstr(p);
7230 TRACE(("expandarg: p:'%s'\n", p));
7231 exparg.lastp = &exparg.list;
7235 if (flag & EXP_FULL) {
7236 ifsbreakup(p, &exparg);
7237 *exparg.lastp = NULL;
7238 exparg.lastp = &exparg.list;
7239 expandmeta(exparg.list /*, flag*/);
7241 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7243 TRACE(("expandarg: rmescapes:'%s'\n", p));
7245 sp = stzalloc(sizeof(*sp));
7248 exparg.lastp = &sp->next;
7252 *exparg.lastp = NULL;
7254 *arglist->lastp = exparg.list;
7255 arglist->lastp = exparg.lastp;
7260 * Expand shell variables and backquotes inside a here document.
7263 expandhere(union node *arg, int fd)
7266 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7267 full_write(fd, stackblock(), expdest - (char *)stackblock());
7271 * Returns true if the pattern matches the string.
7274 patmatch(char *pattern, const char *string)
7276 return pmatch(preglob(pattern, 0), string);
7280 * See if a pattern matches in a case statement.
7283 casematch(union node *pattern, char *val)
7285 struct stackmark smark;
7288 setstackmark(&smark);
7289 argbackq = pattern->narg.backquote;
7290 STARTSTACKSTR(expdest);
7292 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7293 /* var_str_list: */ NULL);
7294 STACKSTRNUL(expdest);
7295 result = patmatch(stackblock(), val);
7296 popstackmark(&smark);
7301 /* ============ find_command */
7305 int (*builtin)(int, char **) FAST_FUNC;
7306 /* unsigned flags; */
7308 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7309 /* "regular" builtins always take precedence over commands,
7310 * regardless of PATH=....%builtin... position */
7311 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7312 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7315 smallint cmdtype; /* CMDxxx */
7318 /* index >= 0 for commands without path (slashes) */
7319 /* (TODO: what exactly does the value mean? PATH position?) */
7320 /* index == -1 for commands with slashes */
7321 /* index == (-2 - applet_no) for NOFORK applets */
7322 const struct builtincmd *cmd;
7323 struct funcnode *func;
7326 /* values of cmdtype */
7327 #define CMDUNKNOWN -1 /* no entry in table for command */
7328 #define CMDNORMAL 0 /* command is an executable program */
7329 #define CMDFUNCTION 1 /* command is a shell function */
7330 #define CMDBUILTIN 2 /* command is a shell builtin */
7332 /* action to find_command() */
7333 #define DO_ERR 0x01 /* prints errors */
7334 #define DO_ABS 0x02 /* checks absolute paths */
7335 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7336 #define DO_ALTPATH 0x08 /* using alternate path */
7337 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7339 static void find_command(char *, struct cmdentry *, int, const char *);
7342 /* ============ Hashing commands */
7345 * When commands are first encountered, they are entered in a hash table.
7346 * This ensures that a full path search will not have to be done for them
7347 * on each invocation.
7349 * We should investigate converting to a linear search, even though that
7350 * would make the command name "hash" a misnomer.
7354 struct tblentry *next; /* next entry in hash chain */
7355 union param param; /* definition of builtin function */
7356 smallint cmdtype; /* CMDxxx */
7357 char rehash; /* if set, cd done since entry created */
7358 char cmdname[1]; /* name of command */
7361 static struct tblentry **cmdtable;
7362 #define INIT_G_cmdtable() do { \
7363 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7366 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7370 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7372 #if ENABLE_FEATURE_SH_STANDALONE
7373 if (applet_no >= 0) {
7374 if (APPLET_IS_NOEXEC(applet_no)) {
7378 run_applet_no_and_exit(applet_no, argv);
7380 /* re-exec ourselves with the new arguments */
7381 execve(bb_busybox_exec_path, argv, envp);
7382 /* If they called chroot or otherwise made the binary no longer
7383 * executable, fall through */
7390 execve(cmd, argv, envp);
7391 } while (errno == EINTR);
7393 execve(cmd, argv, envp);
7395 if (cmd == (char*) bb_busybox_exec_path) {
7396 /* We already visited ENOEXEC branch below, don't do it again */
7397 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7401 if (errno == ENOEXEC) {
7402 /* Run "cmd" as a shell script:
7403 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7404 * "If the execve() function fails with ENOEXEC, the shell
7405 * shall execute a command equivalent to having a shell invoked
7406 * with the command name as its first operand,
7407 * with any remaining arguments passed to the new shell"
7409 * That is, do not use $SHELL, user's shell, or /bin/sh;
7410 * just call ourselves.
7412 * Note that bash reads ~80 chars of the file, and if it sees
7413 * a zero byte before it sees newline, it doesn't try to
7414 * interpret it, but fails with "cannot execute binary file"
7415 * message and exit code 126. For one, this prevents attempts
7416 * to interpret foreign ELF binaries as shell scripts.
7421 for (ap = argv; *ap; ap++)
7423 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7424 new[0] = (char*) "ash";
7427 while ((*ap++ = *++argv) != NULL)
7429 cmd = (char*) bb_busybox_exec_path;
7436 * Exec a program. Never returns. If you change this routine, you may
7437 * have to change the find_command routine as well.
7439 static void shellexec(char **, const char *, int) NORETURN;
7441 shellexec(char **argv, const char *path, int idx)
7447 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7449 clearredir(/*drop:*/ 1);
7450 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7451 if (strchr(argv[0], '/') != NULL
7452 #if ENABLE_FEATURE_SH_STANDALONE
7453 || (applet_no = find_applet_by_name(argv[0])) >= 0
7456 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7457 if (applet_no >= 0) {
7458 /* We tried execing ourself, but it didn't work.
7459 * Maybe /proc/self/exe doesn't exist?
7468 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7469 if (--idx < 0 && pathopt == NULL) {
7470 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7471 if (errno != ENOENT && errno != ENOTDIR)
7478 /* Map to POSIX errors */
7490 exitstatus = exerrno;
7491 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7492 argv[0], e, suppress_int));
7493 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7498 printentry(struct tblentry *cmdp)
7504 idx = cmdp->param.index;
7507 name = path_advance(&path, cmdp->cmdname);
7509 } while (--idx >= 0);
7510 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7514 * Clear out command entries. The argument specifies the first entry in
7515 * PATH which has changed.
7518 clearcmdentry(int firstchange)
7520 struct tblentry **tblp;
7521 struct tblentry **pp;
7522 struct tblentry *cmdp;
7525 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7527 while ((cmdp = *pp) != NULL) {
7528 if ((cmdp->cmdtype == CMDNORMAL &&
7529 cmdp->param.index >= firstchange)
7530 || (cmdp->cmdtype == CMDBUILTIN &&
7531 builtinloc >= firstchange)
7544 * Locate a command in the command hash table. If "add" is nonzero,
7545 * add the command to the table if it is not already present. The
7546 * variable "lastcmdentry" is set to point to the address of the link
7547 * pointing to the entry, so that delete_cmd_entry can delete the
7550 * Interrupts must be off if called with add != 0.
7552 static struct tblentry **lastcmdentry;
7554 static struct tblentry *
7555 cmdlookup(const char *name, int add)
7557 unsigned int hashval;
7559 struct tblentry *cmdp;
7560 struct tblentry **pp;
7563 hashval = (unsigned char)*p << 4;
7565 hashval += (unsigned char)*p++;
7567 pp = &cmdtable[hashval % CMDTABLESIZE];
7568 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7569 if (strcmp(cmdp->cmdname, name) == 0)
7573 if (add && cmdp == NULL) {
7574 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7576 /* + 1 - already done because
7577 * tblentry::cmdname is char[1] */);
7578 /*cmdp->next = NULL; - ckzalloc did it */
7579 cmdp->cmdtype = CMDUNKNOWN;
7580 strcpy(cmdp->cmdname, name);
7587 * Delete the command entry returned on the last lookup.
7590 delete_cmd_entry(void)
7592 struct tblentry *cmdp;
7595 cmdp = *lastcmdentry;
7596 *lastcmdentry = cmdp->next;
7597 if (cmdp->cmdtype == CMDFUNCTION)
7598 freefunc(cmdp->param.func);
7604 * Add a new command entry, replacing any existing command entry for
7605 * the same name - except special builtins.
7608 addcmdentry(char *name, struct cmdentry *entry)
7610 struct tblentry *cmdp;
7612 cmdp = cmdlookup(name, 1);
7613 if (cmdp->cmdtype == CMDFUNCTION) {
7614 freefunc(cmdp->param.func);
7616 cmdp->cmdtype = entry->cmdtype;
7617 cmdp->param = entry->u;
7621 static int FAST_FUNC
7622 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7624 struct tblentry **pp;
7625 struct tblentry *cmdp;
7627 struct cmdentry entry;
7630 if (nextopt("r") != '\0') {
7635 if (*argptr == NULL) {
7636 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7637 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7638 if (cmdp->cmdtype == CMDNORMAL)
7646 while ((name = *argptr) != NULL) {
7647 cmdp = cmdlookup(name, 0);
7649 && (cmdp->cmdtype == CMDNORMAL
7650 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7654 find_command(name, &entry, DO_ERR, pathval());
7655 if (entry.cmdtype == CMDUNKNOWN)
7663 * Called when a cd is done. Marks all commands so the next time they
7664 * are executed they will be rehashed.
7669 struct tblentry **pp;
7670 struct tblentry *cmdp;
7672 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7673 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7674 if (cmdp->cmdtype == CMDNORMAL
7675 || (cmdp->cmdtype == CMDBUILTIN
7676 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7686 * Fix command hash table when PATH changed.
7687 * Called before PATH is changed. The argument is the new value of PATH;
7688 * pathval() still returns the old value at this point.
7689 * Called with interrupts off.
7691 static void FAST_FUNC
7692 changepath(const char *new)
7700 firstchange = 9999; /* assume no change */
7706 if ((*old == '\0' && *new == ':')
7707 || (*old == ':' && *new == '\0')
7711 old = new; /* ignore subsequent differences */
7715 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7722 if (builtinloc < 0 && idx_bltin >= 0)
7723 builtinloc = idx_bltin; /* zap builtins */
7724 if (builtinloc >= 0 && idx_bltin < 0)
7726 clearcmdentry(firstchange);
7727 builtinloc = idx_bltin;
7742 #define TENDBQUOTE 12
7759 typedef smallint token_id_t;
7761 /* first char is indicating which tokens mark the end of a list */
7762 static const char *const tokname_array[] = {
7776 #define KWDOFFSET 13
7777 /* the following are keywords */
7796 /* Wrapper around strcmp for qsort/bsearch/... */
7798 pstrcmp(const void *a, const void *b)
7800 return strcmp((char*) a, (*(char**) b) + 1);
7803 static const char *const *
7804 findkwd(const char *s)
7806 return bsearch(s, tokname_array + KWDOFFSET,
7807 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7808 sizeof(tokname_array[0]), pstrcmp);
7812 * Locate and print what a word is...
7815 describe_command(char *command, int describe_command_verbose)
7817 struct cmdentry entry;
7818 struct tblentry *cmdp;
7819 #if ENABLE_ASH_ALIAS
7820 const struct alias *ap;
7822 const char *path = pathval();
7824 if (describe_command_verbose) {
7828 /* First look at the keywords */
7829 if (findkwd(command)) {
7830 out1str(describe_command_verbose ? " is a shell keyword" : command);
7834 #if ENABLE_ASH_ALIAS
7835 /* Then look at the aliases */
7836 ap = lookupalias(command, 0);
7838 if (!describe_command_verbose) {
7843 out1fmt(" is an alias for %s", ap->val);
7847 /* Then check if it is a tracked alias */
7848 cmdp = cmdlookup(command, 0);
7850 entry.cmdtype = cmdp->cmdtype;
7851 entry.u = cmdp->param;
7853 /* Finally use brute force */
7854 find_command(command, &entry, DO_ABS, path);
7857 switch (entry.cmdtype) {
7859 int j = entry.u.index;
7865 p = path_advance(&path, command);
7869 if (describe_command_verbose) {
7871 (cmdp ? " a tracked alias for" : nullstr), p
7880 if (describe_command_verbose) {
7881 out1str(" is a shell function");
7888 if (describe_command_verbose) {
7889 out1fmt(" is a %sshell builtin",
7890 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7891 "special " : nullstr
7899 if (describe_command_verbose) {
7900 out1str(": not found\n");
7909 static int FAST_FUNC
7910 typecmd(int argc UNUSED_PARAM, char **argv)
7916 /* type -p ... ? (we don't bother checking for 'p') */
7917 if (argv[1] && argv[1][0] == '-') {
7922 err |= describe_command(argv[i++], verbose);
7927 #if ENABLE_ASH_CMDCMD
7928 static int FAST_FUNC
7929 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7937 while ((c = nextopt("pvV")) != '\0')
7939 verify |= VERIFY_VERBOSE;
7941 verify |= VERIFY_BRIEF;
7946 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7947 if (verify && (*argptr != NULL)) {
7948 return describe_command(*argptr, verify - VERIFY_BRIEF);
7956 /* ============ eval.c */
7958 static int funcblocksize; /* size of structures in function */
7959 static int funcstringsize; /* size of strings in node */
7960 static void *funcblock; /* block to allocate function from */
7961 static char *funcstring; /* block to allocate strings from */
7963 /* flags in argument to evaltree */
7964 #define EV_EXIT 01 /* exit after evaluating tree */
7965 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7966 #define EV_BACKCMD 04 /* command executing within back quotes */
7968 static const uint8_t nodesize[N_NUMBER] = {
7969 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7970 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7971 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7972 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7973 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7974 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7975 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7976 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7977 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7978 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7979 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7980 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7981 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7982 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7983 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7984 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7985 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7986 #if ENABLE_ASH_BASH_COMPAT
7987 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7989 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7990 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7991 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7992 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7993 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7994 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7995 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7996 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7997 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8000 static void calcsize(union node *n);
8003 sizenodelist(struct nodelist *lp)
8006 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8013 calcsize(union node *n)
8017 funcblocksize += nodesize[n->type];
8020 calcsize(n->ncmd.redirect);
8021 calcsize(n->ncmd.args);
8022 calcsize(n->ncmd.assign);
8025 sizenodelist(n->npipe.cmdlist);
8030 calcsize(n->nredir.redirect);
8031 calcsize(n->nredir.n);
8038 calcsize(n->nbinary.ch2);
8039 calcsize(n->nbinary.ch1);
8042 calcsize(n->nif.elsepart);
8043 calcsize(n->nif.ifpart);
8044 calcsize(n->nif.test);
8047 funcstringsize += strlen(n->nfor.var) + 1;
8048 calcsize(n->nfor.body);
8049 calcsize(n->nfor.args);
8052 calcsize(n->ncase.cases);
8053 calcsize(n->ncase.expr);
8056 calcsize(n->nclist.body);
8057 calcsize(n->nclist.pattern);
8058 calcsize(n->nclist.next);
8062 sizenodelist(n->narg.backquote);
8063 funcstringsize += strlen(n->narg.text) + 1;
8064 calcsize(n->narg.next);
8067 #if ENABLE_ASH_BASH_COMPAT
8074 calcsize(n->nfile.fname);
8075 calcsize(n->nfile.next);
8079 calcsize(n->ndup.vname);
8080 calcsize(n->ndup.next);
8084 calcsize(n->nhere.doc);
8085 calcsize(n->nhere.next);
8088 calcsize(n->nnot.com);
8094 nodeckstrdup(char *s)
8096 char *rtn = funcstring;
8098 strcpy(funcstring, s);
8099 funcstring += strlen(s) + 1;
8103 static union node *copynode(union node *);
8105 static struct nodelist *
8106 copynodelist(struct nodelist *lp)
8108 struct nodelist *start;
8109 struct nodelist **lpp;
8114 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8115 (*lpp)->n = copynode(lp->n);
8117 lpp = &(*lpp)->next;
8124 copynode(union node *n)
8131 funcblock = (char *) funcblock + nodesize[n->type];
8135 new->ncmd.redirect = copynode(n->ncmd.redirect);
8136 new->ncmd.args = copynode(n->ncmd.args);
8137 new->ncmd.assign = copynode(n->ncmd.assign);
8140 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8141 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8146 new->nredir.redirect = copynode(n->nredir.redirect);
8147 new->nredir.n = copynode(n->nredir.n);
8154 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8155 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8158 new->nif.elsepart = copynode(n->nif.elsepart);
8159 new->nif.ifpart = copynode(n->nif.ifpart);
8160 new->nif.test = copynode(n->nif.test);
8163 new->nfor.var = nodeckstrdup(n->nfor.var);
8164 new->nfor.body = copynode(n->nfor.body);
8165 new->nfor.args = copynode(n->nfor.args);
8168 new->ncase.cases = copynode(n->ncase.cases);
8169 new->ncase.expr = copynode(n->ncase.expr);
8172 new->nclist.body = copynode(n->nclist.body);
8173 new->nclist.pattern = copynode(n->nclist.pattern);
8174 new->nclist.next = copynode(n->nclist.next);
8178 new->narg.backquote = copynodelist(n->narg.backquote);
8179 new->narg.text = nodeckstrdup(n->narg.text);
8180 new->narg.next = copynode(n->narg.next);
8183 #if ENABLE_ASH_BASH_COMPAT
8190 new->nfile.fname = copynode(n->nfile.fname);
8191 new->nfile.fd = n->nfile.fd;
8192 new->nfile.next = copynode(n->nfile.next);
8196 new->ndup.vname = copynode(n->ndup.vname);
8197 new->ndup.dupfd = n->ndup.dupfd;
8198 new->ndup.fd = n->ndup.fd;
8199 new->ndup.next = copynode(n->ndup.next);
8203 new->nhere.doc = copynode(n->nhere.doc);
8204 new->nhere.fd = n->nhere.fd;
8205 new->nhere.next = copynode(n->nhere.next);
8208 new->nnot.com = copynode(n->nnot.com);
8211 new->type = n->type;
8216 * Make a copy of a parse tree.
8218 static struct funcnode *
8219 copyfunc(union node *n)
8224 funcblocksize = offsetof(struct funcnode, n);
8227 blocksize = funcblocksize;
8228 f = ckmalloc(blocksize + funcstringsize);
8229 funcblock = (char *) f + offsetof(struct funcnode, n);
8230 funcstring = (char *) f + blocksize;
8237 * Define a shell function.
8240 defun(char *name, union node *func)
8242 struct cmdentry entry;
8245 entry.cmdtype = CMDFUNCTION;
8246 entry.u.func = copyfunc(func);
8247 addcmdentry(name, &entry);
8251 /* Reasons for skipping commands (see comment on breakcmd routine) */
8252 #define SKIPBREAK (1 << 0)
8253 #define SKIPCONT (1 << 1)
8254 #define SKIPFUNC (1 << 2)
8255 #define SKIPFILE (1 << 3)
8256 #define SKIPEVAL (1 << 4)
8257 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8258 static int skipcount; /* number of levels to skip */
8259 static int funcnest; /* depth of function calls */
8260 static int loopnest; /* current loop nesting level */
8262 /* Forward decl way out to parsing code - dotrap needs it */
8263 static int evalstring(char *s, int mask);
8265 /* Called to execute a trap.
8266 * Single callsite - at the end of evaltree().
8267 * If we return non-zero, evaltree raises EXEXIT exception.
8269 * Perhaps we should avoid entering new trap handlers
8270 * while we are executing a trap handler. [is it a TODO?]
8279 savestatus = exitstatus;
8283 TRACE(("dotrap entered\n"));
8284 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8291 /* non-trapped SIGINT is handled separately by raise_interrupt,
8292 * don't upset it by resetting gotsig[SIGINT-1] */
8293 if (sig == SIGINT && !t)
8296 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8300 want_exexit = evalstring(t, SKIPEVAL);
8301 exitstatus = savestatus;
8303 TRACE(("dotrap returns %d\n", want_exexit));
8308 TRACE(("dotrap returns 0\n"));
8312 /* forward declarations - evaluation is fairly recursive business... */
8313 static void evalloop(union node *, int);
8314 static void evalfor(union node *, int);
8315 static void evalcase(union node *, int);
8316 static void evalsubshell(union node *, int);
8317 static void expredir(union node *);
8318 static void evalpipe(union node *, int);
8319 static void evalcommand(union node *, int);
8320 static int evalbltin(const struct builtincmd *, int, char **);
8321 static void prehash(union node *);
8324 * Evaluate a parse tree. The value is left in the global variable
8328 evaltree(union node *n, int flags)
8330 struct jmploc *volatile savehandler = exception_handler;
8331 struct jmploc jmploc;
8333 void (*evalfn)(union node *, int);
8337 SAVE_INT(int_level);
8340 TRACE(("evaltree(NULL) called\n"));
8343 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8345 exception_handler = &jmploc;
8347 int err = setjmp(jmploc.loc);
8349 /* if it was a signal, check for trap handlers */
8350 if (exception_type == EXSIG) {
8351 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8352 exception_type, err));
8355 /* continue on the way out */
8356 TRACE(("exception %d in evaltree, propagating err=%d\n",
8357 exception_type, err));
8358 exception_handler = savehandler;
8359 longjmp(exception_handler->loc, err);
8366 out1fmt("Node type = %d\n", n->type);
8371 evaltree(n->nnot.com, EV_TESTED);
8372 status = !exitstatus;
8375 expredir(n->nredir.redirect);
8376 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8378 evaltree(n->nredir.n, flags & EV_TESTED);
8379 status = exitstatus;
8381 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8384 evalfn = evalcommand;
8386 if (eflag && !(flags & EV_TESTED))
8398 evalfn = evalsubshell;
8411 #error NAND + 1 != NOR
8413 #if NOR + 1 != NSEMI
8414 #error NOR + 1 != NSEMI
8416 unsigned is_or = n->type - NAND;
8419 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8421 if (!exitstatus == is_or)
8434 evaltree(n->nif.test, EV_TESTED);
8437 if (exitstatus == 0) {
8441 if (n->nif.elsepart) {
8442 n = n->nif.elsepart;
8447 defun(n->narg.text, n->narg.next);
8451 exitstatus = status;
8456 exception_handler = savehandler;
8459 /* Order of checks below is important:
8460 * signal handlers trigger before exit caused by "set -e".
8462 if (pending_sig && dotrap())
8464 if (checkexit & exitstatus)
8465 evalskip |= SKIPEVAL;
8467 if (flags & EV_EXIT) {
8469 raise_exception(EXEXIT);
8472 RESTORE_INT(int_level);
8473 TRACE(("leaving evaltree (no interrupts)\n"));
8476 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8479 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8482 evalloop(union node *n, int flags)
8492 evaltree(n->nbinary.ch1, EV_TESTED);
8495 if (evalskip == SKIPCONT && --skipcount <= 0) {
8499 if (evalskip == SKIPBREAK && --skipcount <= 0)
8504 if (n->type != NWHILE)
8508 evaltree(n->nbinary.ch2, flags);
8509 status = exitstatus;
8514 exitstatus = status;
8518 evalfor(union node *n, int flags)
8520 struct arglist arglist;
8523 struct stackmark smark;
8525 setstackmark(&smark);
8526 arglist.list = NULL;
8527 arglist.lastp = &arglist.list;
8528 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8529 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8534 *arglist.lastp = NULL;
8539 for (sp = arglist.list; sp; sp = sp->next) {
8540 setvar0(n->nfor.var, sp->text);
8541 evaltree(n->nfor.body, flags);
8543 if (evalskip == SKIPCONT && --skipcount <= 0) {
8547 if (evalskip == SKIPBREAK && --skipcount <= 0)
8554 popstackmark(&smark);
8558 evalcase(union node *n, int flags)
8562 struct arglist arglist;
8563 struct stackmark smark;
8565 setstackmark(&smark);
8566 arglist.list = NULL;
8567 arglist.lastp = &arglist.list;
8568 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8570 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8571 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8572 if (casematch(patp, arglist.list->text)) {
8573 if (evalskip == 0) {
8574 evaltree(cp->nclist.body, flags);
8581 popstackmark(&smark);
8585 * Kick off a subshell to evaluate a tree.
8588 evalsubshell(union node *n, int flags)
8591 int backgnd = (n->type == NBACKGND);
8594 expredir(n->nredir.redirect);
8595 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8598 jp = makejob(/*n,*/ 1);
8599 if (forkshell(jp, n, backgnd) == 0) {
8604 flags &= ~EV_TESTED;
8606 redirect(n->nredir.redirect, 0);
8607 evaltreenr(n->nredir.n, flags);
8612 status = waitforjob(jp);
8613 exitstatus = status;
8618 * Compute the names of the files in a redirection list.
8620 static void fixredir(union node *, const char *, int);
8622 expredir(union node *n)
8626 for (redir = n; redir; redir = redir->nfile.next) {
8630 fn.lastp = &fn.list;
8631 switch (redir->type) {
8635 #if ENABLE_ASH_BASH_COMPAT
8640 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8641 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8642 #if ENABLE_ASH_BASH_COMPAT
8646 // By the design of stack allocator, the loop of this kind:
8647 // while true; do while true; do break; done </dev/null; done
8648 // will look like a memory leak: ash plans to free expfname's
8649 // of "/dev/null" as soon as it finishes running the loop
8650 // (in this case, never).
8651 // This "fix" is wrong:
8652 if (redir->nfile.expfname)
8653 stunalloc(redir->nfile.expfname);
8654 // It results in corrupted state of stacked allocations.
8656 redir->nfile.expfname = fn.list->text;
8659 case NTOFD: /* >& */
8660 if (redir->ndup.vname) {
8661 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8662 if (fn.list == NULL)
8663 ash_msg_and_raise_error("redir error");
8664 #if ENABLE_ASH_BASH_COMPAT
8665 //FIXME: we used expandarg with different args!
8666 if (!isdigit_str9(fn.list->text)) {
8667 /* >&file, not >&fd */
8668 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8669 ash_msg_and_raise_error("redir error");
8671 goto store_expfname;
8674 fixredir(redir, fn.list->text, 1);
8682 * Evaluate a pipeline. All the processes in the pipeline are children
8683 * of the process creating the pipeline. (This differs from some versions
8684 * of the shell, which make the last process in a pipeline the parent
8688 evalpipe(union node *n, int flags)
8691 struct nodelist *lp;
8696 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8698 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8702 jp = makejob(/*n,*/ pipelen);
8704 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8708 if (pipe(pip) < 0) {
8710 ash_msg_and_raise_error("pipe call failed");
8713 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8726 evaltreenr(lp->n, flags);
8732 /* Don't want to trigger debugging */
8736 if (n->npipe.pipe_backgnd == 0) {
8737 exitstatus = waitforjob(jp);
8738 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8744 * Controls whether the shell is interactive or not.
8747 setinteractive(int on)
8749 static smallint is_interactive;
8751 if (++on == is_interactive)
8753 is_interactive = on;
8757 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8758 if (is_interactive > 1) {
8759 /* Looks like they want an interactive shell */
8760 static smallint did_banner;
8763 /* note: ash and hush share this string */
8764 out1fmt("\n\n%s %s\n"
8765 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8768 "built-in shell (ash)"
8782 setinteractive(iflag);
8784 #if ENABLE_FEATURE_EDITING_VI
8786 line_input_state->flags |= VI_MODE;
8788 line_input_state->flags &= ~VI_MODE;
8790 viflag = 0; /* forcibly keep the option off */
8794 static struct localvar *localvars;
8797 * Called after a function returns.
8798 * Interrupts must be off.
8803 struct localvar *lvp;
8806 while ((lvp = localvars) != NULL) {
8807 localvars = lvp->next;
8809 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8810 if (vp == NULL) { /* $- saved */
8811 memcpy(optlist, lvp->text, sizeof(optlist));
8812 free((char*)lvp->text);
8814 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8815 unsetvar(vp->var_text);
8818 vp->var_func(var_end(lvp->text));
8819 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8820 free((char*)vp->var_text);
8821 vp->flags = lvp->flags;
8822 vp->var_text = lvp->text;
8829 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8831 volatile struct shparam saveparam;
8832 struct localvar *volatile savelocalvars;
8833 struct jmploc *volatile savehandler;
8834 struct jmploc jmploc;
8837 saveparam = shellparam;
8838 savelocalvars = localvars;
8839 e = setjmp(jmploc.loc);
8844 savehandler = exception_handler;
8845 exception_handler = &jmploc;
8847 shellparam.malloced = 0;
8851 shellparam.nparam = argc - 1;
8852 shellparam.p = argv + 1;
8853 #if ENABLE_ASH_GETOPTS
8854 shellparam.optind = 1;
8855 shellparam.optoff = -1;
8857 evaltree(&func->n, flags & EV_TESTED);
8863 localvars = savelocalvars;
8864 freeparam(&shellparam);
8865 shellparam = saveparam;
8866 exception_handler = savehandler;
8868 evalskip &= ~SKIPFUNC;
8872 #if ENABLE_ASH_CMDCMD
8874 parse_command_args(char **argv, const char **path)
8887 if (c == '-' && !*cp) {
8894 *path = bb_default_path;
8897 /* run 'typecmd' for other options */
8908 * Make a variable a local variable. When a variable is made local, it's
8909 * value and flags are saved in a localvar structure. The saved values
8910 * will be restored when the shell function returns. We handle the name
8911 * "-" as a special case: it makes changes to "set +-options" local
8912 * (options will be restored on return from the function).
8917 struct localvar *lvp;
8920 char *eq = strchr(name, '=');
8923 /* Cater for duplicate "local". Examples:
8924 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
8925 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
8929 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
8933 * it's a duplicate "local VAR" declaration, do nothing
8940 lvp = ckzalloc(sizeof(*lvp));
8941 if (LONE_DASH(name)) {
8943 p = ckmalloc(sizeof(optlist));
8944 lvp->text = memcpy(p, optlist, sizeof(optlist));
8947 vpp = hashvar(name);
8948 vp = *findvar(vpp, name);
8950 /* variable did not exist yet */
8952 setvareq(name, VSTRFIXED);
8954 setvar(name, NULL, VSTRFIXED);
8955 vp = *vpp; /* the new variable */
8956 lvp->flags = VUNSET;
8958 lvp->text = vp->var_text;
8959 lvp->flags = vp->flags;
8960 /* make sure neither "struct var" nor string gets freed
8961 * during (un)setting:
8963 vp->flags |= VSTRFIXED|VTEXTFIXED;
8967 /* "local VAR" unsets VAR: */
8968 setvar0(name, NULL);
8972 lvp->next = localvars;
8978 * The "local" command.
8980 static int FAST_FUNC
8981 localcmd(int argc UNUSED_PARAM, char **argv)
8986 while ((name = *argv++) != NULL) {
8992 static int FAST_FUNC
8993 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8998 static int FAST_FUNC
8999 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9004 static int FAST_FUNC
9005 execcmd(int argc UNUSED_PARAM, char **argv)
9008 iflag = 0; /* exit on error */
9011 shellexec(argv + 1, pathval(), 0);
9017 * The return command.
9019 static int FAST_FUNC
9020 returncmd(int argc UNUSED_PARAM, char **argv)
9023 * If called outside a function, do what ksh does;
9024 * skip the rest of the file.
9026 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9027 return argv[1] ? number(argv[1]) : exitstatus;
9030 /* Forward declarations for builtintab[] */
9031 static int breakcmd(int, char **) FAST_FUNC;
9032 static int dotcmd(int, char **) FAST_FUNC;
9033 static int evalcmd(int, char **) FAST_FUNC;
9034 static int exitcmd(int, char **) FAST_FUNC;
9035 static int exportcmd(int, char **) FAST_FUNC;
9036 #if ENABLE_ASH_GETOPTS
9037 static int getoptscmd(int, char **) FAST_FUNC;
9040 static int helpcmd(int, char **) FAST_FUNC;
9043 static int historycmd(int, char **) FAST_FUNC;
9045 #if ENABLE_SH_MATH_SUPPORT
9046 static int letcmd(int, char **) FAST_FUNC;
9048 static int readcmd(int, char **) FAST_FUNC;
9049 static int setcmd(int, char **) FAST_FUNC;
9050 static int shiftcmd(int, char **) FAST_FUNC;
9051 static int timescmd(int, char **) FAST_FUNC;
9052 static int trapcmd(int, char **) FAST_FUNC;
9053 static int umaskcmd(int, char **) FAST_FUNC;
9054 static int unsetcmd(int, char **) FAST_FUNC;
9055 static int ulimitcmd(int, char **) FAST_FUNC;
9057 #define BUILTIN_NOSPEC "0"
9058 #define BUILTIN_SPECIAL "1"
9059 #define BUILTIN_REGULAR "2"
9060 #define BUILTIN_SPEC_REG "3"
9061 #define BUILTIN_ASSIGN "4"
9062 #define BUILTIN_SPEC_ASSG "5"
9063 #define BUILTIN_REG_ASSG "6"
9064 #define BUILTIN_SPEC_REG_ASSG "7"
9066 /* Stubs for calling non-FAST_FUNC's */
9067 #if ENABLE_ASH_BUILTIN_ECHO
9068 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9070 #if ENABLE_ASH_BUILTIN_PRINTF
9071 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9073 #if ENABLE_ASH_BUILTIN_TEST
9074 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9077 /* Keep these in proper order since it is searched via bsearch() */
9078 static const struct builtincmd builtintab[] = {
9079 { BUILTIN_SPEC_REG "." , dotcmd },
9080 { BUILTIN_SPEC_REG ":" , truecmd },
9081 #if ENABLE_ASH_BUILTIN_TEST
9082 { BUILTIN_REGULAR "[" , testcmd },
9083 #if ENABLE_ASH_BASH_COMPAT
9084 { BUILTIN_REGULAR "[[" , testcmd },
9087 #if ENABLE_ASH_ALIAS
9088 { BUILTIN_REG_ASSG "alias" , aliascmd },
9091 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9093 { BUILTIN_SPEC_REG "break" , breakcmd },
9094 { BUILTIN_REGULAR "cd" , cdcmd },
9095 { BUILTIN_NOSPEC "chdir" , cdcmd },
9096 #if ENABLE_ASH_CMDCMD
9097 { BUILTIN_REGULAR "command" , commandcmd },
9099 { BUILTIN_SPEC_REG "continue", breakcmd },
9100 #if ENABLE_ASH_BUILTIN_ECHO
9101 { BUILTIN_REGULAR "echo" , echocmd },
9103 { BUILTIN_SPEC_REG "eval" , evalcmd },
9104 { BUILTIN_SPEC_REG "exec" , execcmd },
9105 { BUILTIN_SPEC_REG "exit" , exitcmd },
9106 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9107 { BUILTIN_REGULAR "false" , falsecmd },
9109 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9111 #if ENABLE_ASH_GETOPTS
9112 { BUILTIN_REGULAR "getopts" , getoptscmd },
9114 { BUILTIN_NOSPEC "hash" , hashcmd },
9116 { BUILTIN_NOSPEC "help" , helpcmd },
9119 { BUILTIN_NOSPEC "history" , historycmd },
9122 { BUILTIN_REGULAR "jobs" , jobscmd },
9123 { BUILTIN_REGULAR "kill" , killcmd },
9125 #if ENABLE_SH_MATH_SUPPORT
9126 { BUILTIN_NOSPEC "let" , letcmd },
9128 { BUILTIN_ASSIGN "local" , localcmd },
9129 #if ENABLE_ASH_BUILTIN_PRINTF
9130 { BUILTIN_REGULAR "printf" , printfcmd },
9132 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9133 { BUILTIN_REGULAR "read" , readcmd },
9134 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9135 { BUILTIN_SPEC_REG "return" , returncmd },
9136 { BUILTIN_SPEC_REG "set" , setcmd },
9137 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9138 #if ENABLE_ASH_BASH_COMPAT
9139 { BUILTIN_SPEC_REG "source" , dotcmd },
9141 #if ENABLE_ASH_BUILTIN_TEST
9142 { BUILTIN_REGULAR "test" , testcmd },
9144 { BUILTIN_SPEC_REG "times" , timescmd },
9145 { BUILTIN_SPEC_REG "trap" , trapcmd },
9146 { BUILTIN_REGULAR "true" , truecmd },
9147 { BUILTIN_NOSPEC "type" , typecmd },
9148 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9149 { BUILTIN_REGULAR "umask" , umaskcmd },
9150 #if ENABLE_ASH_ALIAS
9151 { BUILTIN_REGULAR "unalias" , unaliascmd },
9153 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9154 { BUILTIN_REGULAR "wait" , waitcmd },
9157 /* Should match the above table! */
9158 #define COMMANDCMD (builtintab + \
9160 1 * ENABLE_ASH_BUILTIN_TEST + \
9161 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9162 1 * ENABLE_ASH_ALIAS + \
9163 1 * ENABLE_ASH_JOB_CONTROL + \
9165 #define EXECCMD (builtintab + \
9167 1 * ENABLE_ASH_BUILTIN_TEST + \
9168 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9169 1 * ENABLE_ASH_ALIAS + \
9170 1 * ENABLE_ASH_JOB_CONTROL + \
9172 1 * ENABLE_ASH_CMDCMD + \
9174 ENABLE_ASH_BUILTIN_ECHO + \
9178 * Search the table of builtin commands.
9180 static struct builtincmd *
9181 find_builtin(const char *name)
9183 struct builtincmd *bp;
9186 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9193 * Execute a simple command.
9196 isassignment(const char *p)
9198 const char *q = endofname(p);
9203 static int FAST_FUNC
9204 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9206 /* Preserve exitstatus of a previous possible redirection
9207 * as POSIX mandates */
9208 return back_exitstatus;
9211 evalcommand(union node *cmd, int flags)
9213 static const struct builtincmd null_bltin = {
9214 "\0\0", bltincmd /* why three NULs? */
9216 struct stackmark smark;
9218 struct arglist arglist;
9219 struct arglist varlist;
9222 const struct strlist *sp;
9223 struct cmdentry cmdentry;
9230 struct builtincmd *bcmd;
9231 smallint cmd_is_exec;
9232 smallint pseudovarflag = 0;
9234 /* First expand the arguments. */
9235 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9236 setstackmark(&smark);
9237 back_exitstatus = 0;
9239 cmdentry.cmdtype = CMDBUILTIN;
9240 cmdentry.u.cmd = &null_bltin;
9241 varlist.lastp = &varlist.list;
9242 *varlist.lastp = NULL;
9243 arglist.lastp = &arglist.list;
9244 *arglist.lastp = NULL;
9247 if (cmd->ncmd.args) {
9248 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9249 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9252 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9253 struct strlist **spp;
9255 spp = arglist.lastp;
9256 if (pseudovarflag && isassignment(argp->narg.text))
9257 expandarg(argp, &arglist, EXP_VARTILDE);
9259 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9261 for (sp = *spp; sp; sp = sp->next)
9265 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9266 for (sp = arglist.list; sp; sp = sp->next) {
9267 TRACE(("evalcommand arg: %s\n", sp->text));
9268 *nargv++ = sp->text;
9273 if (iflag && funcnest == 0 && argc > 0)
9274 lastarg = nargv[-1];
9277 expredir(cmd->ncmd.redirect);
9278 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9280 path = vpath.var_text;
9281 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9282 struct strlist **spp;
9285 spp = varlist.lastp;
9286 expandarg(argp, &varlist, EXP_VARTILDE);
9289 * Modify the command lookup path, if a PATH= assignment
9293 if (varcmp(p, path) == 0)
9297 /* Print the command if xflag is set. */
9300 const char *p = " %s" + 1;
9302 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9304 for (n = 0; n < 2; n++) {
9306 fdprintf(preverrout_fd, p, sp->text);
9312 safe_write(preverrout_fd, "\n", 1);
9318 /* Now locate the command. */
9320 int cmd_flag = DO_ERR;
9321 #if ENABLE_ASH_CMDCMD
9322 const char *oldpath = path + 5;
9326 find_command(argv[0], &cmdentry, cmd_flag, path);
9327 if (cmdentry.cmdtype == CMDUNKNOWN) {
9328 flush_stdout_stderr();
9333 /* implement bltin and command here */
9334 if (cmdentry.cmdtype != CMDBUILTIN)
9337 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9338 if (cmdentry.u.cmd == EXECCMD)
9340 #if ENABLE_ASH_CMDCMD
9341 if (cmdentry.u.cmd == COMMANDCMD) {
9343 nargv = parse_command_args(argv, &path);
9346 argc -= nargv - argv;
9348 cmd_flag |= DO_NOFUNC;
9356 /* We have a redirection error. */
9358 raise_exception(EXERROR);
9360 exitstatus = status;
9364 /* Execute the command. */
9365 switch (cmdentry.cmdtype) {
9368 #if ENABLE_FEATURE_SH_NOFORK
9369 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9370 * around run_nofork_applet() call.
9371 * (2) Should this check also be done in forkshell()?
9372 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9374 /* find_command() encodes applet_no as (-2 - applet_no) */
9375 int applet_no = (- cmdentry.u.index - 2);
9376 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9377 listsetvar(varlist.list, VEXPORT|VSTACK);
9378 /* run <applet>_main() */
9379 exitstatus = run_nofork_applet(applet_no, argv);
9383 /* Can we avoid forking off? For example, very last command
9384 * in a script or a subshell does not need forking,
9385 * we can just exec it.
9387 if (!(flags & EV_EXIT) || may_have_traps) {
9388 /* No, forking off a child is necessary */
9390 jp = makejob(/*cmd,*/ 1);
9391 if (forkshell(jp, cmd, FORK_FG) != 0) {
9393 exitstatus = waitforjob(jp);
9395 TRACE(("forked child exited with %d\n", exitstatus));
9400 /* fall through to exec'ing external program */
9402 listsetvar(varlist.list, VEXPORT|VSTACK);
9403 shellexec(argv, path, cmdentry.u.index);
9407 cmdenviron = varlist.list;
9409 struct strlist *list = cmdenviron;
9411 if (spclbltin > 0 || argc == 0) {
9413 if (cmd_is_exec && argc > 1)
9416 listsetvar(list, i);
9418 /* Tight loop with builtins only:
9419 * "while kill -0 $child; do true; done"
9420 * will never exit even if $child died, unless we do this
9421 * to reap the zombie and make kill detect that it's gone: */
9422 dowait(DOWAIT_NONBLOCK, NULL);
9424 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9426 int i = exception_type;
9431 exit_status = 128 + SIGINT;
9433 exit_status = 128 + pending_sig;
9434 exitstatus = exit_status;
9435 if (i == EXINT || spclbltin > 0) {
9437 longjmp(exception_handler->loc, 1);
9444 listsetvar(varlist.list, 0);
9445 /* See above for the rationale */
9446 dowait(DOWAIT_NONBLOCK, NULL);
9447 if (evalfun(cmdentry.u.func, argc, argv, flags))
9454 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9456 /* dsl: I think this is intended to be used to support
9457 * '_' in 'vi' command mode during line editing...
9458 * However I implemented that within libedit itself.
9460 setvar0("_", lastarg);
9462 popstackmark(&smark);
9466 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9468 char *volatile savecmdname;
9469 struct jmploc *volatile savehandler;
9470 struct jmploc jmploc;
9473 savecmdname = commandname;
9474 i = setjmp(jmploc.loc);
9477 savehandler = exception_handler;
9478 exception_handler = &jmploc;
9479 commandname = argv[0];
9481 optptr = NULL; /* initialize nextopt */
9482 exitstatus = (*cmd->builtin)(argc, argv);
9483 flush_stdout_stderr();
9485 exitstatus |= ferror(stdout);
9487 commandname = savecmdname;
9488 exception_handler = savehandler;
9494 goodname(const char *p)
9496 return endofname(p)[0] == '\0';
9501 * Search for a command. This is called before we fork so that the
9502 * location of the command will be available in the parent as well as
9503 * the child. The check for "goodname" is an overly conservative
9504 * check that the name will not be subject to expansion.
9507 prehash(union node *n)
9509 struct cmdentry entry;
9511 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9512 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9516 /* ============ Builtin commands
9518 * Builtin commands whose functions are closely tied to evaluation
9519 * are implemented here.
9523 * Handle break and continue commands. Break, continue, and return are
9524 * all handled by setting the evalskip flag. The evaluation routines
9525 * above all check this flag, and if it is set they start skipping
9526 * commands rather than executing them. The variable skipcount is
9527 * the number of loops to break/continue, or the number of function
9528 * levels to return. (The latter is always 1.) It should probably
9529 * be an error to break out of more loops than exist, but it isn't
9530 * in the standard shell so we don't make it one here.
9532 static int FAST_FUNC
9533 breakcmd(int argc UNUSED_PARAM, char **argv)
9535 int n = argv[1] ? number(argv[1]) : 1;
9538 ash_msg_and_raise_error(msg_illnum, argv[1]);
9542 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9549 /* ============ input.c
9551 * This implements the input routines used by the parser.
9555 INPUT_PUSH_FILE = 1,
9556 INPUT_NOFILE_OK = 2,
9559 static smallint checkkwd;
9560 /* values of checkkwd variable */
9561 #define CHKALIAS 0x1
9566 * Push a string back onto the input at this current parsefile level.
9567 * We handle aliases this way.
9569 #if !ENABLE_ASH_ALIAS
9570 #define pushstring(s, ap) pushstring(s)
9573 pushstring(char *s, struct alias *ap)
9580 if (g_parsefile->strpush) {
9581 sp = ckzalloc(sizeof(*sp));
9582 sp->prev = g_parsefile->strpush;
9584 sp = &(g_parsefile->basestrpush);
9586 g_parsefile->strpush = sp;
9587 sp->prev_string = g_parsefile->next_to_pgetc;
9588 sp->prev_left_in_line = g_parsefile->left_in_line;
9589 #if ENABLE_ASH_ALIAS
9592 ap->flag |= ALIASINUSE;
9596 g_parsefile->next_to_pgetc = s;
9597 g_parsefile->left_in_line = len;
9604 struct strpush *sp = g_parsefile->strpush;
9607 #if ENABLE_ASH_ALIAS
9609 if (g_parsefile->next_to_pgetc[-1] == ' '
9610 || g_parsefile->next_to_pgetc[-1] == '\t'
9612 checkkwd |= CHKALIAS;
9614 if (sp->string != sp->ap->val) {
9617 sp->ap->flag &= ~ALIASINUSE;
9618 if (sp->ap->flag & ALIASDEAD) {
9619 unalias(sp->ap->name);
9623 g_parsefile->next_to_pgetc = sp->prev_string;
9624 g_parsefile->left_in_line = sp->prev_left_in_line;
9625 g_parsefile->strpush = sp->prev;
9626 if (sp != &(g_parsefile->basestrpush))
9631 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9632 //it peeks whether it is &>, and then pushes back both chars.
9633 //This function needs to save last *next_to_pgetc to buf[0]
9634 //to make two pungetc() reliable. Currently,
9635 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9640 char *buf = g_parsefile->buf;
9642 g_parsefile->next_to_pgetc = buf;
9643 #if ENABLE_FEATURE_EDITING
9645 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9646 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9649 # if ENABLE_ASH_IDLE_TIMEOUT
9651 const char *tmout_var = lookupvar("TMOUT");
9653 timeout = atoi(tmout_var) * 1000;
9659 # if ENABLE_FEATURE_TAB_COMPLETION
9660 line_input_state->path_lookup = pathval();
9662 reinit_unicode_for_ash();
9663 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9665 /* Ctrl+C pressed */
9676 /* Ctrl+D pressed */
9679 # if ENABLE_ASH_IDLE_TIMEOUT
9680 else if (errno == EAGAIN && timeout > 0) {
9681 printf("\007timed out waiting for input: auto-logout\n");
9688 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9691 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9693 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9694 int flags = fcntl(0, F_GETFL);
9695 if (flags >= 0 && (flags & O_NONBLOCK)) {
9696 flags &= ~O_NONBLOCK;
9697 if (fcntl(0, F_SETFL, flags) >= 0) {
9698 out2str("sh: turning off NDELAY mode\n");
9709 * Refill the input buffer and return the next input character:
9711 * 1) If a string was pushed back on the input, pop it;
9712 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9713 * or we are reading from a string so we can't refill the buffer,
9715 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9716 * 4) Process input up to the next newline, deleting nul characters.
9718 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9719 #define pgetc_debug(...) ((void)0)
9726 while (g_parsefile->strpush) {
9727 #if ENABLE_ASH_ALIAS
9728 if (g_parsefile->left_in_line == -1
9729 && g_parsefile->strpush->ap
9730 && g_parsefile->next_to_pgetc[-1] != ' '
9731 && g_parsefile->next_to_pgetc[-1] != '\t'
9733 pgetc_debug("preadbuffer PEOA");
9738 /* try "pgetc" now: */
9739 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9740 g_parsefile->left_in_line,
9741 g_parsefile->next_to_pgetc,
9742 g_parsefile->next_to_pgetc);
9743 if (--g_parsefile->left_in_line >= 0)
9744 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9746 /* on both branches above g_parsefile->left_in_line < 0.
9747 * "pgetc" needs refilling.
9750 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9751 * pungetc() may increment it a few times.
9752 * Assuming it won't increment it to less than -90.
9754 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9755 pgetc_debug("preadbuffer PEOF1");
9756 /* even in failure keep left_in_line and next_to_pgetc
9757 * in lock step, for correct multi-layer pungetc.
9758 * left_in_line was decremented before preadbuffer(),
9759 * must inc next_to_pgetc: */
9760 g_parsefile->next_to_pgetc++;
9764 more = g_parsefile->left_in_buffer;
9766 flush_stdout_stderr();
9770 /* don't try reading again */
9771 g_parsefile->left_in_line = -99;
9772 pgetc_debug("preadbuffer PEOF2");
9773 g_parsefile->next_to_pgetc++;
9778 /* Find out where's the end of line.
9779 * Set g_parsefile->left_in_line
9780 * and g_parsefile->left_in_buffer acordingly.
9781 * NUL chars are deleted.
9783 q = g_parsefile->next_to_pgetc;
9791 memmove(q, q + 1, more);
9795 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9801 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9802 if (g_parsefile->left_in_line < 0)
9807 g_parsefile->left_in_buffer = more;
9812 out2str(g_parsefile->next_to_pgetc);
9816 pgetc_debug("preadbuffer at %d:%p'%s'",
9817 g_parsefile->left_in_line,
9818 g_parsefile->next_to_pgetc,
9819 g_parsefile->next_to_pgetc);
9820 return (unsigned char)*g_parsefile->next_to_pgetc++;
9823 #define pgetc_as_macro() \
9824 (--g_parsefile->left_in_line >= 0 \
9825 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9832 pgetc_debug("pgetc_fast at %d:%p'%s'",
9833 g_parsefile->left_in_line,
9834 g_parsefile->next_to_pgetc,
9835 g_parsefile->next_to_pgetc);
9836 return pgetc_as_macro();
9839 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9840 # define pgetc_fast() pgetc()
9842 # define pgetc_fast() pgetc_as_macro()
9845 #if ENABLE_ASH_ALIAS
9847 pgetc_without_PEOA(void)
9851 pgetc_debug("pgetc_fast at %d:%p'%s'",
9852 g_parsefile->left_in_line,
9853 g_parsefile->next_to_pgetc,
9854 g_parsefile->next_to_pgetc);
9856 } while (c == PEOA);
9860 # define pgetc_without_PEOA() pgetc()
9864 * Read a line from the script.
9867 pfgets(char *line, int len)
9873 while (--nleft > 0) {
9874 c = pgetc_without_PEOA();
9889 * Undo the last call to pgetc. Only one character may be pushed back.
9890 * PEOF may be pushed back.
9895 g_parsefile->left_in_line++;
9896 g_parsefile->next_to_pgetc--;
9897 pgetc_debug("pushed back to %d:%p'%s'",
9898 g_parsefile->left_in_line,
9899 g_parsefile->next_to_pgetc,
9900 g_parsefile->next_to_pgetc);
9904 * To handle the "." command, a stack of input files is used. Pushfile
9905 * adds a new entry to the stack and popfile restores the previous level.
9910 struct parsefile *pf;
9912 pf = ckzalloc(sizeof(*pf));
9913 pf->prev = g_parsefile;
9915 /*pf->strpush = NULL; - ckzalloc did it */
9916 /*pf->basestrpush.prev = NULL;*/
9923 struct parsefile *pf = g_parsefile;
9931 g_parsefile = pf->prev;
9937 * Return to top level.
9942 while (g_parsefile != &basepf)
9947 * Close the file(s) that the shell is reading commands from. Called
9948 * after a fork is done.
9954 if (g_parsefile->pf_fd > 0) {
9955 close(g_parsefile->pf_fd);
9956 g_parsefile->pf_fd = 0;
9961 * Like setinputfile, but takes an open file descriptor. Call this with
9965 setinputfd(int fd, int push)
9967 close_on_exec_on(fd);
9970 g_parsefile->buf = NULL;
9972 g_parsefile->pf_fd = fd;
9973 if (g_parsefile->buf == NULL)
9974 g_parsefile->buf = ckmalloc(IBUFSIZ);
9975 g_parsefile->left_in_buffer = 0;
9976 g_parsefile->left_in_line = 0;
9977 g_parsefile->linno = 1;
9981 * Set the input to take input from a file. If push is set, push the
9982 * old input onto the stack first.
9985 setinputfile(const char *fname, int flags)
9991 fd = open(fname, O_RDONLY);
9993 if (flags & INPUT_NOFILE_OK)
9995 ash_msg_and_raise_error("can't open '%s'", fname);
9998 fd2 = copyfd(fd, 10);
10001 ash_msg_and_raise_error("out of file descriptors");
10004 setinputfd(fd, flags & INPUT_PUSH_FILE);
10011 * Like setinputfile, but takes input from a string.
10014 setinputstring(char *string)
10018 g_parsefile->next_to_pgetc = string;
10019 g_parsefile->left_in_line = strlen(string);
10020 g_parsefile->buf = NULL;
10021 g_parsefile->linno = 1;
10026 /* ============ mail.c
10028 * Routines to check for mail.
10031 #if ENABLE_ASH_MAIL
10033 #define MAXMBOXES 10
10035 /* times of mailboxes */
10036 static time_t mailtime[MAXMBOXES];
10037 /* Set if MAIL or MAILPATH is changed. */
10038 static smallint mail_var_path_changed;
10041 * Print appropriate message(s) if mail has arrived.
10042 * If mail_var_path_changed is set,
10043 * then the value of MAIL has mail_var_path_changed,
10044 * so we just update the values.
10053 struct stackmark smark;
10056 setstackmark(&smark);
10057 mpath = mpathset() ? mpathval() : mailval();
10058 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
10059 p = path_advance(&mpath, nullstr);
10064 for (q = p; *q; q++)
10070 q[-1] = '\0'; /* delete trailing '/' */
10071 if (stat(p, &statb) < 0) {
10075 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
10078 pathopt ? pathopt : "you have mail"
10081 *mtp = statb.st_mtime;
10083 mail_var_path_changed = 0;
10084 popstackmark(&smark);
10087 static void FAST_FUNC
10088 changemail(const char *val UNUSED_PARAM)
10090 mail_var_path_changed = 1;
10093 #endif /* ASH_MAIL */
10096 /* ============ ??? */
10099 * Set the shell parameters.
10102 setparam(char **argv)
10108 for (nparam = 0; argv[nparam]; nparam++)
10110 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10112 *ap++ = ckstrdup(*argv++);
10115 freeparam(&shellparam);
10116 shellparam.malloced = 1;
10117 shellparam.nparam = nparam;
10118 shellparam.p = newparam;
10119 #if ENABLE_ASH_GETOPTS
10120 shellparam.optind = 1;
10121 shellparam.optoff = -1;
10126 * Process shell options. The global variable argptr contains a pointer
10127 * to the argument list; we advance it past the options.
10129 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10130 * For a non-interactive shell, an error condition encountered
10131 * by a special built-in ... shall cause the shell to write a diagnostic message
10132 * to standard error and exit as shown in the following table:
10133 * Error Special Built-In
10135 * Utility syntax error (option or operand error) Shall exit
10137 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10138 * we see that bash does not do that (set "finishes" with error code 1 instead,
10139 * and shell continues), and people rely on this behavior!
10141 * set -o barfoo 2>/dev/null
10144 * Oh well. Let's mimic that.
10147 plus_minus_o(char *name, int val)
10152 for (i = 0; i < NOPTS; i++) {
10153 if (strcmp(name, optnames(i)) == 0) {
10158 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10161 for (i = 0; i < NOPTS; i++) {
10163 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10165 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10171 setoption(int flag, int val)
10175 for (i = 0; i < NOPTS; i++) {
10176 if (optletters(i) == flag) {
10181 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10185 options(int cmdline)
10193 while ((p = *argptr) != NULL) {
10195 if (c != '-' && c != '+')
10198 val = 0; /* val = 0 if c == '+' */
10201 if (p[0] == '\0' || LONE_DASH(p)) {
10203 /* "-" means turn off -x and -v */
10206 /* "--" means reset params */
10207 else if (*argptr == NULL)
10210 break; /* "-" or "--" terminates options */
10213 /* first char was + or - */
10214 while ((c = *p++) != '\0') {
10215 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10216 if (c == 'c' && cmdline) {
10217 minusc = p; /* command is after shell args */
10218 } else if (c == 'o') {
10219 if (plus_minus_o(*argptr, val)) {
10220 /* it already printed err message */
10221 return 1; /* error */
10225 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10227 /* bash does not accept +-login, we also won't */
10228 } else if (cmdline && val && (c == '-')) { /* long options */
10229 if (strcmp(p, "login") == 0)
10241 * The shift builtin command.
10243 static int FAST_FUNC
10244 shiftcmd(int argc UNUSED_PARAM, char **argv)
10251 n = number(argv[1]);
10252 if (n > shellparam.nparam)
10253 n = 0; /* bash compat, was = shellparam.nparam; */
10255 shellparam.nparam -= n;
10256 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10257 if (shellparam.malloced)
10260 ap2 = shellparam.p;
10261 while ((*ap2++ = *ap1++) != NULL)
10263 #if ENABLE_ASH_GETOPTS
10264 shellparam.optind = 1;
10265 shellparam.optoff = -1;
10272 * POSIX requires that 'set' (but not export or readonly) output the
10273 * variables in lexicographic order - by the locale's collating order (sigh).
10274 * Maybe we could keep them in an ordered balanced binary tree
10275 * instead of hashed lists.
10276 * For now just roll 'em through qsort for printing...
10279 showvars(const char *sep_prefix, int on, int off)
10282 char **ep, **epend;
10284 ep = listvars(on, off, &epend);
10285 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10287 sep = *sep_prefix ? " " : sep_prefix;
10289 for (; ep < epend; ep++) {
10293 p = strchrnul(*ep, '=');
10296 q = single_quote(++p);
10297 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10303 * The set command builtin.
10305 static int FAST_FUNC
10306 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10311 return showvars(nullstr, 0, VUNSET);
10314 retval = options(/*cmdline:*/ 0);
10315 if (retval == 0) { /* if no parse error... */
10317 if (*argptr != NULL) {
10325 #if ENABLE_ASH_RANDOM_SUPPORT
10326 static void FAST_FUNC
10327 change_random(const char *value)
10331 if (value == NULL) {
10332 /* "get", generate */
10333 t = next_random(&random_gen);
10334 /* set without recursion */
10335 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10336 vrandom.flags &= ~VNOFUNC;
10339 t = strtoul(value, NULL, 10);
10340 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10345 #if ENABLE_ASH_GETOPTS
10347 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10356 if (*param_optind < 1)
10358 optnext = optfirst + *param_optind - 1;
10360 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10363 p = optnext[-1] + *optoff;
10364 if (p == NULL || *p == '\0') {
10365 /* Current word is done, advance */
10367 if (p == NULL || *p != '-' || *++p == '\0') {
10374 if (LONE_DASH(p)) /* check for "--" */
10379 for (q = optstr; *q != c;) {
10381 if (optstr[0] == ':') {
10384 err |= setvarsafe("OPTARG", s, 0);
10386 fprintf(stderr, "Illegal option -%c\n", c);
10387 unsetvar("OPTARG");
10397 if (*p == '\0' && (p = *optnext) == NULL) {
10398 if (optstr[0] == ':') {
10401 err |= setvarsafe("OPTARG", s, 0);
10404 fprintf(stderr, "No arg for -%c option\n", c);
10405 unsetvar("OPTARG");
10413 err |= setvarsafe("OPTARG", p, 0);
10416 err |= setvarsafe("OPTARG", nullstr, 0);
10418 *optoff = p ? p - *(optnext - 1) : -1;
10419 *param_optind = optnext - optfirst + 1;
10420 fmtstr(s, sizeof(s), "%d", *param_optind);
10421 err |= setvarsafe("OPTIND", s, VNOFUNC);
10424 err |= setvarsafe(optvar, s, 0);
10428 flush_stdout_stderr();
10429 raise_exception(EXERROR);
10435 * The getopts builtin. Shellparam.optnext points to the next argument
10436 * to be processed. Shellparam.optptr points to the next character to
10437 * be processed in the current argument. If shellparam.optnext is NULL,
10438 * then it's the first time getopts has been called.
10440 static int FAST_FUNC
10441 getoptscmd(int argc, char **argv)
10446 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10448 optbase = shellparam.p;
10449 if (shellparam.optind > shellparam.nparam + 1) {
10450 shellparam.optind = 1;
10451 shellparam.optoff = -1;
10454 optbase = &argv[3];
10455 if (shellparam.optind > argc - 2) {
10456 shellparam.optind = 1;
10457 shellparam.optoff = -1;
10461 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10462 &shellparam.optoff);
10464 #endif /* ASH_GETOPTS */
10467 /* ============ Shell parser */
10470 struct heredoc *next; /* next here document in list */
10471 union node *here; /* redirection node */
10472 char *eofmark; /* string indicating end of input */
10473 smallint striptabs; /* if set, strip leading tabs */
10476 static smallint tokpushback; /* last token pushed back */
10477 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10478 static smallint quoteflag; /* set if (part of) last token was quoted */
10479 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10480 static struct heredoc *heredoclist; /* list of here documents to read */
10481 static char *wordtext; /* text of last word returned by readtoken */
10482 static struct nodelist *backquotelist;
10483 static union node *redirnode;
10484 static struct heredoc *heredoc;
10486 static const char *
10487 tokname(char *buf, int tok)
10490 return tokname_array[tok] + 1;
10491 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10495 /* raise_error_unexpected_syntax:
10496 * Called when an unexpected token is read during the parse. The argument
10497 * is the token that is expected, or -1 if more than one type of token can
10498 * occur at this point.
10500 static void raise_error_unexpected_syntax(int) NORETURN;
10502 raise_error_unexpected_syntax(int token)
10508 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10510 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10511 raise_error_syntax(msg);
10515 #define EOFMARKLEN 79
10517 /* parsing is heavily cross-recursive, need these forward decls */
10518 static union node *andor(void);
10519 static union node *pipeline(void);
10520 static union node *parse_command(void);
10521 static void parseheredoc(void);
10522 static char nexttoken_ends_list(void);
10523 static int readtoken(void);
10525 static union node *
10528 union node *n1, *n2, *n3;
10531 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10532 if (nlflag == 2 && nexttoken_ends_list())
10538 if (tok == TBACKGND) {
10539 if (n2->type == NPIPE) {
10540 n2->npipe.pipe_backgnd = 1;
10542 if (n2->type != NREDIR) {
10543 n3 = stzalloc(sizeof(struct nredir));
10545 /*n3->nredir.redirect = NULL; - stzalloc did it */
10548 n2->type = NBACKGND;
10554 n3 = stzalloc(sizeof(struct nbinary));
10556 n3->nbinary.ch1 = n1;
10557 n3->nbinary.ch2 = n2;
10573 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10574 if (nexttoken_ends_list()) {
10575 /* Testcase: "<<EOF; then <W".
10576 * It used to segfault w/o this check:
10579 raise_error_unexpected_syntax(-1);
10588 pungetc(); /* push back EOF on input */
10592 raise_error_unexpected_syntax(-1);
10599 static union node *
10602 union node *n1, *n2, *n3;
10610 } else if (t == TOR) {
10616 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10618 n3 = stzalloc(sizeof(struct nbinary));
10620 n3->nbinary.ch1 = n1;
10621 n3->nbinary.ch2 = n2;
10626 static union node *
10629 union node *n1, *n2, *pipenode;
10630 struct nodelist *lp, *prev;
10634 TRACE(("pipeline: entered\n"));
10635 if (readtoken() == TNOT) {
10637 checkkwd = CHKKWD | CHKALIAS;
10640 n1 = parse_command();
10641 if (readtoken() == TPIPE) {
10642 pipenode = stzalloc(sizeof(struct npipe));
10643 pipenode->type = NPIPE;
10644 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10645 lp = stzalloc(sizeof(struct nodelist));
10646 pipenode->npipe.cmdlist = lp;
10650 lp = stzalloc(sizeof(struct nodelist));
10651 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10652 lp->n = parse_command();
10654 } while (readtoken() == TPIPE);
10660 n2 = stzalloc(sizeof(struct nnot));
10668 static union node *
10673 n = stzalloc(sizeof(struct narg));
10675 /*n->narg.next = NULL; - stzalloc did it */
10676 n->narg.text = wordtext;
10677 n->narg.backquote = backquotelist;
10682 fixredir(union node *n, const char *text, int err)
10686 TRACE(("Fix redir %s %d\n", text, err));
10688 n->ndup.vname = NULL;
10690 fd = bb_strtou(text, NULL, 10);
10691 if (!errno && fd >= 0)
10692 n->ndup.dupfd = fd;
10693 else if (LONE_DASH(text))
10694 n->ndup.dupfd = -1;
10697 raise_error_syntax("bad fd number");
10698 n->ndup.vname = makename();
10703 * Returns true if the text contains nothing to expand (no dollar signs
10707 noexpand(const char *text)
10711 while ((c = *text++) != '\0') {
10712 if (c == CTLQUOTEMARK)
10716 else if (SIT(c, BASESYNTAX) == CCTL)
10725 union node *n = redirnode;
10727 if (readtoken() != TWORD)
10728 raise_error_unexpected_syntax(-1);
10729 if (n->type == NHERE) {
10730 struct heredoc *here = heredoc;
10734 if (quoteflag == 0)
10736 TRACE(("Here document %d\n", n->type));
10737 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10738 raise_error_syntax("illegal eof marker for << redirection");
10739 rmescapes(wordtext, 0);
10740 here->eofmark = wordtext;
10742 if (heredoclist == NULL)
10743 heredoclist = here;
10745 for (p = heredoclist; p->next; p = p->next)
10749 } else if (n->type == NTOFD || n->type == NFROMFD) {
10750 fixredir(n, wordtext, 0);
10752 n->nfile.fname = makename();
10756 static union node *
10759 union node *args, **app;
10760 union node *n = NULL;
10761 union node *vars, **vpp;
10762 union node **rpp, *redir;
10764 #if ENABLE_ASH_BASH_COMPAT
10765 smallint double_brackets_flag = 0;
10775 savecheckkwd = CHKALIAS;
10778 checkkwd = savecheckkwd;
10781 #if ENABLE_ASH_BASH_COMPAT
10782 case TAND: /* "&&" */
10783 case TOR: /* "||" */
10784 if (!double_brackets_flag) {
10788 wordtext = (char *) (t == TAND ? "-a" : "-o");
10791 n = stzalloc(sizeof(struct narg));
10793 /*n->narg.next = NULL; - stzalloc did it */
10794 n->narg.text = wordtext;
10795 #if ENABLE_ASH_BASH_COMPAT
10796 if (strcmp("[[", wordtext) == 0)
10797 double_brackets_flag = 1;
10798 else if (strcmp("]]", wordtext) == 0)
10799 double_brackets_flag = 0;
10801 n->narg.backquote = backquotelist;
10802 if (savecheckkwd && isassignment(wordtext)) {
10804 vpp = &n->narg.next;
10807 app = &n->narg.next;
10812 *rpp = n = redirnode;
10813 rpp = &n->nfile.next;
10814 parsefname(); /* read name of redirection file */
10817 if (args && app == &args->narg.next
10820 struct builtincmd *bcmd;
10823 /* We have a function */
10824 if (readtoken() != TRP)
10825 raise_error_unexpected_syntax(TRP);
10826 name = n->narg.text;
10827 if (!goodname(name)
10828 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10830 raise_error_syntax("bad function name");
10833 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10834 n->narg.next = parse_command();
10847 n = stzalloc(sizeof(struct ncmd));
10849 n->ncmd.args = args;
10850 n->ncmd.assign = vars;
10851 n->ncmd.redirect = redir;
10855 static union node *
10856 parse_command(void)
10858 union node *n1, *n2;
10859 union node *ap, **app;
10860 union node *cp, **cpp;
10861 union node *redir, **rpp;
10868 switch (readtoken()) {
10870 raise_error_unexpected_syntax(-1);
10873 n1 = stzalloc(sizeof(struct nif));
10875 n1->nif.test = list(0);
10876 if (readtoken() != TTHEN)
10877 raise_error_unexpected_syntax(TTHEN);
10878 n1->nif.ifpart = list(0);
10880 while (readtoken() == TELIF) {
10881 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10882 n2 = n2->nif.elsepart;
10884 n2->nif.test = list(0);
10885 if (readtoken() != TTHEN)
10886 raise_error_unexpected_syntax(TTHEN);
10887 n2->nif.ifpart = list(0);
10889 if (lasttoken == TELSE)
10890 n2->nif.elsepart = list(0);
10892 n2->nif.elsepart = NULL;
10900 n1 = stzalloc(sizeof(struct nbinary));
10901 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10902 n1->nbinary.ch1 = list(0);
10905 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10906 got == TWORD ? wordtext : ""));
10907 raise_error_unexpected_syntax(TDO);
10909 n1->nbinary.ch2 = list(0);
10914 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10915 raise_error_syntax("bad for loop variable");
10916 n1 = stzalloc(sizeof(struct nfor));
10918 n1->nfor.var = wordtext;
10919 checkkwd = CHKKWD | CHKALIAS;
10920 if (readtoken() == TIN) {
10922 while (readtoken() == TWORD) {
10923 n2 = stzalloc(sizeof(struct narg));
10925 /*n2->narg.next = NULL; - stzalloc did it */
10926 n2->narg.text = wordtext;
10927 n2->narg.backquote = backquotelist;
10929 app = &n2->narg.next;
10932 n1->nfor.args = ap;
10933 if (lasttoken != TNL && lasttoken != TSEMI)
10934 raise_error_unexpected_syntax(-1);
10936 n2 = stzalloc(sizeof(struct narg));
10938 /*n2->narg.next = NULL; - stzalloc did it */
10939 n2->narg.text = (char *)dolatstr;
10940 /*n2->narg.backquote = NULL;*/
10941 n1->nfor.args = n2;
10943 * Newline or semicolon here is optional (but note
10944 * that the original Bourne shell only allowed NL).
10946 if (lasttoken != TNL && lasttoken != TSEMI)
10949 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10950 if (readtoken() != TDO)
10951 raise_error_unexpected_syntax(TDO);
10952 n1->nfor.body = list(0);
10956 n1 = stzalloc(sizeof(struct ncase));
10958 if (readtoken() != TWORD)
10959 raise_error_unexpected_syntax(TWORD);
10960 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10962 /*n2->narg.next = NULL; - stzalloc did it */
10963 n2->narg.text = wordtext;
10964 n2->narg.backquote = backquotelist;
10966 checkkwd = CHKKWD | CHKALIAS;
10967 } while (readtoken() == TNL);
10968 if (lasttoken != TIN)
10969 raise_error_unexpected_syntax(TIN);
10970 cpp = &n1->ncase.cases;
10972 checkkwd = CHKNL | CHKKWD;
10974 while (t != TESAC) {
10975 if (lasttoken == TLP)
10977 *cpp = cp = stzalloc(sizeof(struct nclist));
10979 app = &cp->nclist.pattern;
10981 *app = ap = stzalloc(sizeof(struct narg));
10983 /*ap->narg.next = NULL; - stzalloc did it */
10984 ap->narg.text = wordtext;
10985 ap->narg.backquote = backquotelist;
10986 if (readtoken() != TPIPE)
10988 app = &ap->narg.next;
10991 //ap->narg.next = NULL;
10992 if (lasttoken != TRP)
10993 raise_error_unexpected_syntax(TRP);
10994 cp->nclist.body = list(2);
10996 cpp = &cp->nclist.next;
10998 checkkwd = CHKNL | CHKKWD;
11002 raise_error_unexpected_syntax(TENDCASE);
11009 n1 = stzalloc(sizeof(struct nredir));
11010 n1->type = NSUBSHELL;
11011 n1->nredir.n = list(0);
11012 /*n1->nredir.redirect = NULL; - stzalloc did it */
11022 return simplecmd();
11025 if (readtoken() != t)
11026 raise_error_unexpected_syntax(t);
11029 /* Now check for redirection which may follow command */
11030 checkkwd = CHKKWD | CHKALIAS;
11032 while (readtoken() == TREDIR) {
11033 *rpp = n2 = redirnode;
11034 rpp = &n2->nfile.next;
11040 if (n1->type != NSUBSHELL) {
11041 n2 = stzalloc(sizeof(struct nredir));
11046 n1->nredir.redirect = redir;
11051 #if ENABLE_ASH_BASH_COMPAT
11052 static int decode_dollar_squote(void)
11054 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11060 p = strchr(C_escapes, c);
11065 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11069 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11071 } else if (c == 'x') { /* \xHH */
11075 } while (isxdigit(c) && --cnt);
11077 if (cnt == 3) { /* \x but next char is "bad" */
11081 } else { /* simple seq like \\ or \t */
11086 c = bb_process_escape_sequence((void*)&p);
11087 } else { /* unrecognized "\z": print both chars unless ' or " */
11088 if (c != '\'' && c != '"') {
11090 c |= 0x100; /* "please encode \, then me" */
11098 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11099 * is not NULL, read a here document. In the latter case, eofmark is the
11100 * word which marks the end of the document and striptabs is true if
11101 * leading tabs should be stripped from the document. The argument c
11102 * is the first character of the input token or document.
11104 * Because C does not have internal subroutines, I have simulated them
11105 * using goto's to implement the subroutine linkage. The following macros
11106 * will run code that appears at the end of readtoken1.
11108 #define CHECKEND() {goto checkend; checkend_return:;}
11109 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11110 #define PARSESUB() {goto parsesub; parsesub_return:;}
11111 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11112 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11113 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11115 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11117 /* NB: syntax parameter fits into smallint */
11118 /* c parameter is an unsigned char or PEOF or PEOA */
11121 char line[EOFMARKLEN + 1];
11122 struct nodelist *bqlist;
11126 smallint prevsyntax; /* syntax before arithmetic */
11127 #if ENABLE_ASH_EXPAND_PRMT
11128 smallint pssyntax; /* we are expanding a prompt string */
11130 int varnest; /* levels of variables expansion */
11131 int arinest; /* levels of arithmetic expansion */
11132 int parenlevel; /* levels of parens in arithmetic */
11133 int dqvarnest; /* levels of variables expansion within double quotes */
11135 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11138 /* Avoid longjmp clobbering */
11144 (void) &parenlevel;
11147 (void) &prevsyntax;
11150 startlinno = g_parsefile->linno;
11154 #if ENABLE_ASH_EXPAND_PRMT
11155 pssyntax = (syntax == PSSYNTAX);
11159 dblquote = (syntax == DQSYNTAX);
11165 STARTSTACKSTR(out);
11167 /* For each line, until end of word */
11168 CHECKEND(); /* set c to PEOF if at end of here document */
11169 for (;;) { /* until end of line or end of word */
11170 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11171 switch (SIT(c, syntax)) {
11172 case CNL: /* '\n' */
11173 if (syntax == BASESYNTAX)
11174 goto endword; /* exit outer loop */
11176 g_parsefile->linno++;
11177 setprompt_if(doprompt, 2);
11179 goto loop; /* continue outer loop */
11184 if (eofmark == NULL || dblquote)
11185 USTPUTC(CTLESC, out);
11186 #if ENABLE_ASH_BASH_COMPAT
11187 if (c == '\\' && bash_dollar_squote) {
11188 c = decode_dollar_squote();
11190 USTPUTC('\\', out);
11191 c = (unsigned char)c;
11197 case CBACK: /* backslash */
11198 c = pgetc_without_PEOA();
11200 USTPUTC(CTLESC, out);
11201 USTPUTC('\\', out);
11203 } else if (c == '\n') {
11204 setprompt_if(doprompt, 2);
11206 #if ENABLE_ASH_EXPAND_PRMT
11207 if (c == '$' && pssyntax) {
11208 USTPUTC(CTLESC, out);
11209 USTPUTC('\\', out);
11212 /* Backslash is retained if we are in "str" and next char isn't special */
11217 && (c != '"' || eofmark != NULL)
11219 USTPUTC('\\', out);
11221 USTPUTC(CTLESC, out);
11229 if (eofmark == NULL) {
11230 USTPUTC(CTLQUOTEMARK, out);
11238 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11239 if (eofmark != NULL && varnest == 0) {
11242 if (dqvarnest == 0) {
11243 syntax = BASESYNTAX;
11250 case CVAR: /* '$' */
11251 PARSESUB(); /* parse substitution */
11253 case CENDVAR: /* '}' */
11256 if (dqvarnest > 0) {
11263 #if ENABLE_SH_MATH_SUPPORT
11264 case CLP: /* '(' in arithmetic */
11268 case CRP: /* ')' in arithmetic */
11269 if (parenlevel > 0) {
11272 if (pgetc() == ')') {
11274 if (--arinest == 0) {
11275 syntax = prevsyntax;
11279 * unbalanced parens
11280 * (don't 2nd guess - no error)
11288 case CBQUOTE: /* '`' */
11292 goto endword; /* exit outer loop */
11296 if (varnest == 0) {
11297 #if ENABLE_ASH_BASH_COMPAT
11299 if (pgetc() == '>')
11300 c = 0x100 + '>'; /* flag &> */
11304 goto endword; /* exit outer loop */
11306 IF_ASH_ALIAS(if (c != PEOA))
11313 #if ENABLE_SH_MATH_SUPPORT
11314 if (syntax == ARISYNTAX)
11315 raise_error_syntax("missing '))'");
11317 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11318 raise_error_syntax("unterminated quoted string");
11319 if (varnest != 0) {
11320 startlinno = g_parsefile->linno;
11322 raise_error_syntax("missing '}'");
11324 USTPUTC('\0', out);
11325 len = out - (char *)stackblock();
11326 out = stackblock();
11327 if (eofmark == NULL) {
11328 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11331 if (isdigit_str9(out)) {
11332 PARSEREDIR(); /* passed as params: out, c */
11333 lasttoken = TREDIR;
11336 /* else: non-number X seen, interpret it
11337 * as "NNNX>file" = "NNNX >file" */
11341 quoteflag = quotef;
11342 backquotelist = bqlist;
11343 grabstackblock(len);
11347 /* end of readtoken routine */
11350 * Check to see whether we are at the end of the here document. When this
11351 * is called, c is set to the first character of the next input line. If
11352 * we are at the end of the here document, this routine sets the c to PEOF.
11356 #if ENABLE_ASH_ALIAS
11358 c = pgetc_without_PEOA();
11361 while (c == '\t') {
11362 c = pgetc_without_PEOA();
11365 if (c == *eofmark) {
11366 if (pfgets(line, sizeof(line)) != NULL) {
11370 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11372 if (*p == '\n' && *q == '\0') {
11374 g_parsefile->linno++;
11375 needprompt = doprompt;
11377 pushstring(line, NULL);
11382 goto checkend_return;
11386 * Parse a redirection operator. The variable "out" points to a string
11387 * specifying the fd to be redirected. The variable "c" contains the
11388 * first character of the redirection operator.
11391 /* out is already checked to be a valid number or "" */
11392 int fd = (*out == '\0' ? -1 : atoi(out));
11395 np = stzalloc(sizeof(struct nfile));
11400 np->type = NAPPEND;
11402 np->type = NCLOBBER;
11405 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11411 #if ENABLE_ASH_BASH_COMPAT
11412 else if (c == 0x100 + '>') { /* this flags &> redirection */
11414 pgetc(); /* this is '>', no need to check */
11418 else { /* c == '<' */
11419 /*np->nfile.fd = 0; - stzalloc did it */
11423 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11424 np = stzalloc(sizeof(struct nhere));
11425 /*np->nfile.fd = 0; - stzalloc did it */
11428 heredoc = stzalloc(sizeof(struct heredoc));
11429 heredoc->here = np;
11432 heredoc->striptabs = 1;
11434 /*heredoc->striptabs = 0; - stzalloc did it */
11440 np->type = NFROMFD;
11444 np->type = NFROMTO;
11456 goto parseredir_return;
11460 * Parse a substitution. At this point, we have read the dollar sign
11461 * and nothing else.
11464 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11465 * (assuming ascii char codes, as the original implementation did) */
11466 #define is_special(c) \
11467 (((unsigned)(c) - 33 < 32) \
11468 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11470 unsigned char subtype;
11475 if (c > 255 /* PEOA or PEOF */
11476 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11478 #if ENABLE_ASH_BASH_COMPAT
11480 bash_dollar_squote = 1;
11485 } else if (c == '(') {
11486 /* $(command) or $((arith)) */
11487 if (pgetc() == '(') {
11488 #if ENABLE_SH_MATH_SUPPORT
11491 raise_error_syntax("you disabled math support for $((arith)) syntax");
11498 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11499 USTPUTC(CTLVAR, out);
11500 typeloc = out - (char *)stackblock();
11501 USTPUTC(VSNORMAL, out);
11502 subtype = VSNORMAL;
11508 c = '#'; /* ${#} - same as $# */
11510 subtype = VSLENGTH; /* ${#VAR} */
11515 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11516 /* $[{[#]]NAME[}] */
11520 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11521 } else if (isdigit(c)) {
11522 /* $[{[#]]NUM[}] */
11526 } while (isdigit(c));
11527 } else if (is_special(c)) {
11528 /* $[{[#]]<specialchar>[}] */
11533 raise_error_syntax("bad substitution");
11535 if (c != '}' && subtype == VSLENGTH) {
11536 /* ${#VAR didn't end with } */
11542 if (subtype == 0) {
11543 /* ${VAR...} but not $VAR or ${#VAR} */
11544 /* c == first char after VAR */
11548 #if ENABLE_ASH_BASH_COMPAT
11549 if (c == ':' || c == '$' || isdigit(c)) {
11550 //TODO: support more general format ${v:EXPR:EXPR},
11551 // where EXPR follows $(()) rules
11552 subtype = VSSUBSTR;
11554 break; /* "goto do_pungetc" is bigger (!) */
11560 static const char types[] ALIGN1 = "}-+?=";
11561 const char *p = strchr(types, c);
11564 subtype = p - types + VSNORMAL;
11570 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11577 #if ENABLE_ASH_BASH_COMPAT
11579 /* ${v/[/]pattern/repl} */
11580 //TODO: encode pattern and repl separately.
11581 // Currently ${v/$var_with_slash/repl} is horribly broken
11582 subtype = VSREPLACE;
11586 subtype++; /* VSREPLACEALL */
11594 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11595 if (subtype != VSNORMAL) {
11602 goto parsesub_return;
11606 * Called to parse command substitutions. Newstyle is set if the command
11607 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11608 * list of commands (passed by reference), and savelen is the number of
11609 * characters on the top of the stack which must be preserved.
11612 struct nodelist **nlpp;
11615 char *volatile str;
11616 struct jmploc jmploc;
11617 struct jmploc *volatile savehandler;
11619 smallint saveprompt = 0;
11622 (void) &saveprompt;
11624 savepbq = parsebackquote;
11625 if (setjmp(jmploc.loc)) {
11627 parsebackquote = 0;
11628 exception_handler = savehandler;
11629 longjmp(exception_handler->loc, 1);
11633 savelen = out - (char *)stackblock();
11635 str = ckmalloc(savelen);
11636 memcpy(str, stackblock(), savelen);
11638 savehandler = exception_handler;
11639 exception_handler = &jmploc;
11642 /* We must read until the closing backquote, giving special
11643 * treatment to some slashes, and then push the string and
11644 * reread it as input, interpreting it normally.
11650 STARTSTACKSTR(pout);
11654 setprompt_if(needprompt, 2);
11663 g_parsefile->linno++;
11664 setprompt_if(doprompt, 2);
11666 * If eating a newline, avoid putting
11667 * the newline into the new character
11668 * stream (via the STPUTC after the
11673 if (pc != '\\' && pc != '`' && pc != '$'
11674 && (!dblquote || pc != '"')
11676 STPUTC('\\', pout);
11678 if (pc <= 255 /* not PEOA or PEOF */) {
11684 IF_ASH_ALIAS(case PEOA:)
11685 startlinno = g_parsefile->linno;
11686 raise_error_syntax("EOF in backquote substitution");
11689 g_parsefile->linno++;
11690 needprompt = doprompt;
11699 STPUTC('\0', pout);
11700 psavelen = pout - (char *)stackblock();
11701 if (psavelen > 0) {
11702 pstr = grabstackstr(pout);
11703 setinputstring(pstr);
11708 nlpp = &(*nlpp)->next;
11709 *nlpp = stzalloc(sizeof(**nlpp));
11710 /* (*nlpp)->next = NULL; - stzalloc did it */
11711 parsebackquote = oldstyle;
11714 saveprompt = doprompt;
11721 doprompt = saveprompt;
11722 else if (readtoken() != TRP)
11723 raise_error_unexpected_syntax(TRP);
11728 * Start reading from old file again, ignoring any pushed back
11729 * tokens left from the backquote parsing
11734 while (stackblocksize() <= savelen)
11736 STARTSTACKSTR(out);
11738 memcpy(out, str, savelen);
11739 STADJUST(savelen, out);
11745 parsebackquote = savepbq;
11746 exception_handler = savehandler;
11747 USTPUTC(CTLBACKQ, out);
11749 goto parsebackq_oldreturn;
11750 goto parsebackq_newreturn;
11753 #if ENABLE_SH_MATH_SUPPORT
11755 * Parse an arithmetic expansion (indicate start of one and set state)
11758 if (++arinest == 1) {
11759 prevsyntax = syntax;
11760 syntax = ARISYNTAX;
11762 USTPUTC(CTLARI, out);
11763 goto parsearith_return;
11767 } /* end of readtoken */
11770 * Read the next input token.
11771 * If the token is a word, we set backquotelist to the list of cmds in
11772 * backquotes. We set quoteflag to true if any part of the word was
11774 * If the token is TREDIR, then we set redirnode to a structure containing
11776 * In all cases, the variable startlinno is set to the number of the line
11777 * on which the token starts.
11779 * [Change comment: here documents and internal procedures]
11780 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11781 * word parsing code into a separate routine. In this case, readtoken
11782 * doesn't need to have any internal procedures, but parseword does.
11783 * We could also make parseoperator in essence the main routine, and
11784 * have parseword (readtoken1?) handle both words and redirection.]
11786 #define NEW_xxreadtoken
11787 #ifdef NEW_xxreadtoken
11788 /* singles must be first! */
11789 static const char xxreadtoken_chars[7] ALIGN1 = {
11790 '\n', '(', ')', /* singles */
11791 '&', '|', ';', /* doubles */
11795 #define xxreadtoken_singles 3
11796 #define xxreadtoken_doubles 3
11798 static const char xxreadtoken_tokens[] ALIGN1 = {
11799 TNL, TLP, TRP, /* only single occurrence allowed */
11800 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11801 TEOF, /* corresponds to trailing nul */
11802 TAND, TOR, TENDCASE /* if double occurrence */
11814 setprompt_if(needprompt, 2);
11815 startlinno = g_parsefile->linno;
11816 for (;;) { /* until token or start of word found */
11818 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11822 while ((c = pgetc()) != '\n' && c != PEOF)
11825 } else if (c == '\\') {
11826 if (pgetc() != '\n') {
11828 break; /* return readtoken1(...) */
11830 startlinno = ++g_parsefile->linno;
11831 setprompt_if(doprompt, 2);
11835 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11838 g_parsefile->linno++;
11839 needprompt = doprompt;
11842 p = strchr(xxreadtoken_chars, c);
11844 break; /* return readtoken1(...) */
11846 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11848 if (cc == c) { /* double occurrence? */
11849 p += xxreadtoken_doubles + 1;
11852 #if ENABLE_ASH_BASH_COMPAT
11853 if (c == '&' && cc == '>') /* &> */
11854 break; /* return readtoken1(...) */
11859 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11864 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11866 #else /* old xxreadtoken */
11867 #define RETURN(token) return lasttoken = token
11877 setprompt_if(needprompt, 2);
11878 startlinno = g_parsefile->linno;
11879 for (;;) { /* until token or start of word found */
11882 case ' ': case '\t':
11883 IF_ASH_ALIAS(case PEOA:)
11886 while ((c = pgetc()) != '\n' && c != PEOF)
11891 if (pgetc() == '\n') {
11892 startlinno = ++g_parsefile->linno;
11893 setprompt_if(doprompt, 2);
11899 g_parsefile->linno++;
11900 needprompt = doprompt;
11905 if (pgetc() == '&')
11910 if (pgetc() == '|')
11915 if (pgetc() == ';')
11928 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11931 #endif /* old xxreadtoken */
11938 smallint alreadyseen = tokpushback;
11941 #if ENABLE_ASH_ALIAS
11950 if (checkkwd & CHKNL) {
11957 if (t != TWORD || quoteflag) {
11962 * check for keywords
11964 if (checkkwd & CHKKWD) {
11965 const char *const *pp;
11967 pp = findkwd(wordtext);
11969 lasttoken = t = pp - tokname_array;
11970 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11975 if (checkkwd & CHKALIAS) {
11976 #if ENABLE_ASH_ALIAS
11978 ap = lookupalias(wordtext, 1);
11981 pushstring(ap->val, ap);
11991 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11993 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11999 nexttoken_ends_list(void)
12005 return tokname_array[t][0];
12009 * Read and parse a command. Returns NODE_EOF on end of file.
12010 * (NULL is a valid parse tree indicating a blank line.)
12012 static union node *
12013 parsecmd(int interact)
12018 doprompt = interact;
12019 setprompt_if(doprompt, doprompt);
12031 * Input any here documents.
12036 struct heredoc *here;
12039 here = heredoclist;
12040 heredoclist = NULL;
12043 setprompt_if(needprompt, 2);
12044 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12045 here->eofmark, here->striptabs);
12046 n = stzalloc(sizeof(struct narg));
12047 n->narg.type = NARG;
12048 /*n->narg.next = NULL; - stzalloc did it */
12049 n->narg.text = wordtext;
12050 n->narg.backquote = backquotelist;
12051 here->here->nhere.doc = n;
12058 * called by editline -- any expansions to the prompt should be added here.
12060 #if ENABLE_ASH_EXPAND_PRMT
12061 static const char *
12062 expandstr(const char *ps)
12066 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12067 * and token processing _can_ alter it (delete NULs etc). */
12068 setinputstring((char *)ps);
12069 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12072 n.narg.type = NARG;
12073 n.narg.next = NULL;
12074 n.narg.text = wordtext;
12075 n.narg.backquote = backquotelist;
12077 expandarg(&n, NULL, EXP_QUOTED);
12078 return stackblock();
12083 * Execute a command or commands contained in a string.
12086 evalstring(char *s, int mask)
12089 struct stackmark smark;
12093 setstackmark(&smark);
12096 while ((n = parsecmd(0)) != NODE_EOF) {
12098 popstackmark(&smark);
12111 * The eval command.
12113 static int FAST_FUNC
12114 evalcmd(int argc UNUSED_PARAM, char **argv)
12123 STARTSTACKSTR(concat);
12125 concat = stack_putstr(p, concat);
12129 STPUTC(' ', concat);
12131 STPUTC('\0', concat);
12132 p = grabstackstr(concat);
12134 evalstring(p, ~SKIPEVAL);
12140 * Read and execute commands.
12141 * "Top" is nonzero for the top level command loop;
12142 * it turns on prompting if the shell is interactive.
12148 struct stackmark smark;
12152 TRACE(("cmdloop(%d) called\n", top));
12156 setstackmark(&smark);
12159 showjobs(stderr, SHOW_CHANGED);
12162 if (iflag && top) {
12166 n = parsecmd(inter);
12168 if (DEBUG > 2 && debug && (n != NODE_EOF))
12171 if (n == NODE_EOF) {
12172 if (!top || numeof >= 50)
12174 if (!stoppedjobs()) {
12177 out2str("\nUse \"exit\" to leave shell.\n");
12180 } else if (nflag == 0) {
12181 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12186 popstackmark(&smark);
12191 return skip & SKIPEVAL;
12198 * Take commands from a file. To be compatible we should do a path
12199 * search for the file, which is necessary to find sub-commands.
12202 find_dot_file(char *name)
12205 const char *path = pathval();
12208 /* don't try this for absolute or relative paths */
12209 if (strchr(name, '/'))
12212 /* IIRC standards do not say whether . is to be searched.
12213 * And it is even smaller this way, making it unconditional for now:
12215 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12220 while ((fullname = path_advance(&path, name)) != NULL) {
12222 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12224 * Don't bother freeing here, since it will
12225 * be freed by the caller.
12229 if (fullname != name)
12230 stunalloc(fullname);
12233 /* not found in the PATH */
12234 ash_msg_and_raise_error("%s: not found", name);
12238 static int FAST_FUNC
12239 dotcmd(int argc, char **argv)
12242 struct strlist *sp;
12243 volatile struct shparam saveparam;
12245 for (sp = cmdenviron; sp; sp = sp->next)
12246 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12249 /* bash says: "bash: .: filename argument required" */
12250 return 2; /* bash compat */
12253 /* "false; . empty_file; echo $?" should print 0, not 1: */
12256 /* This aborts if file isn't found, which is POSIXly correct.
12257 * bash returns exitcode 1 instead.
12259 fullname = find_dot_file(argv[1]);
12262 if (argc) { /* argc > 0, argv[0] != NULL */
12263 saveparam = shellparam;
12264 shellparam.malloced = 0;
12265 shellparam.nparam = argc;
12266 shellparam.p = argv;
12269 /* This aborts if file can't be opened, which is POSIXly correct.
12270 * bash returns exitcode 1 instead.
12272 setinputfile(fullname, INPUT_PUSH_FILE);
12273 commandname = fullname;
12278 freeparam(&shellparam);
12279 shellparam = saveparam;
12285 static int FAST_FUNC
12286 exitcmd(int argc UNUSED_PARAM, char **argv)
12291 exitstatus = number(argv[1]);
12292 raise_exception(EXEXIT);
12297 * Read a file containing shell functions.
12300 readcmdfile(char *name)
12302 setinputfile(name, INPUT_PUSH_FILE);
12308 /* ============ find_command inplementation */
12311 * Resolve a command name. If you change this routine, you may have to
12312 * change the shellexec routine as well.
12315 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12317 struct tblentry *cmdp;
12324 struct builtincmd *bcmd;
12326 /* If name contains a slash, don't use PATH or hash table */
12327 if (strchr(name, '/') != NULL) {
12328 entry->u.index = -1;
12329 if (act & DO_ABS) {
12330 while (stat(name, &statb) < 0) {
12332 if (errno == EINTR)
12335 entry->cmdtype = CMDUNKNOWN;
12339 entry->cmdtype = CMDNORMAL;
12343 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12345 updatetbl = (path == pathval());
12348 if (strstr(path, "%builtin") != NULL)
12349 act |= DO_ALTBLTIN;
12352 /* If name is in the table, check answer will be ok */
12353 cmdp = cmdlookup(name, 0);
12354 if (cmdp != NULL) {
12357 switch (cmdp->cmdtype) {
12375 } else if (cmdp->rehash == 0)
12376 /* if not invalidated by cd, we're done */
12380 /* If %builtin not in path, check for builtin next */
12381 bcmd = find_builtin(name);
12383 if (IS_BUILTIN_REGULAR(bcmd))
12384 goto builtin_success;
12385 if (act & DO_ALTPATH) {
12386 if (!(act & DO_ALTBLTIN))
12387 goto builtin_success;
12388 } else if (builtinloc <= 0) {
12389 goto builtin_success;
12393 #if ENABLE_FEATURE_SH_STANDALONE
12395 int applet_no = find_applet_by_name(name);
12396 if (applet_no >= 0) {
12397 entry->cmdtype = CMDNORMAL;
12398 entry->u.index = -2 - applet_no;
12404 /* We have to search path. */
12405 prev = -1; /* where to start */
12406 if (cmdp && cmdp->rehash) { /* doing a rehash */
12407 if (cmdp->cmdtype == CMDBUILTIN)
12410 prev = cmdp->param.index;
12416 while ((fullname = path_advance(&path, name)) != NULL) {
12417 stunalloc(fullname);
12418 /* NB: code below will still use fullname
12419 * despite it being "unallocated" */
12422 if (prefix(pathopt, "builtin")) {
12424 goto builtin_success;
12427 if ((act & DO_NOFUNC)
12428 || !prefix(pathopt, "func")
12429 ) { /* ignore unimplemented options */
12433 /* if rehash, don't redo absolute path names */
12434 if (fullname[0] == '/' && idx <= prev) {
12437 TRACE(("searchexec \"%s\": no change\n", name));
12440 while (stat(fullname, &statb) < 0) {
12442 if (errno == EINTR)
12445 if (errno != ENOENT && errno != ENOTDIR)
12449 e = EACCES; /* if we fail, this will be the error */
12450 if (!S_ISREG(statb.st_mode))
12452 if (pathopt) { /* this is a %func directory */
12453 stalloc(strlen(fullname) + 1);
12454 /* NB: stalloc will return space pointed by fullname
12455 * (because we don't have any intervening allocations
12456 * between stunalloc above and this stalloc) */
12457 readcmdfile(fullname);
12458 cmdp = cmdlookup(name, 0);
12459 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12460 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12461 stunalloc(fullname);
12464 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12466 entry->cmdtype = CMDNORMAL;
12467 entry->u.index = idx;
12471 cmdp = cmdlookup(name, 1);
12472 cmdp->cmdtype = CMDNORMAL;
12473 cmdp->param.index = idx;
12478 /* We failed. If there was an entry for this command, delete it */
12479 if (cmdp && updatetbl)
12480 delete_cmd_entry();
12482 ash_msg("%s: %s", name, errmsg(e, "not found"));
12483 entry->cmdtype = CMDUNKNOWN;
12488 entry->cmdtype = CMDBUILTIN;
12489 entry->u.cmd = bcmd;
12493 cmdp = cmdlookup(name, 1);
12494 cmdp->cmdtype = CMDBUILTIN;
12495 cmdp->param.cmd = bcmd;
12499 entry->cmdtype = cmdp->cmdtype;
12500 entry->u = cmdp->param;
12504 /* ============ trap.c */
12507 * The trap builtin.
12509 static int FAST_FUNC
12510 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12514 int signo, exitcode;
12519 for (signo = 0; signo < NSIG; signo++) {
12520 char *tr = trap_ptr[signo];
12522 /* note: bash adds "SIG", but only if invoked
12523 * as "bash". If called as "sh", or if set -o posix,
12524 * then it prints short signal names.
12525 * We are printing short names: */
12526 out1fmt("trap -- %s %s\n",
12528 get_signame(signo));
12529 /* trap_ptr != trap only if we are in special-cased `trap` code.
12530 * In this case, we will exit very soon, no need to free(). */
12531 /* if (trap_ptr != trap && tp[0]) */
12536 if (trap_ptr != trap) {
12549 signo = get_signum(*ap);
12551 /* Mimic bash message exactly */
12552 ash_msg("%s: invalid signal specification", *ap);
12558 if (LONE_DASH(action))
12561 action = ckstrdup(action);
12565 may_have_traps = 1;
12566 trap[signo] = action;
12577 /* ============ Builtins */
12579 #if ENABLE_ASH_HELP
12580 static int FAST_FUNC
12581 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12587 "Built-in commands:\n"
12588 "------------------\n");
12589 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12590 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12591 builtintab[i].name + 1);
12597 # if ENABLE_FEATURE_SH_STANDALONE
12599 const char *a = applet_names;
12601 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12606 a += strlen(a) + 1;
12611 return EXIT_SUCCESS;
12616 static int FAST_FUNC
12617 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12619 show_history(line_input_state);
12620 return EXIT_SUCCESS;
12625 * The export and readonly commands.
12627 static int FAST_FUNC
12628 exportcmd(int argc UNUSED_PARAM, char **argv)
12638 /* "readonly" in bash accepts, but ignores -n.
12639 * We do the same: it saves a conditional in nextopt's param.
12642 while ((opt = nextopt("np")) != '\0') {
12644 flag_off = VEXPORT;
12647 if (argv[0][0] == 'r') {
12649 flag_off = 0; /* readonly ignores -n */
12651 flag_off = ~flag_off;
12653 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12659 p = strchr(name, '=');
12663 vp = *findvar(hashvar(name), name);
12665 vp->flags = ((vp->flags | flag) & flag_off);
12669 setvar(name, p, (flag & flag_off));
12670 } while ((name = *++aptr) != NULL);
12675 /* No arguments. Show the list of exported or readonly vars.
12678 showvars(argv[0], flag, 0);
12683 * Delete a function if it exists.
12686 unsetfunc(const char *name)
12688 struct tblentry *cmdp;
12690 cmdp = cmdlookup(name, 0);
12691 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12692 delete_cmd_entry();
12696 * The unset builtin command. We unset the function before we unset the
12697 * variable to allow a function to be unset when there is a readonly variable
12698 * with the same name.
12700 static int FAST_FUNC
12701 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12708 while ((i = nextopt("vf")) != 0) {
12712 for (ap = argptr; *ap; ap++) {
12725 static const unsigned char timescmd_str[] ALIGN1 = {
12726 ' ', offsetof(struct tms, tms_utime),
12727 '\n', offsetof(struct tms, tms_stime),
12728 ' ', offsetof(struct tms, tms_cutime),
12729 '\n', offsetof(struct tms, tms_cstime),
12732 static int FAST_FUNC
12733 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12735 unsigned long clk_tck, s, t;
12736 const unsigned char *p;
12739 clk_tck = bb_clk_tck();
12744 t = *(clock_t *)(((char *) &buf) + p[1]);
12747 out1fmt("%lum%lu.%03lus%c",
12749 (t * 1000) / clk_tck,
12757 #if ENABLE_SH_MATH_SUPPORT
12759 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12760 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12762 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12764 static int FAST_FUNC
12765 letcmd(int argc UNUSED_PARAM, char **argv)
12771 ash_msg_and_raise_error("expression expected");
12773 i = ash_arith(*argv);
12781 * The read builtin. Options:
12782 * -r Do not interpret '\' specially
12783 * -s Turn off echo (tty only)
12784 * -n NCHARS Read NCHARS max
12785 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12786 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12787 * -u FD Read from given FD instead of fd 0
12788 * This uses unbuffered input, which may be avoidable in some cases.
12789 * TODO: bash also has:
12790 * -a ARRAY Read into array[0],[1],etc
12791 * -d DELIM End on DELIM char, not newline
12792 * -e Use line editing (tty only)
12794 static int FAST_FUNC
12795 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12797 char *opt_n = NULL;
12798 char *opt_p = NULL;
12799 char *opt_t = NULL;
12800 char *opt_u = NULL;
12801 int read_flags = 0;
12805 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12814 read_flags |= BUILTIN_READ_SILENT;
12820 read_flags |= BUILTIN_READ_RAW;
12830 /* "read -s" needs to save/restore termios, can't allow ^C
12831 * to jump out of it.
12834 r = shell_builtin_read(setvar0,
12836 bltinlookup("IFS"), /* can be NULL */
12845 if ((uintptr_t)r > 1)
12846 ash_msg_and_raise_error(r);
12848 return (uintptr_t)r;
12851 static int FAST_FUNC
12852 umaskcmd(int argc UNUSED_PARAM, char **argv)
12854 static const char permuser[3] ALIGN1 = "ugo";
12855 static const char permmode[3] ALIGN1 = "rwx";
12856 static const short permmask[] ALIGN2 = {
12857 S_IRUSR, S_IWUSR, S_IXUSR,
12858 S_IRGRP, S_IWGRP, S_IXGRP,
12859 S_IROTH, S_IWOTH, S_IXOTH
12862 /* TODO: use bb_parse_mode() instead */
12867 int symbolic_mode = 0;
12869 while (nextopt("S") != '\0') {
12880 if (symbolic_mode) {
12884 for (i = 0; i < 3; i++) {
12887 *p++ = permuser[i];
12889 for (j = 0; j < 3; j++) {
12890 if ((mask & permmask[3 * i + j]) == 0) {
12891 *p++ = permmode[j];
12899 out1fmt("%.4o\n", mask);
12902 if (isdigit((unsigned char) *ap)) {
12905 if (*ap >= '8' || *ap < '0')
12906 ash_msg_and_raise_error(msg_illnum, argv[1]);
12907 mask = (mask << 3) + (*ap - '0');
12908 } while (*++ap != '\0');
12911 mask = ~mask & 0777;
12912 if (!bb_parse_mode(ap, &mask)) {
12913 ash_msg_and_raise_error("illegal mode: %s", ap);
12915 umask(~mask & 0777);
12921 static int FAST_FUNC
12922 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12924 return shell_builtin_ulimit(argv);
12927 /* ============ main() and helpers */
12930 * Called to exit the shell.
12939 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12940 save_history(line_input_state);
12943 status = exitstatus;
12944 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12945 if (setjmp(loc.loc)) {
12946 if (exception_type == EXEXIT)
12947 /* dash bug: it just does _exit(exitstatus) here
12948 * but we have to do setjobctl(0) first!
12949 * (bug is still not fixed in dash-0.5.3 - if you run dash
12950 * under Midnight Commander, on exit from dash MC is backgrounded) */
12951 status = exitstatus;
12954 exception_handler = &loc;
12961 flush_stdout_stderr();
12971 /* from input.c: */
12972 /* we will never free this */
12973 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12976 signal(SIGCHLD, SIG_DFL);
12977 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12978 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12980 signal(SIGHUP, SIG_DFL);
12986 struct stat st1, st2;
12989 for (envp = environ; envp && *envp; envp++) {
12990 if (strchr(*envp, '=')) {
12991 setvareq(*envp, VEXPORT|VTEXTFIXED);
12995 setvar0("PPID", utoa(getppid()));
12996 #if ENABLE_ASH_BASH_COMPAT
12997 p = lookupvar("SHLVL");
12998 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
12999 if (!lookupvar("HOSTNAME")) {
13000 struct utsname uts;
13002 setvar0("HOSTNAME", uts.nodename);
13005 p = lookupvar("PWD");
13007 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13008 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13018 //usage:#define ash_trivial_usage
13019 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13020 //usage:#define ash_full_usage "\n\n"
13021 //usage: "Unix shell interpreter"
13023 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13024 //usage:# define sh_trivial_usage ash_trivial_usage
13025 //usage:# define sh_full_usage ash_full_usage
13027 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13028 //usage:# define bash_trivial_usage ash_trivial_usage
13029 //usage:# define bash_full_usage ash_full_usage
13033 * Process the shell command line arguments.
13036 procargs(char **argv)
13039 const char *xminusc;
13044 /* if (xargv[0]) - mmm, this is always true! */
13046 for (i = 0; i < NOPTS; i++)
13049 if (options(/*cmdline:*/ 1)) {
13050 /* it already printed err message */
13051 raise_exception(EXERROR);
13055 if (*xargv == NULL) {
13057 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13060 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13064 for (i = 0; i < NOPTS; i++)
13065 if (optlist[i] == 2)
13070 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13075 } else if (!sflag) {
13076 setinputfile(*xargv, 0);
13079 commandname = arg0;
13082 shellparam.p = xargv;
13083 #if ENABLE_ASH_GETOPTS
13084 shellparam.optind = 1;
13085 shellparam.optoff = -1;
13087 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13089 shellparam.nparam++;
13096 * Read /etc/profile or .profile.
13099 read_profile(const char *name)
13103 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13112 * This routine is called when an error or an interrupt occurs in an
13113 * interactive shell and control is returned to the main command loop.
13121 /* from input.c: */
13122 g_parsefile->left_in_buffer = 0;
13123 g_parsefile->left_in_line = 0; /* clear input buffer */
13125 /* from parser.c: */
13128 /* from redir.c: */
13129 clearredir(/*drop:*/ 0);
13133 static short profile_buf[16384];
13134 extern int etext();
13138 * Main routine. We initialize things, parse the arguments, execute
13139 * profiles if we're a login shell, and then call cmdloop to execute
13140 * commands. The setjmp call sets up the location to jump to when an
13141 * exception occurs. When an exception occurs the variable "state"
13142 * is used to figure out how far we had gotten.
13144 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13145 int ash_main(int argc UNUSED_PARAM, char **argv)
13147 const char *shinit;
13148 volatile smallint state;
13149 struct jmploc jmploc;
13150 struct stackmark smark;
13152 /* Initialize global data */
13156 #if ENABLE_ASH_ALIAS
13162 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13165 #if ENABLE_FEATURE_EDITING
13166 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13169 if (setjmp(jmploc.loc)) {
13175 e = exception_type;
13179 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13183 outcslow('\n', stderr);
13186 popstackmark(&smark);
13187 FORCE_INT_ON; /* enable interrupts */
13196 exception_handler = &jmploc;
13199 TRACE(("Shell args: "));
13200 trace_puts_args(argv);
13202 rootpid = getpid();
13205 setstackmark(&smark);
13208 if (argv[0] && argv[0][0] == '-')
13214 read_profile("/etc/profile");
13217 hp = lookupvar("HOME");
13219 hp = concat_path_file(hp, ".profile");
13228 getuid() == geteuid() && getgid() == getegid() &&
13232 shinit = lookupvar("ENV");
13233 if (shinit != NULL && *shinit != '\0') {
13234 read_profile(shinit);
13240 /* evalstring pushes parsefile stack.
13241 * Ensure we don't falsely claim that 0 (stdin)
13242 * is one of stacked source fds.
13243 * Testcase: ash -c 'exec 1>&0' must not complain. */
13244 // if (!sflag) g_parsefile->pf_fd = -1;
13245 // ^^ not necessary since now we special-case fd 0
13246 // in is_hidden_fd() to not be considered "hidden fd"
13247 evalstring(minusc, 0);
13250 if (sflag || minusc == NULL) {
13251 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13253 const char *hp = lookupvar("HISTFILE");
13255 hp = lookupvar("HOME");
13257 hp = concat_path_file(hp, ".ash_history");
13258 setvar0("HISTFILE", hp);
13260 hp = lookupvar("HISTFILE");
13264 line_input_state->hist_file = hp;
13265 # if ENABLE_FEATURE_SH_HISTFILESIZE
13266 hp = lookupvar("HISTFILESIZE");
13267 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13271 state4: /* XXX ??? - why isn't this before the "if" statement */
13279 extern void _mcleanup(void);
13283 TRACE(("End of main reached\n"));
13290 * Copyright (c) 1989, 1991, 1993, 1994
13291 * The Regents of the University of California. All rights reserved.
13293 * This code is derived from software contributed to Berkeley by
13294 * Kenneth Almquist.
13296 * Redistribution and use in source and binary forms, with or without
13297 * modification, are permitted provided that the following conditions
13299 * 1. Redistributions of source code must retain the above copyright
13300 * notice, this list of conditions and the following disclaimer.
13301 * 2. Redistributions in binary form must reproduce the above copyright
13302 * notice, this list of conditions and the following disclaimer in the
13303 * documentation and/or other materials provided with the distribution.
13304 * 3. Neither the name of the University nor the names of its contributors
13305 * may be used to endorse or promote products derived from this software
13306 * without specific prior written permission.
13308 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13309 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13310 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13311 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13312 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13313 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13314 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13315 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13316 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13317 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF