1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
12 * This code is derived from software contributed to Berkeley by
15 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
17 * Original BSD copyright notice is retained at the end of this file.
21 * rewrite arith.y to micro stack based cryptic algorithm by
22 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
24 * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
27 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
28 * used in busybox and size optimizations,
29 * rewrote arith (see notes to this), added locale support,
30 * rewrote dynamic variables.
35 * The follow should be set to reflect the type of system you have:
36 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
37 * define SYSV if you are running under System V.
38 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
39 * define DEBUG=2 to compile in and turn on debugging.
41 * When debugging is on, debugging info will be written to ./trace and
42 * a quit signal will generate a core dump.
47 #if ENABLE_ASH_JOB_CONTROL
56 #include "busybox.h" /* for applet_names */
60 #if JOBS || ENABLE_ASH_READ_NCHARS
63 extern char **environ;
65 #if defined(__uClinux__)
66 #error "Do not even bother, ash will not run on uClinux"
70 /* ============ Hash table sizes. Configurable. */
74 #define CMDTABLESIZE 31 /* should be prime */
77 /* ============ Misc helpers */
79 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
81 /* C99 say: "char" declaration may be signed or unsigned default */
82 #define signed_char2int(sc) ((int)((signed char)sc))
85 /* ============ Shell options */
87 static const char *const optletters_optnames[] = {
108 #define optletters(n) optletters_optnames[(n)][0]
109 #define optnames(n) (&optletters_optnames[(n)][1])
111 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
113 static char optlist[NOPTS] ALIGN1;
115 #define eflag optlist[0]
116 #define fflag optlist[1]
117 #define Iflag optlist[2]
118 #define iflag optlist[3]
119 #define mflag optlist[4]
120 #define nflag optlist[5]
121 #define sflag optlist[6]
122 #define xflag optlist[7]
123 #define vflag optlist[8]
124 #define Cflag optlist[9]
125 #define aflag optlist[10]
126 #define bflag optlist[11]
127 #define uflag optlist[12]
128 #define viflag optlist[13]
130 #define nolog optlist[14]
131 #define debug optlist[15]
135 /* ============ Misc data */
137 static const char homestr[] ALIGN1 = "HOME";
138 static const char snlfmt[] ALIGN1 = "%s\n";
139 static const char illnum[] ALIGN1 = "Illegal number: %s";
142 * We enclose jmp_buf in a structure so that we can declare pointers to
143 * jump locations. The global variable handler contains the location to
144 * jump to when an exception occurs, and the global variable exception
145 * contains a code identifying the exception. To implement nested
146 * exception handlers, the user should save the value of handler on entry
147 * to an inner scope, set handler to point to a jmploc structure for the
148 * inner scope, and restore handler on exit from the scope.
154 struct globals_misc {
155 /* pid of main shell */
157 /* shell level: 0 for the main shell, 1 for its children, and so on */
159 #define rootshell (!shlvl)
160 char *minusc; /* argument to -c option */
162 char *curdir; // = nullstr; /* current working directory */
163 char *physdir; // = nullstr; /* physical working directory */
165 char *arg0; /* value of $0 */
167 struct jmploc *exception_handler;
170 #define EXINT 0 /* SIGINT received */
171 #define EXERROR 1 /* a generic error */
172 #define EXSHELLPROC 2 /* execute a shell procedure */
173 #define EXEXEC 3 /* command execution failed */
174 #define EXEXIT 4 /* exit the shell */
175 #define EXSIG 5 /* trapped signal in wait(1) */
176 volatile int suppressint;
177 volatile sig_atomic_t intpending;
178 /* do we generate EXSIG events */
180 /* last pending signal */
181 volatile sig_atomic_t pendingsig;
183 /* trap handler commands */
186 char nullstr[1]; /* zero length string */
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
192 char sigmode[NSIG - 1];
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
197 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
199 /* indicates specified signal received */
200 char gotsig[NSIG - 1];
202 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
203 static struct globals_misc *const ptr_to_globals_misc __attribute__ ((section (".data")));
204 #define G_misc (*ptr_to_globals_misc)
205 #define rootpid (G_misc.rootpid )
206 #define shlvl (G_misc.shlvl )
207 #define minusc (G_misc.minusc )
208 #define curdir (G_misc.curdir )
209 #define physdir (G_misc.physdir )
210 #define arg0 (G_misc.arg0 )
211 #define exception_handler (G_misc.exception_handler)
212 #define exception (G_misc.exception )
213 #define suppressint (G_misc.suppressint )
214 #define intpending (G_misc.intpending )
215 #define exsig (G_misc.exsig )
216 #define pendingsig (G_misc.pendingsig )
217 #define trap (G_misc.trap )
218 #define isloginsh (G_misc.isloginsh)
219 #define nullstr (G_misc.nullstr )
220 #define sigmode (G_misc.sigmode )
221 #define gotsig (G_misc.gotsig )
222 #define INIT_G_misc() do { \
223 (*(struct globals_misc**)&ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
229 /* ============ Interrupts / exceptions */
232 * These macros allow the user to suspend the handling of interrupt signals
233 * over a period of time. This is similar to SIGHOLD to or sigblock, but
234 * much more efficient and portable. (But hacking the kernel is so much
235 * more fun than worrying about efficiency and portability. :-))
244 * Called to raise an exception. Since C doesn't include exceptions, we
245 * just do a longjmp to the exception handler. The type of exception is
246 * stored in the global variable "exception".
248 static void raise_exception(int) ATTRIBUTE_NORETURN;
250 raise_exception(int e)
253 if (exception_handler == NULL)
258 longjmp(exception_handler->loc, 1);
262 * Called from trap.c when a SIGINT is received. (If the user specifies
263 * that SIGINT is to be trapped or ignored using the trap builtin, then
264 * this routine is not called.) Suppressint is nonzero when interrupts
265 * are held using the INT_OFF macro. (The test for iflag is just
266 * defensive programming.)
268 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
270 raise_interrupt(void)
276 /* Signal is not automatically re-enabled after it is raised,
279 sigprocmask(SIG_SETMASK, &mask, 0);
280 /* pendingsig = 0; - now done in onsig() */
283 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
284 if (!(rootshell && iflag)) {
285 signal(SIGINT, SIG_DFL);
294 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
298 if (--suppressint == 0 && intpending) {
302 #define INT_ON int_on()
310 #define FORCE_INT_ON force_int_on()
315 if (--suppressint == 0 && intpending) \
318 #define FORCE_INT_ON \
325 #endif /* ASH_OPTIMIZE_FOR_SIZE */
327 #define SAVE_INT(v) ((v) = suppressint)
329 #define RESTORE_INT(v) \
333 if (suppressint == 0 && intpending) \
342 raise_exception(EXSIG); \
344 /* EXSIG is turned off by evalbltin(). */
347 * Ignore a signal. Only one usage site - in forkchild()
352 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
353 signal(signo, SIG_IGN);
355 sigmode[signo - 1] = S_HARD_IGN;
359 * Signal handler. Only one usage site - in setsignal()
364 gotsig[signo - 1] = 1;
367 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
377 /* ============ Stdout/stderr output */
380 outstr(const char *p, FILE *file)
388 flush_stdout_stderr(void)
405 outcslow(int c, FILE *dest)
413 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
415 out1fmt(const char *fmt, ...)
422 r = vprintf(fmt, ap);
428 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
430 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
437 ret = vsnprintf(outbuf, length, fmt, ap);
444 out1str(const char *p)
450 out2str(const char *p)
457 /* ============ Parser structures */
459 /* control characters in argument strings */
460 #define CTLESC '\201' /* escape next character */
461 #define CTLVAR '\202' /* variable defn */
462 #define CTLENDVAR '\203'
463 #define CTLBACKQ '\204'
464 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
465 /* CTLBACKQ | CTLQUOTE == '\205' */
466 #define CTLARI '\206' /* arithmetic expression */
467 #define CTLENDARI '\207'
468 #define CTLQUOTEMARK '\210'
470 /* variable substitution byte (follows CTLVAR) */
471 #define VSTYPE 0x0f /* type of variable substitution */
472 #define VSNUL 0x10 /* colon--treat the empty string as unset */
473 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475 /* values of VSTYPE field */
476 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
477 #define VSMINUS 0x2 /* ${var-text} */
478 #define VSPLUS 0x3 /* ${var+text} */
479 #define VSQUESTION 0x4 /* ${var?message} */
480 #define VSASSIGN 0x5 /* ${var=text} */
481 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
482 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
483 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
484 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
485 #define VSLENGTH 0xa /* ${#var} */
487 static const char dolatstr[] ALIGN1 = {
488 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
524 union node *redirect;
530 struct nodelist *cmdlist;
536 union node *redirect;
549 union node *elsepart;
576 struct nodelist *backquote;
611 struct nredir nredir;
612 struct nbinary nbinary;
616 struct nclist nclist;
625 struct nodelist *next;
638 freefunc(struct funcnode *f)
640 if (f && --f->count < 0)
645 /* ============ Debugging output */
649 static FILE *tracefile;
652 trace_printf(const char *fmt, ...)
659 vfprintf(tracefile, fmt, va);
664 trace_vprintf(const char *fmt, va_list va)
668 vfprintf(tracefile, fmt, va);
672 trace_puts(const char *s)
680 trace_puts_quoted(char *s)
687 putc('"', tracefile);
688 for (p = s; *p; p++) {
690 case '\n': c = 'n'; goto backslash;
691 case '\t': c = 't'; goto backslash;
692 case '\r': c = 'r'; goto backslash;
693 case '"': c = '"'; goto backslash;
694 case '\\': c = '\\'; goto backslash;
695 case CTLESC: c = 'e'; goto backslash;
696 case CTLVAR: c = 'v'; goto backslash;
697 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
698 case CTLBACKQ: c = 'q'; goto backslash;
699 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
701 putc('\\', tracefile);
705 if (*p >= ' ' && *p <= '~')
708 putc('\\', tracefile);
709 putc(*p >> 6 & 03, tracefile);
710 putc(*p >> 3 & 07, tracefile);
711 putc(*p & 07, tracefile);
716 putc('"', tracefile);
720 trace_puts_args(char **ap)
727 trace_puts_quoted(*ap);
729 putc('\n', tracefile);
732 putc(' ', tracefile);
747 /* leave open because libedit might be using it */
750 strcpy(s, "./trace");
752 if (!freopen(s, "a", tracefile)) {
753 fprintf(stderr, "Can't re-open %s\n", s);
758 tracefile = fopen(s, "a");
759 if (tracefile == NULL) {
760 fprintf(stderr, "Can't open %s\n", s);
766 flags = fcntl(fileno(tracefile), F_GETFL);
768 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
770 setlinebuf(tracefile);
771 fputs("\nTracing started.\n", tracefile);
775 indent(int amount, char *pfx, FILE *fp)
779 for (i = 0; i < amount; i++) {
780 if (pfx && i == amount - 1)
786 /* little circular references here... */
787 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
790 sharg(union node *arg, FILE *fp)
793 struct nodelist *bqlist;
796 if (arg->type != NARG) {
797 out1fmt("<node type %d>\n", arg->type);
800 bqlist = arg->narg.backquote;
801 for (p = arg->narg.text; *p; p++) {
810 if (subtype == VSLENGTH)
819 switch (subtype & VSTYPE) {
852 out1fmt("<subtype %d>", subtype);
859 case CTLBACKQ|CTLQUOTE:
862 shtree(bqlist->n, -1, NULL, fp);
873 shcmd(union node *cmd, FILE *fp)
881 for (np = cmd->ncmd.args; np; np = np->narg.next) {
887 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
891 switch (np->nfile.type) {
892 case NTO: s = ">>"+1; dftfd = 1; break;
893 case NCLOBBER: s = ">|"; dftfd = 1; break;
894 case NAPPEND: s = ">>"; dftfd = 1; break;
895 case NTOFD: s = ">&"; dftfd = 1; break;
896 case NFROM: s = "<"; break;
897 case NFROMFD: s = "<&"; break;
898 case NFROMTO: s = "<>"; break;
899 default: s = "*error*"; break;
901 if (np->nfile.fd != dftfd)
902 fprintf(fp, "%d", np->nfile.fd);
904 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
905 fprintf(fp, "%d", np->ndup.dupfd);
907 sharg(np->nfile.fname, fp);
914 shtree(union node *n, int ind, char *pfx, FILE *fp)
922 indent(ind, pfx, fp);
933 shtree(n->nbinary.ch1, ind, NULL, fp);
936 shtree(n->nbinary.ch2, ind, NULL, fp);
944 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
949 if (n->npipe.backgnd)
955 fprintf(fp, "<node type %d>", n->type);
963 showtree(union node *n)
965 trace_puts("showtree called\n");
966 shtree(n, 1, NULL, stdout);
969 #define TRACE(param) trace_printf param
970 #define TRACEV(param) trace_vprintf param
975 #define TRACEV(param)
980 /* ============ Parser data */
983 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
986 struct strlist *next;
995 struct strpush *prev; /* preceding string on stack */
999 struct alias *ap; /* if push was associated with an alias */
1001 char *string; /* remember the string since it may change */
1005 struct parsefile *prev; /* preceding file on stack */
1006 int linno; /* current line */
1007 int fd; /* file descriptor (or -1 if string) */
1008 int nleft; /* number of chars left in this line */
1009 int lleft; /* number of chars left in this buffer */
1010 char *nextc; /* next char in buffer */
1011 char *buf; /* input buffer */
1012 struct strpush *strpush; /* for pushing strings at this level */
1013 struct strpush basestrpush; /* so pushing one is fast */
1016 static struct parsefile basepf; /* top level input file */
1017 static struct parsefile *parsefile = &basepf; /* current input file */
1018 static int startlinno; /* line # where last token started */
1019 static char *commandname; /* currently executing command */
1020 static struct strlist *cmdenviron; /* environment for builtin command */
1021 static int exitstatus; /* exit status of last command */
1024 /* ============ Message printing */
1027 ash_vmsg(const char *msg, va_list ap)
1029 fprintf(stderr, "%s: ", arg0);
1031 if (strcmp(arg0, commandname))
1032 fprintf(stderr, "%s: ", commandname);
1033 if (!iflag || parsefile->fd)
1034 fprintf(stderr, "line %d: ", startlinno);
1036 vfprintf(stderr, msg, ap);
1037 outcslow('\n', stderr);
1041 * Exverror is called to raise the error exception. If the second argument
1042 * is not NULL then error prints an error message using printf style
1043 * formatting. It then raises the error exception.
1045 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1047 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1051 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1053 TRACE(("\") pid=%d\n", getpid()));
1055 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1060 flush_stdout_stderr();
1061 raise_exception(cond);
1065 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1067 ash_msg_and_raise_error(const char *msg, ...)
1072 ash_vmsg_and_raise(EXERROR, msg, ap);
1077 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1079 ash_msg_and_raise(int cond, const char *msg, ...)
1084 ash_vmsg_and_raise(cond, msg, ap);
1090 * error/warning routines for external builtins
1093 ash_msg(const char *fmt, ...)
1103 * Return a string describing an error. The returned string may be a
1104 * pointer to a static buffer that will be overwritten on the next call.
1105 * Action describes the operation that got the error.
1108 errmsg(int e, const char *em)
1110 if (e == ENOENT || e == ENOTDIR) {
1117 /* ============ Memory allocation */
1120 * It appears that grabstackstr() will barf with such alignments
1121 * because stalloc() will return a string allocated in a new stackblock.
1123 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1125 /* Most machines require the value returned from malloc to be aligned
1126 * in some way. The following macro will get this right
1127 * on many machines. */
1128 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1129 /* Minimum size of a block */
1130 MINSIZE = SHELL_ALIGN(504),
1133 struct stack_block {
1134 struct stack_block *prev;
1135 char space[MINSIZE];
1139 struct stack_block *stackp;
1142 struct stackmark *marknext;
1146 struct globals_memstack {
1147 struct stack_block *g_stackp; // = &stackbase;
1148 struct stackmark *markp;
1149 char *g_stacknxt; // = stackbase.space;
1150 char *sstrend; // = stackbase.space + MINSIZE;
1151 size_t g_stacknleft; // = MINSIZE;
1152 int herefd; // = -1;
1153 struct stack_block stackbase;
1155 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1156 static struct globals_memstack *const ptr_to_globals_memstack __attribute__ ((section (".data")));
1157 #define G_memstack (*ptr_to_globals_memstack)
1158 #define g_stackp (G_memstack.g_stackp )
1159 #define markp (G_memstack.markp )
1160 #define g_stacknxt (G_memstack.g_stacknxt )
1161 #define sstrend (G_memstack.sstrend )
1162 #define g_stacknleft (G_memstack.g_stacknleft)
1163 #define herefd (G_memstack.herefd )
1164 #define stackbase (G_memstack.stackbase )
1165 #define INIT_G_memstack() do { \
1166 (*(struct globals_memstack**)&ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1167 g_stackp = &stackbase; \
1168 g_stacknxt = stackbase.space; \
1169 g_stacknleft = MINSIZE; \
1170 sstrend = stackbase.space + MINSIZE; \
1174 #define stackblock() ((void *)g_stacknxt)
1175 #define stackblocksize() g_stacknleft
1179 ckrealloc(void * p, size_t nbytes)
1181 p = realloc(p, nbytes);
1183 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1188 ckmalloc(size_t nbytes)
1190 return ckrealloc(NULL, nbytes);
1194 * Make a copy of a string in safe storage.
1197 ckstrdup(const char *s)
1199 char *p = strdup(s);
1201 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1206 * Parse trees for commands are allocated in lifo order, so we use a stack
1207 * to make this more efficient, and also to avoid all sorts of exception
1208 * handling code to handle interrupts in the middle of a parse.
1210 * The size 504 was chosen because the Ultrix malloc handles that size
1214 stalloc(size_t nbytes)
1219 aligned = SHELL_ALIGN(nbytes);
1220 if (aligned > g_stacknleft) {
1223 struct stack_block *sp;
1225 blocksize = aligned;
1226 if (blocksize < MINSIZE)
1227 blocksize = MINSIZE;
1228 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1229 if (len < blocksize)
1230 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1233 sp->prev = g_stackp;
1234 g_stacknxt = sp->space;
1235 g_stacknleft = blocksize;
1236 sstrend = g_stacknxt + blocksize;
1241 g_stacknxt += aligned;
1242 g_stacknleft -= aligned;
1250 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1251 write(2, "stunalloc\n", 10);
1255 g_stacknleft += g_stacknxt - (char *)p;
1260 * Like strdup but works with the ash stack.
1263 ststrdup(const char *p)
1265 size_t len = strlen(p) + 1;
1266 return memcpy(stalloc(len), p, len);
1270 setstackmark(struct stackmark *mark)
1272 mark->stackp = g_stackp;
1273 mark->stacknxt = g_stacknxt;
1274 mark->stacknleft = g_stacknleft;
1275 mark->marknext = markp;
1280 popstackmark(struct stackmark *mark)
1282 struct stack_block *sp;
1288 markp = mark->marknext;
1289 while (g_stackp != mark->stackp) {
1291 g_stackp = sp->prev;
1294 g_stacknxt = mark->stacknxt;
1295 g_stacknleft = mark->stacknleft;
1296 sstrend = mark->stacknxt + mark->stacknleft;
1301 * When the parser reads in a string, it wants to stick the string on the
1302 * stack and only adjust the stack pointer when it knows how big the
1303 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1304 * of space on top of the stack and stackblocklen returns the length of
1305 * this block. Growstackblock will grow this space by at least one byte,
1306 * possibly moving it (like realloc). Grabstackblock actually allocates the
1307 * part of the block that has been used.
1310 growstackblock(void)
1314 newlen = g_stacknleft * 2;
1315 if (newlen < g_stacknleft)
1316 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1320 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1321 struct stack_block *oldstackp;
1322 struct stackmark *xmark;
1323 struct stack_block *sp;
1324 struct stack_block *prevstackp;
1328 oldstackp = g_stackp;
1330 prevstackp = sp->prev;
1331 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1332 sp = ckrealloc(sp, grosslen);
1333 sp->prev = prevstackp;
1335 g_stacknxt = sp->space;
1336 g_stacknleft = newlen;
1337 sstrend = sp->space + newlen;
1340 * Stack marks pointing to the start of the old block
1341 * must be relocated to point to the new block
1344 while (xmark != NULL && xmark->stackp == oldstackp) {
1345 xmark->stackp = g_stackp;
1346 xmark->stacknxt = g_stacknxt;
1347 xmark->stacknleft = g_stacknleft;
1348 xmark = xmark->marknext;
1352 char *oldspace = g_stacknxt;
1353 int oldlen = g_stacknleft;
1354 char *p = stalloc(newlen);
1356 /* free the space we just allocated */
1357 g_stacknxt = memcpy(p, oldspace, oldlen);
1358 g_stacknleft += newlen;
1363 grabstackblock(size_t len)
1365 len = SHELL_ALIGN(len);
1367 g_stacknleft -= len;
1371 * The following routines are somewhat easier to use than the above.
1372 * The user declares a variable of type STACKSTR, which may be declared
1373 * to be a register. The macro STARTSTACKSTR initializes things. Then
1374 * the user uses the macro STPUTC to add characters to the string. In
1375 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1376 * grown as necessary. When the user is done, she can just leave the
1377 * string there and refer to it using stackblock(). Or she can allocate
1378 * the space for it using grabstackstr(). If it is necessary to allow
1379 * someone else to use the stack temporarily and then continue to grow
1380 * the string, the user should use grabstack to allocate the space, and
1381 * then call ungrabstr(p) to return to the previous mode of operation.
1383 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1384 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1385 * is space for at least one character.
1390 size_t len = stackblocksize();
1391 if (herefd >= 0 && len >= 1024) {
1392 full_write(herefd, stackblock(), len);
1393 return stackblock();
1396 return stackblock() + len;
1400 * Called from CHECKSTRSPACE.
1403 makestrspace(size_t newlen, char *p)
1405 size_t len = p - g_stacknxt;
1406 size_t size = stackblocksize();
1411 size = stackblocksize();
1413 if (nleft >= newlen)
1417 return stackblock() + len;
1421 stack_nputstr(const char *s, size_t n, char *p)
1423 p = makestrspace(n, p);
1424 p = memcpy(p, s, n) + n;
1429 stack_putstr(const char *s, char *p)
1431 return stack_nputstr(s, strlen(s), p);
1435 _STPUTC(int c, char *p)
1443 #define STARTSTACKSTR(p) ((p) = stackblock())
1444 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1445 #define CHECKSTRSPACE(n, p) \
1449 size_t m = sstrend - q; \
1451 (p) = makestrspace(l, q); \
1453 #define USTPUTC(c, p) (*p++ = (c))
1454 #define STACKSTRNUL(p) \
1456 if ((p) == sstrend) \
1457 p = growstackstr(); \
1460 #define STUNPUTC(p) (--p)
1461 #define STTOPC(p) (p[-1])
1462 #define STADJUST(amount, p) (p += (amount))
1464 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1465 #define ungrabstackstr(s, p) stunalloc((s))
1466 #define stackstrend() ((void *)sstrend)
1469 /* ============ String helpers */
1472 * prefix -- see if pfx is a prefix of string.
1475 prefix(const char *string, const char *pfx)
1478 if (*pfx++ != *string++)
1481 return (char *) string;
1485 * Check for a valid number. This should be elsewhere.
1488 is_number(const char *p)
1493 } while (*++p != '\0');
1498 * Convert a string of digits to an integer, printing an error message on
1502 number(const char *s)
1505 ash_msg_and_raise_error(illnum, s);
1510 * Produce a possibly single quoted string suitable as input to the shell.
1511 * The return string is allocated on the stack.
1514 single_quote(const char *s)
1524 len = strchrnul(s, '\'') - s;
1526 q = p = makestrspace(len + 3, p);
1529 q = memcpy(q, s, len) + len;
1535 len = strspn(s, "'");
1539 q = p = makestrspace(len + 3, p);
1542 q = memcpy(q, s, len) + len;
1551 return stackblock();
1555 /* ============ nextopt */
1557 static char **argptr; /* argument list for builtin commands */
1558 static char *optionarg; /* set by nextopt (like getopt) */
1559 static char *optptr; /* used by nextopt */
1562 * XXX - should get rid of. have all builtins use getopt(3). the
1563 * library getopt must have the BSD extension static variable "optreset"
1564 * otherwise it can't be used within the shell safely.
1566 * Standard option processing (a la getopt) for builtin routines. The
1567 * only argument that is passed to nextopt is the option string; the
1568 * other arguments are unnecessary. It return the character, or '\0' on
1572 nextopt(const char *optstring)
1579 if (p == NULL || *p == '\0') {
1581 if (p == NULL || *p != '-' || *++p == '\0')
1584 if (LONE_DASH(p)) /* check for "--" */
1588 for (q = optstring; *q != c; ) {
1590 ash_msg_and_raise_error("illegal option -%c", c);
1595 if (*p == '\0' && (p = *argptr++) == NULL)
1596 ash_msg_and_raise_error("no arg for -%c option", c);
1605 /* ============ Math support definitions */
1607 #if ENABLE_ASH_MATH_SUPPORT_64
1608 typedef int64_t arith_t;
1609 #define arith_t_type long long
1611 typedef long arith_t;
1612 #define arith_t_type long
1615 #if ENABLE_ASH_MATH_SUPPORT
1616 static arith_t dash_arith(const char *);
1617 static arith_t arith(const char *expr, int *perrcode);
1620 #if ENABLE_ASH_RANDOM_SUPPORT
1621 static unsigned long rseed;
1628 /* ============ Shell variables */
1631 * The parsefile structure pointed to by the global variable parsefile
1632 * contains information about the current file being read.
1635 struct redirtab *next;
1641 int nparam; /* # of positional parameters (without $0) */
1642 #if ENABLE_ASH_GETOPTS
1643 int optind; /* next parameter to be processed by getopts */
1644 int optoff; /* used by getopts */
1646 unsigned char malloced; /* if parameter list dynamically allocated */
1647 char **p; /* parameter list */
1651 * Free the list of positional parameters.
1654 freeparam(volatile struct shparam *param)
1658 if (param->malloced) {
1659 for (ap = param->p; *ap; ap++)
1665 #if ENABLE_ASH_GETOPTS
1666 static void getoptsreset(const char *value);
1670 struct var *next; /* next entry in hash list */
1671 int flags; /* flags are defined above */
1672 const char *text; /* name=value */
1673 void (*func)(const char *); /* function to be called when */
1674 /* the variable gets set/unset */
1678 struct localvar *next; /* next local variable in list */
1679 struct var *vp; /* the variable that was made local */
1680 int flags; /* saved flags */
1681 const char *text; /* saved text */
1685 #define VEXPORT 0x01 /* variable is exported */
1686 #define VREADONLY 0x02 /* variable cannot be modified */
1687 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1688 #define VTEXTFIXED 0x08 /* text is statically allocated */
1689 #define VSTACK 0x10 /* text is allocated on the stack */
1690 #define VUNSET 0x20 /* the variable is not set */
1691 #define VNOFUNC 0x40 /* don't call the callback function */
1692 #define VNOSET 0x80 /* do not set variable - just readonly test */
1693 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1695 # define VDYNAMIC 0x200 /* dynamic variable */
1701 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1702 #define defifs (defifsvar + 4)
1704 static const char defifs[] ALIGN1 = " \t\n";
1708 /* Need to be before varinit_data[] */
1709 #if ENABLE_LOCALE_SUPPORT
1711 change_lc_all(const char *value)
1713 if (value && *value != '\0')
1714 setlocale(LC_ALL, value);
1717 change_lc_ctype(const char *value)
1719 if (value && *value != '\0')
1720 setlocale(LC_CTYPE, value);
1724 static void chkmail(void);
1725 static void changemail(const char *);
1727 static void changepath(const char *);
1728 #if ENABLE_ASH_RANDOM_SUPPORT
1729 static void change_random(const char *);
1732 static const struct {
1735 void (*func)(const char *);
1736 } varinit_data[] = {
1738 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1740 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1743 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1744 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1746 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1747 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1748 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1749 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1750 #if ENABLE_ASH_GETOPTS
1751 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1753 #if ENABLE_ASH_RANDOM_SUPPORT
1754 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1756 #if ENABLE_LOCALE_SUPPORT
1757 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1758 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1760 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1761 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1766 struct globals_var {
1767 struct shparam shellparam; /* $@ current positional parameters */
1768 struct redirtab *redirlist;
1770 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1771 struct var *vartab[VTABSIZE];
1772 struct var varinit[ARRAY_SIZE(varinit_data)];
1774 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1775 static struct globals_var *const ptr_to_globals_var __attribute__ ((section (".data")));
1776 #define G_var (*ptr_to_globals_var)
1777 #define shellparam (G_var.shellparam )
1778 #define redirlist (G_var.redirlist )
1779 #define g_nullredirs (G_var.g_nullredirs )
1780 #define preverrout_fd (G_var.preverrout_fd)
1781 #define vartab (G_var.vartab )
1782 #define varinit (G_var.varinit )
1783 #define INIT_G_var() do { \
1785 (*(struct globals_var**)&ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1786 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1787 varinit[i].flags = varinit_data[i].flags; \
1788 varinit[i].text = varinit_data[i].text; \
1789 varinit[i].func = varinit_data[i].func; \
1793 #define vifs varinit[0]
1795 #define vmail (&vifs)[1]
1796 #define vmpath (&vmail)[1]
1800 #define vpath (&vmpath)[1]
1801 #define vps1 (&vpath)[1]
1802 #define vps2 (&vps1)[1]
1803 #define vps4 (&vps2)[1]
1804 #define voptind (&vps4)[1]
1805 #if ENABLE_ASH_GETOPTS
1806 #define vrandom (&voptind)[1]
1808 #define vrandom (&vps4)[1]
1812 * The following macros access the values of the above variables.
1813 * They have to skip over the name. They return the null string
1814 * for unset variables.
1816 #define ifsval() (vifs.text + 4)
1817 #define ifsset() ((vifs.flags & VUNSET) == 0)
1818 #define mailval() (vmail.text + 5)
1819 #define mpathval() (vmpath.text + 9)
1820 #define pathval() (vpath.text + 5)
1821 #define ps1val() (vps1.text + 4)
1822 #define ps2val() (vps2.text + 4)
1823 #define ps4val() (vps4.text + 4)
1824 #define optindval() (voptind.text + 7)
1826 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1829 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1830 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1832 #if ENABLE_ASH_GETOPTS
1834 getoptsreset(const char *value)
1836 shellparam.optind = number(value);
1837 shellparam.optoff = -1;
1842 * Return of a legal variable name (a letter or underscore followed by zero or
1843 * more letters, underscores, and digits).
1846 endofname(const char *name)
1854 if (!is_in_name(*p))
1861 * Compares two strings up to the first = or '\0'. The first
1862 * string must be terminated by '='; the second may be terminated by
1863 * either '=' or '\0'.
1866 varcmp(const char *p, const char *q)
1870 while ((c = *p) == (d = *q)) {
1885 varequal(const char *a, const char *b)
1887 return !varcmp(a, b);
1891 * Find the appropriate entry in the hash table from the name.
1893 static struct var **
1894 hashvar(const char *p)
1898 hashval = ((unsigned char) *p) << 4;
1899 while (*p && *p != '=')
1900 hashval += (unsigned char) *p++;
1901 return &vartab[hashval % VTABSIZE];
1905 vpcmp(const void *a, const void *b)
1907 return varcmp(*(const char **)a, *(const char **)b);
1911 * This routine initializes the builtin variables.
1921 * PS1 depends on uid
1923 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1924 vps1.text = "PS1=\\w \\$ ";
1927 vps1.text = "PS1=# ";
1930 end = vp + ARRAY_SIZE(varinit);
1932 vpp = hashvar(vp->text);
1935 } while (++vp < end);
1938 static struct var **
1939 findvar(struct var **vpp, const char *name)
1941 for (; *vpp; vpp = &(*vpp)->next) {
1942 if (varequal((*vpp)->text, name)) {
1950 * Find the value of a variable. Returns NULL if not set.
1953 lookupvar(const char *name)
1957 v = *findvar(hashvar(name), name);
1961 * Dynamic variables are implemented roughly the same way they are
1962 * in bash. Namely, they're "special" so long as they aren't unset.
1963 * As soon as they're unset, they're no longer dynamic, and dynamic
1964 * lookup will no longer happen at that point. -- PFM.
1966 if ((v->flags & VDYNAMIC))
1969 if (!(v->flags & VUNSET))
1970 return strchrnul(v->text, '=') + 1;
1976 * Search the environment of a builtin command.
1979 bltinlookup(const char *name)
1983 for (sp = cmdenviron; sp; sp = sp->next) {
1984 if (varequal(sp->text, name))
1985 return strchrnul(sp->text, '=') + 1;
1987 return lookupvar(name);
1991 * Same as setvar except that the variable and value are passed in
1992 * the first argument as name=value. Since the first argument will
1993 * be actually stored in the table, it should not be a string that
1995 * Called with interrupts off.
1998 setvareq(char *s, int flags)
2000 struct var *vp, **vpp;
2003 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2004 vp = *findvar(vpp, s);
2006 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2009 if (flags & VNOSAVE)
2012 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2018 if (vp->func && (flags & VNOFUNC) == 0)
2019 (*vp->func)(strchrnul(s, '=') + 1);
2021 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2022 free((char*)vp->text);
2024 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2029 vp = ckmalloc(sizeof(*vp));
2034 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2041 * Set the value of a variable. The flags argument is ored with the
2042 * flags of the variable. If val is NULL, the variable is unset.
2045 setvar(const char *name, const char *val, int flags)
2052 q = endofname(name);
2053 p = strchrnul(q, '=');
2055 if (!namelen || p != q)
2056 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2061 vallen = strlen(val);
2064 nameeq = ckmalloc(namelen + vallen + 2);
2065 p = memcpy(nameeq, name, namelen) + namelen;
2068 p = memcpy(p, val, vallen) + vallen;
2071 setvareq(nameeq, flags | VNOSAVE);
2075 #if ENABLE_ASH_GETOPTS
2077 * Safe version of setvar, returns 1 on success 0 on failure.
2080 setvarsafe(const char *name, const char *val, int flags)
2083 volatile int saveint;
2084 struct jmploc *volatile savehandler = exception_handler;
2085 struct jmploc jmploc;
2088 if (setjmp(jmploc.loc))
2091 exception_handler = &jmploc;
2092 setvar(name, val, flags);
2095 exception_handler = savehandler;
2096 RESTORE_INT(saveint);
2102 * Unset the specified variable.
2105 unsetvar(const char *s)
2111 vpp = findvar(hashvar(s), s);
2115 int flags = vp->flags;
2118 if (flags & VREADONLY)
2121 vp->flags &= ~VDYNAMIC;
2125 if ((flags & VSTRFIXED) == 0) {
2127 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2128 free((char*)vp->text);
2134 vp->flags &= ~VEXPORT;
2144 * Process a linked list of variable assignments.
2147 listsetvar(struct strlist *list_set_var, int flags)
2149 struct strlist *lp = list_set_var;
2155 setvareq(lp->text, flags);
2162 * Generate a list of variables satisfying the given conditions.
2165 listvars(int on, int off, char ***end)
2176 for (vp = *vpp; vp; vp = vp->next) {
2177 if ((vp->flags & mask) == on) {
2178 if (ep == stackstrend())
2179 ep = growstackstr();
2180 *ep++ = (char *) vp->text;
2183 } while (++vpp < vartab + VTABSIZE);
2184 if (ep == stackstrend())
2185 ep = growstackstr();
2189 return grabstackstr(ep);
2193 /* ============ Path search helper
2195 * The variable path (passed by reference) should be set to the start
2196 * of the path before the first call; padvance will update
2197 * this value as it proceeds. Successive calls to padvance will return
2198 * the possible path expansions in sequence. If an option (indicated by
2199 * a percent sign) appears in the path entry then the global variable
2200 * pathopt will be set to point to it; otherwise pathopt will be set to
2203 static const char *pathopt; /* set by padvance */
2206 padvance(const char **path, const char *name)
2216 for (p = start; *p && *p != ':' && *p != '%'; p++);
2217 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2218 while (stackblocksize() < len)
2222 memcpy(q, start, p - start);
2230 while (*p && *p != ':') p++;
2236 return stalloc(len);
2240 /* ============ Prompt */
2242 static smallint doprompt; /* if set, prompt the user */
2243 static smallint needprompt; /* true if interactive and at start of line */
2245 #if ENABLE_FEATURE_EDITING
2246 static line_input_t *line_input_state;
2247 static const char *cmdedit_prompt;
2249 putprompt(const char *s)
2251 if (ENABLE_ASH_EXPAND_PRMT) {
2252 free((char*)cmdedit_prompt);
2253 cmdedit_prompt = ckstrdup(s);
2260 putprompt(const char *s)
2266 #if ENABLE_ASH_EXPAND_PRMT
2267 /* expandstr() needs parsing machinery, so it is far away ahead... */
2268 static const char *expandstr(const char *ps);
2270 #define expandstr(s) s
2274 setprompt(int whichprompt)
2277 #if ENABLE_ASH_EXPAND_PRMT
2278 struct stackmark smark;
2283 switch (whichprompt) {
2293 #if ENABLE_ASH_EXPAND_PRMT
2294 setstackmark(&smark);
2295 stalloc(stackblocksize());
2297 putprompt(expandstr(prompt));
2298 #if ENABLE_ASH_EXPAND_PRMT
2299 popstackmark(&smark);
2304 /* ============ The cd and pwd commands */
2306 #define CD_PHYSICAL 1
2309 static int docd(const char *, int);
2318 while ((i = nextopt("LP"))) {
2320 flags ^= CD_PHYSICAL;
2329 * Update curdir (the name of the current directory) in response to a
2333 updatepwd(const char *dir)
2340 cdcomppath = ststrdup(dir);
2343 if (curdir == nullstr)
2345 new = stack_putstr(curdir, new);
2347 new = makestrspace(strlen(dir) + 2, new);
2348 lim = stackblock() + 1;
2352 if (new > lim && *lim == '/')
2357 if (dir[1] == '/' && dir[2] != '/') {
2363 p = strtok(cdcomppath, "/");
2367 if (p[1] == '.' && p[2] == '\0') {
2379 new = stack_putstr(p, new);
2387 return stackblock();
2391 * Find out what the current directory is. If we already know the current
2392 * directory, this routine returns immediately.
2397 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2398 return dir ? dir : nullstr;
2402 setpwd(const char *val, int setold)
2406 oldcur = dir = curdir;
2409 setvar("OLDPWD", oldcur, VEXPORT);
2412 if (physdir != nullstr) {
2413 if (physdir != oldcur)
2417 if (oldcur == val || !val) {
2423 dir = ckstrdup(val);
2424 if (oldcur != dir && oldcur != nullstr) {
2429 setvar("PWD", dir, VEXPORT);
2432 static void hashcd(void);
2435 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2436 * know that the current directory has changed.
2439 docd(const char *dest, int flags)
2441 const char *dir = 0;
2444 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2447 if (!(flags & CD_PHYSICAL)) {
2448 dir = updatepwd(dest);
2463 cdcmd(int argc, char **argv)
2475 dest = bltinlookup(homestr);
2476 else if (LONE_DASH(dest)) {
2477 dest = bltinlookup("OLDPWD");
2499 path = bltinlookup("CDPATH");
2508 p = padvance(&path, dest);
2509 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2513 if (!docd(p, flags))
2518 ash_msg_and_raise_error("can't cd to %s", dest);
2521 if (flags & CD_PRINT)
2522 out1fmt(snlfmt, curdir);
2527 pwdcmd(int argc, char **argv)
2530 const char *dir = curdir;
2534 if (physdir == nullstr)
2538 out1fmt(snlfmt, dir);
2543 /* ============ ... */
2545 #define IBUFSIZ COMMON_BUFSIZE
2546 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2548 /* Syntax classes */
2549 #define CWORD 0 /* character is nothing special */
2550 #define CNL 1 /* newline character */
2551 #define CBACK 2 /* a backslash character */
2552 #define CSQUOTE 3 /* single quote */
2553 #define CDQUOTE 4 /* double quote */
2554 #define CENDQUOTE 5 /* a terminating quote */
2555 #define CBQUOTE 6 /* backwards single quote */
2556 #define CVAR 7 /* a dollar sign */
2557 #define CENDVAR 8 /* a '}' character */
2558 #define CLP 9 /* a left paren in arithmetic */
2559 #define CRP 10 /* a right paren in arithmetic */
2560 #define CENDFILE 11 /* end of file */
2561 #define CCTL 12 /* like CWORD, except it must be escaped */
2562 #define CSPCL 13 /* these terminate a word */
2563 #define CIGN 14 /* character should be ignored */
2565 #if ENABLE_ASH_ALIAS
2569 #define PEOA_OR_PEOF PEOA
2573 #define PEOA_OR_PEOF PEOF
2576 /* number syntax index */
2577 #define BASESYNTAX 0 /* not in quotes */
2578 #define DQSYNTAX 1 /* in double quotes */
2579 #define SQSYNTAX 2 /* in single quotes */
2580 #define ARISYNTAX 3 /* in arithmetic */
2581 #define PSSYNTAX 4 /* prompt */
2583 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2584 #define USE_SIT_FUNCTION
2587 #if ENABLE_ASH_MATH_SUPPORT
2588 static const char S_I_T[][4] = {
2589 #if ENABLE_ASH_ALIAS
2590 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2592 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2593 { CNL, CNL, CNL, CNL }, /* 2, \n */
2594 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2595 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2596 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2597 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2598 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2599 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2600 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2601 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2602 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2603 #ifndef USE_SIT_FUNCTION
2604 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2605 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2606 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2610 static const char S_I_T[][3] = {
2611 #if ENABLE_ASH_ALIAS
2612 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2614 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2615 { CNL, CNL, CNL }, /* 2, \n */
2616 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2617 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2618 { CVAR, CVAR, CWORD }, /* 5, $ */
2619 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2620 { CSPCL, CWORD, CWORD }, /* 7, ( */
2621 { CSPCL, CWORD, CWORD }, /* 8, ) */
2622 { CBACK, CBACK, CCTL }, /* 9, \ */
2623 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2624 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2625 #ifndef USE_SIT_FUNCTION
2626 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2627 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2628 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2631 #endif /* ASH_MATH_SUPPORT */
2633 #ifdef USE_SIT_FUNCTION
2636 SIT(int c, int syntax)
2638 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2639 #if ENABLE_ASH_ALIAS
2640 static const char syntax_index_table[] ALIGN1 = {
2641 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2642 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2643 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2647 static const char syntax_index_table[] ALIGN1 = {
2648 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2649 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2650 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2657 if (c == PEOF) /* 2^8+2 */
2659 #if ENABLE_ASH_ALIAS
2660 if (c == PEOA) /* 2^8+1 */
2664 #define U_C(c) ((unsigned char)(c))
2666 if ((unsigned char)c >= (unsigned char)(CTLESC)
2667 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2671 s = strchr(spec_symbls, c);
2672 if (s == NULL || *s == '\0')
2674 indx = syntax_index_table[(s - spec_symbls)];
2676 return S_I_T[indx][syntax];
2679 #else /* !USE_SIT_FUNCTION */
2681 #if ENABLE_ASH_ALIAS
2682 #define CSPCL_CIGN_CIGN_CIGN 0
2683 #define CSPCL_CWORD_CWORD_CWORD 1
2684 #define CNL_CNL_CNL_CNL 2
2685 #define CWORD_CCTL_CCTL_CWORD 3
2686 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2687 #define CVAR_CVAR_CWORD_CVAR 5
2688 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2689 #define CSPCL_CWORD_CWORD_CLP 7
2690 #define CSPCL_CWORD_CWORD_CRP 8
2691 #define CBACK_CBACK_CCTL_CBACK 9
2692 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2693 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2694 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2695 #define CWORD_CWORD_CWORD_CWORD 13
2696 #define CCTL_CCTL_CCTL_CCTL 14
2698 #define CSPCL_CWORD_CWORD_CWORD 0
2699 #define CNL_CNL_CNL_CNL 1
2700 #define CWORD_CCTL_CCTL_CWORD 2
2701 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2702 #define CVAR_CVAR_CWORD_CVAR 4
2703 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2704 #define CSPCL_CWORD_CWORD_CLP 6
2705 #define CSPCL_CWORD_CWORD_CRP 7
2706 #define CBACK_CBACK_CCTL_CBACK 8
2707 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2708 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2709 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2710 #define CWORD_CWORD_CWORD_CWORD 12
2711 #define CCTL_CCTL_CCTL_CCTL 13
2714 static const char syntax_index_table[258] = {
2715 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2716 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2717 #if ENABLE_ASH_ALIAS
2718 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2720 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2722 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2723 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2724 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2725 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2726 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2727 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2728 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2729 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2858 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2859 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2881 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2882 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2883 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2885 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2887 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2888 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2889 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2890 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2893 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2894 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2895 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2896 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2908 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2911 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2912 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2941 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2945 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2973 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2974 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2978 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2980 #endif /* USE_SIT_FUNCTION */
2983 /* ============ Alias handling */
2985 #if ENABLE_ASH_ALIAS
2987 #define ALIASINUSE 1
2998 static struct alias **atab; // [ATABSIZE];
2999 #define INIT_G_alias() do { \
3000 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3004 static struct alias **
3005 __lookupalias(const char *name) {
3006 unsigned int hashval;
3013 ch = (unsigned char)*p;
3017 ch = (unsigned char)*++p;
3019 app = &atab[hashval % ATABSIZE];
3021 for (; *app; app = &(*app)->next) {
3022 if (strcmp(name, (*app)->name) == 0) {
3030 static struct alias *
3031 lookupalias(const char *name, int check)
3033 struct alias *ap = *__lookupalias(name);
3035 if (check && ap && (ap->flag & ALIASINUSE))
3040 static struct alias *
3041 freealias(struct alias *ap)
3045 if (ap->flag & ALIASINUSE) {
3046 ap->flag |= ALIASDEAD;
3058 setalias(const char *name, const char *val)
3060 struct alias *ap, **app;
3062 app = __lookupalias(name);
3066 if (!(ap->flag & ALIASINUSE)) {
3069 ap->val = ckstrdup(val);
3070 ap->flag &= ~ALIASDEAD;
3073 ap = ckmalloc(sizeof(struct alias));
3074 ap->name = ckstrdup(name);
3075 ap->val = ckstrdup(val);
3084 unalias(const char *name)
3088 app = __lookupalias(name);
3092 *app = freealias(*app);
3103 struct alias *ap, **app;
3107 for (i = 0; i < ATABSIZE; i++) {
3109 for (ap = *app; ap; ap = *app) {
3110 *app = freealias(*app);
3120 printalias(const struct alias *ap)
3122 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3126 * TODO - sort output
3129 aliascmd(int argc, char **argv)
3138 for (i = 0; i < ATABSIZE; i++)
3139 for (ap = atab[i]; ap; ap = ap->next) {
3144 while ((n = *++argv) != NULL) {
3145 v = strchr(n+1, '=');
3146 if (v == NULL) { /* n+1: funny ksh stuff */
3147 ap = *__lookupalias(n);
3149 fprintf(stderr, "%s: %s not found\n", "alias", n);
3163 unaliascmd(int argc, char **argv)
3167 while ((i = nextopt("a")) != '\0') {
3173 for (i = 0; *argptr; argptr++) {
3174 if (unalias(*argptr)) {
3175 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3183 #endif /* ASH_ALIAS */
3186 /* ============ jobs.c */
3188 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3191 #define FORK_NOJOB 2
3193 /* mode flags for showjob(s) */
3194 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3195 #define SHOW_PID 0x04 /* include process pid */
3196 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3199 * A job structure contains information about a job. A job is either a
3200 * single process or a set of processes contained in a pipeline. In the
3201 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3206 pid_t pid; /* process id */
3207 int status; /* last process status from wait() */
3208 char *cmd; /* text of command being run */
3212 struct procstat ps0; /* status of process */
3213 struct procstat *ps; /* status or processes when more than one */
3215 int stopstatus; /* status of a stopped job */
3218 nprocs: 16, /* number of processes */
3220 #define JOBRUNNING 0 /* at least one proc running */
3221 #define JOBSTOPPED 1 /* all procs are stopped */
3222 #define JOBDONE 2 /* all procs are completed */
3224 sigint: 1, /* job was killed by SIGINT */
3225 jobctl: 1, /* job running under job control */
3227 waited: 1, /* true if this entry has been waited for */
3228 used: 1, /* true if this entry is in used */
3229 changed: 1; /* true if status has changed */
3230 struct job *prev_job; /* previous job */
3233 static pid_t backgndpid; /* pid of last background process */
3234 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3236 static struct job *makejob(union node *, int);
3237 static int forkshell(struct job *, union node *, int);
3238 static int waitforjob(struct job *);
3241 enum { jobctl = 0 };
3242 #define setjobctl(on) do {} while (0)
3244 static smallint jobctl; /* true if doing job control */
3245 static void setjobctl(int);
3249 * Set the signal handler for the specified signal. The routine figures
3250 * out what it should be set to.
3253 setsignal(int signo)
3257 struct sigaction act;
3262 else if (*t != '\0')
3266 if (rootshell && action == S_DFL) {
3269 if (iflag || minusc || sflag == 0)
3292 t = &sigmode[signo - 1];
3296 * current setting unknown
3298 if (sigaction(signo, 0, &act) == -1) {
3300 * Pretend it worked; maybe we should give a warning
3301 * here, but other shells don't. We don't alter
3302 * sigmode, so that we retry every time.
3306 if (act.sa_handler == SIG_IGN) {
3308 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3310 tsig = S_IGN; /* don't hard ignore these */
3314 tsig = S_RESET; /* force to be set */
3317 if (tsig == S_HARD_IGN || tsig == action)
3321 act.sa_handler = onsig;
3324 act.sa_handler = SIG_IGN;
3327 act.sa_handler = SIG_DFL;
3331 sigfillset(&act.sa_mask);
3332 sigaction(signo, &act, 0);
3335 /* mode flags for set_curjob */
3336 #define CUR_DELETE 2
3337 #define CUR_RUNNING 1
3338 #define CUR_STOPPED 0
3340 /* mode flags for dowait */
3341 #define DOWAIT_NORMAL 0
3342 #define DOWAIT_BLOCK 1
3345 /* pgrp of shell on invocation */
3346 static int initialpgrp;
3347 static int ttyfd = -1;
3350 static struct job *jobtab;
3352 static unsigned njobs;
3354 static struct job *curjob;
3355 /* number of presumed living untracked jobs */
3359 set_curjob(struct job *jp, unsigned mode)
3362 struct job **jpp, **curp;
3364 /* first remove from list */
3365 jpp = curp = &curjob;
3370 jpp = &jp1->prev_job;
3372 *jpp = jp1->prev_job;
3374 /* Then re-insert in correct position */
3382 /* job being deleted */
3385 /* newly created job or backgrounded job,
3386 put after all stopped jobs. */
3390 if (!jp1 || jp1->state != JOBSTOPPED)
3393 jpp = &jp1->prev_job;
3399 /* newly stopped job - becomes curjob */
3400 jp->prev_job = *jpp;
3408 jobno(const struct job *jp)
3410 return jp - jobtab + 1;
3415 * Convert a job name to a job structure.
3418 getjob(const char *name, int getctl)
3422 const char *err_msg = "No such job: %s";
3426 char *(*match)(const char *, const char *);
3441 if (c == '+' || c == '%') {
3443 err_msg = "No current job";
3449 err_msg = "No previous job";
3460 jp = jobtab + num - 1;
3477 if (match(jp->ps[0].cmd, p)) {
3481 err_msg = "%s: ambiguous";
3488 err_msg = "job %s not created under job control";
3489 if (getctl && jp->jobctl == 0)
3494 ash_msg_and_raise_error(err_msg, name);
3498 * Mark a job structure as unused.
3501 freejob(struct job *jp)
3503 struct procstat *ps;
3507 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3508 if (ps->cmd != nullstr)
3511 if (jp->ps != &jp->ps0)
3514 set_curjob(jp, CUR_DELETE);
3520 xtcsetpgrp(int fd, pid_t pgrp)
3522 if (tcsetpgrp(fd, pgrp))
3523 ash_msg_and_raise_error("cannot set tty process group (%m)");
3527 * Turn job control on and off.
3529 * Note: This code assumes that the third arg to ioctl is a character
3530 * pointer, which is true on Berkeley systems but not System V. Since
3531 * System V doesn't have job control yet, this isn't a problem now.
3533 * Called with interrupts off.
3541 if (on == jobctl || rootshell == 0)
3545 ofd = fd = open(_PATH_TTY, O_RDWR);
3547 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3548 * That sometimes helps to acquire controlling tty.
3549 * Obviously, a workaround for bugs when someone
3550 * failed to provide a controlling tty to bash! :) */
3556 fd = fcntl(fd, F_DUPFD, 10);
3561 /* fd is a tty at this point */
3562 close_on_exec_on(fd);
3563 do { /* while we are in the background */
3564 pgrp = tcgetpgrp(fd);
3567 ash_msg("can't access tty; job control turned off");
3571 if (pgrp == getpgrp())
3582 xtcsetpgrp(fd, pgrp);
3584 /* turning job control off */
3587 /* was xtcsetpgrp, but this can make exiting ash
3588 * with pty already deleted loop forever */
3589 tcsetpgrp(fd, pgrp);
3604 killcmd(int argc, char **argv)
3606 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3609 if (argv[i][0] == '%') {
3610 struct job *jp = getjob(argv[i], 0);
3611 unsigned pid = jp->ps[0].pid;
3612 /* Enough space for ' -NNN<nul>' */
3613 argv[i] = alloca(sizeof(int)*3 + 3);
3614 /* kill_main has matching code to expect
3615 * leading space. Needed to not confuse
3616 * negative pids with "kill -SIGNAL_NO" syntax */
3617 sprintf(argv[i], " -%u", pid);
3619 } while (argv[++i]);
3621 return kill_main(argc, argv);
3625 showpipe(struct job *jp, FILE *out)
3627 struct procstat *sp;
3628 struct procstat *spend;
3630 spend = jp->ps + jp->nprocs;
3631 for (sp = jp->ps + 1; sp < spend; sp++)
3632 fprintf(out, " | %s", sp->cmd);
3633 outcslow('\n', out);
3634 flush_stdout_stderr();
3639 restartjob(struct job *jp, int mode)
3641 struct procstat *ps;
3647 if (jp->state == JOBDONE)
3649 jp->state = JOBRUNNING;
3651 if (mode == FORK_FG)
3652 xtcsetpgrp(ttyfd, pgid);
3653 killpg(pgid, SIGCONT);
3657 if (WIFSTOPPED(ps->status)) {
3663 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3669 fg_bgcmd(int argc, char **argv)
3676 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3681 jp = getjob(*argv, 1);
3682 if (mode == FORK_BG) {
3683 set_curjob(jp, CUR_RUNNING);
3684 fprintf(out, "[%d] ", jobno(jp));
3686 outstr(jp->ps->cmd, out);
3688 retval = restartjob(jp, mode);
3689 } while (*argv && *++argv);
3695 sprint_status(char *s, int status, int sigonly)
3701 if (!WIFEXITED(status)) {
3703 if (WIFSTOPPED(status))
3704 st = WSTOPSIG(status);
3707 st = WTERMSIG(status);
3709 if (st == SIGINT || st == SIGPIPE)
3712 if (WIFSTOPPED(status))
3717 col = fmtstr(s, 32, strsignal(st));
3718 if (WCOREDUMP(status)) {
3719 col += fmtstr(s + col, 16, " (core dumped)");
3721 } else if (!sigonly) {
3722 st = WEXITSTATUS(status);
3724 col = fmtstr(s, 16, "Done(%d)", st);
3726 col = fmtstr(s, 16, "Done");
3733 * Do a wait system call. If job control is compiled in, we accept
3734 * stopped processes. If block is zero, we return a value of zero
3735 * rather than blocking.
3737 * System V doesn't have a non-blocking wait system call. It does
3738 * have a SIGCLD signal that is sent to a process when one of it's
3739 * children dies. The obvious way to use SIGCLD would be to install
3740 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3741 * was received, and have waitproc bump another counter when it got
3742 * the status of a process. Waitproc would then know that a wait
3743 * system call would not block if the two counters were different.
3744 * This approach doesn't work because if a process has children that
3745 * have not been waited for, System V will send it a SIGCLD when it
3746 * installs a signal handler for SIGCLD. What this means is that when
3747 * a child exits, the shell will be sent SIGCLD signals continuously
3748 * until is runs out of stack space, unless it does a wait call before
3749 * restoring the signal handler. The code below takes advantage of
3750 * this (mis)feature by installing a signal handler for SIGCLD and
3751 * then checking to see whether it was called. If there are any
3752 * children to be waited for, it will be.
3754 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3755 * waits at all. In this case, the user will not be informed when
3756 * a background process until the next time she runs a real program
3757 * (as opposed to running a builtin command or just typing return),
3758 * and the jobs command may give out of date information.
3761 waitproc(int block, int *status)
3771 return wait3(status, flags, (struct rusage *)NULL);
3775 * Wait for a process to terminate.
3778 dowait(int block, struct job *job)
3783 struct job *thisjob;
3786 TRACE(("dowait(%d) called\n", block));
3787 pid = waitproc(block, &status);
3788 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3793 for (jp = curjob; jp; jp = jp->prev_job) {
3794 struct procstat *sp;
3795 struct procstat *spend;
3796 if (jp->state == JOBDONE)
3799 spend = jp->ps + jp->nprocs;
3802 if (sp->pid == pid) {
3803 TRACE(("Job %d: changing status of proc %d "
3804 "from 0x%x to 0x%x\n",
3805 jobno(jp), pid, sp->status, status));
3806 sp->status = status;
3809 if (sp->status == -1)
3812 if (state == JOBRUNNING)
3814 if (WIFSTOPPED(sp->status)) {
3815 jp->stopstatus = sp->status;
3819 } while (++sp < spend);
3824 if (!WIFSTOPPED(status))
3831 if (state != JOBRUNNING) {
3832 thisjob->changed = 1;
3834 if (thisjob->state != state) {
3835 TRACE(("Job %d: changing state from %d to %d\n",
3836 jobno(thisjob), thisjob->state, state));
3837 thisjob->state = state;
3839 if (state == JOBSTOPPED) {
3840 set_curjob(thisjob, CUR_STOPPED);
3849 if (thisjob && thisjob == job) {
3853 len = sprint_status(s, status, 1);
3865 showjob(FILE *out, struct job *jp, int mode)
3867 struct procstat *ps;
3868 struct procstat *psend;
3875 if (mode & SHOW_PGID) {
3876 /* just output process (group) id of pipeline */
3877 fprintf(out, "%d\n", ps->pid);
3881 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3886 else if (curjob && jp == curjob->prev_job)
3889 if (mode & SHOW_PID)
3890 col += fmtstr(s + col, 16, "%d ", ps->pid);
3892 psend = ps + jp->nprocs;
3894 if (jp->state == JOBRUNNING) {
3895 strcpy(s + col, "Running");
3896 col += sizeof("Running") - 1;
3898 int status = psend[-1].status;
3899 if (jp->state == JOBSTOPPED)
3900 status = jp->stopstatus;
3901 col += sprint_status(s + col, status, 0);
3907 /* for each process */
3908 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3910 fprintf(out, "%s%*c%s",
3911 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3913 if (!(mode & SHOW_PID)) {
3917 if (++ps == psend) {
3918 outcslow('\n', out);
3925 if (jp->state == JOBDONE) {
3926 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3932 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3933 * statuses have changed since the last call to showjobs.
3936 showjobs(FILE *out, int mode)
3940 TRACE(("showjobs(%x) called\n", mode));
3942 /* If not even one one job changed, there is nothing to do */
3943 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3946 for (jp = curjob; jp; jp = jp->prev_job) {
3947 if (!(mode & SHOW_CHANGED) || jp->changed) {
3948 showjob(out, jp, mode);
3954 jobscmd(int argc, char **argv)
3959 while ((m = nextopt("lp"))) {
3969 showjob(stdout, getjob(*argv,0), mode);
3972 showjobs(stdout, mode);
3979 getstatus(struct job *job)
3984 status = job->ps[job->nprocs - 1].status;
3985 retval = WEXITSTATUS(status);
3986 if (!WIFEXITED(status)) {
3988 retval = WSTOPSIG(status);
3989 if (!WIFSTOPPED(status))
3992 /* XXX: limits number of signals */
3993 retval = WTERMSIG(status);
3995 if (retval == SIGINT)
4001 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4002 jobno(job), job->nprocs, status, retval));
4007 waitcmd(int argc, char **argv)
4020 /* wait for all jobs */
4025 /* no running procs */
4028 if (jp->state == JOBRUNNING)
4033 dowait(DOWAIT_BLOCK, 0);
4039 if (**argv != '%') {
4040 pid_t pid = number(*argv);
4044 if (job->ps[job->nprocs - 1].pid == pid)
4046 job = job->prev_job;
4052 job = getjob(*argv, 0);
4053 /* loop until process terminated or stopped */
4054 while (job->state == JOBRUNNING)
4055 dowait(DOWAIT_BLOCK, 0);
4057 retval = getstatus(job);
4071 struct job *jp, *jq;
4073 len = njobs * sizeof(*jp);
4075 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4077 offset = (char *)jp - (char *)jq;
4079 /* Relocate pointers */
4082 jq = (struct job *)((char *)jq + l);
4086 #define joff(p) ((struct job *)((char *)(p) + l))
4087 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4088 if (joff(jp)->ps == &jq->ps0)
4089 jmove(joff(jp)->ps);
4090 if (joff(jp)->prev_job)
4091 jmove(joff(jp)->prev_job);
4101 jp = (struct job *)((char *)jp + len);
4105 } while (--jq >= jp);
4110 * Return a new job structure.
4111 * Called with interrupts off.
4114 makejob(union node *node, int nprocs)
4119 for (i = njobs, jp = jobtab; ; jp++) {
4126 if (jp->state != JOBDONE || !jp->waited)
4135 memset(jp, 0, sizeof(*jp));
4137 /* jp->jobctl is a bitfield.
4138 * "jp->jobctl |= jobctl" likely to give awful code */
4142 jp->prev_job = curjob;
4147 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4149 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4156 * Return a string identifying a command (to be printed by the
4159 static char *cmdnextc;
4162 cmdputs(const char *s)
4164 const char *p, *str;
4165 char c, cc[2] = " ";
4169 static const char vstype[VSTYPE + 1][4] = {
4170 "", "}", "-", "+", "?", "=",
4171 "%", "%%", "#", "##"
4174 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4176 while ((c = *p++) != 0) {
4184 if ((subtype & VSTYPE) == VSLENGTH)
4188 if (!(subtype & VSQUOTE) == !(quoted & 1))
4194 str = "\"}" + !(quoted & 1);
4201 case CTLBACKQ+CTLQUOTE:
4204 #if ENABLE_ASH_MATH_SUPPORT
4219 if ((subtype & VSTYPE) != VSNORMAL)
4221 str = vstype[subtype & VSTYPE];
4222 if (subtype & VSNUL)
4231 /* These can only happen inside quotes */
4244 while ((c = *str++)) {
4249 USTPUTC('"', nextc);
4255 /* cmdtxt() and cmdlist() call each other */
4256 static void cmdtxt(union node *n);
4259 cmdlist(union node *np, int sep)
4261 for (; np; np = np->narg.next) {
4265 if (sep && np->narg.next)
4271 cmdtxt(union node *n)
4274 struct nodelist *lp;
4286 lp = n->npipe.cmdlist;
4304 cmdtxt(n->nbinary.ch1);
4320 cmdtxt(n->nif.test);
4323 if (n->nif.elsepart) {
4326 n = n->nif.elsepart;
4342 cmdtxt(n->nbinary.ch1);
4352 cmdputs(n->nfor.var);
4354 cmdlist(n->nfor.args, 1);
4359 cmdputs(n->narg.text);
4363 cmdlist(n->ncmd.args, 1);
4364 cmdlist(n->ncmd.redirect, 0);
4377 cmdputs(n->ncase.expr->narg.text);
4379 for (np = n->ncase.cases; np; np = np->nclist.next) {
4380 cmdtxt(np->nclist.pattern);
4382 cmdtxt(np->nclist.body);
4408 s[0] = n->nfile.fd + '0';
4412 if (n->type == NTOFD || n->type == NFROMFD) {
4413 s[0] = n->ndup.dupfd + '0';
4423 commandtext(union node *n)
4427 STARTSTACKSTR(cmdnextc);
4429 name = stackblock();
4430 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4431 name, cmdnextc, cmdnextc));
4432 return ckstrdup(name);
4437 * Fork off a subshell. If we are doing job control, give the subshell its
4438 * own process group. Jp is a job structure that the job is to be added to.
4439 * N is the command that will be evaluated by the child. Both jp and n may
4440 * be NULL. The mode parameter can be one of the following:
4441 * FORK_FG - Fork off a foreground process.
4442 * FORK_BG - Fork off a background process.
4443 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4444 * process group even if job control is on.
4446 * When job control is turned off, background processes have their standard
4447 * input redirected to /dev/null (except for the second and later processes
4450 * Called with interrupts off.
4453 * Clear traps on a fork.
4460 for (tp = trap; tp < &trap[NSIG]; tp++) {
4461 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4466 setsignal(tp - trap);
4472 /* Lives far away from here, needed for forkchild */
4473 static void closescript(void);
4475 /* Called after fork(), in child */
4477 forkchild(struct job *jp, union node *n, int mode)
4481 TRACE(("Child shell %d\n", getpid()));
4488 /* do job control only in root shell */
4490 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4493 if (jp->nprocs == 0)
4496 pgrp = jp->ps[0].pid;
4497 /* This can fail because we are doing it in the parent also */
4498 (void)setpgid(0, pgrp);
4499 if (mode == FORK_FG)
4500 xtcsetpgrp(ttyfd, pgrp);
4505 if (mode == FORK_BG) {
4508 if (jp->nprocs == 0) {
4510 if (open(bb_dev_null, O_RDONLY) != 0)
4511 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4514 if (!oldlvl && iflag) {
4519 for (jp = curjob; jp; jp = jp->prev_job)
4524 /* Called after fork(), in parent */
4526 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4528 TRACE(("In parent shell: child = %d\n", pid));
4530 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4535 if (mode != FORK_NOJOB && jp->jobctl) {
4538 if (jp->nprocs == 0)
4541 pgrp = jp->ps[0].pid;
4542 /* This can fail because we are doing it in the child also */
4546 if (mode == FORK_BG) {
4547 backgndpid = pid; /* set $! */
4548 set_curjob(jp, CUR_RUNNING);
4551 struct procstat *ps = &jp->ps[jp->nprocs++];
4557 ps->cmd = commandtext(n);
4563 forkshell(struct job *jp, union node *n, int mode)
4567 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4570 TRACE(("Fork failed, errno=%d", errno));
4573 ash_msg_and_raise_error("cannot fork");
4576 forkchild(jp, n, mode);
4578 forkparent(jp, n, mode, pid);
4583 * Wait for job to finish.
4585 * Under job control we have the problem that while a child process is
4586 * running interrupts generated by the user are sent to the child but not
4587 * to the shell. This means that an infinite loop started by an inter-
4588 * active user may be hard to kill. With job control turned off, an
4589 * interactive user may place an interactive program inside a loop. If
4590 * the interactive program catches interrupts, the user doesn't want
4591 * these interrupts to also abort the loop. The approach we take here
4592 * is to have the shell ignore interrupt signals while waiting for a
4593 * foreground process to terminate, and then send itself an interrupt
4594 * signal if the child process was terminated by an interrupt signal.
4595 * Unfortunately, some programs want to do a bit of cleanup and then
4596 * exit on interrupt; unless these processes terminate themselves by
4597 * sending a signal to themselves (instead of calling exit) they will
4598 * confuse this approach.
4600 * Called with interrupts off.
4603 waitforjob(struct job *jp)
4607 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4608 while (jp->state == JOBRUNNING) {
4609 dowait(DOWAIT_BLOCK, jp);
4614 xtcsetpgrp(ttyfd, rootpid);
4616 * This is truly gross.
4617 * If we're doing job control, then we did a TIOCSPGRP which
4618 * caused us (the shell) to no longer be in the controlling
4619 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4620 * intuit from the subprocess exit status whether a SIGINT
4621 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4626 if (jp->state == JOBDONE)
4633 * return 1 if there are stopped jobs, otherwise 0
4645 if (jp && jp->state == JOBSTOPPED) {
4646 out2str("You have stopped jobs.\n");
4655 /* ============ redir.c
4657 * Code for dealing with input/output redirection.
4660 #define EMPTY -2 /* marks an unused slot in redirtab */
4661 #define CLOSED -3 /* marks a slot of previously-closed fd */
4663 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4665 # define PIPESIZE PIPE_BUF
4669 * Open a file in noclobber mode.
4670 * The code was copied from bash.
4673 noclobberopen(const char *fname)
4676 struct stat finfo, finfo2;
4679 * If the file exists and is a regular file, return an error
4682 r = stat(fname, &finfo);
4683 if (r == 0 && S_ISREG(finfo.st_mode)) {
4689 * If the file was not present (r != 0), make sure we open it
4690 * exclusively so that if it is created before we open it, our open
4691 * will fail. Make sure that we do not truncate an existing file.
4692 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4693 * file was not a regular file, we leave O_EXCL off.
4696 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4697 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4699 /* If the open failed, return the file descriptor right away. */
4704 * OK, the open succeeded, but the file may have been changed from a
4705 * non-regular file to a regular file between the stat and the open.
4706 * We are assuming that the O_EXCL open handles the case where FILENAME
4707 * did not exist and is symlinked to an existing file between the stat
4712 * If we can open it and fstat the file descriptor, and neither check
4713 * revealed that it was a regular file, and the file has not been
4714 * replaced, return the file descriptor.
4716 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4717 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4720 /* The file has been replaced. badness. */
4727 * Handle here documents. Normally we fork off a process to write the
4728 * data to a pipe. If the document is short, we can stuff the data in
4729 * the pipe without forking.
4731 /* openhere needs this forward reference */
4732 static void expandhere(union node *arg, int fd);
4734 openhere(union node *redir)
4740 ash_msg_and_raise_error("pipe call failed");
4741 if (redir->type == NHERE) {
4742 len = strlen(redir->nhere.doc->narg.text);
4743 if (len <= PIPESIZE) {
4744 full_write(pip[1], redir->nhere.doc->narg.text, len);
4748 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4750 signal(SIGINT, SIG_IGN);
4751 signal(SIGQUIT, SIG_IGN);
4752 signal(SIGHUP, SIG_IGN);
4754 signal(SIGTSTP, SIG_IGN);
4756 signal(SIGPIPE, SIG_DFL);
4757 if (redir->type == NHERE)
4758 full_write(pip[1], redir->nhere.doc->narg.text, len);
4760 expandhere(redir->nhere.doc, pip[1]);
4769 openredirect(union node *redir)
4774 switch (redir->nfile.type) {
4776 fname = redir->nfile.expfname;
4777 f = open(fname, O_RDONLY);
4782 fname = redir->nfile.expfname;
4783 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4788 /* Take care of noclobber mode. */
4790 fname = redir->nfile.expfname;
4791 f = noclobberopen(fname);
4798 fname = redir->nfile.expfname;
4799 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4804 fname = redir->nfile.expfname;
4805 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4813 /* Fall through to eliminate warning. */
4820 f = openhere(redir);
4826 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4828 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4832 * Copy a file descriptor to be >= to. Returns -1
4833 * if the source file descriptor is closed, EMPTY if there are no unused
4834 * file descriptors left.
4837 copyfd(int from, int to)
4841 newfd = fcntl(from, F_DUPFD, to);
4843 if (errno == EMFILE)
4845 ash_msg_and_raise_error("%d: %m", from);
4851 dupredirect(union node *redir, int f)
4853 int fd = redir->nfile.fd;
4855 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4856 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4857 copyfd(redir->ndup.dupfd, fd);
4869 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4870 * old file descriptors are stashed away so that the redirection can be
4871 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4872 * standard output, and the standard error if it becomes a duplicate of
4873 * stdout, is saved in memory.
4875 /* flags passed to redirect */
4876 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4877 #define REDIR_SAVEFD2 03 /* set preverrout */
4879 redirect(union node *redir, int flags)
4882 struct redirtab *sv;
4893 if (flags & REDIR_PUSH) {
4894 sv = ckmalloc(sizeof(*sv));
4895 sv->next = redirlist;
4897 sv->nullredirs = g_nullredirs - 1;
4898 for (i = 0; i < 10; i++)
4899 sv->renamed[i] = EMPTY;
4905 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4906 && n->ndup.dupfd == fd)
4907 continue; /* redirect from/to same file descriptor */
4909 newfd = openredirect(n);
4911 /* Descriptor wasn't open before redirect.
4912 * Mark it for close in the future */
4913 if (sv && sv->renamed[fd] == EMPTY)
4914 sv->renamed[fd] = CLOSED;
4917 if (sv && sv->renamed[fd] == EMPTY) {
4918 i = fcntl(fd, F_DUPFD, 10);
4925 ash_msg_and_raise_error("%d: %m", fd);
4929 sv->renamed[fd] = i;
4935 dupredirect(n, newfd);
4936 } while ((n = n->nfile.next));
4938 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
4939 preverrout_fd = sv->renamed[2];
4943 * Undo the effects of the last redirection.
4948 struct redirtab *rp;
4951 if (--g_nullredirs >= 0)
4955 for (i = 0; i < 10; i++) {
4956 if (rp->renamed[i] == CLOSED) {
4961 if (rp->renamed[i] != EMPTY) {
4964 copyfd(rp->renamed[i], i);
4966 close(rp->renamed[i]);
4969 redirlist = rp->next;
4970 g_nullredirs = rp->nullredirs;
4976 * Undo all redirections. Called on error or interrupt.
4980 * Discard all saved file descriptors.
4983 clearredir(int drop)
4994 redirectsafe(union node *redir, int flags)
4997 volatile int saveint;
4998 struct jmploc *volatile savehandler = exception_handler;
4999 struct jmploc jmploc;
5002 err = setjmp(jmploc.loc) * 2;
5004 exception_handler = &jmploc;
5005 redirect(redir, flags);
5007 exception_handler = savehandler;
5008 if (err && exception != EXERROR)
5009 longjmp(exception_handler->loc, 1);
5010 RESTORE_INT(saveint);
5015 /* ============ Routines to expand arguments to commands
5017 * We have to deal with backquotes, shell variables, and file metacharacters.
5023 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5024 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5025 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5026 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5027 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5028 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5029 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5030 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5031 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5035 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5036 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5037 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5038 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5039 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5042 * Structure specifying which parts of the string should be searched
5043 * for IFS characters.
5046 struct ifsregion *next; /* next region in list */
5047 int begoff; /* offset of start of region */
5048 int endoff; /* offset of end of region */
5049 int nulonly; /* search for nul bytes only */
5053 struct strlist *list;
5054 struct strlist **lastp;
5057 /* output of current string */
5058 static char *expdest;
5059 /* list of back quote expressions */
5060 static struct nodelist *argbackq;
5061 /* first struct in list of ifs regions */
5062 static struct ifsregion ifsfirst;
5063 /* last struct in list */
5064 static struct ifsregion *ifslastp;
5065 /* holds expanded arg list */
5066 static struct arglist exparg;
5076 expdest = makestrspace(32, expdest);
5077 #if ENABLE_ASH_MATH_SUPPORT_64
5078 len = fmtstr(expdest, 32, "%lld", (long long) num);
5080 len = fmtstr(expdest, 32, "%ld", num);
5082 STADJUST(len, expdest);
5087 esclen(const char *start, const char *p)
5091 while (p > start && *--p == CTLESC) {
5098 * Remove any CTLESC characters from a string.
5101 _rmescapes(char *str, int flag)
5103 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5110 p = strpbrk(str, qchars);
5116 if (flag & RMESCAPE_ALLOC) {
5117 size_t len = p - str;
5118 size_t fulllen = len + strlen(p) + 1;
5120 if (flag & RMESCAPE_GROW) {
5121 r = makestrspace(fulllen, expdest);
5122 } else if (flag & RMESCAPE_HEAP) {
5123 r = ckmalloc(fulllen);
5125 r = stalloc(fulllen);
5129 q = memcpy(q, str, len) + len;
5132 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5133 globbing = flag & RMESCAPE_GLOB;
5134 notescaped = globbing;
5136 if (*p == CTLQUOTEMARK) {
5137 inquotes = ~inquotes;
5139 notescaped = globbing;
5143 /* naked back slash */
5149 if (notescaped && inquotes && *p != '/') {
5153 notescaped = globbing;
5158 if (flag & RMESCAPE_GROW) {
5160 STADJUST(q - r + 1, expdest);
5164 #define rmescapes(p) _rmescapes((p), 0)
5166 #define pmatch(a, b) !fnmatch((a), (b), 0)
5169 * Prepare a pattern for a expmeta (internal glob(3)) call.
5171 * Returns an stalloced string.
5174 preglob(const char *pattern, int quoted, int flag)
5176 flag |= RMESCAPE_GLOB;
5178 flag |= RMESCAPE_QUOTED;
5180 return _rmescapes((char *)pattern, flag);
5184 * Put a string on the stack.
5187 memtodest(const char *p, size_t len, int syntax, int quotes)
5191 q = makestrspace(len * 2, q);
5194 int c = signed_char2int(*p++);
5197 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5206 strtodest(const char *p, int syntax, int quotes)
5208 memtodest(p, strlen(p), syntax, quotes);
5212 * Record the fact that we have to scan this region of the
5213 * string for IFS characters.
5216 recordregion(int start, int end, int nulonly)
5218 struct ifsregion *ifsp;
5220 if (ifslastp == NULL) {
5224 ifsp = ckmalloc(sizeof(*ifsp));
5226 ifslastp->next = ifsp;
5230 ifslastp->begoff = start;
5231 ifslastp->endoff = end;
5232 ifslastp->nulonly = nulonly;
5236 removerecordregions(int endoff)
5238 if (ifslastp == NULL)
5241 if (ifsfirst.endoff > endoff) {
5242 while (ifsfirst.next != NULL) {
5243 struct ifsregion *ifsp;
5245 ifsp = ifsfirst.next->next;
5246 free(ifsfirst.next);
5247 ifsfirst.next = ifsp;
5250 if (ifsfirst.begoff > endoff)
5253 ifslastp = &ifsfirst;
5254 ifsfirst.endoff = endoff;
5259 ifslastp = &ifsfirst;
5260 while (ifslastp->next && ifslastp->next->begoff < endoff)
5261 ifslastp=ifslastp->next;
5262 while (ifslastp->next != NULL) {
5263 struct ifsregion *ifsp;
5265 ifsp = ifslastp->next->next;
5266 free(ifslastp->next);
5267 ifslastp->next = ifsp;
5270 if (ifslastp->endoff > endoff)
5271 ifslastp->endoff = endoff;
5275 exptilde(char *startp, char *p, int flag)
5281 int quotes = flag & (EXP_FULL | EXP_CASE);
5286 while ((c = *++p) != '\0') {
5293 if (flag & EXP_VARTILDE)
5303 if (*name == '\0') {
5304 home = lookupvar(homestr);
5306 pw = getpwnam(name);
5311 if (!home || !*home)
5314 startloc = expdest - (char *)stackblock();
5315 strtodest(home, SQSYNTAX, quotes);
5316 recordregion(startloc, expdest - (char *)stackblock(), 0);
5324 * Execute a command inside back quotes. If it's a builtin command, we
5325 * want to save its output in a block obtained from malloc. Otherwise
5326 * we fork off a subprocess and get the output of the command via a pipe.
5327 * Should be called with interrupts off.
5329 struct backcmd { /* result of evalbackcmd */
5330 int fd; /* file descriptor to read from */
5331 char *buf; /* buffer */
5332 int nleft; /* number of chars in buffer */
5333 struct job *jp; /* job structure for command */
5336 /* These forward decls are needed to use "eval" code for backticks handling: */
5337 static int back_exitstatus; /* exit status of backquoted command */
5338 #define EV_EXIT 01 /* exit after evaluating tree */
5339 static void evaltree(union node *, int);
5342 evalbackcmd(union node *n, struct backcmd *result)
5354 saveherefd = herefd;
5362 ash_msg_and_raise_error("pipe call failed");
5364 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5373 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5377 result->fd = pip[0];
5380 herefd = saveherefd;
5382 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5383 result->fd, result->buf, result->nleft, result->jp));
5387 * Expand stuff in backwards quotes.
5390 expbackq(union node *cmd, int quoted, int quotes)
5398 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5399 struct stackmark smark;
5402 setstackmark(&smark);
5404 startloc = dest - (char *)stackblock();
5406 evalbackcmd(cmd, &in);
5407 popstackmark(&smark);
5414 memtodest(p, i, syntax, quotes);
5418 i = safe_read(in.fd, buf, sizeof(buf));
5419 TRACE(("expbackq: read returns %d\n", i));
5428 back_exitstatus = waitforjob(in.jp);
5432 /* Eat all trailing newlines */
5434 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5439 recordregion(startloc, dest - (char *)stackblock(), 0);
5440 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5441 (dest - (char *)stackblock()) - startloc,
5442 (dest - (char *)stackblock()) - startloc,
5443 stackblock() + startloc));
5446 #if ENABLE_ASH_MATH_SUPPORT
5448 * Expand arithmetic expression. Backup to start of expression,
5449 * evaluate, place result in (backed up) result, adjust string position.
5462 * This routine is slightly over-complicated for
5463 * efficiency. Next we scan backwards looking for the
5464 * start of arithmetic.
5466 start = stackblock();
5473 while (*p != CTLARI) {
5477 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5482 esc = esclen(start, p);
5492 removerecordregions(begoff);
5501 len = cvtnum(dash_arith(p + 2));
5504 recordregion(begoff, begoff + len, 0);
5508 /* argstr needs it */
5509 static char *evalvar(char *p, int flag);
5512 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5513 * characters to allow for further processing. Otherwise treat
5514 * $@ like $* since no splitting will be performed.
5517 argstr(char *p, int flag)
5519 static const char spclchars[] ALIGN1 = {
5527 CTLBACKQ | CTLQUOTE,
5528 #if ENABLE_ASH_MATH_SUPPORT
5533 const char *reject = spclchars;
5535 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5536 int breakall = flag & EXP_WORD;
5541 if (!(flag & EXP_VARTILDE)) {
5543 } else if (flag & EXP_VARTILDE2) {
5548 if (flag & EXP_TILDE) {
5554 if (*q == CTLESC && (flag & EXP_QWORD))
5557 p = exptilde(p, q, flag);
5560 startloc = expdest - (char *)stackblock();
5562 length += strcspn(p + length, reject);
5564 if (c && (!(c & 0x80)
5565 #if ENABLE_ASH_MATH_SUPPORT
5569 /* c == '=' || c == ':' || c == CTLENDARI */
5574 expdest = stack_nputstr(p, length, expdest);
5575 newloc = expdest - (char *)stackblock();
5576 if (breakall && !inquotes && newloc > startloc) {
5577 recordregion(startloc, newloc, 0);
5588 if (flag & EXP_VARTILDE2) {
5592 flag |= EXP_VARTILDE2;
5597 * sort of a hack - expand tildes in variable
5598 * assignments (after the first '=' and after ':'s).
5607 case CTLENDVAR: /* ??? */
5610 /* "$@" syntax adherence hack */
5613 !memcmp(p, dolatstr, 4) &&
5614 (p[4] == CTLQUOTEMARK || (
5615 p[4] == CTLENDVAR &&
5616 p[5] == CTLQUOTEMARK
5619 p = evalvar(p + 1, flag) + 1;
5622 inquotes = !inquotes;
5635 p = evalvar(p, flag);
5639 case CTLBACKQ|CTLQUOTE:
5640 expbackq(argbackq->n, c, quotes);
5641 argbackq = argbackq->next;
5643 #if ENABLE_ASH_MATH_SUPPORT
5656 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5667 const char *s = loc2;
5673 match = pmatch(str, s);
5677 if (quotes && *loc == CTLESC)
5686 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5693 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5696 const char *s = loc2;
5701 match = pmatch(str, s);
5708 esc = esclen(startp, loc);
5719 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5721 varunset(const char *end, const char *var, const char *umsg, int varflags)
5727 msg = "parameter not set";
5729 if (*end == CTLENDVAR) {
5730 if (varflags & VSNUL)
5735 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5739 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5743 int saveherefd = herefd;
5744 struct nodelist *saveargbackq = argbackq;
5746 char *rmesc, *rmescend;
5748 char *(*scan)(char *, char *, char *, char *, int , int);
5751 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5752 STPUTC('\0', expdest);
5753 herefd = saveherefd;
5754 argbackq = saveargbackq;
5755 startp = stackblock() + startloc;
5759 setvar(str, startp, 0);
5760 amount = startp - expdest;
5761 STADJUST(amount, expdest);
5765 varunset(p, str, startp, varflags);
5769 subtype -= VSTRIMRIGHT;
5771 if (subtype < 0 || subtype > 3)
5776 rmescend = stackblock() + strloc;
5778 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5779 if (rmesc != startp) {
5781 startp = stackblock() + startloc;
5785 str = stackblock() + strloc;
5786 preglob(str, varflags & VSQUOTE, 0);
5788 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5789 zero = subtype >> 1;
5790 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5791 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5793 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5796 memmove(startp, loc, str - loc);
5797 loc = startp + (str - loc) - 1;
5800 amount = loc - expdest;
5801 STADJUST(amount, expdest);
5807 * Add the value of a specialized variable to the stack string.
5810 varvalue(char *name, int varflags, int flags)
5820 int quoted = varflags & VSQUOTE;
5821 int subtype = varflags & VSTYPE;
5822 int quotes = flags & (EXP_FULL | EXP_CASE);
5824 if (quoted && (flags & EXP_FULL))
5825 sep = 1 << CHAR_BIT;
5827 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5836 num = shellparam.nparam;
5846 p = makestrspace(NOPTS, expdest);
5847 for (i = NOPTS - 1; i >= 0; i--) {
5849 USTPUTC(optletters(i), p);
5860 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5861 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5867 while ((p = *ap++)) {
5870 partlen = strlen(p);
5873 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5874 memtodest(p, partlen, syntax, quotes);
5880 if (subtype == VSPLUS || subtype == VSLENGTH) {
5902 if (num < 0 || num > shellparam.nparam)
5904 p = num ? shellparam.p[num - 1] : arg0;
5907 p = lookupvar(name);
5913 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5914 memtodest(p, len, syntax, quotes);
5918 if (subtype == VSPLUS || subtype == VSLENGTH)
5919 STADJUST(-len, expdest);
5924 * Expand a variable, and return a pointer to the next character in the
5928 evalvar(char *p, int flag)
5941 quotes = flag & (EXP_FULL | EXP_CASE);
5943 subtype = varflags & VSTYPE;
5944 quoted = varflags & VSQUOTE;
5946 easy = (!quoted || (*var == '@' && shellparam.nparam));
5947 startloc = expdest - (char *)stackblock();
5948 p = strchr(p, '=') + 1;
5951 varlen = varvalue(var, varflags, flag);
5952 if (varflags & VSNUL)
5955 if (subtype == VSPLUS) {
5956 varlen = -1 - varlen;
5960 if (subtype == VSMINUS) {
5964 p, flag | EXP_TILDE |
5965 (quoted ? EXP_QWORD : EXP_WORD)
5974 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5976 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5979 * Remove any recorded regions beyond
5982 removerecordregions(startloc);
5992 if (varlen < 0 && uflag)
5993 varunset(p, var, 0, 0);
5995 if (subtype == VSLENGTH) {
5996 cvtnum(varlen > 0 ? varlen : 0);
6000 if (subtype == VSNORMAL) {
6004 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6013 case VSTRIMRIGHTMAX:
6022 * Terminate the string and start recording the pattern
6025 STPUTC('\0', expdest);
6026 patloc = expdest - (char *)stackblock();
6027 if (subevalvar(p, NULL, patloc, subtype,
6028 startloc, varflags, quotes) == 0) {
6029 int amount = expdest - (
6030 (char *)stackblock() + patloc - 1
6032 STADJUST(-amount, expdest);
6034 /* Remove any recorded regions beyond start of variable */
6035 removerecordregions(startloc);
6040 if (subtype != VSNORMAL) { /* skip to end of alternative */
6046 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6048 argbackq = argbackq->next;
6049 } else if (c == CTLVAR) {
6050 if ((*p++ & VSTYPE) != VSNORMAL)
6052 } else if (c == CTLENDVAR) {
6062 * Break the argument string into pieces based upon IFS and add the
6063 * strings to the argument list. The regions of the string to be
6064 * searched for IFS characters have been stored by recordregion.
6067 ifsbreakup(char *string, struct arglist *arglist)
6069 struct ifsregion *ifsp;
6074 const char *ifs, *realifs;
6079 if (ifslastp != NULL) {
6082 realifs = ifsset() ? ifsval() : defifs;
6085 p = string + ifsp->begoff;
6086 nulonly = ifsp->nulonly;
6087 ifs = nulonly ? nullstr : realifs;
6089 while (p < string + ifsp->endoff) {
6093 if (!strchr(ifs, *p)) {
6098 ifsspc = (strchr(defifs, *p) != NULL);
6099 /* Ignore IFS whitespace at start */
6100 if (q == start && ifsspc) {
6106 sp = stalloc(sizeof(*sp));
6108 *arglist->lastp = sp;
6109 arglist->lastp = &sp->next;
6113 if (p >= string + ifsp->endoff) {
6119 if (strchr(ifs, *p) == NULL ) {
6122 } else if (strchr(defifs, *p) == NULL) {
6137 } while (ifsp != NULL);
6146 sp = stalloc(sizeof(*sp));
6148 *arglist->lastp = sp;
6149 arglist->lastp = &sp->next;
6155 struct ifsregion *p;
6160 struct ifsregion *ifsp;
6166 ifsfirst.next = NULL;
6171 * Add a file name to the list.
6174 addfname(const char *name)
6178 sp = stalloc(sizeof(*sp));
6179 sp->text = ststrdup(name);
6181 exparg.lastp = &sp->next;
6184 static char *expdir;
6187 * Do metacharacter (i.e. *, ?, [...]) expansion.
6190 expmeta(char *enddir, char *name)
6205 for (p = name; *p; p++) {
6206 if (*p == '*' || *p == '?')
6208 else if (*p == '[') {
6215 if (*q == '/' || *q == '\0')
6222 } else if (*p == '\\')
6224 else if (*p == '/') {
6231 if (metaflag == 0) { /* we've reached the end of the file name */
6232 if (enddir != expdir)
6240 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6251 } while (p < start);
6253 if (enddir == expdir) {
6255 } else if (enddir == expdir + 1 && *expdir == '/') {
6264 if (enddir != expdir)
6266 if (*endname == 0) {
6278 while (! intpending && (dp = readdir(dirp)) != NULL) {
6279 if (dp->d_name[0] == '.' && ! matchdot)
6281 if (pmatch(start, dp->d_name)) {
6283 strcpy(enddir, dp->d_name);
6286 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6289 expmeta(p, endname);
6298 static struct strlist *
6299 msort(struct strlist *list, int len)
6301 struct strlist *p, *q = NULL;
6302 struct strlist **lpp;
6310 for (n = half; --n >= 0; ) {
6314 q->next = NULL; /* terminate first half of list */
6315 q = msort(list, half); /* sort first half of list */
6316 p = msort(p, len - half); /* sort second half */
6319 #if ENABLE_LOCALE_SUPPORT
6320 if (strcoll(p->text, q->text) < 0)
6322 if (strcmp(p->text, q->text) < 0)
6346 * Sort the results of file name expansion. It calculates the number of
6347 * strings to sort and then calls msort (short for merge sort) to do the
6350 static struct strlist *
6351 expsort(struct strlist *str)
6357 for (sp = str; sp; sp = sp->next)
6359 return msort(str, len);
6363 expandmeta(struct strlist *str, int flag)
6365 static const char metachars[] ALIGN1 = {
6368 /* TODO - EXP_REDIR */
6371 struct strlist **savelastp;
6377 if (!strpbrk(str->text, metachars))
6379 savelastp = exparg.lastp;
6382 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6384 int i = strlen(str->text);
6385 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6393 if (exparg.lastp == savelastp) {
6398 *exparg.lastp = str;
6399 rmescapes(str->text);
6400 exparg.lastp = &str->next;
6402 *exparg.lastp = NULL;
6403 *savelastp = sp = expsort(*savelastp);
6404 while (sp->next != NULL)
6406 exparg.lastp = &sp->next;
6413 * Perform variable substitution and command substitution on an argument,
6414 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6415 * perform splitting and file name expansion. When arglist is NULL, perform
6416 * here document expansion.
6419 expandarg(union node *arg, struct arglist *arglist, int flag)
6424 argbackq = arg->narg.backquote;
6425 STARTSTACKSTR(expdest);
6426 ifsfirst.next = NULL;
6428 argstr(arg->narg.text, flag);
6429 p = _STPUTC('\0', expdest);
6431 if (arglist == NULL) {
6432 return; /* here document expanded */
6434 p = grabstackstr(p);
6435 exparg.lastp = &exparg.list;
6439 if (flag & EXP_FULL) {
6440 ifsbreakup(p, &exparg);
6441 *exparg.lastp = NULL;
6442 exparg.lastp = &exparg.list;
6443 expandmeta(exparg.list, flag);
6445 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6447 sp = stalloc(sizeof(*sp));
6450 exparg.lastp = &sp->next;
6454 *exparg.lastp = NULL;
6456 *arglist->lastp = exparg.list;
6457 arglist->lastp = exparg.lastp;
6462 * Expand shell variables and backquotes inside a here document.
6465 expandhere(union node *arg, int fd)
6468 expandarg(arg, (struct arglist *)NULL, 0);
6469 full_write(fd, stackblock(), expdest - (char *)stackblock());
6473 * Returns true if the pattern matches the string.
6476 patmatch(char *pattern, const char *string)
6478 return pmatch(preglob(pattern, 0, 0), string);
6482 * See if a pattern matches in a case statement.
6485 casematch(union node *pattern, char *val)
6487 struct stackmark smark;
6490 setstackmark(&smark);
6491 argbackq = pattern->narg.backquote;
6492 STARTSTACKSTR(expdest);
6494 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6495 STACKSTRNUL(expdest);
6496 result = patmatch(stackblock(), val);
6497 popstackmark(&smark);
6502 /* ============ find_command */
6506 int (*builtin)(int, char **);
6507 /* unsigned flags; */
6509 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6510 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6511 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6517 const struct builtincmd *cmd;
6518 struct funcnode *func;
6521 /* values of cmdtype */
6522 #define CMDUNKNOWN -1 /* no entry in table for command */
6523 #define CMDNORMAL 0 /* command is an executable program */
6524 #define CMDFUNCTION 1 /* command is a shell function */
6525 #define CMDBUILTIN 2 /* command is a shell builtin */
6527 /* action to find_command() */
6528 #define DO_ERR 0x01 /* prints errors */
6529 #define DO_ABS 0x02 /* checks absolute paths */
6530 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6531 #define DO_ALTPATH 0x08 /* using alternate path */
6532 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6534 static void find_command(char *, struct cmdentry *, int, const char *);
6537 /* ============ Hashing commands */
6540 * When commands are first encountered, they are entered in a hash table.
6541 * This ensures that a full path search will not have to be done for them
6542 * on each invocation.
6544 * We should investigate converting to a linear search, even though that
6545 * would make the command name "hash" a misnomer.
6548 #define ARB 1 /* actual size determined at run time */
6551 struct tblentry *next; /* next entry in hash chain */
6552 union param param; /* definition of builtin function */
6553 short cmdtype; /* index identifying command */
6554 char rehash; /* if set, cd done since entry created */
6555 char cmdname[ARB]; /* name of command */
6558 static struct tblentry **cmdtable;
6559 #define INIT_G_cmdtable() do { \
6560 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
6563 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6567 tryexec(char *cmd, char **argv, char **envp)
6571 #if ENABLE_FEATURE_SH_STANDALONE
6572 if (strchr(cmd, '/') == NULL) {
6573 int a = find_applet_by_name(cmd);
6575 if (APPLET_IS_NOEXEC(a))
6576 run_applet_no_and_exit(a, argv);
6577 /* re-exec ourselves with the new arguments */
6578 execve(bb_busybox_exec_path, argv, envp);
6579 /* If they called chroot or otherwise made the binary no longer
6580 * executable, fall through */
6588 execve(cmd, argv, envp);
6589 } while (errno == EINTR);
6591 execve(cmd, argv, envp);
6595 } else if (errno == ENOEXEC) {
6599 for (ap = argv; *ap; ap++)
6601 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6603 ap[0] = cmd = (char *)DEFAULT_SHELL;
6606 while ((*ap++ = *argv++))
6614 * Exec a program. Never returns. If you change this routine, you may
6615 * have to change the find_command routine as well.
6617 #define environment() listvars(VEXPORT, VUNSET, 0)
6618 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6620 shellexec(char **argv, const char *path, int idx)
6628 envp = environment();
6629 if (strchr(argv[0], '/')
6630 #if ENABLE_FEATURE_SH_STANDALONE
6631 || find_applet_by_name(argv[0]) >= 0
6634 tryexec(argv[0], argv, envp);
6638 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6639 if (--idx < 0 && pathopt == NULL) {
6640 tryexec(cmdname, argv, envp);
6641 if (errno != ENOENT && errno != ENOTDIR)
6648 /* Map to POSIX errors */
6660 exitstatus = exerrno;
6661 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6662 argv[0], e, suppressint ));
6663 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6668 printentry(struct tblentry *cmdp)
6674 idx = cmdp->param.index;
6677 name = padvance(&path, cmdp->cmdname);
6679 } while (--idx >= 0);
6680 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6684 * Clear out command entries. The argument specifies the first entry in
6685 * PATH which has changed.
6688 clearcmdentry(int firstchange)
6690 struct tblentry **tblp;
6691 struct tblentry **pp;
6692 struct tblentry *cmdp;
6695 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6697 while ((cmdp = *pp) != NULL) {
6698 if ((cmdp->cmdtype == CMDNORMAL &&
6699 cmdp->param.index >= firstchange)
6700 || (cmdp->cmdtype == CMDBUILTIN &&
6701 builtinloc >= firstchange)
6714 * Locate a command in the command hash table. If "add" is nonzero,
6715 * add the command to the table if it is not already present. The
6716 * variable "lastcmdentry" is set to point to the address of the link
6717 * pointing to the entry, so that delete_cmd_entry can delete the
6720 * Interrupts must be off if called with add != 0.
6722 static struct tblentry **lastcmdentry;
6724 static struct tblentry *
6725 cmdlookup(const char *name, int add)
6727 unsigned int hashval;
6729 struct tblentry *cmdp;
6730 struct tblentry **pp;
6733 hashval = (unsigned char)*p << 4;
6735 hashval += (unsigned char)*p++;
6737 pp = &cmdtable[hashval % CMDTABLESIZE];
6738 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6739 if (strcmp(cmdp->cmdname, name) == 0)
6743 if (add && cmdp == NULL) {
6744 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6745 + strlen(name) + 1);
6747 cmdp->cmdtype = CMDUNKNOWN;
6748 strcpy(cmdp->cmdname, name);
6755 * Delete the command entry returned on the last lookup.
6758 delete_cmd_entry(void)
6760 struct tblentry *cmdp;
6763 cmdp = *lastcmdentry;
6764 *lastcmdentry = cmdp->next;
6765 if (cmdp->cmdtype == CMDFUNCTION)
6766 freefunc(cmdp->param.func);
6772 * Add a new command entry, replacing any existing command entry for
6773 * the same name - except special builtins.
6776 addcmdentry(char *name, struct cmdentry *entry)
6778 struct tblentry *cmdp;
6780 cmdp = cmdlookup(name, 1);
6781 if (cmdp->cmdtype == CMDFUNCTION) {
6782 freefunc(cmdp->param.func);
6784 cmdp->cmdtype = entry->cmdtype;
6785 cmdp->param = entry->u;
6790 hashcmd(int argc, char **argv)
6792 struct tblentry **pp;
6793 struct tblentry *cmdp;
6795 struct cmdentry entry;
6798 while ((c = nextopt("r")) != '\0') {
6802 if (*argptr == NULL) {
6803 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6804 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6805 if (cmdp->cmdtype == CMDNORMAL)
6812 while ((name = *argptr) != NULL) {
6813 cmdp = cmdlookup(name, 0);
6815 && (cmdp->cmdtype == CMDNORMAL
6816 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6818 find_command(name, &entry, DO_ERR, pathval());
6819 if (entry.cmdtype == CMDUNKNOWN)
6827 * Called when a cd is done. Marks all commands so the next time they
6828 * are executed they will be rehashed.
6833 struct tblentry **pp;
6834 struct tblentry *cmdp;
6836 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6837 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6838 if (cmdp->cmdtype == CMDNORMAL || (
6839 cmdp->cmdtype == CMDBUILTIN &&
6840 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6849 * Fix command hash table when PATH changed.
6850 * Called before PATH is changed. The argument is the new value of PATH;
6851 * pathval() still returns the old value at this point.
6852 * Called with interrupts off.
6855 changepath(const char *newval)
6857 const char *old, *new;
6864 firstchange = 9999; /* assume no change */
6870 if ((*old == '\0' && *new == ':')
6871 || (*old == ':' && *new == '\0'))
6873 old = new; /* ignore subsequent differences */
6877 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6884 if (builtinloc < 0 && idx_bltin >= 0)
6885 builtinloc = idx_bltin; /* zap builtins */
6886 if (builtinloc >= 0 && idx_bltin < 0)
6888 clearcmdentry(firstchange);
6889 builtinloc = idx_bltin;
6904 #define TENDBQUOTE 12
6922 /* first char is indicating which tokens mark the end of a list */
6923 static const char *const tokname_array[] = {
6937 #define KWDOFFSET 13
6938 /* the following are keywords */
6960 static char buf[16];
6963 //if (tok < TSEMI) return tokname_array[tok] + 1;
6964 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6969 sprintf(buf + (tok >= TSEMI), "%s%c",
6970 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6974 /* Wrapper around strcmp for qsort/bsearch/... */
6976 pstrcmp(const void *a, const void *b)
6978 return strcmp((char*) a, (*(char**) b) + 1);
6981 static const char *const *
6982 findkwd(const char *s)
6984 return bsearch(s, tokname_array + KWDOFFSET,
6985 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6986 sizeof(tokname_array[0]), pstrcmp);
6990 * Locate and print what a word is...
6993 describe_command(char *command, int describe_command_verbose)
6995 struct cmdentry entry;
6996 struct tblentry *cmdp;
6997 #if ENABLE_ASH_ALIAS
6998 const struct alias *ap;
7000 const char *path = pathval();
7002 if (describe_command_verbose) {
7006 /* First look at the keywords */
7007 if (findkwd(command)) {
7008 out1str(describe_command_verbose ? " is a shell keyword" : command);
7012 #if ENABLE_ASH_ALIAS
7013 /* Then look at the aliases */
7014 ap = lookupalias(command, 0);
7016 if (!describe_command_verbose) {
7021 out1fmt(" is an alias for %s", ap->val);
7025 /* Then check if it is a tracked alias */
7026 cmdp = cmdlookup(command, 0);
7028 entry.cmdtype = cmdp->cmdtype;
7029 entry.u = cmdp->param;
7031 /* Finally use brute force */
7032 find_command(command, &entry, DO_ABS, path);
7035 switch (entry.cmdtype) {
7037 int j = entry.u.index;
7043 p = padvance(&path, command);
7047 if (describe_command_verbose) {
7049 (cmdp ? " a tracked alias for" : nullstr), p
7058 if (describe_command_verbose) {
7059 out1str(" is a shell function");
7066 if (describe_command_verbose) {
7067 out1fmt(" is a %sshell builtin",
7068 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7069 "special " : nullstr
7077 if (describe_command_verbose) {
7078 out1str(": not found\n");
7083 outstr("\n", stdout);
7088 typecmd(int argc, char **argv)
7094 /* type -p ... ? (we don't bother checking for 'p') */
7095 if (argv[1] && argv[1][0] == '-') {
7100 err |= describe_command(argv[i++], verbose);
7105 #if ENABLE_ASH_CMDCMD
7107 commandcmd(int argc, char **argv)
7115 while ((c = nextopt("pvV")) != '\0')
7117 verify |= VERIFY_VERBOSE;
7119 verify |= VERIFY_BRIEF;
7125 return describe_command(*argptr, verify - VERIFY_BRIEF);
7132 /* ============ eval.c */
7134 static int funcblocksize; /* size of structures in function */
7135 static int funcstringsize; /* size of strings in node */
7136 static void *funcblock; /* block to allocate function from */
7137 static char *funcstring; /* block to allocate strings from */
7139 /* flags in argument to evaltree */
7140 #define EV_EXIT 01 /* exit after evaluating tree */
7141 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7142 #define EV_BACKCMD 04 /* command executing within back quotes */
7144 static const short nodesize[26] = {
7145 SHELL_ALIGN(sizeof(struct ncmd)),
7146 SHELL_ALIGN(sizeof(struct npipe)),
7147 SHELL_ALIGN(sizeof(struct nredir)),
7148 SHELL_ALIGN(sizeof(struct nredir)),
7149 SHELL_ALIGN(sizeof(struct nredir)),
7150 SHELL_ALIGN(sizeof(struct nbinary)),
7151 SHELL_ALIGN(sizeof(struct nbinary)),
7152 SHELL_ALIGN(sizeof(struct nbinary)),
7153 SHELL_ALIGN(sizeof(struct nif)),
7154 SHELL_ALIGN(sizeof(struct nbinary)),
7155 SHELL_ALIGN(sizeof(struct nbinary)),
7156 SHELL_ALIGN(sizeof(struct nfor)),
7157 SHELL_ALIGN(sizeof(struct ncase)),
7158 SHELL_ALIGN(sizeof(struct nclist)),
7159 SHELL_ALIGN(sizeof(struct narg)),
7160 SHELL_ALIGN(sizeof(struct narg)),
7161 SHELL_ALIGN(sizeof(struct nfile)),
7162 SHELL_ALIGN(sizeof(struct nfile)),
7163 SHELL_ALIGN(sizeof(struct nfile)),
7164 SHELL_ALIGN(sizeof(struct nfile)),
7165 SHELL_ALIGN(sizeof(struct nfile)),
7166 SHELL_ALIGN(sizeof(struct ndup)),
7167 SHELL_ALIGN(sizeof(struct ndup)),
7168 SHELL_ALIGN(sizeof(struct nhere)),
7169 SHELL_ALIGN(sizeof(struct nhere)),
7170 SHELL_ALIGN(sizeof(struct nnot)),
7173 static void calcsize(union node *n);
7176 sizenodelist(struct nodelist *lp)
7179 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7186 calcsize(union node *n)
7190 funcblocksize += nodesize[n->type];
7193 calcsize(n->ncmd.redirect);
7194 calcsize(n->ncmd.args);
7195 calcsize(n->ncmd.assign);
7198 sizenodelist(n->npipe.cmdlist);
7203 calcsize(n->nredir.redirect);
7204 calcsize(n->nredir.n);
7211 calcsize(n->nbinary.ch2);
7212 calcsize(n->nbinary.ch1);
7215 calcsize(n->nif.elsepart);
7216 calcsize(n->nif.ifpart);
7217 calcsize(n->nif.test);
7220 funcstringsize += strlen(n->nfor.var) + 1;
7221 calcsize(n->nfor.body);
7222 calcsize(n->nfor.args);
7225 calcsize(n->ncase.cases);
7226 calcsize(n->ncase.expr);
7229 calcsize(n->nclist.body);
7230 calcsize(n->nclist.pattern);
7231 calcsize(n->nclist.next);
7235 sizenodelist(n->narg.backquote);
7236 funcstringsize += strlen(n->narg.text) + 1;
7237 calcsize(n->narg.next);
7244 calcsize(n->nfile.fname);
7245 calcsize(n->nfile.next);
7249 calcsize(n->ndup.vname);
7250 calcsize(n->ndup.next);
7254 calcsize(n->nhere.doc);
7255 calcsize(n->nhere.next);
7258 calcsize(n->nnot.com);
7264 nodeckstrdup(char *s)
7266 char *rtn = funcstring;
7268 strcpy(funcstring, s);
7269 funcstring += strlen(s) + 1;
7273 static union node *copynode(union node *);
7275 static struct nodelist *
7276 copynodelist(struct nodelist *lp)
7278 struct nodelist *start;
7279 struct nodelist **lpp;
7284 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7285 (*lpp)->n = copynode(lp->n);
7287 lpp = &(*lpp)->next;
7294 copynode(union node *n)
7301 funcblock = (char *) funcblock + nodesize[n->type];
7305 new->ncmd.redirect = copynode(n->ncmd.redirect);
7306 new->ncmd.args = copynode(n->ncmd.args);
7307 new->ncmd.assign = copynode(n->ncmd.assign);
7310 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7311 new->npipe.backgnd = n->npipe.backgnd;
7316 new->nredir.redirect = copynode(n->nredir.redirect);
7317 new->nredir.n = copynode(n->nredir.n);
7324 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7325 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7328 new->nif.elsepart = copynode(n->nif.elsepart);
7329 new->nif.ifpart = copynode(n->nif.ifpart);
7330 new->nif.test = copynode(n->nif.test);
7333 new->nfor.var = nodeckstrdup(n->nfor.var);
7334 new->nfor.body = copynode(n->nfor.body);
7335 new->nfor.args = copynode(n->nfor.args);
7338 new->ncase.cases = copynode(n->ncase.cases);
7339 new->ncase.expr = copynode(n->ncase.expr);
7342 new->nclist.body = copynode(n->nclist.body);
7343 new->nclist.pattern = copynode(n->nclist.pattern);
7344 new->nclist.next = copynode(n->nclist.next);
7348 new->narg.backquote = copynodelist(n->narg.backquote);
7349 new->narg.text = nodeckstrdup(n->narg.text);
7350 new->narg.next = copynode(n->narg.next);
7357 new->nfile.fname = copynode(n->nfile.fname);
7358 new->nfile.fd = n->nfile.fd;
7359 new->nfile.next = copynode(n->nfile.next);
7363 new->ndup.vname = copynode(n->ndup.vname);
7364 new->ndup.dupfd = n->ndup.dupfd;
7365 new->ndup.fd = n->ndup.fd;
7366 new->ndup.next = copynode(n->ndup.next);
7370 new->nhere.doc = copynode(n->nhere.doc);
7371 new->nhere.fd = n->nhere.fd;
7372 new->nhere.next = copynode(n->nhere.next);
7375 new->nnot.com = copynode(n->nnot.com);
7378 new->type = n->type;
7383 * Make a copy of a parse tree.
7385 static struct funcnode *
7386 copyfunc(union node *n)
7391 funcblocksize = offsetof(struct funcnode, n);
7394 blocksize = funcblocksize;
7395 f = ckmalloc(blocksize + funcstringsize);
7396 funcblock = (char *) f + offsetof(struct funcnode, n);
7397 funcstring = (char *) f + blocksize;
7404 * Define a shell function.
7407 defun(char *name, union node *func)
7409 struct cmdentry entry;
7412 entry.cmdtype = CMDFUNCTION;
7413 entry.u.func = copyfunc(func);
7414 addcmdentry(name, &entry);
7418 static int evalskip; /* set if we are skipping commands */
7419 /* reasons for skipping commands (see comment on breakcmd routine) */
7420 #define SKIPBREAK (1 << 0)
7421 #define SKIPCONT (1 << 1)
7422 #define SKIPFUNC (1 << 2)
7423 #define SKIPFILE (1 << 3)
7424 #define SKIPEVAL (1 << 4)
7425 static int skipcount; /* number of levels to skip */
7426 static int funcnest; /* depth of function calls */
7428 /* forward decl way out to parsing code - dotrap needs it */
7429 static int evalstring(char *s, int mask);
7432 * Called to execute a trap. Perhaps we should avoid entering new trap
7433 * handlers while we are executing a trap handler.
7444 savestatus = exitstatus;
7448 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7456 skip = evalstring(p, SKIPEVAL);
7457 exitstatus = savestatus;
7465 /* forward declarations - evaluation is fairly recursive business... */
7466 static void evalloop(union node *, int);
7467 static void evalfor(union node *, int);
7468 static void evalcase(union node *, int);
7469 static void evalsubshell(union node *, int);
7470 static void expredir(union node *);
7471 static void evalpipe(union node *, int);
7472 static void evalcommand(union node *, int);
7473 static int evalbltin(const struct builtincmd *, int, char **);
7474 static void prehash(union node *);
7477 * Evaluate a parse tree. The value is left in the global variable
7481 evaltree(union node *n, int flags)
7484 void (*evalfn)(union node *, int);
7488 TRACE(("evaltree(NULL) called\n"));
7491 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7492 getpid(), n, n->type, flags));
7496 out1fmt("Node type = %d\n", n->type);
7501 evaltree(n->nnot.com, EV_TESTED);
7502 status = !exitstatus;
7505 expredir(n->nredir.redirect);
7506 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7508 evaltree(n->nredir.n, flags & EV_TESTED);
7509 status = exitstatus;
7514 evalfn = evalcommand;
7516 if (eflag && !(flags & EV_TESTED))
7528 evalfn = evalsubshell;
7540 #error NAND + 1 != NOR
7542 #if NOR + 1 != NSEMI
7543 #error NOR + 1 != NSEMI
7545 isor = n->type - NAND;
7548 (flags | ((isor >> 1) - 1)) & EV_TESTED
7550 if (!exitstatus == isor)
7562 evaltree(n->nif.test, EV_TESTED);
7565 if (exitstatus == 0) {
7568 } else if (n->nif.elsepart) {
7569 n = n->nif.elsepart;
7574 defun(n->narg.text, n->narg.next);
7578 exitstatus = status;
7582 if ((checkexit & exitstatus))
7583 evalskip |= SKIPEVAL;
7584 else if (pendingsig && dotrap())
7587 if (flags & EV_EXIT) {
7589 raise_exception(EXEXIT);
7593 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7596 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7598 static int loopnest; /* current loop nesting level */
7601 evalloop(union node *n, int flags)
7611 evaltree(n->nbinary.ch1, EV_TESTED);
7614 if (evalskip == SKIPCONT && --skipcount <= 0) {
7618 if (evalskip == SKIPBREAK && --skipcount <= 0)
7623 if (n->type != NWHILE)
7627 evaltree(n->nbinary.ch2, flags);
7628 status = exitstatus;
7633 exitstatus = status;
7637 evalfor(union node *n, int flags)
7639 struct arglist arglist;
7642 struct stackmark smark;
7644 setstackmark(&smark);
7645 arglist.lastp = &arglist.list;
7646 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7647 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7652 *arglist.lastp = NULL;
7657 for (sp = arglist.list; sp; sp = sp->next) {
7658 setvar(n->nfor.var, sp->text, 0);
7659 evaltree(n->nfor.body, flags);
7661 if (evalskip == SKIPCONT && --skipcount <= 0) {
7665 if (evalskip == SKIPBREAK && --skipcount <= 0)
7672 popstackmark(&smark);
7676 evalcase(union node *n, int flags)
7680 struct arglist arglist;
7681 struct stackmark smark;
7683 setstackmark(&smark);
7684 arglist.lastp = &arglist.list;
7685 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7687 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7688 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7689 if (casematch(patp, arglist.list->text)) {
7690 if (evalskip == 0) {
7691 evaltree(cp->nclist.body, flags);
7698 popstackmark(&smark);
7702 * Kick off a subshell to evaluate a tree.
7705 evalsubshell(union node *n, int flags)
7708 int backgnd = (n->type == NBACKGND);
7711 expredir(n->nredir.redirect);
7712 if (!backgnd && flags & EV_EXIT && !trap[0])
7716 if (forkshell(jp, n, backgnd) == 0) {
7720 flags &=~ EV_TESTED;
7722 redirect(n->nredir.redirect, 0);
7723 evaltreenr(n->nredir.n, flags);
7728 status = waitforjob(jp);
7729 exitstatus = status;
7734 * Compute the names of the files in a redirection list.
7736 static void fixredir(union node *, const char *, int);
7738 expredir(union node *n)
7742 for (redir = n; redir; redir = redir->nfile.next) {
7745 memset(&fn, 0, sizeof(fn));
7746 fn.lastp = &fn.list;
7747 switch (redir->type) {
7753 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7754 redir->nfile.expfname = fn.list->text;
7758 if (redir->ndup.vname) {
7759 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7760 if (fn.list == NULL)
7761 ash_msg_and_raise_error("redir error");
7762 fixredir(redir, fn.list->text, 1);
7770 * Evaluate a pipeline. All the processes in the pipeline are children
7771 * of the process creating the pipeline. (This differs from some versions
7772 * of the shell, which make the last process in a pipeline the parent
7776 evalpipe(union node *n, int flags)
7779 struct nodelist *lp;
7784 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7786 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7790 jp = makejob(n, pipelen);
7792 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7796 if (pipe(pip) < 0) {
7798 ash_msg_and_raise_error("pipe call failed");
7801 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7814 evaltreenr(lp->n, flags);
7822 if (n->npipe.backgnd == 0) {
7823 exitstatus = waitforjob(jp);
7824 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7830 * Controls whether the shell is interactive or not.
7833 setinteractive(int on)
7835 static int is_interactive;
7837 if (++on == is_interactive)
7839 is_interactive = on;
7843 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7844 if (is_interactive > 1) {
7845 /* Looks like they want an interactive shell */
7846 static smallint did_banner;
7851 "%s built-in shell (ash)\n"
7852 "Enter 'help' for a list of built-in commands."
7861 #if ENABLE_FEATURE_EDITING_VI
7862 #define setvimode(on) do { \
7863 if (on) line_input_state->flags |= VI_MODE; \
7864 else line_input_state->flags &= ~VI_MODE; \
7867 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7876 setinteractive(iflag);
7881 static struct localvar *localvars;
7884 * Called after a function returns.
7885 * Interrupts must be off.
7890 struct localvar *lvp;
7893 while ((lvp = localvars) != NULL) {
7894 localvars = lvp->next;
7896 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7897 if (vp == NULL) { /* $- saved */
7898 memcpy(optlist, lvp->text, sizeof(optlist));
7899 free((char*)lvp->text);
7901 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7905 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7906 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7907 free((char*)vp->text);
7908 vp->flags = lvp->flags;
7909 vp->text = lvp->text;
7916 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7918 volatile struct shparam saveparam;
7919 struct localvar *volatile savelocalvars;
7920 struct jmploc *volatile savehandler;
7921 struct jmploc jmploc;
7924 saveparam = shellparam;
7925 savelocalvars = localvars;
7926 e = setjmp(jmploc.loc);
7931 savehandler = exception_handler;
7932 exception_handler = &jmploc;
7934 shellparam.malloced = 0;
7938 shellparam.nparam = argc - 1;
7939 shellparam.p = argv + 1;
7940 #if ENABLE_ASH_GETOPTS
7941 shellparam.optind = 1;
7942 shellparam.optoff = -1;
7944 evaltree(&func->n, flags & EV_TESTED);
7950 localvars = savelocalvars;
7951 freeparam(&shellparam);
7952 shellparam = saveparam;
7953 exception_handler = savehandler;
7955 evalskip &= ~SKIPFUNC;
7959 #if ENABLE_ASH_CMDCMD
7961 parse_command_args(char **argv, const char **path)
7974 if (c == '-' && !*cp) {
7981 *path = bb_default_path;
7984 /* run 'typecmd' for other options */
7995 * Make a variable a local variable. When a variable is made local, it's
7996 * value and flags are saved in a localvar structure. The saved values
7997 * will be restored when the shell function returns. We handle the name
7998 * "-" as a special case.
8003 struct localvar *lvp;
8008 lvp = ckmalloc(sizeof(struct localvar));
8009 if (LONE_DASH(name)) {
8011 p = ckmalloc(sizeof(optlist));
8012 lvp->text = memcpy(p, optlist, sizeof(optlist));
8017 vpp = hashvar(name);
8018 vp = *findvar(vpp, name);
8019 eq = strchr(name, '=');
8022 setvareq(name, VSTRFIXED);
8024 setvar(name, NULL, VSTRFIXED);
8025 vp = *vpp; /* the new variable */
8026 lvp->flags = VUNSET;
8028 lvp->text = vp->text;
8029 lvp->flags = vp->flags;
8030 vp->flags |= VSTRFIXED|VTEXTFIXED;
8036 lvp->next = localvars;
8042 * The "local" command.
8045 localcmd(int argc, char **argv)
8050 while ((name = *argv++) != NULL) {
8057 falsecmd(int argc, char **argv)
8063 truecmd(int argc, char **argv)
8069 execcmd(int argc, char **argv)
8072 iflag = 0; /* exit on error */
8075 shellexec(argv + 1, pathval(), 0);
8081 * The return command.
8084 returncmd(int argc, char **argv)
8087 * If called outside a function, do what ksh does;
8088 * skip the rest of the file.
8090 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8091 return argv[1] ? number(argv[1]) : exitstatus;
8094 /* Forward declarations for builtintab[] */
8095 static int breakcmd(int, char **);
8096 static int dotcmd(int, char **);
8097 static int evalcmd(int, char **);
8098 #if ENABLE_ASH_BUILTIN_ECHO
8099 static int echocmd(int, char **);
8101 #if ENABLE_ASH_BUILTIN_TEST
8102 static int testcmd(int, char **);
8104 static int exitcmd(int, char **);
8105 static int exportcmd(int, char **);
8106 #if ENABLE_ASH_GETOPTS
8107 static int getoptscmd(int, char **);
8109 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8110 static int helpcmd(int argc, char **argv);
8112 #if ENABLE_ASH_MATH_SUPPORT
8113 static int letcmd(int, char **);
8115 static int readcmd(int, char **);
8116 static int setcmd(int, char **);
8117 static int shiftcmd(int, char **);
8118 static int timescmd(int, char **);
8119 static int trapcmd(int, char **);
8120 static int umaskcmd(int, char **);
8121 static int unsetcmd(int, char **);
8122 static int ulimitcmd(int, char **);
8124 #define BUILTIN_NOSPEC "0"
8125 #define BUILTIN_SPECIAL "1"
8126 #define BUILTIN_REGULAR "2"
8127 #define BUILTIN_SPEC_REG "3"
8128 #define BUILTIN_ASSIGN "4"
8129 #define BUILTIN_SPEC_ASSG "5"
8130 #define BUILTIN_REG_ASSG "6"
8131 #define BUILTIN_SPEC_REG_ASSG "7"
8133 /* make sure to keep these in proper order since it is searched via bsearch() */
8134 static const struct builtincmd builtintab[] = {
8135 { BUILTIN_SPEC_REG ".", dotcmd },
8136 { BUILTIN_SPEC_REG ":", truecmd },
8137 #if ENABLE_ASH_BUILTIN_TEST
8138 { BUILTIN_REGULAR "[", testcmd },
8139 { BUILTIN_REGULAR "[[", testcmd },
8141 #if ENABLE_ASH_ALIAS
8142 { BUILTIN_REG_ASSG "alias", aliascmd },
8145 { BUILTIN_REGULAR "bg", fg_bgcmd },
8147 { BUILTIN_SPEC_REG "break", breakcmd },
8148 { BUILTIN_REGULAR "cd", cdcmd },
8149 { BUILTIN_NOSPEC "chdir", cdcmd },
8150 #if ENABLE_ASH_CMDCMD
8151 { BUILTIN_REGULAR "command", commandcmd },
8153 { BUILTIN_SPEC_REG "continue", breakcmd },
8154 #if ENABLE_ASH_BUILTIN_ECHO
8155 { BUILTIN_REGULAR "echo", echocmd },
8157 { BUILTIN_SPEC_REG "eval", evalcmd },
8158 { BUILTIN_SPEC_REG "exec", execcmd },
8159 { BUILTIN_SPEC_REG "exit", exitcmd },
8160 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8161 { BUILTIN_REGULAR "false", falsecmd },
8163 { BUILTIN_REGULAR "fg", fg_bgcmd },
8165 #if ENABLE_ASH_GETOPTS
8166 { BUILTIN_REGULAR "getopts", getoptscmd },
8168 { BUILTIN_NOSPEC "hash", hashcmd },
8169 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8170 { BUILTIN_NOSPEC "help", helpcmd },
8173 { BUILTIN_REGULAR "jobs", jobscmd },
8174 { BUILTIN_REGULAR "kill", killcmd },
8176 #if ENABLE_ASH_MATH_SUPPORT
8177 { BUILTIN_NOSPEC "let", letcmd },
8179 { BUILTIN_ASSIGN "local", localcmd },
8180 { BUILTIN_NOSPEC "pwd", pwdcmd },
8181 { BUILTIN_REGULAR "read", readcmd },
8182 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8183 { BUILTIN_SPEC_REG "return", returncmd },
8184 { BUILTIN_SPEC_REG "set", setcmd },
8185 { BUILTIN_SPEC_REG "shift", shiftcmd },
8186 { BUILTIN_SPEC_REG "source", dotcmd },
8187 #if ENABLE_ASH_BUILTIN_TEST
8188 { BUILTIN_REGULAR "test", testcmd },
8190 { BUILTIN_SPEC_REG "times", timescmd },
8191 { BUILTIN_SPEC_REG "trap", trapcmd },
8192 { BUILTIN_REGULAR "true", truecmd },
8193 { BUILTIN_NOSPEC "type", typecmd },
8194 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8195 { BUILTIN_REGULAR "umask", umaskcmd },
8196 #if ENABLE_ASH_ALIAS
8197 { BUILTIN_REGULAR "unalias", unaliascmd },
8199 { BUILTIN_SPEC_REG "unset", unsetcmd },
8200 { BUILTIN_REGULAR "wait", waitcmd },
8204 #define COMMANDCMD (builtintab + 5 + \
8205 2 * ENABLE_ASH_BUILTIN_TEST + \
8206 ENABLE_ASH_ALIAS + \
8207 ENABLE_ASH_JOB_CONTROL)
8208 #define EXECCMD (builtintab + 7 + \
8209 2 * ENABLE_ASH_BUILTIN_TEST + \
8210 ENABLE_ASH_ALIAS + \
8211 ENABLE_ASH_JOB_CONTROL + \
8212 ENABLE_ASH_CMDCMD + \
8213 ENABLE_ASH_BUILTIN_ECHO)
8216 * Search the table of builtin commands.
8218 static struct builtincmd *
8219 find_builtin(const char *name)
8221 struct builtincmd *bp;
8224 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8231 * Execute a simple command.
8233 static int back_exitstatus; /* exit status of backquoted command */
8235 isassignment(const char *p)
8237 const char *q = endofname(p);
8243 bltincmd(int argc, char **argv)
8245 /* Preserve exitstatus of a previous possible redirection
8246 * as POSIX mandates */
8247 return back_exitstatus;
8250 evalcommand(union node *cmd, int flags)
8252 static const struct builtincmd bltin = {
8255 struct stackmark smark;
8257 struct arglist arglist;
8258 struct arglist varlist;
8261 const struct strlist *sp;
8262 struct cmdentry cmdentry;
8270 struct builtincmd *bcmd;
8271 int pseudovarflag = 0;
8273 /* First expand the arguments. */
8274 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8275 setstackmark(&smark);
8276 back_exitstatus = 0;
8278 cmdentry.cmdtype = CMDBUILTIN;
8279 cmdentry.u.cmd = &bltin;
8280 varlist.lastp = &varlist.list;
8281 *varlist.lastp = NULL;
8282 arglist.lastp = &arglist.list;
8283 *arglist.lastp = NULL;
8286 if (cmd->ncmd.args) {
8287 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8288 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8291 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8292 struct strlist **spp;
8294 spp = arglist.lastp;
8295 if (pseudovarflag && isassignment(argp->narg.text))
8296 expandarg(argp, &arglist, EXP_VARTILDE);
8298 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8300 for (sp = *spp; sp; sp = sp->next)
8304 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8305 for (sp = arglist.list; sp; sp = sp->next) {
8306 TRACE(("evalcommand arg: %s\n", sp->text));
8307 *nargv++ = sp->text;
8312 if (iflag && funcnest == 0 && argc > 0)
8313 lastarg = nargv[-1];
8316 expredir(cmd->ncmd.redirect);
8317 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8320 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8321 struct strlist **spp;
8324 spp = varlist.lastp;
8325 expandarg(argp, &varlist, EXP_VARTILDE);
8328 * Modify the command lookup path, if a PATH= assignment
8332 if (varequal(p, path))
8336 /* Print the command if xflag is set. */
8339 const char *p = " %s";
8342 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8345 for (n = 0; n < 2; n++) {
8347 fdprintf(preverrout_fd, p, sp->text);
8355 full_write(preverrout_fd, "\n", 1);
8361 /* Now locate the command. */
8363 const char *oldpath;
8364 int cmd_flag = DO_ERR;
8369 find_command(argv[0], &cmdentry, cmd_flag, path);
8370 if (cmdentry.cmdtype == CMDUNKNOWN) {
8376 /* implement bltin and command here */
8377 if (cmdentry.cmdtype != CMDBUILTIN)
8380 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8381 if (cmdentry.u.cmd == EXECCMD)
8383 #if ENABLE_ASH_CMDCMD
8384 if (cmdentry.u.cmd == COMMANDCMD) {
8386 nargv = parse_command_args(argv, &path);
8389 argc -= nargv - argv;
8391 cmd_flag |= DO_NOFUNC;
8399 /* We have a redirection error. */
8401 raise_exception(EXERROR);
8403 exitstatus = status;
8407 /* Execute the command. */
8408 switch (cmdentry.cmdtype) {
8410 /* Fork off a child process if necessary. */
8411 if (!(flags & EV_EXIT) || trap[0]) {
8413 jp = makejob(cmd, 1);
8414 if (forkshell(jp, cmd, FORK_FG) != 0) {
8415 exitstatus = waitforjob(jp);
8421 listsetvar(varlist.list, VEXPORT|VSTACK);
8422 shellexec(argv, path, cmdentry.u.index);
8426 cmdenviron = varlist.list;
8428 struct strlist *list = cmdenviron;
8430 if (spclbltin > 0 || argc == 0) {
8432 if (cmd_is_exec && argc > 1)
8435 listsetvar(list, i);
8437 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8452 exit_status = j + 128;
8453 exitstatus = exit_status;
8455 if (i == EXINT || spclbltin > 0) {
8457 longjmp(exception_handler->loc, 1);
8464 listsetvar(varlist.list, 0);
8465 if (evalfun(cmdentry.u.func, argc, argv, flags))
8471 popredir(cmd_is_exec);
8473 /* dsl: I think this is intended to be used to support
8474 * '_' in 'vi' command mode during line editing...
8475 * However I implemented that within libedit itself.
8477 setvar("_", lastarg, 0);
8478 popstackmark(&smark);
8482 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8484 char *volatile savecmdname;
8485 struct jmploc *volatile savehandler;
8486 struct jmploc jmploc;
8489 savecmdname = commandname;
8490 i = setjmp(jmploc.loc);
8493 savehandler = exception_handler;
8494 exception_handler = &jmploc;
8495 commandname = argv[0];
8497 optptr = NULL; /* initialize nextopt */
8498 exitstatus = (*cmd->builtin)(argc, argv);
8499 flush_stdout_stderr();
8501 exitstatus |= ferror(stdout);
8503 commandname = savecmdname;
8505 exception_handler = savehandler;
8511 goodname(const char *p)
8513 return !*endofname(p);
8518 * Search for a command. This is called before we fork so that the
8519 * location of the command will be available in the parent as well as
8520 * the child. The check for "goodname" is an overly conservative
8521 * check that the name will not be subject to expansion.
8524 prehash(union node *n)
8526 struct cmdentry entry;
8528 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8529 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8533 /* ============ Builtin commands
8535 * Builtin commands whose functions are closely tied to evaluation
8536 * are implemented here.
8540 * Handle break and continue commands. Break, continue, and return are
8541 * all handled by setting the evalskip flag. The evaluation routines
8542 * above all check this flag, and if it is set they start skipping
8543 * commands rather than executing them. The variable skipcount is
8544 * the number of loops to break/continue, or the number of function
8545 * levels to return. (The latter is always 1.) It should probably
8546 * be an error to break out of more loops than exist, but it isn't
8547 * in the standard shell so we don't make it one here.
8550 breakcmd(int argc, char **argv)
8552 int n = argc > 1 ? number(argv[1]) : 1;
8555 ash_msg_and_raise_error(illnum, argv[1]);
8559 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8566 /* ============ input.c
8568 * This implements the input routines used by the parser.
8571 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8574 INPUT_PUSH_FILE = 1,
8575 INPUT_NOFILE_OK = 2,
8578 static int plinno = 1; /* input line number */
8579 /* number of characters left in input buffer */
8580 static int parsenleft; /* copy of parsefile->nleft */
8581 static int parselleft; /* copy of parsefile->lleft */
8582 /* next character in input buffer */
8583 static char *parsenextc; /* copy of parsefile->nextc */
8585 static int checkkwd;
8586 /* values of checkkwd variable */
8587 #define CHKALIAS 0x1
8594 struct strpush *sp = parsefile->strpush;
8597 #if ENABLE_ASH_ALIAS
8599 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8600 checkkwd |= CHKALIAS;
8602 if (sp->string != sp->ap->val) {
8605 sp->ap->flag &= ~ALIASINUSE;
8606 if (sp->ap->flag & ALIASDEAD) {
8607 unalias(sp->ap->name);
8611 parsenextc = sp->prevstring;
8612 parsenleft = sp->prevnleft;
8613 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8614 parsefile->strpush = sp->prev;
8615 if (sp != &(parsefile->basestrpush))
8624 char *buf = parsefile->buf;
8628 #if ENABLE_FEATURE_EDITING
8629 if (!iflag || parsefile->fd)
8630 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8632 #if ENABLE_FEATURE_TAB_COMPLETION
8633 line_input_state->path_lookup = pathval();
8635 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8637 /* Ctrl+C pressed */
8646 if (nr < 0 && errno == 0) {
8647 /* Ctrl+D pressed */
8652 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8656 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8657 int flags = fcntl(0, F_GETFL);
8658 if (flags >= 0 && (flags & O_NONBLOCK)) {
8659 flags &= ~O_NONBLOCK;
8660 if (fcntl(0, F_SETFL, flags) >= 0) {
8661 out2str("sh: turning off NDELAY mode\n");
8671 * Refill the input buffer and return the next input character:
8673 * 1) If a string was pushed back on the input, pop it;
8674 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8675 * from a string so we can't refill the buffer, return EOF.
8676 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8677 * 4) Process input up to the next newline, deleting nul characters.
8686 while (parsefile->strpush) {
8687 #if ENABLE_ASH_ALIAS
8688 if (parsenleft == -1 && parsefile->strpush->ap &&
8689 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8694 if (--parsenleft >= 0)
8695 return signed_char2int(*parsenextc++);
8697 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8699 flush_stdout_stderr();
8706 parselleft = parsenleft = EOF_NLEFT;
8713 /* delete nul characters */
8721 memmove(q, q + 1, more);
8725 parsenleft = q - parsenextc - 1;
8731 parsenleft = q - parsenextc - 1;
8743 out2str(parsenextc);
8748 return signed_char2int(*parsenextc++);
8751 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8755 return pgetc_as_macro();
8758 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8759 #define pgetc_macro() pgetc()
8761 #define pgetc_macro() pgetc_as_macro()
8765 * Same as pgetc(), but ignores PEOA.
8767 #if ENABLE_ASH_ALIAS
8775 } while (c == PEOA);
8782 return pgetc_macro();
8787 * Read a line from the script.
8790 pfgets(char *line, int len)
8796 while (--nleft > 0) {
8812 * Undo the last call to pgetc. Only one character may be pushed back.
8813 * PEOF may be pushed back.
8823 * Push a string back onto the input at this current parsefile level.
8824 * We handle aliases this way.
8827 pushstring(char *s, void *ap)
8834 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8835 if (parsefile->strpush) {
8836 sp = ckmalloc(sizeof(struct strpush));
8837 sp->prev = parsefile->strpush;
8838 parsefile->strpush = sp;
8840 sp = parsefile->strpush = &(parsefile->basestrpush);
8841 sp->prevstring = parsenextc;
8842 sp->prevnleft = parsenleft;
8843 #if ENABLE_ASH_ALIAS
8844 sp->ap = (struct alias *)ap;
8846 ((struct alias *)ap)->flag |= ALIASINUSE;
8856 * To handle the "." command, a stack of input files is used. Pushfile
8857 * adds a new entry to the stack and popfile restores the previous level.
8862 struct parsefile *pf;
8864 parsefile->nleft = parsenleft;
8865 parsefile->lleft = parselleft;
8866 parsefile->nextc = parsenextc;
8867 parsefile->linno = plinno;
8868 pf = ckmalloc(sizeof(*pf));
8869 pf->prev = parsefile;
8872 pf->basestrpush.prev = NULL;
8879 struct parsefile *pf = parsefile;
8887 parsefile = pf->prev;
8889 parsenleft = parsefile->nleft;
8890 parselleft = parsefile->lleft;
8891 parsenextc = parsefile->nextc;
8892 plinno = parsefile->linno;
8897 * Return to top level.
8902 while (parsefile != &basepf)
8907 * Close the file(s) that the shell is reading commands from. Called
8908 * after a fork is done.
8914 if (parsefile->fd > 0) {
8915 close(parsefile->fd);
8921 * Like setinputfile, but takes an open file descriptor. Call this with
8925 setinputfd(int fd, int push)
8927 close_on_exec_on(fd);
8933 if (parsefile->buf == NULL)
8934 parsefile->buf = ckmalloc(IBUFSIZ);
8935 parselleft = parsenleft = 0;
8940 * Set the input to take input from a file. If push is set, push the
8941 * old input onto the stack first.
8944 setinputfile(const char *fname, int flags)
8950 fd = open(fname, O_RDONLY);
8952 if (flags & INPUT_NOFILE_OK)
8954 ash_msg_and_raise_error("can't open %s", fname);
8957 fd2 = copyfd(fd, 10);
8960 ash_msg_and_raise_error("out of file descriptors");
8963 setinputfd(fd, flags & INPUT_PUSH_FILE);
8970 * Like setinputfile, but takes input from a string.
8973 setinputstring(char *string)
8977 parsenextc = string;
8978 parsenleft = strlen(string);
8979 parsefile->buf = NULL;
8985 /* ============ mail.c
8987 * Routines to check for mail.
8992 #define MAXMBOXES 10
8994 /* times of mailboxes */
8995 static time_t mailtime[MAXMBOXES];
8996 /* Set if MAIL or MAILPATH is changed. */
8997 static smallint mail_var_path_changed;
9000 * Print appropriate message(s) if mail has arrived.
9001 * If mail_var_path_changed is set,
9002 * then the value of MAIL has mail_var_path_changed,
9003 * so we just update the values.
9012 struct stackmark smark;
9015 setstackmark(&smark);
9016 mpath = mpathset() ? mpathval() : mailval();
9017 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9018 p = padvance(&mpath, nullstr);
9023 for (q = p; *q; q++);
9028 q[-1] = '\0'; /* delete trailing '/' */
9029 if (stat(p, &statb) < 0) {
9033 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9036 pathopt ? pathopt : "you have mail"
9039 *mtp = statb.st_mtime;
9041 mail_var_path_changed = 0;
9042 popstackmark(&smark);
9046 changemail(const char *val)
9048 mail_var_path_changed = 1;
9051 #endif /* ASH_MAIL */
9054 /* ============ ??? */
9057 * Set the shell parameters.
9060 setparam(char **argv)
9066 for (nparam = 0; argv[nparam]; nparam++);
9067 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9069 *ap++ = ckstrdup(*argv++);
9072 freeparam(&shellparam);
9073 shellparam.malloced = 1;
9074 shellparam.nparam = nparam;
9075 shellparam.p = newparam;
9076 #if ENABLE_ASH_GETOPTS
9077 shellparam.optind = 1;
9078 shellparam.optoff = -1;
9083 * Process shell options. The global variable argptr contains a pointer
9084 * to the argument list; we advance it past the options.
9087 minus_o(char *name, int val)
9092 for (i = 0; i < NOPTS; i++) {
9093 if (strcmp(name, optnames(i)) == 0) {
9098 ash_msg_and_raise_error("illegal option -o %s", name);
9100 out1str("Current option settings\n");
9101 for (i = 0; i < NOPTS; i++)
9102 out1fmt("%-16s%s\n", optnames(i),
9103 optlist[i] ? "on" : "off");
9106 setoption(int flag, int val)
9110 for (i = 0; i < NOPTS; i++) {
9111 if (optletters(i) == flag) {
9116 ash_msg_and_raise_error("illegal option -%c", flag);
9120 options(int cmdline)
9128 while ((p = *argptr) != NULL) {
9130 if (c != '-' && c != '+')
9133 val = 0; /* val = 0 if c == '+' */
9136 if (p[0] == '\0' || LONE_DASH(p)) {
9138 /* "-" means turn off -x and -v */
9141 /* "--" means reset params */
9142 else if (*argptr == NULL)
9145 break; /* "-" or "--" terminates options */
9148 /* first char was + or - */
9149 while ((c = *p++) != '\0') {
9150 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9151 if (c == 'c' && cmdline) {
9152 minusc = p; /* command is after shell args */
9153 } else if (c == 'o') {
9154 minus_o(*argptr, val);
9157 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9159 /* bash does not accept +-login, we also won't */
9160 } else if (cmdline && val && (c == '-')) { /* long options */
9161 if (strcmp(p, "login") == 0)
9172 * The shift builtin command.
9175 shiftcmd(int argc, char **argv)
9182 n = number(argv[1]);
9183 if (n > shellparam.nparam)
9184 ash_msg_and_raise_error("can't shift that many");
9186 shellparam.nparam -= n;
9187 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9188 if (shellparam.malloced)
9192 while ((*ap2++ = *ap1++) != NULL);
9193 #if ENABLE_ASH_GETOPTS
9194 shellparam.optind = 1;
9195 shellparam.optoff = -1;
9202 * POSIX requires that 'set' (but not export or readonly) output the
9203 * variables in lexicographic order - by the locale's collating order (sigh).
9204 * Maybe we could keep them in an ordered balanced binary tree
9205 * instead of hashed lists.
9206 * For now just roll 'em through qsort for printing...
9209 showvars(const char *sep_prefix, int on, int off)
9214 ep = listvars(on, off, &epend);
9215 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9217 sep = *sep_prefix ? " " : sep_prefix;
9219 for (; ep < epend; ep++) {
9223 p = strchrnul(*ep, '=');
9226 q = single_quote(++p);
9227 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9233 * The set command builtin.
9236 setcmd(int argc, char **argv)
9239 return showvars(nullstr, 0, VUNSET);
9243 if (*argptr != NULL) {
9250 #if ENABLE_ASH_RANDOM_SUPPORT
9251 /* Roughly copied from bash.. */
9253 change_random(const char *value)
9255 if (value == NULL) {
9256 /* "get", generate */
9259 rseed = rseed * 1103515245 + 12345;
9260 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9261 /* set without recursion */
9262 setvar(vrandom.text, buf, VNOFUNC);
9263 vrandom.flags &= ~VNOFUNC;
9266 rseed = strtoul(value, (char **)NULL, 10);
9271 #if ENABLE_ASH_GETOPTS
9273 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9282 if (*param_optind < 1)
9284 optnext = optfirst + *param_optind - 1;
9286 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9289 p = optnext[-1] + *optoff;
9290 if (p == NULL || *p == '\0') {
9291 /* Current word is done, advance */
9293 if (p == NULL || *p != '-' || *++p == '\0') {
9300 if (LONE_DASH(p)) /* check for "--" */
9305 for (q = optstr; *q != c; ) {
9307 if (optstr[0] == ':') {
9310 err |= setvarsafe("OPTARG", s, 0);
9312 fprintf(stderr, "Illegal option -%c\n", c);
9323 if (*p == '\0' && (p = *optnext) == NULL) {
9324 if (optstr[0] == ':') {
9327 err |= setvarsafe("OPTARG", s, 0);
9330 fprintf(stderr, "No arg for -%c option\n", c);
9339 err |= setvarsafe("OPTARG", p, 0);
9342 err |= setvarsafe("OPTARG", nullstr, 0);
9344 *optoff = p ? p - *(optnext - 1) : -1;
9345 *param_optind = optnext - optfirst + 1;
9346 fmtstr(s, sizeof(s), "%d", *param_optind);
9347 err |= setvarsafe("OPTIND", s, VNOFUNC);
9350 err |= setvarsafe(optvar, s, 0);
9354 flush_stdout_stderr();
9355 raise_exception(EXERROR);
9361 * The getopts builtin. Shellparam.optnext points to the next argument
9362 * to be processed. Shellparam.optptr points to the next character to
9363 * be processed in the current argument. If shellparam.optnext is NULL,
9364 * then it's the first time getopts has been called.
9367 getoptscmd(int argc, char **argv)
9372 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9374 optbase = shellparam.p;
9375 if (shellparam.optind > shellparam.nparam + 1) {
9376 shellparam.optind = 1;
9377 shellparam.optoff = -1;
9381 if (shellparam.optind > argc - 2) {
9382 shellparam.optind = 1;
9383 shellparam.optoff = -1;
9387 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9388 &shellparam.optoff);
9390 #endif /* ASH_GETOPTS */
9393 /* ============ Shell parser */
9396 * NEOF is returned by parsecmd when it encounters an end of file. It
9397 * must be distinct from NULL, so we use the address of a variable that
9398 * happens to be handy.
9400 static smallint tokpushback; /* last token pushed back */
9401 #define NEOF ((union node *)&tokpushback)
9402 static smallint parsebackquote; /* nonzero if we are inside backquotes */
9403 static int lasttoken; /* last token read */
9404 static char *wordtext; /* text of last word returned by readtoken */
9405 static struct nodelist *backquotelist;
9406 static union node *redirnode;
9407 static struct heredoc *heredoc;
9408 static smallint quoteflag; /* set if (part of) last token was quoted */
9410 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9412 raise_error_syntax(const char *msg)
9414 ash_msg_and_raise_error("syntax error: %s", msg);
9419 * Called when an unexpected token is read during the parse. The argument
9420 * is the token that is expected, or -1 if more than one type of token can
9421 * occur at this point.
9423 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9425 raise_error_unexpected_syntax(int token)
9430 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9432 sprintf(msg + l, " (expecting %s)", tokname(token));
9433 raise_error_syntax(msg);
9437 #define EOFMARKLEN 79
9440 struct heredoc *next; /* next here document in list */
9441 union node *here; /* redirection node */
9442 char *eofmark; /* string indicating end of input */
9443 int striptabs; /* if set, strip leading tabs */
9446 static struct heredoc *heredoclist; /* list of here documents to read */
9448 /* parsing is heavily cross-recursive, need these forward decls */
9449 static union node *andor(void);
9450 static union node *pipeline(void);
9451 static union node *parse_command(void);
9452 static void parseheredoc(void);
9453 static char peektoken(void);
9454 static int readtoken(void);
9459 union node *n1, *n2, *n3;
9462 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9463 if (nlflag == 2 && peektoken())
9469 if (tok == TBACKGND) {
9470 if (n2->type == NPIPE) {
9471 n2->npipe.backgnd = 1;
9473 if (n2->type != NREDIR) {
9474 n3 = stalloc(sizeof(struct nredir));
9476 n3->nredir.redirect = NULL;
9479 n2->type = NBACKGND;
9485 n3 = stalloc(sizeof(struct nbinary));
9487 n3->nbinary.ch1 = n1;
9488 n3->nbinary.ch2 = n2;
9504 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9512 pungetc(); /* push back EOF on input */
9516 raise_error_unexpected_syntax(-1);
9526 union node *n1, *n2, *n3;
9534 } else if (t == TOR) {
9540 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9542 n3 = stalloc(sizeof(struct nbinary));
9544 n3->nbinary.ch1 = n1;
9545 n3->nbinary.ch2 = n2;
9553 union node *n1, *n2, *pipenode;
9554 struct nodelist *lp, *prev;
9558 TRACE(("pipeline: entered\n"));
9559 if (readtoken() == TNOT) {
9561 checkkwd = CHKKWD | CHKALIAS;
9564 n1 = parse_command();
9565 if (readtoken() == TPIPE) {
9566 pipenode = stalloc(sizeof(struct npipe));
9567 pipenode->type = NPIPE;
9568 pipenode->npipe.backgnd = 0;
9569 lp = stalloc(sizeof(struct nodelist));
9570 pipenode->npipe.cmdlist = lp;
9574 lp = stalloc(sizeof(struct nodelist));
9575 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9576 lp->n = parse_command();
9578 } while (readtoken() == TPIPE);
9584 n2 = stalloc(sizeof(struct nnot));
9597 n = stalloc(sizeof(struct narg));
9599 n->narg.next = NULL;
9600 n->narg.text = wordtext;
9601 n->narg.backquote = backquotelist;
9606 fixredir(union node *n, const char *text, int err)
9608 TRACE(("Fix redir %s %d\n", text, err));
9610 n->ndup.vname = NULL;
9612 if (isdigit(text[0]) && text[1] == '\0')
9613 n->ndup.dupfd = text[0] - '0';
9614 else if (LONE_DASH(text))
9618 raise_error_syntax("Bad fd number");
9619 n->ndup.vname = makename();
9624 * Returns true if the text contains nothing to expand (no dollar signs
9628 noexpand(char *text)
9634 while ((c = *p++) != '\0') {
9635 if (c == CTLQUOTEMARK)
9639 else if (SIT(c, BASESYNTAX) == CCTL)
9648 union node *n = redirnode;
9650 if (readtoken() != TWORD)
9651 raise_error_unexpected_syntax(-1);
9652 if (n->type == NHERE) {
9653 struct heredoc *here = heredoc;
9659 TRACE(("Here document %d\n", n->type));
9660 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9661 raise_error_syntax("Illegal eof marker for << redirection");
9662 rmescapes(wordtext);
9663 here->eofmark = wordtext;
9665 if (heredoclist == NULL)
9668 for (p = heredoclist; p->next; p = p->next);
9671 } else if (n->type == NTOFD || n->type == NFROMFD) {
9672 fixredir(n, wordtext, 0);
9674 n->nfile.fname = makename();
9681 union node *args, **app;
9682 union node *n = NULL;
9683 union node *vars, **vpp;
9684 union node **rpp, *redir;
9694 savecheckkwd = CHKALIAS;
9696 checkkwd = savecheckkwd;
9697 switch (readtoken()) {
9699 n = stalloc(sizeof(struct narg));
9701 n->narg.text = wordtext;
9702 n->narg.backquote = backquotelist;
9703 if (savecheckkwd && isassignment(wordtext)) {
9705 vpp = &n->narg.next;
9708 app = &n->narg.next;
9713 *rpp = n = redirnode;
9714 rpp = &n->nfile.next;
9715 parsefname(); /* read name of redirection file */
9718 if (args && app == &args->narg.next
9721 struct builtincmd *bcmd;
9724 /* We have a function */
9725 if (readtoken() != TRP)
9726 raise_error_unexpected_syntax(TRP);
9727 name = n->narg.text;
9729 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9731 raise_error_syntax("Bad function name");
9734 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9735 n->narg.next = parse_command();
9748 n = stalloc(sizeof(struct ncmd));
9750 n->ncmd.args = args;
9751 n->ncmd.assign = vars;
9752 n->ncmd.redirect = redir;
9759 union node *n1, *n2;
9760 union node *ap, **app;
9761 union node *cp, **cpp;
9762 union node *redir, **rpp;
9769 switch (readtoken()) {
9771 raise_error_unexpected_syntax(-1);
9774 n1 = stalloc(sizeof(struct nif));
9776 n1->nif.test = list(0);
9777 if (readtoken() != TTHEN)
9778 raise_error_unexpected_syntax(TTHEN);
9779 n1->nif.ifpart = list(0);
9781 while (readtoken() == TELIF) {
9782 n2->nif.elsepart = stalloc(sizeof(struct nif));
9783 n2 = n2->nif.elsepart;
9785 n2->nif.test = list(0);
9786 if (readtoken() != TTHEN)
9787 raise_error_unexpected_syntax(TTHEN);
9788 n2->nif.ifpart = list(0);
9790 if (lasttoken == TELSE)
9791 n2->nif.elsepart = list(0);
9793 n2->nif.elsepart = NULL;
9801 n1 = stalloc(sizeof(struct nbinary));
9802 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9803 n1->nbinary.ch1 = list(0);
9806 TRACE(("expecting DO got %s %s\n", tokname(got),
9807 got == TWORD ? wordtext : ""));
9808 raise_error_unexpected_syntax(TDO);
9810 n1->nbinary.ch2 = list(0);
9815 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9816 raise_error_syntax("Bad for loop variable");
9817 n1 = stalloc(sizeof(struct nfor));
9819 n1->nfor.var = wordtext;
9820 checkkwd = CHKKWD | CHKALIAS;
9821 if (readtoken() == TIN) {
9823 while (readtoken() == TWORD) {
9824 n2 = stalloc(sizeof(struct narg));
9826 n2->narg.text = wordtext;
9827 n2->narg.backquote = backquotelist;
9829 app = &n2->narg.next;
9833 if (lasttoken != TNL && lasttoken != TSEMI)
9834 raise_error_unexpected_syntax(-1);
9836 n2 = stalloc(sizeof(struct narg));
9838 n2->narg.text = (char *)dolatstr;
9839 n2->narg.backquote = NULL;
9840 n2->narg.next = NULL;
9843 * Newline or semicolon here is optional (but note
9844 * that the original Bourne shell only allowed NL).
9846 if (lasttoken != TNL && lasttoken != TSEMI)
9849 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9850 if (readtoken() != TDO)
9851 raise_error_unexpected_syntax(TDO);
9852 n1->nfor.body = list(0);
9856 n1 = stalloc(sizeof(struct ncase));
9858 if (readtoken() != TWORD)
9859 raise_error_unexpected_syntax(TWORD);
9860 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9862 n2->narg.text = wordtext;
9863 n2->narg.backquote = backquotelist;
9864 n2->narg.next = NULL;
9866 checkkwd = CHKKWD | CHKALIAS;
9867 } while (readtoken() == TNL);
9868 if (lasttoken != TIN)
9869 raise_error_unexpected_syntax(TIN);
9870 cpp = &n1->ncase.cases;
9872 checkkwd = CHKNL | CHKKWD;
9874 while (t != TESAC) {
9875 if (lasttoken == TLP)
9877 *cpp = cp = stalloc(sizeof(struct nclist));
9879 app = &cp->nclist.pattern;
9881 *app = ap = stalloc(sizeof(struct narg));
9883 ap->narg.text = wordtext;
9884 ap->narg.backquote = backquotelist;
9885 if (readtoken() != TPIPE)
9887 app = &ap->narg.next;
9890 ap->narg.next = NULL;
9891 if (lasttoken != TRP)
9892 raise_error_unexpected_syntax(TRP);
9893 cp->nclist.body = list(2);
9895 cpp = &cp->nclist.next;
9897 checkkwd = CHKNL | CHKKWD;
9901 raise_error_unexpected_syntax(TENDCASE);
9908 n1 = stalloc(sizeof(struct nredir));
9909 n1->type = NSUBSHELL;
9910 n1->nredir.n = list(0);
9911 n1->nredir.redirect = NULL;
9924 if (readtoken() != t)
9925 raise_error_unexpected_syntax(t);
9928 /* Now check for redirection which may follow command */
9929 checkkwd = CHKKWD | CHKALIAS;
9931 while (readtoken() == TREDIR) {
9932 *rpp = n2 = redirnode;
9933 rpp = &n2->nfile.next;
9939 if (n1->type != NSUBSHELL) {
9940 n2 = stalloc(sizeof(struct nredir));
9945 n1->nredir.redirect = redir;
9951 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9952 * is not NULL, read a here document. In the latter case, eofmark is the
9953 * word which marks the end of the document and striptabs is true if
9954 * leading tabs should be stripped from the document. The argument firstc
9955 * is the first character of the input token or document.
9957 * Because C does not have internal subroutines, I have simulated them
9958 * using goto's to implement the subroutine linkage. The following macros
9959 * will run code that appears at the end of readtoken1.
9962 #define CHECKEND() {goto checkend; checkend_return:;}
9963 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9964 #define PARSESUB() {goto parsesub; parsesub_return:;}
9965 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9966 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9967 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9970 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9972 /* NB: syntax parameter fits into smallint */
9976 char line[EOFMARKLEN + 1];
9977 struct nodelist *bqlist;
9981 smallint prevsyntax; /* syntax before arithmetic */
9982 #if ENABLE_ASH_EXPAND_PRMT
9983 smallint pssyntax; /* we are expanding a prompt string */
9985 int varnest; /* levels of variables expansion */
9986 int arinest; /* levels of arithmetic expansion */
9987 int parenlevel; /* levels of parens in arithmetic */
9988 int dqvarnest; /* levels of variables expansion within double quotes */
9991 /* Avoid longjmp clobbering */
10000 (void) &prevsyntax;
10003 startlinno = plinno;
10008 #if ENABLE_ASH_EXPAND_PRMT
10009 pssyntax = (syntax == PSSYNTAX);
10013 dblquote = (syntax == DQSYNTAX);
10019 STARTSTACKSTR(out);
10020 loop: { /* for each line, until end of word */
10021 CHECKEND(); /* set c to PEOF if at end of here document */
10022 for (;;) { /* until end of line or end of word */
10023 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10024 switch (SIT(c, syntax)) {
10025 case CNL: /* '\n' */
10026 if (syntax == BASESYNTAX)
10027 goto endword; /* exit outer loop */
10033 goto loop; /* continue outer loop */
10038 if (eofmark == NULL || dblquote)
10039 USTPUTC(CTLESC, out);
10042 case CBACK: /* backslash */
10045 USTPUTC(CTLESC, out);
10046 USTPUTC('\\', out);
10048 } else if (c == '\n') {
10052 #if ENABLE_ASH_EXPAND_PRMT
10053 if (c == '$' && pssyntax) {
10054 USTPUTC(CTLESC, out);
10055 USTPUTC('\\', out);
10059 c != '\\' && c != '`' &&
10064 USTPUTC(CTLESC, out);
10065 USTPUTC('\\', out);
10067 if (SIT(c, SQSYNTAX) == CCTL)
10068 USTPUTC(CTLESC, out);
10076 if (eofmark == NULL) {
10077 USTPUTC(CTLQUOTEMARK, out);
10085 if (eofmark != NULL && arinest == 0
10090 if (dqvarnest == 0) {
10091 syntax = BASESYNTAX;
10098 case CVAR: /* '$' */
10099 PARSESUB(); /* parse substitution */
10101 case CENDVAR: /* '}' */
10104 if (dqvarnest > 0) {
10107 USTPUTC(CTLENDVAR, out);
10112 #if ENABLE_ASH_MATH_SUPPORT
10113 case CLP: /* '(' in arithmetic */
10117 case CRP: /* ')' in arithmetic */
10118 if (parenlevel > 0) {
10122 if (pgetc() == ')') {
10123 if (--arinest == 0) {
10124 USTPUTC(CTLENDARI, out);
10125 syntax = prevsyntax;
10126 dblquote = (syntax == DQSYNTAX);
10131 * unbalanced parens
10132 * (don't 2nd guess - no error)
10140 case CBQUOTE: /* '`' */
10144 goto endword; /* exit outer loop */
10149 goto endword; /* exit outer loop */
10150 #if ENABLE_ASH_ALIAS
10160 #if ENABLE_ASH_MATH_SUPPORT
10161 if (syntax == ARISYNTAX)
10162 raise_error_syntax("Missing '))'");
10164 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10165 raise_error_syntax("Unterminated quoted string");
10166 if (varnest != 0) {
10167 startlinno = plinno;
10169 raise_error_syntax("Missing '}'");
10171 USTPUTC('\0', out);
10172 len = out - (char *)stackblock();
10173 out = stackblock();
10174 if (eofmark == NULL) {
10175 if ((c == '>' || c == '<')
10178 && (*out == '\0' || isdigit(*out))) {
10180 return lasttoken = TREDIR;
10185 quoteflag = quotef;
10186 backquotelist = bqlist;
10187 grabstackblock(len);
10191 /* end of readtoken routine */
10194 * Check to see whether we are at the end of the here document. When this
10195 * is called, c is set to the first character of the next input line. If
10196 * we are at the end of the here document, this routine sets the c to PEOF.
10200 #if ENABLE_ASH_ALIAS
10206 while (c == '\t') {
10210 if (c == *eofmark) {
10211 if (pfgets(line, sizeof(line)) != NULL) {
10215 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10216 if (*p == '\n' && *q == '\0') {
10219 needprompt = doprompt;
10221 pushstring(line, NULL);
10226 goto checkend_return;
10230 * Parse a redirection operator. The variable "out" points to a string
10231 * specifying the fd to be redirected. The variable "c" contains the
10232 * first character of the redirection operator.
10238 np = stalloc(sizeof(struct nfile));
10243 np->type = NAPPEND;
10245 np->type = NCLOBBER;
10252 } else { /* c == '<' */
10257 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10258 np = stalloc(sizeof(struct nhere));
10262 heredoc = stalloc(sizeof(struct heredoc));
10263 heredoc->here = np;
10266 heredoc->striptabs = 1;
10268 heredoc->striptabs = 0;
10274 np->type = NFROMFD;
10278 np->type = NFROMTO;
10288 np->nfile.fd = fd - '0';
10290 goto parseredir_return;
10294 * Parse a substitution. At this point, we have read the dollar sign
10295 * and nothing else.
10298 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10299 * (assuming ascii char codes, as the original implementation did) */
10300 #define is_special(c) \
10301 ((((unsigned int)c) - 33 < 32) \
10302 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10308 static const char types[] ALIGN1 = "}-+?=";
10312 c <= PEOA_OR_PEOF ||
10313 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10317 } else if (c == '(') { /* $(command) or $((arith)) */
10318 if (pgetc() == '(') {
10319 #if ENABLE_ASH_MATH_SUPPORT
10322 raise_error_syntax("We unsupport $((arith))");
10329 USTPUTC(CTLVAR, out);
10330 typeloc = out - (char *)stackblock();
10331 USTPUTC(VSNORMAL, out);
10332 subtype = VSNORMAL;
10340 subtype = VSLENGTH;
10344 if (c > PEOA_OR_PEOF && is_name(c)) {
10348 } while (c > PEOA_OR_PEOF && is_in_name(c));
10349 } else if (isdigit(c)) {
10353 } while (isdigit(c));
10354 } else if (is_special(c)) {
10358 badsub: raise_error_syntax("Bad substitution");
10362 if (subtype == 0) {
10369 p = strchr(types, c);
10372 subtype = p - types + VSNORMAL;
10378 subtype = c == '#' ? VSTRIMLEFT :
10391 if (dblquote || arinest)
10393 *((char *)stackblock() + typeloc) = subtype | flags;
10394 if (subtype != VSNORMAL) {
10396 if (dblquote || arinest) {
10401 goto parsesub_return;
10405 * Called to parse command substitutions. Newstyle is set if the command
10406 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10407 * list of commands (passed by reference), and savelen is the number of
10408 * characters on the top of the stack which must be preserved.
10411 struct nodelist **nlpp;
10414 char *volatile str;
10415 struct jmploc jmploc;
10416 struct jmploc *volatile savehandler;
10418 smallint saveprompt = 0;
10421 (void) &saveprompt;
10423 savepbq = parsebackquote;
10424 if (setjmp(jmploc.loc)) {
10426 parsebackquote = 0;
10427 exception_handler = savehandler;
10428 longjmp(exception_handler->loc, 1);
10432 savelen = out - (char *)stackblock();
10434 str = ckmalloc(savelen);
10435 memcpy(str, stackblock(), savelen);
10437 savehandler = exception_handler;
10438 exception_handler = &jmploc;
10441 /* We must read until the closing backquote, giving special
10442 treatment to some slashes, and then push the string and
10443 reread it as input, interpreting it normally. */
10450 STARTSTACKSTR(pout);
10467 * If eating a newline, avoid putting
10468 * the newline into the new character
10469 * stream (via the STPUTC after the
10474 if (pc != '\\' && pc != '`' && pc != '$'
10475 && (!dblquote || pc != '"'))
10476 STPUTC('\\', pout);
10477 if (pc > PEOA_OR_PEOF) {
10483 #if ENABLE_ASH_ALIAS
10486 startlinno = plinno;
10487 raise_error_syntax("EOF in backquote substitution");
10491 needprompt = doprompt;
10500 STPUTC('\0', pout);
10501 psavelen = pout - (char *)stackblock();
10502 if (psavelen > 0) {
10503 pstr = grabstackstr(pout);
10504 setinputstring(pstr);
10509 nlpp = &(*nlpp)->next;
10510 *nlpp = stalloc(sizeof(**nlpp));
10511 (*nlpp)->next = NULL;
10512 parsebackquote = oldstyle;
10515 saveprompt = doprompt;
10522 doprompt = saveprompt;
10523 else if (readtoken() != TRP)
10524 raise_error_unexpected_syntax(TRP);
10529 * Start reading from old file again, ignoring any pushed back
10530 * tokens left from the backquote parsing
10535 while (stackblocksize() <= savelen)
10537 STARTSTACKSTR(out);
10539 memcpy(out, str, savelen);
10540 STADJUST(savelen, out);
10546 parsebackquote = savepbq;
10547 exception_handler = savehandler;
10548 if (arinest || dblquote)
10549 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10551 USTPUTC(CTLBACKQ, out);
10553 goto parsebackq_oldreturn;
10554 goto parsebackq_newreturn;
10557 #if ENABLE_ASH_MATH_SUPPORT
10559 * Parse an arithmetic expansion (indicate start of one and set state)
10562 if (++arinest == 1) {
10563 prevsyntax = syntax;
10564 syntax = ARISYNTAX;
10565 USTPUTC(CTLARI, out);
10572 * we collapse embedded arithmetic expansion to
10573 * parenthesis, which should be equivalent
10577 goto parsearith_return;
10581 } /* end of readtoken */
10584 * Read the next input token.
10585 * If the token is a word, we set backquotelist to the list of cmds in
10586 * backquotes. We set quoteflag to true if any part of the word was
10588 * If the token is TREDIR, then we set redirnode to a structure containing
10590 * In all cases, the variable startlinno is set to the number of the line
10591 * on which the token starts.
10593 * [Change comment: here documents and internal procedures]
10594 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10595 * word parsing code into a separate routine. In this case, readtoken
10596 * doesn't need to have any internal procedures, but parseword does.
10597 * We could also make parseoperator in essence the main routine, and
10598 * have parseword (readtoken1?) handle both words and redirection.]
10600 #define NEW_xxreadtoken
10601 #ifdef NEW_xxreadtoken
10602 /* singles must be first! */
10603 static const char xxreadtoken_chars[7] ALIGN1 = {
10604 '\n', '(', ')', '&', '|', ';', 0
10607 static const char xxreadtoken_tokens[] ALIGN1 = {
10608 TNL, TLP, TRP, /* only single occurrence allowed */
10609 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10610 TEOF, /* corresponds to trailing nul */
10611 TAND, TOR, TENDCASE /* if double occurrence */
10614 #define xxreadtoken_doubles \
10615 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10616 #define xxreadtoken_singles \
10617 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10631 startlinno = plinno;
10632 for (;;) { /* until token or start of word found */
10635 if ((c != ' ') && (c != '\t')
10636 #if ENABLE_ASH_ALIAS
10641 while ((c = pgetc()) != '\n' && c != PEOF);
10643 } else if (c == '\\') {
10644 if (pgetc() != '\n') {
10648 startlinno = ++plinno;
10653 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10658 needprompt = doprompt;
10661 p = strchr(xxreadtoken_chars, c);
10664 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10667 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10668 if (pgetc() == *p) { /* double occurrence? */
10669 p += xxreadtoken_doubles + 1;
10675 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10681 #define RETURN(token) return lasttoken = token
10694 startlinno = plinno;
10695 for (;;) { /* until token or start of word found */
10698 case ' ': case '\t':
10699 #if ENABLE_ASH_ALIAS
10704 while ((c = pgetc()) != '\n' && c != PEOF);
10708 if (pgetc() == '\n') {
10709 startlinno = ++plinno;
10718 needprompt = doprompt;
10723 if (pgetc() == '&')
10728 if (pgetc() == '|')
10733 if (pgetc() == ';')
10746 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10749 #endif /* NEW_xxreadtoken */
10756 smallint alreadyseen = tokpushback;
10759 #if ENABLE_ASH_ALIAS
10768 if (checkkwd & CHKNL) {
10775 if (t != TWORD || quoteflag) {
10780 * check for keywords
10782 if (checkkwd & CHKKWD) {
10783 const char *const *pp;
10785 pp = findkwd(wordtext);
10787 lasttoken = t = pp - tokname_array;
10788 TRACE(("keyword %s recognized\n", tokname(t)));
10793 if (checkkwd & CHKALIAS) {
10794 #if ENABLE_ASH_ALIAS
10796 ap = lookupalias(wordtext, 1);
10799 pushstring(ap->val, ap);
10809 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10811 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10823 return tokname_array[t][0];
10827 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10828 * valid parse tree indicating a blank line.)
10830 static union node *
10831 parsecmd(int interact)
10836 doprompt = interact;
10838 setprompt(doprompt);
10850 * Input any here documents.
10855 struct heredoc *here;
10858 here = heredoclist;
10865 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10866 here->eofmark, here->striptabs);
10867 n = stalloc(sizeof(struct narg));
10868 n->narg.type = NARG;
10869 n->narg.next = NULL;
10870 n->narg.text = wordtext;
10871 n->narg.backquote = backquotelist;
10872 here->here->nhere.doc = n;
10879 * called by editline -- any expansions to the prompt should be added here.
10881 #if ENABLE_ASH_EXPAND_PRMT
10882 static const char *
10883 expandstr(const char *ps)
10887 /* XXX Fix (char *) cast. */
10888 setinputstring((char *)ps);
10889 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
10892 n.narg.type = NARG;
10893 n.narg.next = NULL;
10894 n.narg.text = wordtext;
10895 n.narg.backquote = backquotelist;
10897 expandarg(&n, NULL, 0);
10898 return stackblock();
10903 * Execute a command or commands contained in a string.
10906 evalstring(char *s, int mask)
10909 struct stackmark smark;
10913 setstackmark(&smark);
10916 while ((n = parsecmd(0)) != NEOF) {
10918 popstackmark(&smark);
10931 * The eval command.
10934 evalcmd(int argc, char **argv)
10943 STARTSTACKSTR(concat);
10946 concat = stack_putstr(p, concat);
10950 STPUTC(' ', concat);
10952 STPUTC('\0', concat);
10953 p = grabstackstr(concat);
10955 evalstring(p, ~SKIPEVAL);
10962 * Read and execute commands. "Top" is nonzero for the top level command
10963 * loop; it turns on prompting if the shell is interactive.
10969 struct stackmark smark;
10973 TRACE(("cmdloop(%d) called\n", top));
10977 setstackmark(&smark);
10980 showjobs(stderr, SHOW_CHANGED);
10983 if (iflag && top) {
10985 #if ENABLE_ASH_MAIL
10989 n = parsecmd(inter);
10990 /* showtree(n); DEBUG */
10992 if (!top || numeof >= 50)
10994 if (!stoppedjobs()) {
10997 out2str("\nUse \"exit\" to leave shell.\n");
11000 } else if (nflag == 0) {
11001 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11006 popstackmark(&smark);
11011 return skip & SKIPEVAL;
11018 * Take commands from a file. To be compatible we should do a path
11019 * search for the file, which is necessary to find sub-commands.
11022 find_dot_file(char *name)
11025 const char *path = pathval();
11028 /* don't try this for absolute or relative paths */
11029 if (strchr(name, '/'))
11032 while ((fullname = padvance(&path, name)) != NULL) {
11033 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11035 * Don't bother freeing here, since it will
11036 * be freed by the caller.
11040 stunalloc(fullname);
11043 /* not found in the PATH */
11044 ash_msg_and_raise_error("%s: not found", name);
11049 dotcmd(int argc, char **argv)
11051 struct strlist *sp;
11052 volatile struct shparam saveparam;
11055 for (sp = cmdenviron; sp; sp = sp->next)
11056 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11058 if (argc >= 2) { /* That's what SVR2 does */
11061 fullname = find_dot_file(argv[1]);
11064 saveparam = shellparam;
11065 shellparam.malloced = 0;
11066 shellparam.nparam = argc - 2;
11067 shellparam.p = argv + 2;
11070 setinputfile(fullname, INPUT_PUSH_FILE);
11071 commandname = fullname;
11076 freeparam(&shellparam);
11077 shellparam = saveparam;
11079 status = exitstatus;
11085 exitcmd(int argc, char **argv)
11090 exitstatus = number(argv[1]);
11091 raise_exception(EXEXIT);
11095 #if ENABLE_ASH_BUILTIN_ECHO
11097 echocmd(int argc, char **argv)
11099 return echo_main(argc, argv);
11103 #if ENABLE_ASH_BUILTIN_TEST
11105 testcmd(int argc, char **argv)
11107 return test_main(argc, argv);
11112 * Read a file containing shell functions.
11115 readcmdfile(char *name)
11117 setinputfile(name, INPUT_PUSH_FILE);
11123 /* ============ find_command inplementation */
11126 * Resolve a command name. If you change this routine, you may have to
11127 * change the shellexec routine as well.
11130 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11132 struct tblentry *cmdp;
11139 struct builtincmd *bcmd;
11141 /* If name contains a slash, don't use PATH or hash table */
11142 if (strchr(name, '/') != NULL) {
11143 entry->u.index = -1;
11144 if (act & DO_ABS) {
11145 while (stat(name, &statb) < 0) {
11147 if (errno == EINTR)
11150 entry->cmdtype = CMDUNKNOWN;
11154 entry->cmdtype = CMDNORMAL;
11158 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11160 updatetbl = (path == pathval());
11163 if (strstr(path, "%builtin") != NULL)
11164 act |= DO_ALTBLTIN;
11167 /* If name is in the table, check answer will be ok */
11168 cmdp = cmdlookup(name, 0);
11169 if (cmdp != NULL) {
11172 switch (cmdp->cmdtype) {
11190 } else if (cmdp->rehash == 0)
11191 /* if not invalidated by cd, we're done */
11195 /* If %builtin not in path, check for builtin next */
11196 bcmd = find_builtin(name);
11198 if (IS_BUILTIN_REGULAR(bcmd))
11199 goto builtin_success;
11200 if (act & DO_ALTPATH) {
11201 if (!(act & DO_ALTBLTIN))
11202 goto builtin_success;
11203 } else if (builtinloc <= 0) {
11204 goto builtin_success;
11208 #if ENABLE_FEATURE_SH_STANDALONE
11209 if (find_applet_by_name(name) >= 0) {
11210 entry->cmdtype = CMDNORMAL;
11211 entry->u.index = -1;
11216 /* We have to search path. */
11217 prev = -1; /* where to start */
11218 if (cmdp && cmdp->rehash) { /* doing a rehash */
11219 if (cmdp->cmdtype == CMDBUILTIN)
11222 prev = cmdp->param.index;
11228 while ((fullname = padvance(&path, name)) != NULL) {
11229 stunalloc(fullname);
11230 /* NB: code below will still use fullname
11231 * despite it being "unallocated" */
11234 if (prefix(pathopt, "builtin")) {
11236 goto builtin_success;
11238 } else if (!(act & DO_NOFUNC)
11239 && prefix(pathopt, "func")) {
11240 /* handled below */
11242 /* ignore unimplemented options */
11246 /* if rehash, don't redo absolute path names */
11247 if (fullname[0] == '/' && idx <= prev) {
11250 TRACE(("searchexec \"%s\": no change\n", name));
11253 while (stat(fullname, &statb) < 0) {
11255 if (errno == EINTR)
11258 if (errno != ENOENT && errno != ENOTDIR)
11262 e = EACCES; /* if we fail, this will be the error */
11263 if (!S_ISREG(statb.st_mode))
11265 if (pathopt) { /* this is a %func directory */
11266 stalloc(strlen(fullname) + 1);
11267 /* NB: stalloc will return space pointed by fullname
11268 * (because we don't have any intervening allocations
11269 * between stunalloc above and this stalloc) */
11270 readcmdfile(fullname);
11271 cmdp = cmdlookup(name, 0);
11272 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11273 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11274 stunalloc(fullname);
11277 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11279 entry->cmdtype = CMDNORMAL;
11280 entry->u.index = idx;
11284 cmdp = cmdlookup(name, 1);
11285 cmdp->cmdtype = CMDNORMAL;
11286 cmdp->param.index = idx;
11291 /* We failed. If there was an entry for this command, delete it */
11292 if (cmdp && updatetbl)
11293 delete_cmd_entry();
11295 ash_msg("%s: %s", name, errmsg(e, "not found"));
11296 entry->cmdtype = CMDUNKNOWN;
11301 entry->cmdtype = CMDBUILTIN;
11302 entry->u.cmd = bcmd;
11306 cmdp = cmdlookup(name, 1);
11307 cmdp->cmdtype = CMDBUILTIN;
11308 cmdp->param.cmd = bcmd;
11312 entry->cmdtype = cmdp->cmdtype;
11313 entry->u = cmdp->param;
11317 /* ============ trap.c */
11320 * The trap builtin.
11323 trapcmd(int argc, char **argv)
11332 for (signo = 0; signo < NSIG; signo++) {
11333 if (trap[signo] != NULL) {
11336 sn = get_signame(signo);
11337 out1fmt("trap -- %s %s\n",
11338 single_quote(trap[signo]), sn);
11348 signo = get_signum(*ap);
11350 ash_msg_and_raise_error("%s: bad trap", *ap);
11353 if (LONE_DASH(action))
11356 action = ckstrdup(action);
11359 trap[signo] = action;
11369 /* ============ Builtins */
11371 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11373 * Lists available builtins
11376 helpcmd(int argc, char **argv)
11380 out1fmt("\nBuilt-in commands:\n-------------------\n");
11381 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11382 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11383 builtintab[i].name + 1);
11389 #if ENABLE_FEATURE_SH_STANDALONE
11391 const char *a = applet_names;
11393 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11398 a += strlen(a) + 1;
11403 return EXIT_SUCCESS;
11405 #endif /* FEATURE_SH_EXTRA_QUIET */
11408 * The export and readonly commands.
11411 exportcmd(int argc, char **argv)
11417 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11419 if (nextopt("p") != 'p') {
11424 p = strchr(name, '=');
11428 vp = *findvar(hashvar(name), name);
11434 setvar(name, p, flag);
11435 } while ((name = *++aptr) != NULL);
11439 showvars(argv[0], flag, 0);
11444 * Delete a function if it exists.
11447 unsetfunc(const char *name)
11449 struct tblentry *cmdp;
11451 cmdp = cmdlookup(name, 0);
11452 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11453 delete_cmd_entry();
11457 * The unset builtin command. We unset the function before we unset the
11458 * variable to allow a function to be unset when there is a readonly variable
11459 * with the same name.
11462 unsetcmd(int argc, char **argv)
11469 while ((i = nextopt("vf")) != '\0') {
11473 for (ap = argptr; *ap; ap++) {
11489 #include <sys/times.h>
11491 static const unsigned char timescmd_str[] ALIGN1 = {
11492 ' ', offsetof(struct tms, tms_utime),
11493 '\n', offsetof(struct tms, tms_stime),
11494 ' ', offsetof(struct tms, tms_cutime),
11495 '\n', offsetof(struct tms, tms_cstime),
11500 timescmd(int ac, char **av)
11502 long clk_tck, s, t;
11503 const unsigned char *p;
11506 clk_tck = sysconf(_SC_CLK_TCK);
11511 t = *(clock_t *)(((char *) &buf) + p[1]);
11513 out1fmt("%ldm%ld.%.3lds%c",
11515 ((t - s * clk_tck) * 1000) / clk_tck,
11517 } while (*(p += 2));
11522 #if ENABLE_ASH_MATH_SUPPORT
11524 dash_arith(const char *s)
11530 result = arith(s, &errcode);
11533 ash_msg_and_raise_error("exponent less than 0");
11535 ash_msg_and_raise_error("divide by zero");
11537 ash_msg_and_raise_error("expression recursion loop detected");
11538 raise_error_syntax(s);
11546 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11547 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11549 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11552 letcmd(int argc, char **argv)
11559 ash_msg_and_raise_error("expression expected");
11560 for (ap = argv + 1; *ap; ap++) {
11561 i = dash_arith(*ap);
11566 #endif /* ASH_MATH_SUPPORT */
11569 /* ============ miscbltin.c
11571 * Miscellaneous builtins.
11576 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11577 typedef enum __rlimit_resource rlim_t;
11581 * The read builtin. The -e option causes backslashes to escape the
11582 * following character.
11584 * This uses unbuffered input, which may be avoidable in some cases.
11587 readcmd(int argc, char **argv)
11599 #if ENABLE_ASH_READ_NCHARS
11603 struct termios tty, old_tty;
11605 #if ENABLE_ASH_READ_TIMEOUT
11609 ts.tv_sec = ts.tv_usec = 0;
11614 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11615 while ((i = nextopt("p:rt:n:s")) != '\0')
11616 #elif ENABLE_ASH_READ_NCHARS
11617 while ((i = nextopt("p:rn:s")) != '\0')
11618 #elif ENABLE_ASH_READ_TIMEOUT
11619 while ((i = nextopt("p:rt:")) != '\0')
11621 while ((i = nextopt("p:r")) != '\0')
11626 prompt = optionarg;
11628 #if ENABLE_ASH_READ_NCHARS
11630 nchars = bb_strtou(optionarg, NULL, 10);
11631 if (nchars < 0 || errno)
11632 ash_msg_and_raise_error("invalid count");
11633 n_flag = nchars; /* just a flag "nchars is nonzero" */
11639 #if ENABLE_ASH_READ_TIMEOUT
11641 ts.tv_sec = bb_strtou(optionarg, &p, 10);
11643 /* EINVAL means number is ok, but not terminated by NUL */
11644 if (*p == '.' && errno == EINVAL) {
11648 ts.tv_usec = bb_strtou(p, &p2, 10);
11650 ash_msg_and_raise_error("invalid timeout");
11652 /* normalize to usec */
11654 ash_msg_and_raise_error("invalid timeout");
11655 while (scale++ < 6)
11658 } else if (ts.tv_sec < 0 || errno) {
11659 ash_msg_and_raise_error("invalid timeout");
11661 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
11662 ash_msg_and_raise_error("invalid timeout");
11673 if (prompt && isatty(0)) {
11678 ash_msg_and_raise_error("arg count");
11679 ifs = bltinlookup("IFS");
11682 #if ENABLE_ASH_READ_NCHARS
11683 if (n_flag || silent) {
11684 if (tcgetattr(0, &tty) != 0) {
11691 tty.c_lflag &= ~ICANON;
11692 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
11695 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
11697 tcsetattr(0, TCSANOW, &tty);
11701 #if ENABLE_ASH_READ_TIMEOUT
11702 if (ts.tv_sec || ts.tv_usec) {
11706 /* poll-based wait produces bigger code, using select */
11707 i = select(1, &set, NULL, NULL, &ts);
11708 if (!i) { /* timed out! */
11709 #if ENABLE_ASH_READ_NCHARS
11711 tcsetattr(0, TCSANOW, &old_tty);
11722 if (read(0, &c, 1) != 1) {
11734 if (!rflag && c == '\\') {
11740 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11744 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11746 setvar(*ap, stackblock(), 0);
11755 /* end of do {} while: */
11756 #if ENABLE_ASH_READ_NCHARS
11757 while (!n_flag || --nchars);
11762 #if ENABLE_ASH_READ_NCHARS
11763 if (n_flag || silent)
11764 tcsetattr(0, TCSANOW, &old_tty);
11768 /* Remove trailing blanks */
11769 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11771 setvar(*ap, stackblock(), 0);
11772 while (*++ap != NULL)
11773 setvar(*ap, nullstr, 0);
11778 umaskcmd(int argc, char **argv)
11780 static const char permuser[3] ALIGN1 = "ugo";
11781 static const char permmode[3] ALIGN1 = "rwx";
11782 static const short permmask[] ALIGN2 = {
11783 S_IRUSR, S_IWUSR, S_IXUSR,
11784 S_IRGRP, S_IWGRP, S_IXGRP,
11785 S_IROTH, S_IWOTH, S_IXOTH
11791 int symbolic_mode = 0;
11793 while (nextopt("S") != '\0') {
11804 if (symbolic_mode) {
11808 for (i = 0; i < 3; i++) {
11811 *p++ = permuser[i];
11813 for (j = 0; j < 3; j++) {
11814 if ((mask & permmask[3 * i + j]) == 0) {
11815 *p++ = permmode[j];
11823 out1fmt("%.4o\n", mask);
11826 if (isdigit((unsigned char) *ap)) {
11829 if (*ap >= '8' || *ap < '0')
11830 ash_msg_and_raise_error(illnum, argv[1]);
11831 mask = (mask << 3) + (*ap - '0');
11832 } while (*++ap != '\0');
11835 mask = ~mask & 0777;
11836 if (!bb_parse_mode(ap, &mask)) {
11837 ash_msg_and_raise_error("illegal mode: %s", ap);
11839 umask(~mask & 0777);
11848 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11849 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11850 * ash by J.T. Conklin.
11856 uint8_t cmd; /* RLIMIT_xxx fit into it */
11857 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
11861 static const struct limits limits_tbl[] = {
11863 { RLIMIT_CPU, 0, 't' },
11865 #ifdef RLIMIT_FSIZE
11866 { RLIMIT_FSIZE, 9, 'f' },
11869 { RLIMIT_DATA, 10, 'd' },
11871 #ifdef RLIMIT_STACK
11872 { RLIMIT_STACK, 10, 's' },
11875 { RLIMIT_CORE, 9, 'c' },
11878 { RLIMIT_RSS, 10, 'm' },
11880 #ifdef RLIMIT_MEMLOCK
11881 { RLIMIT_MEMLOCK, 10, 'l' },
11883 #ifdef RLIMIT_NPROC
11884 { RLIMIT_NPROC, 0, 'p' },
11886 #ifdef RLIMIT_NOFILE
11887 { RLIMIT_NOFILE, 0, 'n' },
11890 { RLIMIT_AS, 10, 'v' },
11892 #ifdef RLIMIT_LOCKS
11893 { RLIMIT_LOCKS, 0, 'w' },
11896 static const char limits_name[] =
11898 "time(seconds)" "\0"
11900 #ifdef RLIMIT_FSIZE
11901 "file(blocks)" "\0"
11906 #ifdef RLIMIT_STACK
11910 "coredump(blocks)" "\0"
11915 #ifdef RLIMIT_MEMLOCK
11916 "locked memory(kb)" "\0"
11918 #ifdef RLIMIT_NPROC
11921 #ifdef RLIMIT_NOFILE
11927 #ifdef RLIMIT_LOCKS
11932 enum limtype { SOFT = 0x1, HARD = 0x2 };
11935 printlim(enum limtype how, const struct rlimit *limit,
11936 const struct limits *l)
11940 val = limit->rlim_max;
11942 val = limit->rlim_cur;
11944 if (val == RLIM_INFINITY)
11945 out1fmt("unlimited\n");
11947 val >>= l->factor_shift;
11948 out1fmt("%lld\n", (long long) val);
11953 ulimitcmd(int argc, char **argv)
11957 enum limtype how = SOFT | HARD;
11958 const struct limits *l;
11961 struct rlimit limit;
11964 while ((optc = nextopt("HSa"
11968 #ifdef RLIMIT_FSIZE
11974 #ifdef RLIMIT_STACK
11983 #ifdef RLIMIT_MEMLOCK
11986 #ifdef RLIMIT_NPROC
11989 #ifdef RLIMIT_NOFILE
11995 #ifdef RLIMIT_LOCKS
12013 for (l = limits_tbl; l->option != what; l++)
12016 set = *argptr ? 1 : 0;
12020 if (all || argptr[1])
12021 ash_msg_and_raise_error("too many arguments");
12022 if (strncmp(p, "unlimited\n", 9) == 0)
12023 val = RLIM_INFINITY;
12027 while ((c = *p++) >= '0' && c <= '9') {
12028 val = (val * 10) + (long)(c - '0');
12029 if (val < (rlim_t) 0)
12033 ash_msg_and_raise_error("bad number");
12034 val <<= l->factor_shift;
12038 const char *lname = limits_name;
12039 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12040 getrlimit(l->cmd, &limit);
12041 out1fmt("%-20s ", lname);
12042 lname += strlen(lname) + 1;
12043 printlim(how, &limit, l);
12048 getrlimit(l->cmd, &limit);
12051 limit.rlim_max = val;
12053 limit.rlim_cur = val;
12054 if (setrlimit(l->cmd, &limit) < 0)
12055 ash_msg_and_raise_error("error setting limit (%m)");
12057 printlim(how, &limit, l);
12063 /* ============ Math support */
12065 #if ENABLE_ASH_MATH_SUPPORT
12067 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12069 Permission is hereby granted, free of charge, to any person obtaining
12070 a copy of this software and associated documentation files (the
12071 "Software"), to deal in the Software without restriction, including
12072 without limitation the rights to use, copy, modify, merge, publish,
12073 distribute, sublicense, and/or sell copies of the Software, and to
12074 permit persons to whom the Software is furnished to do so, subject to
12075 the following conditions:
12077 The above copyright notice and this permission notice shall be
12078 included in all copies or substantial portions of the Software.
12080 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12081 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12082 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12083 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12084 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12085 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12086 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12089 /* This is my infix parser/evaluator. It is optimized for size, intended
12090 * as a replacement for yacc-based parsers. However, it may well be faster
12091 * than a comparable parser written in yacc. The supported operators are
12092 * listed in #defines below. Parens, order of operations, and error handling
12093 * are supported. This code is thread safe. The exact expression format should
12094 * be that which POSIX specifies for shells. */
12096 /* The code uses a simple two-stack algorithm. See
12097 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12098 * for a detailed explanation of the infix-to-postfix algorithm on which
12099 * this is based (this code differs in that it applies operators immediately
12100 * to the stack instead of adding them to a queue to end up with an
12103 /* To use the routine, call it with an expression string and error return
12107 * Aug 24, 2001 Manuel Novoa III
12109 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12111 * 1) In arith_apply():
12112 * a) Cached values of *numptr and &(numptr[-1]).
12113 * b) Removed redundant test for zero denominator.
12116 * a) Eliminated redundant code for processing operator tokens by moving
12117 * to a table-based implementation. Also folded handling of parens
12119 * b) Combined all 3 loops which called arith_apply to reduce generated
12120 * code size at the cost of speed.
12122 * 3) The following expressions were treated as valid by the original code:
12123 * 1() , 0! , 1 ( *3 ) .
12124 * These bugs have been fixed by internally enclosing the expression in
12125 * parens and then checking that all binary ops and right parens are
12126 * preceded by a valid expression (NUM_TOKEN).
12128 * Note: It may be desirable to replace Aaron's test for whitespace with
12129 * ctype's isspace() if it is used by another busybox applet or if additional
12130 * whitespace chars should be considered. Look below the "#include"s for a
12131 * precompiler test.
12135 * Aug 26, 2001 Manuel Novoa III
12137 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12139 * Merge in Aaron's comments previously posted to the busybox list,
12140 * modified slightly to take account of my changes to the code.
12145 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12147 * - allow access to variable,
12148 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12149 * - realize assign syntax (VAR=expr, +=, *= etc)
12150 * - realize exponentiation (** operator)
12151 * - realize comma separated - expr, expr
12152 * - realise ++expr --expr expr++ expr--
12153 * - realise expr ? expr : expr (but, second expr calculate always)
12154 * - allow hexadecimal and octal numbers
12155 * - was restored loses XOR operator
12156 * - remove one goto label, added three ;-)
12157 * - protect $((num num)) as true zero expr (Manuel`s error)
12158 * - always use special isspace(), see comment from bash ;-)
12161 #define arith_isspace(arithval) \
12162 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12164 typedef unsigned char operator;
12166 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12167 * precedence, and 3 high bits are an ID unique across operators of that
12168 * precedence. The ID portion is so that multiple operators can have the
12169 * same precedence, ensuring that the leftmost one is evaluated first.
12170 * Consider * and /. */
12172 #define tok_decl(prec,id) (((id)<<5)|(prec))
12173 #define PREC(op) ((op) & 0x1F)
12175 #define TOK_LPAREN tok_decl(0,0)
12177 #define TOK_COMMA tok_decl(1,0)
12179 #define TOK_ASSIGN tok_decl(2,0)
12180 #define TOK_AND_ASSIGN tok_decl(2,1)
12181 #define TOK_OR_ASSIGN tok_decl(2,2)
12182 #define TOK_XOR_ASSIGN tok_decl(2,3)
12183 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12184 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12185 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12186 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12188 #define TOK_MUL_ASSIGN tok_decl(3,0)
12189 #define TOK_DIV_ASSIGN tok_decl(3,1)
12190 #define TOK_REM_ASSIGN tok_decl(3,2)
12192 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12193 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12195 /* conditional is right associativity too */
12196 #define TOK_CONDITIONAL tok_decl(4,0)
12197 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12199 #define TOK_OR tok_decl(5,0)
12201 #define TOK_AND tok_decl(6,0)
12203 #define TOK_BOR tok_decl(7,0)
12205 #define TOK_BXOR tok_decl(8,0)
12207 #define TOK_BAND tok_decl(9,0)
12209 #define TOK_EQ tok_decl(10,0)
12210 #define TOK_NE tok_decl(10,1)
12212 #define TOK_LT tok_decl(11,0)
12213 #define TOK_GT tok_decl(11,1)
12214 #define TOK_GE tok_decl(11,2)
12215 #define TOK_LE tok_decl(11,3)
12217 #define TOK_LSHIFT tok_decl(12,0)
12218 #define TOK_RSHIFT tok_decl(12,1)
12220 #define TOK_ADD tok_decl(13,0)
12221 #define TOK_SUB tok_decl(13,1)
12223 #define TOK_MUL tok_decl(14,0)
12224 #define TOK_DIV tok_decl(14,1)
12225 #define TOK_REM tok_decl(14,2)
12227 /* exponent is right associativity */
12228 #define TOK_EXPONENT tok_decl(15,1)
12230 /* For now unary operators. */
12231 #define UNARYPREC 16
12232 #define TOK_BNOT tok_decl(UNARYPREC,0)
12233 #define TOK_NOT tok_decl(UNARYPREC,1)
12235 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12236 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12238 #define PREC_PRE (UNARYPREC+2)
12240 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12241 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12243 #define PREC_POST (UNARYPREC+3)
12245 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12246 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12248 #define SPEC_PREC (UNARYPREC+4)
12250 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12251 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12253 #define NUMPTR (*numstackptr)
12256 tok_have_assign(operator op)
12258 operator prec = PREC(op);
12260 convert_prec_is_assing(prec);
12261 return (prec == PREC(TOK_ASSIGN) ||
12262 prec == PREC_PRE || prec == PREC_POST);
12266 is_right_associativity(operator prec)
12268 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12269 || prec == PREC(TOK_CONDITIONAL));
12272 typedef struct ARITCH_VAR_NUM {
12274 arith_t contidional_second_val;
12275 char contidional_second_val_initialized;
12276 char *var; /* if NULL then is regular number,
12277 else is variable name */
12280 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12282 struct CHK_VAR_RECURSIVE_LOOPED *next;
12283 } chk_var_recursive_looped_t;
12285 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12288 arith_lookup_val(v_n_t *t)
12291 const char * p = lookupvar(t->var);
12296 /* recursive try as expression */
12297 chk_var_recursive_looped_t *cur;
12298 chk_var_recursive_looped_t cur_save;
12300 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12301 if (strcmp(cur->var, t->var) == 0) {
12302 /* expression recursion loop detected */
12306 /* save current lookuped var name */
12307 cur = prev_chk_var_recursive;
12308 cur_save.var = t->var;
12309 cur_save.next = cur;
12310 prev_chk_var_recursive = &cur_save;
12312 t->val = arith (p, &errcode);
12313 /* restore previous ptr after recursiving */
12314 prev_chk_var_recursive = cur;
12317 /* allow undefined var as 0 */
12323 /* "applying" a token means performing it on the top elements on the integer
12324 * stack. For a unary operator it will only change the top element, but a
12325 * binary operator will pop two arguments and push a result */
12327 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12330 arith_t numptr_val, rez;
12331 int ret_arith_lookup_val;
12333 /* There is no operator that can work without arguments */
12334 if (NUMPTR == numstack) goto err;
12335 numptr_m1 = NUMPTR - 1;
12337 /* check operand is var with noninteger value */
12338 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12339 if (ret_arith_lookup_val)
12340 return ret_arith_lookup_val;
12342 rez = numptr_m1->val;
12343 if (op == TOK_UMINUS)
12345 else if (op == TOK_NOT)
12347 else if (op == TOK_BNOT)
12349 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12351 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12353 else if (op != TOK_UPLUS) {
12354 /* Binary operators */
12356 /* check and binary operators need two arguments */
12357 if (numptr_m1 == numstack) goto err;
12359 /* ... and they pop one */
12362 if (op == TOK_CONDITIONAL) {
12363 if (! numptr_m1->contidional_second_val_initialized) {
12364 /* protect $((expr1 ? expr2)) without ": expr" */
12367 rez = numptr_m1->contidional_second_val;
12368 } else if (numptr_m1->contidional_second_val_initialized) {
12369 /* protect $((expr1 : expr2)) without "expr ? " */
12372 numptr_m1 = NUMPTR - 1;
12373 if (op != TOK_ASSIGN) {
12374 /* check operand is var with noninteger value for not '=' */
12375 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12376 if (ret_arith_lookup_val)
12377 return ret_arith_lookup_val;
12379 if (op == TOK_CONDITIONAL) {
12380 numptr_m1->contidional_second_val = rez;
12382 rez = numptr_m1->val;
12383 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12385 else if (op == TOK_OR)
12386 rez = numptr_val || rez;
12387 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12389 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12391 else if (op == TOK_AND)
12392 rez = rez && numptr_val;
12393 else if (op == TOK_EQ)
12394 rez = (rez == numptr_val);
12395 else if (op == TOK_NE)
12396 rez = (rez != numptr_val);
12397 else if (op == TOK_GE)
12398 rez = (rez >= numptr_val);
12399 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12400 rez >>= numptr_val;
12401 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12402 rez <<= numptr_val;
12403 else if (op == TOK_GT)
12404 rez = (rez > numptr_val);
12405 else if (op == TOK_LT)
12406 rez = (rez < numptr_val);
12407 else if (op == TOK_LE)
12408 rez = (rez <= numptr_val);
12409 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12411 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12413 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12415 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12417 else if (op == TOK_CONDITIONAL_SEP) {
12418 if (numptr_m1 == numstack) {
12419 /* protect $((expr : expr)) without "expr ? " */
12422 numptr_m1->contidional_second_val_initialized = op;
12423 numptr_m1->contidional_second_val = numptr_val;
12424 } else if (op == TOK_CONDITIONAL) {
12426 numptr_val : numptr_m1->contidional_second_val;
12427 } else if (op == TOK_EXPONENT) {
12428 if (numptr_val < 0)
12429 return -3; /* exponent less than 0 */
12434 while (numptr_val--)
12438 } else if (numptr_val==0) /* zero divisor check */
12440 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12442 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12445 if (tok_have_assign(op)) {
12446 char buf[sizeof(arith_t_type)*3 + 2];
12448 if (numptr_m1->var == NULL) {
12452 /* save to shell variable */
12453 #if ENABLE_ASH_MATH_SUPPORT_64
12454 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12456 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12458 setvar(numptr_m1->var, buf, 0);
12459 /* after saving, make previous value for v++ or v-- */
12460 if (op == TOK_POST_INC)
12462 else if (op == TOK_POST_DEC)
12465 numptr_m1->val = rez;
12466 /* protect geting var value, is number now */
12467 numptr_m1->var = NULL;
12473 /* longest must be first */
12474 static const char op_tokens[] ALIGN1 = {
12475 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12476 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12477 '<','<', 0, TOK_LSHIFT,
12478 '>','>', 0, TOK_RSHIFT,
12479 '|','|', 0, TOK_OR,
12480 '&','&', 0, TOK_AND,
12481 '!','=', 0, TOK_NE,
12482 '<','=', 0, TOK_LE,
12483 '>','=', 0, TOK_GE,
12484 '=','=', 0, TOK_EQ,
12485 '|','=', 0, TOK_OR_ASSIGN,
12486 '&','=', 0, TOK_AND_ASSIGN,
12487 '*','=', 0, TOK_MUL_ASSIGN,
12488 '/','=', 0, TOK_DIV_ASSIGN,
12489 '%','=', 0, TOK_REM_ASSIGN,
12490 '+','=', 0, TOK_PLUS_ASSIGN,
12491 '-','=', 0, TOK_MINUS_ASSIGN,
12492 '-','-', 0, TOK_POST_DEC,
12493 '^','=', 0, TOK_XOR_ASSIGN,
12494 '+','+', 0, TOK_POST_INC,
12495 '*','*', 0, TOK_EXPONENT,
12499 '=', 0, TOK_ASSIGN,
12511 '?', 0, TOK_CONDITIONAL,
12512 ':', 0, TOK_CONDITIONAL_SEP,
12513 ')', 0, TOK_RPAREN,
12514 '(', 0, TOK_LPAREN,
12518 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12521 arith(const char *expr, int *perrcode)
12523 char arithval; /* Current character under analysis */
12524 operator lasttok, op;
12527 const char *p = endexpression;
12530 size_t datasizes = strlen(expr) + 2;
12532 /* Stack of integers */
12533 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12534 * in any given correct or incorrect expression is left as an exercise to
12536 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12537 *numstackptr = numstack;
12538 /* Stack of operator tokens */
12539 operator *stack = alloca((datasizes) * sizeof(operator)),
12542 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12543 *perrcode = errcode = 0;
12547 if (arithval == 0) {
12548 if (p == endexpression) {
12549 /* Null expression. */
12553 /* This is only reached after all tokens have been extracted from the
12554 * input stream. If there are still tokens on the operator stack, they
12555 * are to be applied in order. At the end, there should be a final
12556 * result on the integer stack */
12558 if (expr != endexpression + 1) {
12559 /* If we haven't done so already, */
12560 /* append a closing right paren */
12561 expr = endexpression;
12562 /* and let the loop process it. */
12565 /* At this point, we're done with the expression. */
12566 if (numstackptr != numstack+1) {
12567 /* ... but if there isn't, it's bad */
12569 return (*perrcode = -1);
12571 if (numstack->var) {
12572 /* expression is $((var)) only, lookup now */
12573 errcode = arith_lookup_val(numstack);
12576 *perrcode = errcode;
12577 return numstack->val;
12580 /* Continue processing the expression. */
12581 if (arith_isspace(arithval)) {
12582 /* Skip whitespace */
12585 p = endofname(expr);
12587 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12589 numstackptr->var = alloca(var_name_size);
12590 safe_strncpy(numstackptr->var, expr, var_name_size);
12593 numstackptr->contidional_second_val_initialized = 0;
12598 if (isdigit(arithval)) {
12599 numstackptr->var = NULL;
12600 #if ENABLE_ASH_MATH_SUPPORT_64
12601 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12603 numstackptr->val = strtol(expr, (char **) &expr, 0);
12607 for (p = op_tokens; ; p++) {
12611 /* strange operator not found */
12614 for (o = expr; *p && *o == *p; p++)
12621 /* skip tail uncompared token */
12624 /* skip zero delim */
12629 /* post grammar: a++ reduce to num */
12630 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12633 /* Plus and minus are binary (not unary) _only_ if the last
12634 * token was as number, or a right paren (which pretends to be
12635 * a number, since it evaluates to one). Think about it.
12636 * It makes sense. */
12637 if (lasttok != TOK_NUM) {
12653 /* We don't want a unary operator to cause recursive descent on the
12654 * stack, because there can be many in a row and it could cause an
12655 * operator to be evaluated before its argument is pushed onto the
12656 * integer stack. */
12657 /* But for binary operators, "apply" everything on the operator
12658 * stack until we find an operator with a lesser priority than the
12659 * one we have just extracted. */
12660 /* Left paren is given the lowest priority so it will never be
12661 * "applied" in this way.
12662 * if associativity is right and priority eq, applied also skip
12665 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12666 /* not left paren or unary */
12667 if (lasttok != TOK_NUM) {
12668 /* binary op must be preceded by a num */
12671 while (stackptr != stack) {
12672 if (op == TOK_RPAREN) {
12673 /* The algorithm employed here is simple: while we don't
12674 * hit an open paren nor the bottom of the stack, pop
12675 * tokens and apply them */
12676 if (stackptr[-1] == TOK_LPAREN) {
12678 /* Any operator directly after a */
12680 /* close paren should consider itself binary */
12684 operator prev_prec = PREC(stackptr[-1]);
12686 convert_prec_is_assing(prec);
12687 convert_prec_is_assing(prev_prec);
12688 if (prev_prec < prec)
12690 /* check right assoc */
12691 if (prev_prec == prec && is_right_associativity(prec))
12694 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12695 if (errcode) goto ret;
12697 if (op == TOK_RPAREN) {
12702 /* Push this operator to the stack and remember it. */
12703 *stackptr++ = lasttok = op;
12708 #endif /* ASH_MATH_SUPPORT */
12711 /* ============ main() and helpers */
12714 * Called to exit the shell.
12716 static void exitshell(void) ATTRIBUTE_NORETURN;
12724 status = exitstatus;
12725 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12726 if (setjmp(loc.loc)) {
12727 if (exception == EXEXIT)
12728 /* dash bug: it just does _exit(exitstatus) here
12729 * but we have to do setjobctl(0) first!
12730 * (bug is still not fixed in dash-0.5.3 - if you run dash
12731 * under Midnight Commander, on exit from dash MC is backgrounded) */
12732 status = exitstatus;
12735 exception_handler = &loc;
12741 flush_stdout_stderr();
12751 /* from input.c: */
12752 basepf.nextc = basepf.buf = basebuf;
12755 signal(SIGCHLD, SIG_DFL);
12760 char ppid[sizeof(int)*3 + 1];
12762 struct stat st1, st2;
12765 for (envp = environ; envp && *envp; envp++) {
12766 if (strchr(*envp, '=')) {
12767 setvareq(*envp, VEXPORT|VTEXTFIXED);
12771 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12772 setvar("PPID", ppid, 0);
12774 p = lookupvar("PWD");
12776 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12777 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12784 * Process the shell command line arguments.
12787 procargs(int argc, char **argv)
12790 const char *xminusc;
12797 for (i = 0; i < NOPTS; i++)
12803 if (*xargv == NULL) {
12805 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12808 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12812 for (i = 0; i < NOPTS; i++)
12813 if (optlist[i] == 2)
12818 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12823 } else if (!sflag) {
12824 setinputfile(*xargv, 0);
12827 commandname = arg0;
12830 shellparam.p = xargv;
12831 #if ENABLE_ASH_GETOPTS
12832 shellparam.optind = 1;
12833 shellparam.optoff = -1;
12835 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12837 shellparam.nparam++;
12844 * Read /etc/profile or .profile.
12847 read_profile(const char *name)
12851 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12860 * This routine is called when an error or an interrupt occurs in an
12861 * interactive shell and control is returned to the main command loop.
12869 /* from input.c: */
12870 parselleft = parsenleft = 0; /* clear input buffer */
12872 /* from parser.c: */
12875 /* from redir.c: */
12880 static short profile_buf[16384];
12881 extern int etext();
12885 * Main routine. We initialize things, parse the arguments, execute
12886 * profiles if we're a login shell, and then call cmdloop to execute
12887 * commands. The setjmp call sets up the location to jump to when an
12888 * exception occurs. When an exception occurs the variable "state"
12889 * is used to figure out how far we had gotten.
12891 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12892 int ash_main(int argc, char **argv)
12895 volatile int state;
12896 struct jmploc jmploc;
12897 struct stackmark smark;
12899 /* Initialize global data */
12903 #if ENABLE_ASH_ALIAS
12909 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12912 #if ENABLE_FEATURE_EDITING
12913 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12916 if (setjmp(jmploc.loc)) {
12926 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12930 outcslow('\n', stderr);
12932 popstackmark(&smark);
12933 FORCE_INT_ON; /* enable interrupts */
12942 exception_handler = &jmploc;
12945 trace_puts("Shell args: ");
12946 trace_puts_args(argv);
12948 rootpid = getpid();
12950 #if ENABLE_ASH_RANDOM_SUPPORT
12951 rseed = rootpid + time(NULL);
12954 setstackmark(&smark);
12955 procargs(argc, argv);
12956 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12958 const char *hp = lookupvar("HISTFILE");
12961 hp = lookupvar("HOME");
12963 char *defhp = concat_path_file(hp, ".ash_history");
12964 setvar("HISTFILE", defhp, 0);
12970 if (argv[0] && argv[0][0] == '-')
12974 read_profile("/etc/profile");
12977 read_profile(".profile");
12983 getuid() == geteuid() && getgid() == getegid() &&
12987 shinit = lookupvar("ENV");
12988 if (shinit != NULL && *shinit != '\0') {
12989 read_profile(shinit);
12995 evalstring(minusc, 0);
12997 if (sflag || minusc == NULL) {
12998 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13000 const char *hp = lookupvar("HISTFILE");
13003 line_input_state->hist_file = hp;
13006 state4: /* XXX ??? - why isn't this before the "if" statement */
13014 extern void _mcleanup(void);
13023 const char *applet_name = "debug stuff usage";
13024 int main(int argc, char **argv)
13026 return ash_main(argc, argv);
13032 * Copyright (c) 1989, 1991, 1993, 1994
13033 * The Regents of the University of California. All rights reserved.
13035 * This code is derived from software contributed to Berkeley by
13036 * Kenneth Almquist.
13038 * Redistribution and use in source and binary forms, with or without
13039 * modification, are permitted provided that the following conditions
13041 * 1. Redistributions of source code must retain the above copyright
13042 * notice, this list of conditions and the following disclaimer.
13043 * 2. Redistributions in binary form must reproduce the above copyright
13044 * notice, this list of conditions and the following disclaimer in the
13045 * documentation and/or other materials provided with the distribution.
13046 * 3. Neither the name of the University nor the names of its contributors
13047 * may be used to endorse or promote products derived from this software
13048 * without specific prior written permission.
13050 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13051 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13052 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13053 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13054 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13055 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13056 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13057 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13058 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13059 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF