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 /* ============ Misc helpers */
72 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
74 /* C99 say: "char" declaration may be signed or unsigned default */
75 #define signed_char2int(sc) ((int)((signed char)sc))
78 /* ============ Shell options */
80 static const char *const optletters_optnames[] = {
101 #define optletters(n) optletters_optnames[(n)][0]
102 #define optnames(n) (&optletters_optnames[(n)][1])
104 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
106 static char optlist[NOPTS] ALIGN1;
108 #define eflag optlist[0]
109 #define fflag optlist[1]
110 #define Iflag optlist[2]
111 #define iflag optlist[3]
112 #define mflag optlist[4]
113 #define nflag optlist[5]
114 #define sflag optlist[6]
115 #define xflag optlist[7]
116 #define vflag optlist[8]
117 #define Cflag optlist[9]
118 #define aflag optlist[10]
119 #define bflag optlist[11]
120 #define uflag optlist[12]
121 #define viflag optlist[13]
123 #define nolog optlist[14]
124 #define debug optlist[15]
128 /* ============ Misc data */
130 static char nullstr[1] ALIGN1; /* zero length string */
131 static const char homestr[] ALIGN1 = "HOME";
132 static const char snlfmt[] ALIGN1 = "%s\n";
133 static const char illnum[] ALIGN1 = "Illegal number: %s";
135 static char *minusc; /* argument to -c option */
137 /* pid of main shell */
139 /* shell level: 0 for the main shell, 1 for its children, and so on */
141 #define rootshell (!shlvl)
142 /* trap handler commands */
143 static char *trap[NSIG];
144 static smallint isloginsh;
145 /* current value of signal */
146 static char sigmode[NSIG - 1];
147 /* indicates specified signal received */
148 static char gotsig[NSIG - 1];
149 static char *arg0; /* value of $0 */
152 /* ============ Interrupts / exceptions */
155 * We enclose jmp_buf in a structure so that we can declare pointers to
156 * jump locations. The global variable handler contains the location to
157 * jump to when an exception occurs, and the global variable exception
158 * contains a code identifying the exception. To implement nested
159 * exception handlers, the user should save the value of handler on entry
160 * to an inner scope, set handler to point to a jmploc structure for the
161 * inner scope, and restore handler on exit from the scope.
166 static struct jmploc *exception_handler;
167 static int exception;
169 #define EXINT 0 /* SIGINT received */
170 #define EXERROR 1 /* a generic error */
171 #define EXSHELLPROC 2 /* execute a shell procedure */
172 #define EXEXEC 3 /* command execution failed */
173 #define EXEXIT 4 /* exit the shell */
174 #define EXSIG 5 /* trapped signal in wait(1) */
175 static volatile int suppressint;
176 static volatile sig_atomic_t intpending;
177 /* do we generate EXSIG events */
179 /* last pending signal */
180 static volatile sig_atomic_t pendingsig;
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
188 #define S_DFL 1 /* default signal handling (SIG_DFL) */
189 #define S_CATCH 2 /* signal is caught */
190 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
191 #define S_HARD_IGN 4 /* signal is ignored permenantly */
192 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
195 * These macros allow the user to suspend the handling of interrupt signals
196 * over a period of time. This is similar to SIGHOLD to or sigblock, but
197 * much more efficient and portable. (But hacking the kernel is so much
198 * more fun than worrying about efficiency and portability. :-))
207 * Called to raise an exception. Since C doesn't include exceptions, we
208 * just do a longjmp to the exception handler. The type of exception is
209 * stored in the global variable "exception".
211 static void raise_exception(int) ATTRIBUTE_NORETURN;
213 raise_exception(int e)
216 if (exception_handler == NULL)
221 longjmp(exception_handler->loc, 1);
225 * Called from trap.c when a SIGINT is received. (If the user specifies
226 * that SIGINT is to be trapped or ignored using the trap builtin, then
227 * this routine is not called.) Suppressint is nonzero when interrupts
228 * are held using the INT_OFF macro. (The test for iflag is just
229 * defensive programming.)
231 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
233 raise_interrupt(void)
239 /* Signal is not automatically re-enabled after it is raised,
242 sigprocmask(SIG_SETMASK, &mask, 0);
243 /* pendingsig = 0; - now done in onsig() */
246 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
247 if (!(rootshell && iflag)) {
248 signal(SIGINT, SIG_DFL);
257 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
261 if (--suppressint == 0 && intpending) {
265 #define INT_ON int_on()
273 #define FORCE_INT_ON force_int_on()
278 if (--suppressint == 0 && intpending) \
281 #define FORCE_INT_ON \
288 #endif /* ASH_OPTIMIZE_FOR_SIZE */
290 #define SAVE_INT(v) ((v) = suppressint)
292 #define RESTORE_INT(v) \
296 if (suppressint == 0 && intpending) \
305 raise_exception(EXSIG); \
307 /* EXSIG is turned off by evalbltin(). */
310 * Ignore a signal. Only one usage site - in forkchild()
315 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
316 signal(signo, SIG_IGN);
318 sigmode[signo - 1] = S_HARD_IGN;
322 * Signal handler. Only one usage site - in setsignal()
327 gotsig[signo - 1] = 1;
330 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
340 /* ============ Stdout/stderr output */
343 outstr(const char *p, FILE *file)
351 flush_stdout_stderr(void)
368 outcslow(int c, FILE *dest)
376 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
378 out1fmt(const char *fmt, ...)
385 r = vprintf(fmt, ap);
391 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
393 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
400 ret = vsnprintf(outbuf, length, fmt, ap);
407 out1str(const char *p)
413 out2str(const char *p)
420 /* ============ Parser structures */
422 /* control characters in argument strings */
423 #define CTLESC '\201' /* escape next character */
424 #define CTLVAR '\202' /* variable defn */
425 #define CTLENDVAR '\203'
426 #define CTLBACKQ '\204'
427 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
428 /* CTLBACKQ | CTLQUOTE == '\205' */
429 #define CTLARI '\206' /* arithmetic expression */
430 #define CTLENDARI '\207'
431 #define CTLQUOTEMARK '\210'
433 /* variable substitution byte (follows CTLVAR) */
434 #define VSTYPE 0x0f /* type of variable substitution */
435 #define VSNUL 0x10 /* colon--treat the empty string as unset */
436 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
438 /* values of VSTYPE field */
439 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
440 #define VSMINUS 0x2 /* ${var-text} */
441 #define VSPLUS 0x3 /* ${var+text} */
442 #define VSQUESTION 0x4 /* ${var?message} */
443 #define VSASSIGN 0x5 /* ${var=text} */
444 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
445 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
446 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
447 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
448 #define VSLENGTH 0xa /* ${#var} */
450 static const char dolatstr[] ALIGN1 = {
451 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
487 union node *redirect;
493 struct nodelist *cmdlist;
499 union node *redirect;
512 union node *elsepart;
539 struct nodelist *backquote;
574 struct nredir nredir;
575 struct nbinary nbinary;
579 struct nclist nclist;
588 struct nodelist *next;
601 freefunc(struct funcnode *f)
603 if (f && --f->count < 0)
608 /* ============ Debugging output */
612 static FILE *tracefile;
615 trace_printf(const char *fmt, ...)
622 vfprintf(tracefile, fmt, va);
627 trace_vprintf(const char *fmt, va_list va)
631 vfprintf(tracefile, fmt, va);
635 trace_puts(const char *s)
643 trace_puts_quoted(char *s)
650 putc('"', tracefile);
651 for (p = s; *p; p++) {
653 case '\n': c = 'n'; goto backslash;
654 case '\t': c = 't'; goto backslash;
655 case '\r': c = 'r'; goto backslash;
656 case '"': c = '"'; goto backslash;
657 case '\\': c = '\\'; goto backslash;
658 case CTLESC: c = 'e'; goto backslash;
659 case CTLVAR: c = 'v'; goto backslash;
660 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
661 case CTLBACKQ: c = 'q'; goto backslash;
662 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
664 putc('\\', tracefile);
668 if (*p >= ' ' && *p <= '~')
671 putc('\\', tracefile);
672 putc(*p >> 6 & 03, tracefile);
673 putc(*p >> 3 & 07, tracefile);
674 putc(*p & 07, tracefile);
679 putc('"', tracefile);
683 trace_puts_args(char **ap)
690 trace_puts_quoted(*ap);
692 putc('\n', tracefile);
695 putc(' ', tracefile);
710 /* leave open because libedit might be using it */
713 strcpy(s, "./trace");
715 if (!freopen(s, "a", tracefile)) {
716 fprintf(stderr, "Can't re-open %s\n", s);
721 tracefile = fopen(s, "a");
722 if (tracefile == NULL) {
723 fprintf(stderr, "Can't open %s\n", s);
729 flags = fcntl(fileno(tracefile), F_GETFL);
731 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
733 setlinebuf(tracefile);
734 fputs("\nTracing started.\n", tracefile);
738 indent(int amount, char *pfx, FILE *fp)
742 for (i = 0; i < amount; i++) {
743 if (pfx && i == amount - 1)
749 /* little circular references here... */
750 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
753 sharg(union node *arg, FILE *fp)
756 struct nodelist *bqlist;
759 if (arg->type != NARG) {
760 out1fmt("<node type %d>\n", arg->type);
763 bqlist = arg->narg.backquote;
764 for (p = arg->narg.text; *p; p++) {
773 if (subtype == VSLENGTH)
782 switch (subtype & VSTYPE) {
815 out1fmt("<subtype %d>", subtype);
822 case CTLBACKQ|CTLQUOTE:
825 shtree(bqlist->n, -1, NULL, fp);
836 shcmd(union node *cmd, FILE *fp)
844 for (np = cmd->ncmd.args; np; np = np->narg.next) {
850 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
854 switch (np->nfile.type) {
855 case NTO: s = ">>"+1; dftfd = 1; break;
856 case NCLOBBER: s = ">|"; dftfd = 1; break;
857 case NAPPEND: s = ">>"; dftfd = 1; break;
858 case NTOFD: s = ">&"; dftfd = 1; break;
859 case NFROM: s = "<"; break;
860 case NFROMFD: s = "<&"; break;
861 case NFROMTO: s = "<>"; break;
862 default: s = "*error*"; break;
864 if (np->nfile.fd != dftfd)
865 fprintf(fp, "%d", np->nfile.fd);
867 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
868 fprintf(fp, "%d", np->ndup.dupfd);
870 sharg(np->nfile.fname, fp);
877 shtree(union node *n, int ind, char *pfx, FILE *fp)
885 indent(ind, pfx, fp);
896 shtree(n->nbinary.ch1, ind, NULL, fp);
899 shtree(n->nbinary.ch2, ind, NULL, fp);
907 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
912 if (n->npipe.backgnd)
918 fprintf(fp, "<node type %d>", n->type);
926 showtree(union node *n)
928 trace_puts("showtree called\n");
929 shtree(n, 1, NULL, stdout);
932 #define TRACE(param) trace_printf param
933 #define TRACEV(param) trace_vprintf param
938 #define TRACEV(param)
943 /* ============ Parser data */
946 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
949 struct strlist *next;
958 struct strpush *prev; /* preceding string on stack */
962 struct alias *ap; /* if push was associated with an alias */
964 char *string; /* remember the string since it may change */
968 struct parsefile *prev; /* preceding file on stack */
969 int linno; /* current line */
970 int fd; /* file descriptor (or -1 if string) */
971 int nleft; /* number of chars left in this line */
972 int lleft; /* number of chars left in this buffer */
973 char *nextc; /* next char in buffer */
974 char *buf; /* input buffer */
975 struct strpush *strpush; /* for pushing strings at this level */
976 struct strpush basestrpush; /* so pushing one is fast */
979 static struct parsefile basepf; /* top level input file */
980 static struct parsefile *parsefile = &basepf; /* current input file */
981 static int startlinno; /* line # where last token started */
982 static char *commandname; /* currently executing command */
983 static struct strlist *cmdenviron; /* environment for builtin command */
984 static int exitstatus; /* exit status of last command */
987 /* ============ Message printing */
990 ash_vmsg(const char *msg, va_list ap)
992 fprintf(stderr, "%s: ", arg0);
994 if (strcmp(arg0, commandname))
995 fprintf(stderr, "%s: ", commandname);
996 if (!iflag || parsefile->fd)
997 fprintf(stderr, "line %d: ", startlinno);
999 vfprintf(stderr, msg, ap);
1000 outcslow('\n', stderr);
1004 * Exverror is called to raise the error exception. If the second argument
1005 * is not NULL then error prints an error message using printf style
1006 * formatting. It then raises the error exception.
1008 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1010 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1014 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1016 TRACE(("\") pid=%d\n", getpid()));
1018 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1023 flush_stdout_stderr();
1024 raise_exception(cond);
1028 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1030 ash_msg_and_raise_error(const char *msg, ...)
1035 ash_vmsg_and_raise(EXERROR, msg, ap);
1040 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1042 ash_msg_and_raise(int cond, const char *msg, ...)
1047 ash_vmsg_and_raise(cond, msg, ap);
1053 * error/warning routines for external builtins
1056 ash_msg(const char *fmt, ...)
1066 * Return a string describing an error. The returned string may be a
1067 * pointer to a static buffer that will be overwritten on the next call.
1068 * Action describes the operation that got the error.
1071 errmsg(int e, const char *em)
1073 if (e == ENOENT || e == ENOTDIR) {
1080 /* ============ Memory allocation */
1083 * It appears that grabstackstr() will barf with such alignments
1084 * because stalloc() will return a string allocated in a new stackblock.
1086 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1088 /* Most machines require the value returned from malloc to be aligned
1089 * in some way. The following macro will get this right
1090 * on many machines. */
1091 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1092 /* Minimum size of a block */
1093 MINSIZE = SHELL_ALIGN(504),
1096 struct stack_block {
1097 struct stack_block *prev;
1098 char space[MINSIZE];
1102 struct stack_block *stackp;
1105 struct stackmark *marknext;
1108 static struct stack_block stackbase;
1109 static struct stack_block *stackp = &stackbase;
1110 static struct stackmark *markp;
1111 static char *stacknxt = stackbase.space;
1112 static size_t stacknleft = MINSIZE;
1113 static char *sstrend = stackbase.space + MINSIZE;
1114 static int herefd = -1;
1116 #define stackblock() ((void *)stacknxt)
1117 #define stackblocksize() stacknleft
1120 ckrealloc(void * p, size_t nbytes)
1122 p = realloc(p, nbytes);
1124 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1129 ckmalloc(size_t nbytes)
1131 return ckrealloc(NULL, nbytes);
1135 * Make a copy of a string in safe storage.
1138 ckstrdup(const char *s)
1140 char *p = strdup(s);
1142 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1147 * Parse trees for commands are allocated in lifo order, so we use a stack
1148 * to make this more efficient, and also to avoid all sorts of exception
1149 * handling code to handle interrupts in the middle of a parse.
1151 * The size 504 was chosen because the Ultrix malloc handles that size
1155 stalloc(size_t nbytes)
1160 aligned = SHELL_ALIGN(nbytes);
1161 if (aligned > stacknleft) {
1164 struct stack_block *sp;
1166 blocksize = aligned;
1167 if (blocksize < MINSIZE)
1168 blocksize = MINSIZE;
1169 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1170 if (len < blocksize)
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1175 stacknxt = sp->space;
1176 stacknleft = blocksize;
1177 sstrend = stacknxt + blocksize;
1182 stacknxt += aligned;
1183 stacknleft -= aligned;
1191 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1192 write(2, "stunalloc\n", 10);
1196 stacknleft += stacknxt - (char *)p;
1201 * Like strdup but works with the ash stack.
1204 ststrdup(const char *p)
1206 size_t len = strlen(p) + 1;
1207 return memcpy(stalloc(len), p, len);
1211 setstackmark(struct stackmark *mark)
1213 mark->stackp = stackp;
1214 mark->stacknxt = stacknxt;
1215 mark->stacknleft = stacknleft;
1216 mark->marknext = markp;
1221 popstackmark(struct stackmark *mark)
1223 struct stack_block *sp;
1229 markp = mark->marknext;
1230 while (stackp != mark->stackp) {
1235 stacknxt = mark->stacknxt;
1236 stacknleft = mark->stacknleft;
1237 sstrend = mark->stacknxt + mark->stacknleft;
1242 * When the parser reads in a string, it wants to stick the string on the
1243 * stack and only adjust the stack pointer when it knows how big the
1244 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1245 * of space on top of the stack and stackblocklen returns the length of
1246 * this block. Growstackblock will grow this space by at least one byte,
1247 * possibly moving it (like realloc). Grabstackblock actually allocates the
1248 * part of the block that has been used.
1251 growstackblock(void)
1255 newlen = stacknleft * 2;
1256 if (newlen < stacknleft)
1257 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1261 if (stacknxt == stackp->space && stackp != &stackbase) {
1262 struct stack_block *oldstackp;
1263 struct stackmark *xmark;
1264 struct stack_block *sp;
1265 struct stack_block *prevstackp;
1271 prevstackp = sp->prev;
1272 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1273 sp = ckrealloc(sp, grosslen);
1274 sp->prev = prevstackp;
1276 stacknxt = sp->space;
1277 stacknleft = newlen;
1278 sstrend = sp->space + newlen;
1281 * Stack marks pointing to the start of the old block
1282 * must be relocated to point to the new block
1285 while (xmark != NULL && xmark->stackp == oldstackp) {
1286 xmark->stackp = stackp;
1287 xmark->stacknxt = stacknxt;
1288 xmark->stacknleft = stacknleft;
1289 xmark = xmark->marknext;
1293 char *oldspace = stacknxt;
1294 int oldlen = stacknleft;
1295 char *p = stalloc(newlen);
1297 /* free the space we just allocated */
1298 stacknxt = memcpy(p, oldspace, oldlen);
1299 stacknleft += newlen;
1304 grabstackblock(size_t len)
1306 len = SHELL_ALIGN(len);
1312 * The following routines are somewhat easier to use than the above.
1313 * The user declares a variable of type STACKSTR, which may be declared
1314 * to be a register. The macro STARTSTACKSTR initializes things. Then
1315 * the user uses the macro STPUTC to add characters to the string. In
1316 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1317 * grown as necessary. When the user is done, she can just leave the
1318 * string there and refer to it using stackblock(). Or she can allocate
1319 * the space for it using grabstackstr(). If it is necessary to allow
1320 * someone else to use the stack temporarily and then continue to grow
1321 * the string, the user should use grabstack to allocate the space, and
1322 * then call ungrabstr(p) to return to the previous mode of operation.
1324 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1325 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1326 * is space for at least one character.
1331 size_t len = stackblocksize();
1332 if (herefd >= 0 && len >= 1024) {
1333 full_write(herefd, stackblock(), len);
1334 return stackblock();
1337 return stackblock() + len;
1341 * Called from CHECKSTRSPACE.
1344 makestrspace(size_t newlen, char *p)
1346 size_t len = p - stacknxt;
1347 size_t size = stackblocksize();
1352 size = stackblocksize();
1354 if (nleft >= newlen)
1358 return stackblock() + len;
1362 stack_nputstr(const char *s, size_t n, char *p)
1364 p = makestrspace(n, p);
1365 p = memcpy(p, s, n) + n;
1370 stack_putstr(const char *s, char *p)
1372 return stack_nputstr(s, strlen(s), p);
1376 _STPUTC(int c, char *p)
1384 #define STARTSTACKSTR(p) ((p) = stackblock())
1385 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1386 #define CHECKSTRSPACE(n, p) \
1390 size_t m = sstrend - q; \
1392 (p) = makestrspace(l, q); \
1394 #define USTPUTC(c, p) (*p++ = (c))
1395 #define STACKSTRNUL(p) \
1397 if ((p) == sstrend) \
1398 p = growstackstr(); \
1401 #define STUNPUTC(p) (--p)
1402 #define STTOPC(p) (p[-1])
1403 #define STADJUST(amount, p) (p += (amount))
1405 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1406 #define ungrabstackstr(s, p) stunalloc((s))
1407 #define stackstrend() ((void *)sstrend)
1410 /* ============ String helpers */
1413 * prefix -- see if pfx is a prefix of string.
1416 prefix(const char *string, const char *pfx)
1419 if (*pfx++ != *string++)
1422 return (char *) string;
1426 * Check for a valid number. This should be elsewhere.
1429 is_number(const char *p)
1434 } while (*++p != '\0');
1439 * Convert a string of digits to an integer, printing an error message on
1443 number(const char *s)
1446 ash_msg_and_raise_error(illnum, s);
1451 * Produce a possibly single quoted string suitable as input to the shell.
1452 * The return string is allocated on the stack.
1455 single_quote(const char *s)
1465 len = strchrnul(s, '\'') - s;
1467 q = p = makestrspace(len + 3, p);
1470 q = memcpy(q, s, len) + len;
1476 len = strspn(s, "'");
1480 q = p = makestrspace(len + 3, p);
1483 q = memcpy(q, s, len) + len;
1492 return stackblock();
1496 /* ============ nextopt */
1498 static char **argptr; /* argument list for builtin commands */
1499 static char *optionarg; /* set by nextopt (like getopt) */
1500 static char *optptr; /* used by nextopt */
1503 * XXX - should get rid of. have all builtins use getopt(3). the
1504 * library getopt must have the BSD extension static variable "optreset"
1505 * otherwise it can't be used within the shell safely.
1507 * Standard option processing (a la getopt) for builtin routines. The
1508 * only argument that is passed to nextopt is the option string; the
1509 * other arguments are unnecessary. It return the character, or '\0' on
1513 nextopt(const char *optstring)
1520 if (p == NULL || *p == '\0') {
1522 if (p == NULL || *p != '-' || *++p == '\0')
1525 if (LONE_DASH(p)) /* check for "--" */
1529 for (q = optstring; *q != c; ) {
1531 ash_msg_and_raise_error("illegal option -%c", c);
1536 if (*p == '\0' && (p = *argptr++) == NULL)
1537 ash_msg_and_raise_error("no arg for -%c option", c);
1546 /* ============ Math support definitions */
1548 #if ENABLE_ASH_MATH_SUPPORT_64
1549 typedef int64_t arith_t;
1550 #define arith_t_type long long
1552 typedef long arith_t;
1553 #define arith_t_type long
1556 #if ENABLE_ASH_MATH_SUPPORT
1557 static arith_t dash_arith(const char *);
1558 static arith_t arith(const char *expr, int *perrcode);
1561 #if ENABLE_ASH_RANDOM_SUPPORT
1562 static unsigned long rseed;
1569 /* ============ Shell variables */
1572 #define VEXPORT 0x01 /* variable is exported */
1573 #define VREADONLY 0x02 /* variable cannot be modified */
1574 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1575 #define VTEXTFIXED 0x08 /* text is statically allocated */
1576 #define VSTACK 0x10 /* text is allocated on the stack */
1577 #define VUNSET 0x20 /* the variable is not set */
1578 #define VNOFUNC 0x40 /* don't call the callback function */
1579 #define VNOSET 0x80 /* do not set variable - just readonly test */
1580 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1582 # define VDYNAMIC 0x200 /* dynamic variable */
1588 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1589 #define defifs (defifsvar + 4)
1591 static const char defifs[] ALIGN1 = " \t\n";
1595 int nparam; /* # of positional parameters (without $0) */
1596 unsigned char malloc; /* if parameter list dynamically allocated */
1597 char **p; /* parameter list */
1598 #if ENABLE_ASH_GETOPTS
1599 int optind; /* next parameter to be processed by getopts */
1600 int optoff; /* used by getopts */
1604 static struct shparam shellparam; /* $@ current positional parameters */
1607 * Free the list of positional parameters.
1610 freeparam(volatile struct shparam *param)
1614 if (param->malloc) {
1615 for (ap = param->p; *ap; ap++)
1621 #if ENABLE_ASH_GETOPTS
1623 getoptsreset(const char *value)
1625 shellparam.optind = number(value);
1626 shellparam.optoff = -1;
1631 struct var *next; /* next entry in hash list */
1632 int flags; /* flags are defined above */
1633 const char *text; /* name=value */
1634 void (*func)(const char *); /* function to be called when */
1635 /* the variable gets set/unset */
1639 struct localvar *next; /* next local variable in list */
1640 struct var *vp; /* the variable that was made local */
1641 int flags; /* saved flags */
1642 const char *text; /* saved text */
1645 /* Forward decls for varinit[] */
1646 #if ENABLE_LOCALE_SUPPORT
1648 change_lc_all(const char *value)
1650 if (value && *value != '\0')
1651 setlocale(LC_ALL, value);
1654 change_lc_ctype(const char *value)
1656 if (value && *value != '\0')
1657 setlocale(LC_CTYPE, value);
1661 static void chkmail(void);
1662 static void changemail(const char *);
1664 static void changepath(const char *);
1665 #if ENABLE_ASH_RANDOM_SUPPORT
1666 static void change_random(const char *);
1669 static struct var varinit[] = {
1671 { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
1673 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
1676 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1677 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1679 { NULL, VSTRFIXED|VTEXTFIXED, bb_PATH_root_path, changepath },
1680 { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
1681 { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
1682 { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
1683 #if ENABLE_ASH_GETOPTS
1684 { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1686 #if ENABLE_ASH_RANDOM_SUPPORT
1687 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1689 #if ENABLE_LOCALE_SUPPORT
1690 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1691 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1693 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1694 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1698 #define vifs varinit[0]
1700 #define vmail (&vifs)[1]
1701 #define vmpath (&vmail)[1]
1705 #define vpath (&vmpath)[1]
1706 #define vps1 (&vpath)[1]
1707 #define vps2 (&vps1)[1]
1708 #define vps4 (&vps2)[1]
1709 #define voptind (&vps4)[1]
1710 #if ENABLE_ASH_GETOPTS
1711 #define vrandom (&voptind)[1]
1713 #define vrandom (&vps4)[1]
1717 * The following macros access the values of the above variables.
1718 * They have to skip over the name. They return the null string
1719 * for unset variables.
1721 #define ifsval() (vifs.text + 4)
1722 #define ifsset() ((vifs.flags & VUNSET) == 0)
1723 #define mailval() (vmail.text + 5)
1724 #define mpathval() (vmpath.text + 9)
1725 #define pathval() (vpath.text + 5)
1726 #define ps1val() (vps1.text + 4)
1727 #define ps2val() (vps2.text + 4)
1728 #define ps4val() (vps4.text + 4)
1729 #define optindval() (voptind.text + 7)
1731 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1734 * The parsefile structure pointed to by the global variable parsefile
1735 * contains information about the current file being read.
1738 struct redirtab *next;
1743 static struct redirtab *redirlist;
1744 static int nullredirs;
1745 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1749 static struct var *vartab[VTABSIZE];
1751 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1752 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1755 * Return of a legal variable name (a letter or underscore followed by zero or
1756 * more letters, underscores, and digits).
1759 endofname(const char *name)
1767 if (!is_in_name(*p))
1774 * Compares two strings up to the first = or '\0'. The first
1775 * string must be terminated by '='; the second may be terminated by
1776 * either '=' or '\0'.
1779 varcmp(const char *p, const char *q)
1783 while ((c = *p) == (d = *q)) {
1798 varequal(const char *a, const char *b)
1800 return !varcmp(a, b);
1804 * Find the appropriate entry in the hash table from the name.
1806 static struct var **
1807 hashvar(const char *p)
1811 hashval = ((unsigned char) *p) << 4;
1812 while (*p && *p != '=')
1813 hashval += (unsigned char) *p++;
1814 return &vartab[hashval % VTABSIZE];
1818 vpcmp(const void *a, const void *b)
1820 return varcmp(*(const char **)a, *(const char **)b);
1824 * This routine initializes the builtin variables.
1834 * PS1 depends on uid
1836 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1837 vps1.text = "PS1=\\w \\$ ";
1840 vps1.text = "PS1=# ";
1843 end = vp + ARRAY_SIZE(varinit);
1845 vpp = hashvar(vp->text);
1848 } while (++vp < end);
1851 static struct var **
1852 findvar(struct var **vpp, const char *name)
1854 for (; *vpp; vpp = &(*vpp)->next) {
1855 if (varequal((*vpp)->text, name)) {
1863 * Find the value of a variable. Returns NULL if not set.
1866 lookupvar(const char *name)
1870 v = *findvar(hashvar(name), name);
1874 * Dynamic variables are implemented roughly the same way they are
1875 * in bash. Namely, they're "special" so long as they aren't unset.
1876 * As soon as they're unset, they're no longer dynamic, and dynamic
1877 * lookup will no longer happen at that point. -- PFM.
1879 if ((v->flags & VDYNAMIC))
1882 if (!(v->flags & VUNSET))
1883 return strchrnul(v->text, '=') + 1;
1889 * Search the environment of a builtin command.
1892 bltinlookup(const char *name)
1896 for (sp = cmdenviron; sp; sp = sp->next) {
1897 if (varequal(sp->text, name))
1898 return strchrnul(sp->text, '=') + 1;
1900 return lookupvar(name);
1904 * Same as setvar except that the variable and value are passed in
1905 * the first argument as name=value. Since the first argument will
1906 * be actually stored in the table, it should not be a string that
1908 * Called with interrupts off.
1911 setvareq(char *s, int flags)
1913 struct var *vp, **vpp;
1916 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1917 vp = *findvar(vpp, s);
1919 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1922 if (flags & VNOSAVE)
1925 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1931 if (vp->func && (flags & VNOFUNC) == 0)
1932 (*vp->func)(strchrnul(s, '=') + 1);
1934 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1935 free((char*)vp->text);
1937 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1942 vp = ckmalloc(sizeof(*vp));
1947 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1954 * Set the value of a variable. The flags argument is ored with the
1955 * flags of the variable. If val is NULL, the variable is unset.
1958 setvar(const char *name, const char *val, int flags)
1965 q = endofname(name);
1966 p = strchrnul(q, '=');
1968 if (!namelen || p != q)
1969 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1974 vallen = strlen(val);
1977 nameeq = ckmalloc(namelen + vallen + 2);
1978 p = memcpy(nameeq, name, namelen) + namelen;
1981 p = memcpy(p, val, vallen) + vallen;
1984 setvareq(nameeq, flags | VNOSAVE);
1988 #if ENABLE_ASH_GETOPTS
1990 * Safe version of setvar, returns 1 on success 0 on failure.
1993 setvarsafe(const char *name, const char *val, int flags)
1996 volatile int saveint;
1997 struct jmploc *volatile savehandler = exception_handler;
1998 struct jmploc jmploc;
2001 if (setjmp(jmploc.loc))
2004 exception_handler = &jmploc;
2005 setvar(name, val, flags);
2008 exception_handler = savehandler;
2009 RESTORE_INT(saveint);
2015 * Unset the specified variable.
2018 unsetvar(const char *s)
2024 vpp = findvar(hashvar(s), s);
2028 int flags = vp->flags;
2031 if (flags & VREADONLY)
2034 vp->flags &= ~VDYNAMIC;
2038 if ((flags & VSTRFIXED) == 0) {
2040 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2041 free((char*)vp->text);
2047 vp->flags &= ~VEXPORT;
2057 * Process a linked list of variable assignments.
2060 listsetvar(struct strlist *list_set_var, int flags)
2062 struct strlist *lp = list_set_var;
2068 setvareq(lp->text, flags);
2075 * Generate a list of variables satisfying the given conditions.
2078 listvars(int on, int off, char ***end)
2089 for (vp = *vpp; vp; vp = vp->next) {
2090 if ((vp->flags & mask) == on) {
2091 if (ep == stackstrend())
2092 ep = growstackstr();
2093 *ep++ = (char *) vp->text;
2096 } while (++vpp < vartab + VTABSIZE);
2097 if (ep == stackstrend())
2098 ep = growstackstr();
2102 return grabstackstr(ep);
2106 /* ============ Path search helper
2108 * The variable path (passed by reference) should be set to the start
2109 * of the path before the first call; padvance will update
2110 * this value as it proceeds. Successive calls to padvance will return
2111 * the possible path expansions in sequence. If an option (indicated by
2112 * a percent sign) appears in the path entry then the global variable
2113 * pathopt will be set to point to it; otherwise pathopt will be set to
2116 static const char *pathopt; /* set by padvance */
2119 padvance(const char **path, const char *name)
2129 for (p = start; *p && *p != ':' && *p != '%'; p++);
2130 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2131 while (stackblocksize() < len)
2135 memcpy(q, start, p - start);
2143 while (*p && *p != ':') p++;
2149 return stalloc(len);
2153 /* ============ Prompt */
2155 static smallint doprompt; /* if set, prompt the user */
2156 static smallint needprompt; /* true if interactive and at start of line */
2158 #if ENABLE_FEATURE_EDITING
2159 static line_input_t *line_input_state;
2160 static const char *cmdedit_prompt;
2162 putprompt(const char *s)
2164 if (ENABLE_ASH_EXPAND_PRMT) {
2165 free((char*)cmdedit_prompt);
2166 cmdedit_prompt = ckstrdup(s);
2173 putprompt(const char *s)
2179 #if ENABLE_ASH_EXPAND_PRMT
2180 /* expandstr() needs parsing machinery, so it is far away ahead... */
2181 static const char *expandstr(const char *ps);
2183 #define expandstr(s) s
2187 setprompt(int whichprompt)
2190 #if ENABLE_ASH_EXPAND_PRMT
2191 struct stackmark smark;
2196 switch (whichprompt) {
2206 #if ENABLE_ASH_EXPAND_PRMT
2207 setstackmark(&smark);
2208 stalloc(stackblocksize());
2210 putprompt(expandstr(prompt));
2211 #if ENABLE_ASH_EXPAND_PRMT
2212 popstackmark(&smark);
2217 /* ============ The cd and pwd commands */
2219 #define CD_PHYSICAL 1
2222 static int docd(const char *, int);
2224 static char *curdir = nullstr; /* current working directory */
2225 static char *physdir = nullstr; /* physical working directory */
2234 while ((i = nextopt("LP"))) {
2236 flags ^= CD_PHYSICAL;
2245 * Update curdir (the name of the current directory) in response to a
2249 updatepwd(const char *dir)
2256 cdcomppath = ststrdup(dir);
2259 if (curdir == nullstr)
2261 new = stack_putstr(curdir, new);
2263 new = makestrspace(strlen(dir) + 2, new);
2264 lim = stackblock() + 1;
2268 if (new > lim && *lim == '/')
2273 if (dir[1] == '/' && dir[2] != '/') {
2279 p = strtok(cdcomppath, "/");
2283 if (p[1] == '.' && p[2] == '\0') {
2295 new = stack_putstr(p, new);
2303 return stackblock();
2307 * Find out what the current directory is. If we already know the current
2308 * directory, this routine returns immediately.
2313 char *dir = getcwd(0, 0);
2314 return dir ? dir : nullstr;
2318 setpwd(const char *val, int setold)
2322 oldcur = dir = curdir;
2325 setvar("OLDPWD", oldcur, VEXPORT);
2328 if (physdir != nullstr) {
2329 if (physdir != oldcur)
2333 if (oldcur == val || !val) {
2339 dir = ckstrdup(val);
2340 if (oldcur != dir && oldcur != nullstr) {
2345 setvar("PWD", dir, VEXPORT);
2348 static void hashcd(void);
2351 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2352 * know that the current directory has changed.
2355 docd(const char *dest, int flags)
2357 const char *dir = 0;
2360 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2363 if (!(flags & CD_PHYSICAL)) {
2364 dir = updatepwd(dest);
2379 cdcmd(int argc, char **argv)
2391 dest = bltinlookup(homestr);
2392 else if (LONE_DASH(dest)) {
2393 dest = bltinlookup("OLDPWD");
2415 path = bltinlookup("CDPATH");
2424 p = padvance(&path, dest);
2425 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2429 if (!docd(p, flags))
2434 ash_msg_and_raise_error("can't cd to %s", dest);
2437 if (flags & CD_PRINT)
2438 out1fmt(snlfmt, curdir);
2443 pwdcmd(int argc, char **argv)
2446 const char *dir = curdir;
2450 if (physdir == nullstr)
2454 out1fmt(snlfmt, dir);
2459 /* ============ ... */
2461 #define IBUFSIZ COMMON_BUFSIZE
2462 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2464 /* Syntax classes */
2465 #define CWORD 0 /* character is nothing special */
2466 #define CNL 1 /* newline character */
2467 #define CBACK 2 /* a backslash character */
2468 #define CSQUOTE 3 /* single quote */
2469 #define CDQUOTE 4 /* double quote */
2470 #define CENDQUOTE 5 /* a terminating quote */
2471 #define CBQUOTE 6 /* backwards single quote */
2472 #define CVAR 7 /* a dollar sign */
2473 #define CENDVAR 8 /* a '}' character */
2474 #define CLP 9 /* a left paren in arithmetic */
2475 #define CRP 10 /* a right paren in arithmetic */
2476 #define CENDFILE 11 /* end of file */
2477 #define CCTL 12 /* like CWORD, except it must be escaped */
2478 #define CSPCL 13 /* these terminate a word */
2479 #define CIGN 14 /* character should be ignored */
2481 #if ENABLE_ASH_ALIAS
2485 #define PEOA_OR_PEOF PEOA
2489 #define PEOA_OR_PEOF PEOF
2492 /* number syntax index */
2493 #define BASESYNTAX 0 /* not in quotes */
2494 #define DQSYNTAX 1 /* in double quotes */
2495 #define SQSYNTAX 2 /* in single quotes */
2496 #define ARISYNTAX 3 /* in arithmetic */
2497 #define PSSYNTAX 4 /* prompt */
2499 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2500 #define USE_SIT_FUNCTION
2503 #if ENABLE_ASH_MATH_SUPPORT
2504 static const char S_I_T[][4] = {
2505 #if ENABLE_ASH_ALIAS
2506 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2508 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2509 { CNL, CNL, CNL, CNL }, /* 2, \n */
2510 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2511 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2512 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2513 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2514 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2515 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2516 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2517 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2518 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2519 #ifndef USE_SIT_FUNCTION
2520 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2521 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2522 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2526 static const char S_I_T[][3] = {
2527 #if ENABLE_ASH_ALIAS
2528 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2530 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2531 { CNL, CNL, CNL }, /* 2, \n */
2532 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2533 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2534 { CVAR, CVAR, CWORD }, /* 5, $ */
2535 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2536 { CSPCL, CWORD, CWORD }, /* 7, ( */
2537 { CSPCL, CWORD, CWORD }, /* 8, ) */
2538 { CBACK, CBACK, CCTL }, /* 9, \ */
2539 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2540 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2541 #ifndef USE_SIT_FUNCTION
2542 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2543 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2544 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2547 #endif /* ASH_MATH_SUPPORT */
2549 #ifdef USE_SIT_FUNCTION
2552 SIT(int c, int syntax)
2554 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2555 #if ENABLE_ASH_ALIAS
2556 static const char syntax_index_table[] ALIGN1 = {
2557 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2558 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2559 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2563 static const char syntax_index_table[] ALIGN1 = {
2564 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2565 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2566 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2573 if (c == PEOF) /* 2^8+2 */
2575 #if ENABLE_ASH_ALIAS
2576 if (c == PEOA) /* 2^8+1 */
2580 #define U_C(c) ((unsigned char)(c))
2582 if ((unsigned char)c >= (unsigned char)(CTLESC)
2583 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2587 s = strchr(spec_symbls, c);
2588 if (s == NULL || *s == '\0')
2590 indx = syntax_index_table[(s - spec_symbls)];
2592 return S_I_T[indx][syntax];
2595 #else /* !USE_SIT_FUNCTION */
2597 #if ENABLE_ASH_ALIAS
2598 #define CSPCL_CIGN_CIGN_CIGN 0
2599 #define CSPCL_CWORD_CWORD_CWORD 1
2600 #define CNL_CNL_CNL_CNL 2
2601 #define CWORD_CCTL_CCTL_CWORD 3
2602 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2603 #define CVAR_CVAR_CWORD_CVAR 5
2604 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2605 #define CSPCL_CWORD_CWORD_CLP 7
2606 #define CSPCL_CWORD_CWORD_CRP 8
2607 #define CBACK_CBACK_CCTL_CBACK 9
2608 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2609 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2610 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2611 #define CWORD_CWORD_CWORD_CWORD 13
2612 #define CCTL_CCTL_CCTL_CCTL 14
2614 #define CSPCL_CWORD_CWORD_CWORD 0
2615 #define CNL_CNL_CNL_CNL 1
2616 #define CWORD_CCTL_CCTL_CWORD 2
2617 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2618 #define CVAR_CVAR_CWORD_CVAR 4
2619 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2620 #define CSPCL_CWORD_CWORD_CLP 6
2621 #define CSPCL_CWORD_CWORD_CRP 7
2622 #define CBACK_CBACK_CCTL_CBACK 8
2623 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2624 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2625 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2626 #define CWORD_CWORD_CWORD_CWORD 12
2627 #define CCTL_CCTL_CCTL_CCTL 13
2630 static const char syntax_index_table[258] = {
2631 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2632 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2633 #if ENABLE_ASH_ALIAS
2634 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2636 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2637 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2638 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2639 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2640 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2641 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2642 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2643 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2644 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2645 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2646 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2647 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2648 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2649 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2774 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2775 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2797 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2798 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2799 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2801 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2803 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2804 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2805 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2806 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2807 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2809 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2810 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2811 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2812 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2824 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2825 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2826 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2827 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2828 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2856 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2857 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2858 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2861 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2889 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2890 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2894 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2896 #endif /* USE_SIT_FUNCTION */
2899 /* ============ Alias handling */
2901 #if ENABLE_ASH_ALIAS
2903 #define ALIASINUSE 1
2915 static struct alias *atab[ATABSIZE];
2917 static struct alias **
2918 __lookupalias(const char *name) {
2919 unsigned int hashval;
2926 ch = (unsigned char)*p;
2930 ch = (unsigned char)*++p;
2932 app = &atab[hashval % ATABSIZE];
2934 for (; *app; app = &(*app)->next) {
2935 if (strcmp(name, (*app)->name) == 0) {
2943 static struct alias *
2944 lookupalias(const char *name, int check)
2946 struct alias *ap = *__lookupalias(name);
2948 if (check && ap && (ap->flag & ALIASINUSE))
2953 static struct alias *
2954 freealias(struct alias *ap)
2958 if (ap->flag & ALIASINUSE) {
2959 ap->flag |= ALIASDEAD;
2971 setalias(const char *name, const char *val)
2973 struct alias *ap, **app;
2975 app = __lookupalias(name);
2979 if (!(ap->flag & ALIASINUSE)) {
2982 ap->val = ckstrdup(val);
2983 ap->flag &= ~ALIASDEAD;
2986 ap = ckmalloc(sizeof(struct alias));
2987 ap->name = ckstrdup(name);
2988 ap->val = ckstrdup(val);
2997 unalias(const char *name)
3001 app = __lookupalias(name);
3005 *app = freealias(*app);
3016 struct alias *ap, **app;
3020 for (i = 0; i < ATABSIZE; i++) {
3022 for (ap = *app; ap; ap = *app) {
3023 *app = freealias(*app);
3033 printalias(const struct alias *ap)
3035 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3039 * TODO - sort output
3042 aliascmd(int argc, char **argv)
3051 for (i = 0; i < ATABSIZE; i++)
3052 for (ap = atab[i]; ap; ap = ap->next) {
3057 while ((n = *++argv) != NULL) {
3058 v = strchr(n+1, '=');
3059 if (v == NULL) { /* n+1: funny ksh stuff */
3060 ap = *__lookupalias(n);
3062 fprintf(stderr, "%s: %s not found\n", "alias", n);
3076 unaliascmd(int argc, char **argv)
3080 while ((i = nextopt("a")) != '\0') {
3086 for (i = 0; *argptr; argptr++) {
3087 if (unalias(*argptr)) {
3088 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3096 #endif /* ASH_ALIAS */
3099 /* ============ jobs.c */
3101 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3104 #define FORK_NOJOB 2
3106 /* mode flags for showjob(s) */
3107 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3108 #define SHOW_PID 0x04 /* include process pid */
3109 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3112 * A job structure contains information about a job. A job is either a
3113 * single process or a set of processes contained in a pipeline. In the
3114 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3119 pid_t pid; /* process id */
3120 int status; /* last process status from wait() */
3121 char *cmd; /* text of command being run */
3125 struct procstat ps0; /* status of process */
3126 struct procstat *ps; /* status or processes when more than one */
3128 int stopstatus; /* status of a stopped job */
3131 nprocs: 16, /* number of processes */
3133 #define JOBRUNNING 0 /* at least one proc running */
3134 #define JOBSTOPPED 1 /* all procs are stopped */
3135 #define JOBDONE 2 /* all procs are completed */
3137 sigint: 1, /* job was killed by SIGINT */
3138 jobctl: 1, /* job running under job control */
3140 waited: 1, /* true if this entry has been waited for */
3141 used: 1, /* true if this entry is in used */
3142 changed: 1; /* true if status has changed */
3143 struct job *prev_job; /* previous job */
3146 static pid_t backgndpid; /* pid of last background process */
3147 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3149 static struct job *makejob(union node *, int);
3150 static int forkshell(struct job *, union node *, int);
3151 static int waitforjob(struct job *);
3154 enum { jobctl = 0 };
3155 #define setjobctl(on) do {} while (0)
3157 static smallint jobctl; /* true if doing job control */
3158 static void setjobctl(int);
3162 * Set the signal handler for the specified signal. The routine figures
3163 * out what it should be set to.
3166 setsignal(int signo)
3170 struct sigaction act;
3175 else if (*t != '\0')
3179 if (rootshell && action == S_DFL) {
3182 if (iflag || minusc || sflag == 0)
3205 t = &sigmode[signo - 1];
3209 * current setting unknown
3211 if (sigaction(signo, 0, &act) == -1) {
3213 * Pretend it worked; maybe we should give a warning
3214 * here, but other shells don't. We don't alter
3215 * sigmode, so that we retry every time.
3219 if (act.sa_handler == SIG_IGN) {
3221 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3223 tsig = S_IGN; /* don't hard ignore these */
3227 tsig = S_RESET; /* force to be set */
3230 if (tsig == S_HARD_IGN || tsig == action)
3234 act.sa_handler = onsig;
3237 act.sa_handler = SIG_IGN;
3240 act.sa_handler = SIG_DFL;
3244 sigfillset(&act.sa_mask);
3245 sigaction(signo, &act, 0);
3248 /* mode flags for set_curjob */
3249 #define CUR_DELETE 2
3250 #define CUR_RUNNING 1
3251 #define CUR_STOPPED 0
3253 /* mode flags for dowait */
3254 #define DOWAIT_NORMAL 0
3255 #define DOWAIT_BLOCK 1
3258 /* pgrp of shell on invocation */
3259 static int initialpgrp;
3260 static int ttyfd = -1;
3263 static struct job *jobtab;
3265 static unsigned njobs;
3267 static struct job *curjob;
3268 /* number of presumed living untracked jobs */
3272 set_curjob(struct job *jp, unsigned mode)
3275 struct job **jpp, **curp;
3277 /* first remove from list */
3278 jpp = curp = &curjob;
3283 jpp = &jp1->prev_job;
3285 *jpp = jp1->prev_job;
3287 /* Then re-insert in correct position */
3295 /* job being deleted */
3298 /* newly created job or backgrounded job,
3299 put after all stopped jobs. */
3303 if (!jp1 || jp1->state != JOBSTOPPED)
3306 jpp = &jp1->prev_job;
3312 /* newly stopped job - becomes curjob */
3313 jp->prev_job = *jpp;
3321 jobno(const struct job *jp)
3323 return jp - jobtab + 1;
3328 * Convert a job name to a job structure.
3331 getjob(const char *name, int getctl)
3335 const char *err_msg = "No such job: %s";
3339 char *(*match)(const char *, const char *);
3354 if (c == '+' || c == '%') {
3356 err_msg = "No current job";
3362 err_msg = "No previous job";
3373 jp = jobtab + num - 1;
3390 if (match(jp->ps[0].cmd, p)) {
3394 err_msg = "%s: ambiguous";
3401 err_msg = "job %s not created under job control";
3402 if (getctl && jp->jobctl == 0)
3407 ash_msg_and_raise_error(err_msg, name);
3411 * Mark a job structure as unused.
3414 freejob(struct job *jp)
3416 struct procstat *ps;
3420 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3421 if (ps->cmd != nullstr)
3424 if (jp->ps != &jp->ps0)
3427 set_curjob(jp, CUR_DELETE);
3433 xtcsetpgrp(int fd, pid_t pgrp)
3435 if (tcsetpgrp(fd, pgrp))
3436 ash_msg_and_raise_error("cannot set tty process group (%m)");
3440 * Turn job control on and off.
3442 * Note: This code assumes that the third arg to ioctl is a character
3443 * pointer, which is true on Berkeley systems but not System V. Since
3444 * System V doesn't have job control yet, this isn't a problem now.
3446 * Called with interrupts off.
3454 if (on == jobctl || rootshell == 0)
3458 ofd = fd = open(_PATH_TTY, O_RDWR);
3460 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3461 * That sometimes helps to acquire controlling tty.
3462 * Obviously, a workaround for bugs when someone
3463 * failed to provide a controlling tty to bash! :) */
3469 fd = fcntl(fd, F_DUPFD, 10);
3474 /* fd is a tty at this point */
3475 close_on_exec_on(fd);
3476 do { /* while we are in the background */
3477 pgrp = tcgetpgrp(fd);
3480 ash_msg("can't access tty; job control turned off");
3484 if (pgrp == getpgrp())
3495 xtcsetpgrp(fd, pgrp);
3497 /* turning job control off */
3500 /* was xtcsetpgrp, but this can make exiting ash
3501 * with pty already deleted loop forever */
3502 tcsetpgrp(fd, pgrp);
3517 killcmd(int argc, char **argv)
3519 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3522 if (argv[i][0] == '%') {
3523 struct job *jp = getjob(argv[i], 0);
3524 unsigned pid = jp->ps[0].pid;
3525 /* Enough space for ' -NNN<nul>' */
3526 argv[i] = alloca(sizeof(int)*3 + 3);
3527 /* kill_main has matching code to expect
3528 * leading space. Needed to not confuse
3529 * negative pids with "kill -SIGNAL_NO" syntax */
3530 sprintf(argv[i], " -%u", pid);
3532 } while (argv[++i]);
3534 return kill_main(argc, argv);
3538 showpipe(struct job *jp, FILE *out)
3540 struct procstat *sp;
3541 struct procstat *spend;
3543 spend = jp->ps + jp->nprocs;
3544 for (sp = jp->ps + 1; sp < spend; sp++)
3545 fprintf(out, " | %s", sp->cmd);
3546 outcslow('\n', out);
3547 flush_stdout_stderr();
3552 restartjob(struct job *jp, int mode)
3554 struct procstat *ps;
3560 if (jp->state == JOBDONE)
3562 jp->state = JOBRUNNING;
3564 if (mode == FORK_FG)
3565 xtcsetpgrp(ttyfd, pgid);
3566 killpg(pgid, SIGCONT);
3570 if (WIFSTOPPED(ps->status)) {
3576 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3582 fg_bgcmd(int argc, char **argv)
3589 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3594 jp = getjob(*argv, 1);
3595 if (mode == FORK_BG) {
3596 set_curjob(jp, CUR_RUNNING);
3597 fprintf(out, "[%d] ", jobno(jp));
3599 outstr(jp->ps->cmd, out);
3601 retval = restartjob(jp, mode);
3602 } while (*argv && *++argv);
3608 sprint_status(char *s, int status, int sigonly)
3614 if (!WIFEXITED(status)) {
3616 if (WIFSTOPPED(status))
3617 st = WSTOPSIG(status);
3620 st = WTERMSIG(status);
3622 if (st == SIGINT || st == SIGPIPE)
3625 if (WIFSTOPPED(status))
3630 col = fmtstr(s, 32, strsignal(st));
3631 if (WCOREDUMP(status)) {
3632 col += fmtstr(s + col, 16, " (core dumped)");
3634 } else if (!sigonly) {
3635 st = WEXITSTATUS(status);
3637 col = fmtstr(s, 16, "Done(%d)", st);
3639 col = fmtstr(s, 16, "Done");
3646 * Do a wait system call. If job control is compiled in, we accept
3647 * stopped processes. If block is zero, we return a value of zero
3648 * rather than blocking.
3650 * System V doesn't have a non-blocking wait system call. It does
3651 * have a SIGCLD signal that is sent to a process when one of it's
3652 * children dies. The obvious way to use SIGCLD would be to install
3653 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3654 * was received, and have waitproc bump another counter when it got
3655 * the status of a process. Waitproc would then know that a wait
3656 * system call would not block if the two counters were different.
3657 * This approach doesn't work because if a process has children that
3658 * have not been waited for, System V will send it a SIGCLD when it
3659 * installs a signal handler for SIGCLD. What this means is that when
3660 * a child exits, the shell will be sent SIGCLD signals continuously
3661 * until is runs out of stack space, unless it does a wait call before
3662 * restoring the signal handler. The code below takes advantage of
3663 * this (mis)feature by installing a signal handler for SIGCLD and
3664 * then checking to see whether it was called. If there are any
3665 * children to be waited for, it will be.
3667 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3668 * waits at all. In this case, the user will not be informed when
3669 * a background process until the next time she runs a real program
3670 * (as opposed to running a builtin command or just typing return),
3671 * and the jobs command may give out of date information.
3674 waitproc(int block, int *status)
3684 return wait3(status, flags, (struct rusage *)NULL);
3688 * Wait for a process to terminate.
3691 dowait(int block, struct job *job)
3696 struct job *thisjob;
3699 TRACE(("dowait(%d) called\n", block));
3700 pid = waitproc(block, &status);
3701 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3706 for (jp = curjob; jp; jp = jp->prev_job) {
3707 struct procstat *sp;
3708 struct procstat *spend;
3709 if (jp->state == JOBDONE)
3712 spend = jp->ps + jp->nprocs;
3715 if (sp->pid == pid) {
3716 TRACE(("Job %d: changing status of proc %d "
3717 "from 0x%x to 0x%x\n",
3718 jobno(jp), pid, sp->status, status));
3719 sp->status = status;
3722 if (sp->status == -1)
3725 if (state == JOBRUNNING)
3727 if (WIFSTOPPED(sp->status)) {
3728 jp->stopstatus = sp->status;
3732 } while (++sp < spend);
3737 if (!WIFSTOPPED(status))
3744 if (state != JOBRUNNING) {
3745 thisjob->changed = 1;
3747 if (thisjob->state != state) {
3748 TRACE(("Job %d: changing state from %d to %d\n",
3749 jobno(thisjob), thisjob->state, state));
3750 thisjob->state = state;
3752 if (state == JOBSTOPPED) {
3753 set_curjob(thisjob, CUR_STOPPED);
3762 if (thisjob && thisjob == job) {
3766 len = sprint_status(s, status, 1);
3778 showjob(FILE *out, struct job *jp, int mode)
3780 struct procstat *ps;
3781 struct procstat *psend;
3788 if (mode & SHOW_PGID) {
3789 /* just output process (group) id of pipeline */
3790 fprintf(out, "%d\n", ps->pid);
3794 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3799 else if (curjob && jp == curjob->prev_job)
3802 if (mode & SHOW_PID)
3803 col += fmtstr(s + col, 16, "%d ", ps->pid);
3805 psend = ps + jp->nprocs;
3807 if (jp->state == JOBRUNNING) {
3808 strcpy(s + col, "Running");
3809 col += sizeof("Running") - 1;
3811 int status = psend[-1].status;
3812 if (jp->state == JOBSTOPPED)
3813 status = jp->stopstatus;
3814 col += sprint_status(s + col, status, 0);
3820 /* for each process */
3821 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3823 fprintf(out, "%s%*c%s",
3824 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3826 if (!(mode & SHOW_PID)) {
3830 if (++ps == psend) {
3831 outcslow('\n', out);
3838 if (jp->state == JOBDONE) {
3839 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3845 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3846 * statuses have changed since the last call to showjobs.
3849 showjobs(FILE *out, int mode)
3853 TRACE(("showjobs(%x) called\n", mode));
3855 /* If not even one one job changed, there is nothing to do */
3856 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3859 for (jp = curjob; jp; jp = jp->prev_job) {
3860 if (!(mode & SHOW_CHANGED) || jp->changed) {
3861 showjob(out, jp, mode);
3867 jobscmd(int argc, char **argv)
3872 while ((m = nextopt("lp"))) {
3882 showjob(stdout, getjob(*argv,0), mode);
3885 showjobs(stdout, mode);
3892 getstatus(struct job *job)
3897 status = job->ps[job->nprocs - 1].status;
3898 retval = WEXITSTATUS(status);
3899 if (!WIFEXITED(status)) {
3901 retval = WSTOPSIG(status);
3902 if (!WIFSTOPPED(status))
3905 /* XXX: limits number of signals */
3906 retval = WTERMSIG(status);
3908 if (retval == SIGINT)
3914 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3915 jobno(job), job->nprocs, status, retval));
3920 waitcmd(int argc, char **argv)
3933 /* wait for all jobs */
3938 /* no running procs */
3941 if (jp->state == JOBRUNNING)
3946 dowait(DOWAIT_BLOCK, 0);
3952 if (**argv != '%') {
3953 pid_t pid = number(*argv);
3957 if (job->ps[job->nprocs - 1].pid == pid)
3959 job = job->prev_job;
3965 job = getjob(*argv, 0);
3966 /* loop until process terminated or stopped */
3967 while (job->state == JOBRUNNING)
3968 dowait(DOWAIT_BLOCK, 0);
3970 retval = getstatus(job);
3984 struct job *jp, *jq;
3986 len = njobs * sizeof(*jp);
3988 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
3990 offset = (char *)jp - (char *)jq;
3992 /* Relocate pointers */
3995 jq = (struct job *)((char *)jq + l);
3999 #define joff(p) ((struct job *)((char *)(p) + l))
4000 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4001 if (joff(jp)->ps == &jq->ps0)
4002 jmove(joff(jp)->ps);
4003 if (joff(jp)->prev_job)
4004 jmove(joff(jp)->prev_job);
4014 jp = (struct job *)((char *)jp + len);
4018 } while (--jq >= jp);
4023 * Return a new job structure.
4024 * Called with interrupts off.
4027 makejob(union node *node, int nprocs)
4032 for (i = njobs, jp = jobtab; ; jp++) {
4039 if (jp->state != JOBDONE || !jp->waited)
4048 memset(jp, 0, sizeof(*jp));
4050 /* jp->jobctl is a bitfield.
4051 * "jp->jobctl |= jobctl" likely to give awful code */
4055 jp->prev_job = curjob;
4060 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4062 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4069 * Return a string identifying a command (to be printed by the
4072 static char *cmdnextc;
4075 cmdputs(const char *s)
4077 const char *p, *str;
4078 char c, cc[2] = " ";
4082 static const char vstype[VSTYPE + 1][4] = {
4083 "", "}", "-", "+", "?", "=",
4084 "%", "%%", "#", "##"
4087 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4089 while ((c = *p++) != 0) {
4097 if ((subtype & VSTYPE) == VSLENGTH)
4101 if (!(subtype & VSQUOTE) == !(quoted & 1))
4107 str = "\"}" + !(quoted & 1);
4114 case CTLBACKQ+CTLQUOTE:
4117 #if ENABLE_ASH_MATH_SUPPORT
4132 if ((subtype & VSTYPE) != VSNORMAL)
4134 str = vstype[subtype & VSTYPE];
4135 if (subtype & VSNUL)
4144 /* These can only happen inside quotes */
4157 while ((c = *str++)) {
4162 USTPUTC('"', nextc);
4168 /* cmdtxt() and cmdlist() call each other */
4169 static void cmdtxt(union node *n);
4172 cmdlist(union node *np, int sep)
4174 for (; np; np = np->narg.next) {
4178 if (sep && np->narg.next)
4184 cmdtxt(union node *n)
4187 struct nodelist *lp;
4199 lp = n->npipe.cmdlist;
4217 cmdtxt(n->nbinary.ch1);
4233 cmdtxt(n->nif.test);
4236 if (n->nif.elsepart) {
4239 n = n->nif.elsepart;
4255 cmdtxt(n->nbinary.ch1);
4265 cmdputs(n->nfor.var);
4267 cmdlist(n->nfor.args, 1);
4272 cmdputs(n->narg.text);
4276 cmdlist(n->ncmd.args, 1);
4277 cmdlist(n->ncmd.redirect, 0);
4290 cmdputs(n->ncase.expr->narg.text);
4292 for (np = n->ncase.cases; np; np = np->nclist.next) {
4293 cmdtxt(np->nclist.pattern);
4295 cmdtxt(np->nclist.body);
4321 s[0] = n->nfile.fd + '0';
4325 if (n->type == NTOFD || n->type == NFROMFD) {
4326 s[0] = n->ndup.dupfd + '0';
4336 commandtext(union node *n)
4340 STARTSTACKSTR(cmdnextc);
4342 name = stackblock();
4343 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4344 name, cmdnextc, cmdnextc));
4345 return ckstrdup(name);
4350 * Fork off a subshell. If we are doing job control, give the subshell its
4351 * own process group. Jp is a job structure that the job is to be added to.
4352 * N is the command that will be evaluated by the child. Both jp and n may
4353 * be NULL. The mode parameter can be one of the following:
4354 * FORK_FG - Fork off a foreground process.
4355 * FORK_BG - Fork off a background process.
4356 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4357 * process group even if job control is on.
4359 * When job control is turned off, background processes have their standard
4360 * input redirected to /dev/null (except for the second and later processes
4363 * Called with interrupts off.
4366 * Clear traps on a fork.
4373 for (tp = trap; tp < &trap[NSIG]; tp++) {
4374 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4379 setsignal(tp - trap);
4385 /* Lives far away from here, needed for forkchild */
4386 static void closescript(void);
4388 /* Called after fork(), in child */
4390 forkchild(struct job *jp, union node *n, int mode)
4394 TRACE(("Child shell %d\n", getpid()));
4401 /* do job control only in root shell */
4403 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4406 if (jp->nprocs == 0)
4409 pgrp = jp->ps[0].pid;
4410 /* This can fail because we are doing it in the parent also */
4411 (void)setpgid(0, pgrp);
4412 if (mode == FORK_FG)
4413 xtcsetpgrp(ttyfd, pgrp);
4418 if (mode == FORK_BG) {
4421 if (jp->nprocs == 0) {
4423 if (open(bb_dev_null, O_RDONLY) != 0)
4424 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4427 if (!oldlvl && iflag) {
4432 for (jp = curjob; jp; jp = jp->prev_job)
4437 /* Called after fork(), in parent */
4439 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4441 TRACE(("In parent shell: child = %d\n", pid));
4443 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4448 if (mode != FORK_NOJOB && jp->jobctl) {
4451 if (jp->nprocs == 0)
4454 pgrp = jp->ps[0].pid;
4455 /* This can fail because we are doing it in the child also */
4459 if (mode == FORK_BG) {
4460 backgndpid = pid; /* set $! */
4461 set_curjob(jp, CUR_RUNNING);
4464 struct procstat *ps = &jp->ps[jp->nprocs++];
4470 ps->cmd = commandtext(n);
4476 forkshell(struct job *jp, union node *n, int mode)
4480 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4483 TRACE(("Fork failed, errno=%d", errno));
4486 ash_msg_and_raise_error("cannot fork");
4489 forkchild(jp, n, mode);
4491 forkparent(jp, n, mode, pid);
4496 * Wait for job to finish.
4498 * Under job control we have the problem that while a child process is
4499 * running interrupts generated by the user are sent to the child but not
4500 * to the shell. This means that an infinite loop started by an inter-
4501 * active user may be hard to kill. With job control turned off, an
4502 * interactive user may place an interactive program inside a loop. If
4503 * the interactive program catches interrupts, the user doesn't want
4504 * these interrupts to also abort the loop. The approach we take here
4505 * is to have the shell ignore interrupt signals while waiting for a
4506 * foreground process to terminate, and then send itself an interrupt
4507 * signal if the child process was terminated by an interrupt signal.
4508 * Unfortunately, some programs want to do a bit of cleanup and then
4509 * exit on interrupt; unless these processes terminate themselves by
4510 * sending a signal to themselves (instead of calling exit) they will
4511 * confuse this approach.
4513 * Called with interrupts off.
4516 waitforjob(struct job *jp)
4520 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4521 while (jp->state == JOBRUNNING) {
4522 dowait(DOWAIT_BLOCK, jp);
4527 xtcsetpgrp(ttyfd, rootpid);
4529 * This is truly gross.
4530 * If we're doing job control, then we did a TIOCSPGRP which
4531 * caused us (the shell) to no longer be in the controlling
4532 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4533 * intuit from the subprocess exit status whether a SIGINT
4534 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4539 if (jp->state == JOBDONE)
4546 * return 1 if there are stopped jobs, otherwise 0
4558 if (jp && jp->state == JOBSTOPPED) {
4559 out2str("You have stopped jobs.\n");
4568 /* ============ redir.c
4570 * Code for dealing with input/output redirection.
4573 #define EMPTY -2 /* marks an unused slot in redirtab */
4574 #define CLOSED -3 /* marks a slot of previously-closed fd */
4576 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4578 # define PIPESIZE PIPE_BUF
4582 * Open a file in noclobber mode.
4583 * The code was copied from bash.
4586 noclobberopen(const char *fname)
4589 struct stat finfo, finfo2;
4592 * If the file exists and is a regular file, return an error
4595 r = stat(fname, &finfo);
4596 if (r == 0 && S_ISREG(finfo.st_mode)) {
4602 * If the file was not present (r != 0), make sure we open it
4603 * exclusively so that if it is created before we open it, our open
4604 * will fail. Make sure that we do not truncate an existing file.
4605 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4606 * file was not a regular file, we leave O_EXCL off.
4609 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4610 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4612 /* If the open failed, return the file descriptor right away. */
4617 * OK, the open succeeded, but the file may have been changed from a
4618 * non-regular file to a regular file between the stat and the open.
4619 * We are assuming that the O_EXCL open handles the case where FILENAME
4620 * did not exist and is symlinked to an existing file between the stat
4625 * If we can open it and fstat the file descriptor, and neither check
4626 * revealed that it was a regular file, and the file has not been
4627 * replaced, return the file descriptor.
4629 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4630 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4633 /* The file has been replaced. badness. */
4640 * Handle here documents. Normally we fork off a process to write the
4641 * data to a pipe. If the document is short, we can stuff the data in
4642 * the pipe without forking.
4644 /* openhere needs this forward reference */
4645 static void expandhere(union node *arg, int fd);
4647 openhere(union node *redir)
4653 ash_msg_and_raise_error("pipe call failed");
4654 if (redir->type == NHERE) {
4655 len = strlen(redir->nhere.doc->narg.text);
4656 if (len <= PIPESIZE) {
4657 full_write(pip[1], redir->nhere.doc->narg.text, len);
4661 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4663 signal(SIGINT, SIG_IGN);
4664 signal(SIGQUIT, SIG_IGN);
4665 signal(SIGHUP, SIG_IGN);
4667 signal(SIGTSTP, SIG_IGN);
4669 signal(SIGPIPE, SIG_DFL);
4670 if (redir->type == NHERE)
4671 full_write(pip[1], redir->nhere.doc->narg.text, len);
4673 expandhere(redir->nhere.doc, pip[1]);
4682 openredirect(union node *redir)
4687 switch (redir->nfile.type) {
4689 fname = redir->nfile.expfname;
4690 f = open(fname, O_RDONLY);
4695 fname = redir->nfile.expfname;
4696 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4701 /* Take care of noclobber mode. */
4703 fname = redir->nfile.expfname;
4704 f = noclobberopen(fname);
4711 fname = redir->nfile.expfname;
4712 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4717 fname = redir->nfile.expfname;
4718 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4726 /* Fall through to eliminate warning. */
4733 f = openhere(redir);
4739 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4741 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4745 * Copy a file descriptor to be >= to. Returns -1
4746 * if the source file descriptor is closed, EMPTY if there are no unused
4747 * file descriptors left.
4750 copyfd(int from, int to)
4754 newfd = fcntl(from, F_DUPFD, to);
4756 if (errno == EMFILE)
4758 ash_msg_and_raise_error("%d: %m", from);
4764 dupredirect(union node *redir, int f)
4766 int fd = redir->nfile.fd;
4768 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4769 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4770 copyfd(redir->ndup.dupfd, fd);
4782 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4783 * old file descriptors are stashed away so that the redirection can be
4784 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4785 * standard output, and the standard error if it becomes a duplicate of
4786 * stdout, is saved in memory.
4788 /* flags passed to redirect */
4789 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4790 #define REDIR_SAVEFD2 03 /* set preverrout */
4792 redirect(union node *redir, int flags)
4795 struct redirtab *sv;
4806 if (flags & REDIR_PUSH) {
4807 sv = ckmalloc(sizeof(*sv));
4808 sv->next = redirlist;
4810 sv->nullredirs = nullredirs - 1;
4811 for (i = 0; i < 10; i++)
4812 sv->renamed[i] = EMPTY;
4818 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4819 && n->ndup.dupfd == fd)
4820 continue; /* redirect from/to same file descriptor */
4822 newfd = openredirect(n);
4824 /* Descriptor wasn't open before redirect.
4825 * Mark it for close in the future */
4826 if (sv && sv->renamed[fd] == EMPTY)
4827 sv->renamed[fd] = CLOSED;
4830 if (sv && sv->renamed[fd] == EMPTY) {
4831 i = fcntl(fd, F_DUPFD, 10);
4838 ash_msg_and_raise_error("%d: %m", fd);
4842 sv->renamed[fd] = i;
4848 dupredirect(n, newfd);
4849 } while ((n = n->nfile.next));
4851 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
4852 preverrout_fd = sv->renamed[2];
4856 * Undo the effects of the last redirection.
4861 struct redirtab *rp;
4864 if (--nullredirs >= 0)
4868 for (i = 0; i < 10; i++) {
4869 if (rp->renamed[i] == CLOSED) {
4874 if (rp->renamed[i] != EMPTY) {
4877 copyfd(rp->renamed[i], i);
4879 close(rp->renamed[i]);
4882 redirlist = rp->next;
4883 nullredirs = rp->nullredirs;
4889 * Undo all redirections. Called on error or interrupt.
4893 * Discard all saved file descriptors.
4896 clearredir(int drop)
4907 redirectsafe(union node *redir, int flags)
4910 volatile int saveint;
4911 struct jmploc *volatile savehandler = exception_handler;
4912 struct jmploc jmploc;
4915 err = setjmp(jmploc.loc) * 2;
4917 exception_handler = &jmploc;
4918 redirect(redir, flags);
4920 exception_handler = savehandler;
4921 if (err && exception != EXERROR)
4922 longjmp(exception_handler->loc, 1);
4923 RESTORE_INT(saveint);
4928 /* ============ Routines to expand arguments to commands
4930 * We have to deal with backquotes, shell variables, and file metacharacters.
4936 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4937 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4938 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4939 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4940 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4941 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4942 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4943 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4944 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
4948 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4949 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4950 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4951 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4952 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4955 * Structure specifying which parts of the string should be searched
4956 * for IFS characters.
4959 struct ifsregion *next; /* next region in list */
4960 int begoff; /* offset of start of region */
4961 int endoff; /* offset of end of region */
4962 int nulonly; /* search for nul bytes only */
4966 struct strlist *list;
4967 struct strlist **lastp;
4970 /* output of current string */
4971 static char *expdest;
4972 /* list of back quote expressions */
4973 static struct nodelist *argbackq;
4974 /* first struct in list of ifs regions */
4975 static struct ifsregion ifsfirst;
4976 /* last struct in list */
4977 static struct ifsregion *ifslastp;
4978 /* holds expanded arg list */
4979 static struct arglist exparg;
4989 expdest = makestrspace(32, expdest);
4990 #if ENABLE_ASH_MATH_SUPPORT_64
4991 len = fmtstr(expdest, 32, "%lld", (long long) num);
4993 len = fmtstr(expdest, 32, "%ld", num);
4995 STADJUST(len, expdest);
5000 esclen(const char *start, const char *p)
5004 while (p > start && *--p == CTLESC) {
5011 * Remove any CTLESC characters from a string.
5014 _rmescapes(char *str, int flag)
5016 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5023 p = strpbrk(str, qchars);
5029 if (flag & RMESCAPE_ALLOC) {
5030 size_t len = p - str;
5031 size_t fulllen = len + strlen(p) + 1;
5033 if (flag & RMESCAPE_GROW) {
5034 r = makestrspace(fulllen, expdest);
5035 } else if (flag & RMESCAPE_HEAP) {
5036 r = ckmalloc(fulllen);
5038 r = stalloc(fulllen);
5042 q = memcpy(q, str, len) + len;
5045 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5046 globbing = flag & RMESCAPE_GLOB;
5047 notescaped = globbing;
5049 if (*p == CTLQUOTEMARK) {
5050 inquotes = ~inquotes;
5052 notescaped = globbing;
5056 /* naked back slash */
5062 if (notescaped && inquotes && *p != '/') {
5066 notescaped = globbing;
5071 if (flag & RMESCAPE_GROW) {
5073 STADJUST(q - r + 1, expdest);
5077 #define rmescapes(p) _rmescapes((p), 0)
5079 #define pmatch(a, b) !fnmatch((a), (b), 0)
5082 * Prepare a pattern for a expmeta (internal glob(3)) call.
5084 * Returns an stalloced string.
5087 preglob(const char *pattern, int quoted, int flag)
5089 flag |= RMESCAPE_GLOB;
5091 flag |= RMESCAPE_QUOTED;
5093 return _rmescapes((char *)pattern, flag);
5097 * Put a string on the stack.
5100 memtodest(const char *p, size_t len, int syntax, int quotes)
5104 q = makestrspace(len * 2, q);
5107 int c = signed_char2int(*p++);
5110 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5119 strtodest(const char *p, int syntax, int quotes)
5121 memtodest(p, strlen(p), syntax, quotes);
5125 * Record the fact that we have to scan this region of the
5126 * string for IFS characters.
5129 recordregion(int start, int end, int nulonly)
5131 struct ifsregion *ifsp;
5133 if (ifslastp == NULL) {
5137 ifsp = ckmalloc(sizeof(*ifsp));
5139 ifslastp->next = ifsp;
5143 ifslastp->begoff = start;
5144 ifslastp->endoff = end;
5145 ifslastp->nulonly = nulonly;
5149 removerecordregions(int endoff)
5151 if (ifslastp == NULL)
5154 if (ifsfirst.endoff > endoff) {
5155 while (ifsfirst.next != NULL) {
5156 struct ifsregion *ifsp;
5158 ifsp = ifsfirst.next->next;
5159 free(ifsfirst.next);
5160 ifsfirst.next = ifsp;
5163 if (ifsfirst.begoff > endoff)
5166 ifslastp = &ifsfirst;
5167 ifsfirst.endoff = endoff;
5172 ifslastp = &ifsfirst;
5173 while (ifslastp->next && ifslastp->next->begoff < endoff)
5174 ifslastp=ifslastp->next;
5175 while (ifslastp->next != NULL) {
5176 struct ifsregion *ifsp;
5178 ifsp = ifslastp->next->next;
5179 free(ifslastp->next);
5180 ifslastp->next = ifsp;
5183 if (ifslastp->endoff > endoff)
5184 ifslastp->endoff = endoff;
5188 exptilde(char *startp, char *p, int flag)
5194 int quotes = flag & (EXP_FULL | EXP_CASE);
5199 while ((c = *++p) != '\0') {
5206 if (flag & EXP_VARTILDE)
5216 if (*name == '\0') {
5217 home = lookupvar(homestr);
5219 pw = getpwnam(name);
5224 if (!home || !*home)
5227 startloc = expdest - (char *)stackblock();
5228 strtodest(home, SQSYNTAX, quotes);
5229 recordregion(startloc, expdest - (char *)stackblock(), 0);
5237 * Execute a command inside back quotes. If it's a builtin command, we
5238 * want to save its output in a block obtained from malloc. Otherwise
5239 * we fork off a subprocess and get the output of the command via a pipe.
5240 * Should be called with interrupts off.
5242 struct backcmd { /* result of evalbackcmd */
5243 int fd; /* file descriptor to read from */
5244 char *buf; /* buffer */
5245 int nleft; /* number of chars in buffer */
5246 struct job *jp; /* job structure for command */
5249 /* These forward decls are needed to use "eval" code for backticks handling: */
5250 static int back_exitstatus; /* exit status of backquoted command */
5251 #define EV_EXIT 01 /* exit after evaluating tree */
5252 static void evaltree(union node *, int);
5255 evalbackcmd(union node *n, struct backcmd *result)
5267 saveherefd = herefd;
5275 ash_msg_and_raise_error("pipe call failed");
5277 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5286 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5290 result->fd = pip[0];
5293 herefd = saveherefd;
5295 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5296 result->fd, result->buf, result->nleft, result->jp));
5300 * Expand stuff in backwards quotes.
5303 expbackq(union node *cmd, int quoted, int quotes)
5311 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5312 struct stackmark smark;
5315 setstackmark(&smark);
5317 startloc = dest - (char *)stackblock();
5319 evalbackcmd(cmd, &in);
5320 popstackmark(&smark);
5327 memtodest(p, i, syntax, quotes);
5331 i = safe_read(in.fd, buf, sizeof(buf));
5332 TRACE(("expbackq: read returns %d\n", i));
5341 back_exitstatus = waitforjob(in.jp);
5345 /* Eat all trailing newlines */
5347 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5352 recordregion(startloc, dest - (char *)stackblock(), 0);
5353 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5354 (dest - (char *)stackblock()) - startloc,
5355 (dest - (char *)stackblock()) - startloc,
5356 stackblock() + startloc));
5359 #if ENABLE_ASH_MATH_SUPPORT
5361 * Expand arithmetic expression. Backup to start of expression,
5362 * evaluate, place result in (backed up) result, adjust string position.
5375 * This routine is slightly over-complicated for
5376 * efficiency. Next we scan backwards looking for the
5377 * start of arithmetic.
5379 start = stackblock();
5386 while (*p != CTLARI) {
5390 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5395 esc = esclen(start, p);
5405 removerecordregions(begoff);
5414 len = cvtnum(dash_arith(p + 2));
5417 recordregion(begoff, begoff + len, 0);
5421 /* argstr needs it */
5422 static char *evalvar(char *p, int flag);
5425 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5426 * characters to allow for further processing. Otherwise treat
5427 * $@ like $* since no splitting will be performed.
5430 argstr(char *p, int flag)
5432 static const char spclchars[] ALIGN1 = {
5440 CTLBACKQ | CTLQUOTE,
5441 #if ENABLE_ASH_MATH_SUPPORT
5446 const char *reject = spclchars;
5448 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5449 int breakall = flag & EXP_WORD;
5454 if (!(flag & EXP_VARTILDE)) {
5456 } else if (flag & EXP_VARTILDE2) {
5461 if (flag & EXP_TILDE) {
5467 if (*q == CTLESC && (flag & EXP_QWORD))
5470 p = exptilde(p, q, flag);
5473 startloc = expdest - (char *)stackblock();
5475 length += strcspn(p + length, reject);
5477 if (c && (!(c & 0x80)
5478 #if ENABLE_ASH_MATH_SUPPORT
5482 /* c == '=' || c == ':' || c == CTLENDARI */
5487 expdest = stack_nputstr(p, length, expdest);
5488 newloc = expdest - (char *)stackblock();
5489 if (breakall && !inquotes && newloc > startloc) {
5490 recordregion(startloc, newloc, 0);
5501 if (flag & EXP_VARTILDE2) {
5505 flag |= EXP_VARTILDE2;
5510 * sort of a hack - expand tildes in variable
5511 * assignments (after the first '=' and after ':'s).
5520 case CTLENDVAR: /* ??? */
5523 /* "$@" syntax adherence hack */
5526 !memcmp(p, dolatstr, 4) &&
5527 (p[4] == CTLQUOTEMARK || (
5528 p[4] == CTLENDVAR &&
5529 p[5] == CTLQUOTEMARK
5532 p = evalvar(p + 1, flag) + 1;
5535 inquotes = !inquotes;
5548 p = evalvar(p, flag);
5552 case CTLBACKQ|CTLQUOTE:
5553 expbackq(argbackq->n, c, quotes);
5554 argbackq = argbackq->next;
5556 #if ENABLE_ASH_MATH_SUPPORT
5569 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5580 const char *s = loc2;
5586 match = pmatch(str, s);
5590 if (quotes && *loc == CTLESC)
5599 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5606 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5609 const char *s = loc2;
5614 match = pmatch(str, s);
5621 esc = esclen(startp, loc);
5632 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5634 varunset(const char *end, const char *var, const char *umsg, int varflags)
5640 msg = "parameter not set";
5642 if (*end == CTLENDVAR) {
5643 if (varflags & VSNUL)
5648 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5652 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5656 int saveherefd = herefd;
5657 struct nodelist *saveargbackq = argbackq;
5659 char *rmesc, *rmescend;
5661 char *(*scan)(char *, char *, char *, char *, int , int);
5664 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5665 STPUTC('\0', expdest);
5666 herefd = saveherefd;
5667 argbackq = saveargbackq;
5668 startp = stackblock() + startloc;
5672 setvar(str, startp, 0);
5673 amount = startp - expdest;
5674 STADJUST(amount, expdest);
5678 varunset(p, str, startp, varflags);
5682 subtype -= VSTRIMRIGHT;
5684 if (subtype < 0 || subtype > 3)
5689 rmescend = stackblock() + strloc;
5691 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5692 if (rmesc != startp) {
5694 startp = stackblock() + startloc;
5698 str = stackblock() + strloc;
5699 preglob(str, varflags & VSQUOTE, 0);
5701 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5702 zero = subtype >> 1;
5703 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5704 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5706 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5709 memmove(startp, loc, str - loc);
5710 loc = startp + (str - loc) - 1;
5713 amount = loc - expdest;
5714 STADJUST(amount, expdest);
5720 * Add the value of a specialized variable to the stack string.
5723 varvalue(char *name, int varflags, int flags)
5733 int quoted = varflags & VSQUOTE;
5734 int subtype = varflags & VSTYPE;
5735 int quotes = flags & (EXP_FULL | EXP_CASE);
5737 if (quoted && (flags & EXP_FULL))
5738 sep = 1 << CHAR_BIT;
5740 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5749 num = shellparam.nparam;
5759 p = makestrspace(NOPTS, expdest);
5760 for (i = NOPTS - 1; i >= 0; i--) {
5762 USTPUTC(optletters(i), p);
5773 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5774 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5780 while ((p = *ap++)) {
5783 partlen = strlen(p);
5786 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5787 memtodest(p, partlen, syntax, quotes);
5793 if (subtype == VSPLUS || subtype == VSLENGTH) {
5815 if (num < 0 || num > shellparam.nparam)
5817 p = num ? shellparam.p[num - 1] : arg0;
5820 p = lookupvar(name);
5826 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5827 memtodest(p, len, syntax, quotes);
5831 if (subtype == VSPLUS || subtype == VSLENGTH)
5832 STADJUST(-len, expdest);
5837 * Expand a variable, and return a pointer to the next character in the
5841 evalvar(char *p, int flag)
5854 quotes = flag & (EXP_FULL | EXP_CASE);
5856 subtype = varflags & VSTYPE;
5857 quoted = varflags & VSQUOTE;
5859 easy = (!quoted || (*var == '@' && shellparam.nparam));
5860 startloc = expdest - (char *)stackblock();
5861 p = strchr(p, '=') + 1;
5864 varlen = varvalue(var, varflags, flag);
5865 if (varflags & VSNUL)
5868 if (subtype == VSPLUS) {
5869 varlen = -1 - varlen;
5873 if (subtype == VSMINUS) {
5877 p, flag | EXP_TILDE |
5878 (quoted ? EXP_QWORD : EXP_WORD)
5887 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5889 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5892 * Remove any recorded regions beyond
5895 removerecordregions(startloc);
5905 if (varlen < 0 && uflag)
5906 varunset(p, var, 0, 0);
5908 if (subtype == VSLENGTH) {
5909 cvtnum(varlen > 0 ? varlen : 0);
5913 if (subtype == VSNORMAL) {
5917 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5926 case VSTRIMRIGHTMAX:
5935 * Terminate the string and start recording the pattern
5938 STPUTC('\0', expdest);
5939 patloc = expdest - (char *)stackblock();
5940 if (subevalvar(p, NULL, patloc, subtype,
5941 startloc, varflags, quotes) == 0) {
5942 int amount = expdest - (
5943 (char *)stackblock() + patloc - 1
5945 STADJUST(-amount, expdest);
5947 /* Remove any recorded regions beyond start of variable */
5948 removerecordregions(startloc);
5953 if (subtype != VSNORMAL) { /* skip to end of alternative */
5959 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5961 argbackq = argbackq->next;
5962 } else if (c == CTLVAR) {
5963 if ((*p++ & VSTYPE) != VSNORMAL)
5965 } else if (c == CTLENDVAR) {
5975 * Break the argument string into pieces based upon IFS and add the
5976 * strings to the argument list. The regions of the string to be
5977 * searched for IFS characters have been stored by recordregion.
5980 ifsbreakup(char *string, struct arglist *arglist)
5982 struct ifsregion *ifsp;
5987 const char *ifs, *realifs;
5992 if (ifslastp != NULL) {
5995 realifs = ifsset() ? ifsval() : defifs;
5998 p = string + ifsp->begoff;
5999 nulonly = ifsp->nulonly;
6000 ifs = nulonly ? nullstr : realifs;
6002 while (p < string + ifsp->endoff) {
6006 if (!strchr(ifs, *p)) {
6011 ifsspc = (strchr(defifs, *p) != NULL);
6012 /* Ignore IFS whitespace at start */
6013 if (q == start && ifsspc) {
6019 sp = stalloc(sizeof(*sp));
6021 *arglist->lastp = sp;
6022 arglist->lastp = &sp->next;
6026 if (p >= string + ifsp->endoff) {
6032 if (strchr(ifs, *p) == NULL ) {
6035 } else if (strchr(defifs, *p) == NULL) {
6050 } while (ifsp != NULL);
6059 sp = stalloc(sizeof(*sp));
6061 *arglist->lastp = sp;
6062 arglist->lastp = &sp->next;
6068 struct ifsregion *p;
6073 struct ifsregion *ifsp;
6079 ifsfirst.next = NULL;
6084 * Add a file name to the list.
6087 addfname(const char *name)
6091 sp = stalloc(sizeof(*sp));
6092 sp->text = ststrdup(name);
6094 exparg.lastp = &sp->next;
6097 static char *expdir;
6100 * Do metacharacter (i.e. *, ?, [...]) expansion.
6103 expmeta(char *enddir, char *name)
6118 for (p = name; *p; p++) {
6119 if (*p == '*' || *p == '?')
6121 else if (*p == '[') {
6128 if (*q == '/' || *q == '\0')
6135 } else if (*p == '\\')
6137 else if (*p == '/') {
6144 if (metaflag == 0) { /* we've reached the end of the file name */
6145 if (enddir != expdir)
6153 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6164 } while (p < start);
6166 if (enddir == expdir) {
6168 } else if (enddir == expdir + 1 && *expdir == '/') {
6177 if (enddir != expdir)
6179 if (*endname == 0) {
6191 while (! intpending && (dp = readdir(dirp)) != NULL) {
6192 if (dp->d_name[0] == '.' && ! matchdot)
6194 if (pmatch(start, dp->d_name)) {
6196 strcpy(enddir, dp->d_name);
6199 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6202 expmeta(p, endname);
6211 static struct strlist *
6212 msort(struct strlist *list, int len)
6214 struct strlist *p, *q = NULL;
6215 struct strlist **lpp;
6223 for (n = half; --n >= 0; ) {
6227 q->next = NULL; /* terminate first half of list */
6228 q = msort(list, half); /* sort first half of list */
6229 p = msort(p, len - half); /* sort second half */
6232 #if ENABLE_LOCALE_SUPPORT
6233 if (strcoll(p->text, q->text) < 0)
6235 if (strcmp(p->text, q->text) < 0)
6259 * Sort the results of file name expansion. It calculates the number of
6260 * strings to sort and then calls msort (short for merge sort) to do the
6263 static struct strlist *
6264 expsort(struct strlist *str)
6270 for (sp = str; sp; sp = sp->next)
6272 return msort(str, len);
6276 expandmeta(struct strlist *str, int flag)
6278 static const char metachars[] ALIGN1 = {
6281 /* TODO - EXP_REDIR */
6284 struct strlist **savelastp;
6290 if (!strpbrk(str->text, metachars))
6292 savelastp = exparg.lastp;
6295 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6297 int i = strlen(str->text);
6298 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6306 if (exparg.lastp == savelastp) {
6311 *exparg.lastp = str;
6312 rmescapes(str->text);
6313 exparg.lastp = &str->next;
6315 *exparg.lastp = NULL;
6316 *savelastp = sp = expsort(*savelastp);
6317 while (sp->next != NULL)
6319 exparg.lastp = &sp->next;
6326 * Perform variable substitution and command substitution on an argument,
6327 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6328 * perform splitting and file name expansion. When arglist is NULL, perform
6329 * here document expansion.
6332 expandarg(union node *arg, struct arglist *arglist, int flag)
6337 argbackq = arg->narg.backquote;
6338 STARTSTACKSTR(expdest);
6339 ifsfirst.next = NULL;
6341 argstr(arg->narg.text, flag);
6342 p = _STPUTC('\0', expdest);
6344 if (arglist == NULL) {
6345 return; /* here document expanded */
6347 p = grabstackstr(p);
6348 exparg.lastp = &exparg.list;
6352 if (flag & EXP_FULL) {
6353 ifsbreakup(p, &exparg);
6354 *exparg.lastp = NULL;
6355 exparg.lastp = &exparg.list;
6356 expandmeta(exparg.list, flag);
6358 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6360 sp = stalloc(sizeof(*sp));
6363 exparg.lastp = &sp->next;
6367 *exparg.lastp = NULL;
6369 *arglist->lastp = exparg.list;
6370 arglist->lastp = exparg.lastp;
6375 * Expand shell variables and backquotes inside a here document.
6378 expandhere(union node *arg, int fd)
6381 expandarg(arg, (struct arglist *)NULL, 0);
6382 full_write(fd, stackblock(), expdest - (char *)stackblock());
6386 * Returns true if the pattern matches the string.
6389 patmatch(char *pattern, const char *string)
6391 return pmatch(preglob(pattern, 0, 0), string);
6395 * See if a pattern matches in a case statement.
6398 casematch(union node *pattern, char *val)
6400 struct stackmark smark;
6403 setstackmark(&smark);
6404 argbackq = pattern->narg.backquote;
6405 STARTSTACKSTR(expdest);
6407 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6408 STACKSTRNUL(expdest);
6409 result = patmatch(stackblock(), val);
6410 popstackmark(&smark);
6415 /* ============ find_command */
6419 int (*builtin)(int, char **);
6420 /* unsigned flags; */
6422 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6423 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6424 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6430 const struct builtincmd *cmd;
6431 struct funcnode *func;
6434 /* values of cmdtype */
6435 #define CMDUNKNOWN -1 /* no entry in table for command */
6436 #define CMDNORMAL 0 /* command is an executable program */
6437 #define CMDFUNCTION 1 /* command is a shell function */
6438 #define CMDBUILTIN 2 /* command is a shell builtin */
6440 /* action to find_command() */
6441 #define DO_ERR 0x01 /* prints errors */
6442 #define DO_ABS 0x02 /* checks absolute paths */
6443 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6444 #define DO_ALTPATH 0x08 /* using alternate path */
6445 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6447 static void find_command(char *, struct cmdentry *, int, const char *);
6450 /* ============ Hashing commands */
6453 * When commands are first encountered, they are entered in a hash table.
6454 * This ensures that a full path search will not have to be done for them
6455 * on each invocation.
6457 * We should investigate converting to a linear search, even though that
6458 * would make the command name "hash" a misnomer.
6461 #define CMDTABLESIZE 31 /* should be prime */
6462 #define ARB 1 /* actual size determined at run time */
6465 struct tblentry *next; /* next entry in hash chain */
6466 union param param; /* definition of builtin function */
6467 short cmdtype; /* index identifying command */
6468 char rehash; /* if set, cd done since entry created */
6469 char cmdname[ARB]; /* name of command */
6472 static struct tblentry *cmdtable[CMDTABLESIZE];
6473 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6476 tryexec(char *cmd, char **argv, char **envp)
6480 #if ENABLE_FEATURE_SH_STANDALONE
6481 if (strchr(cmd, '/') == NULL) {
6482 int a = find_applet_by_name(cmd);
6484 if (APPLET_IS_NOEXEC(a))
6485 run_applet_no_and_exit(a, argv);
6486 /* re-exec ourselves with the new arguments */
6487 execve(bb_busybox_exec_path, argv, envp);
6488 /* If they called chroot or otherwise made the binary no longer
6489 * executable, fall through */
6497 execve(cmd, argv, envp);
6498 } while (errno == EINTR);
6500 execve(cmd, argv, envp);
6504 } else if (errno == ENOEXEC) {
6508 for (ap = argv; *ap; ap++)
6510 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6512 ap[0] = cmd = (char *)DEFAULT_SHELL;
6515 while ((*ap++ = *argv++))
6523 * Exec a program. Never returns. If you change this routine, you may
6524 * have to change the find_command routine as well.
6526 #define environment() listvars(VEXPORT, VUNSET, 0)
6527 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6529 shellexec(char **argv, const char *path, int idx)
6537 envp = environment();
6538 if (strchr(argv[0], '/')
6539 #if ENABLE_FEATURE_SH_STANDALONE
6540 || find_applet_by_name(argv[0]) >= 0
6543 tryexec(argv[0], argv, envp);
6547 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6548 if (--idx < 0 && pathopt == NULL) {
6549 tryexec(cmdname, argv, envp);
6550 if (errno != ENOENT && errno != ENOTDIR)
6557 /* Map to POSIX errors */
6569 exitstatus = exerrno;
6570 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6571 argv[0], e, suppressint ));
6572 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6577 printentry(struct tblentry *cmdp)
6583 idx = cmdp->param.index;
6586 name = padvance(&path, cmdp->cmdname);
6588 } while (--idx >= 0);
6589 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6593 * Clear out command entries. The argument specifies the first entry in
6594 * PATH which has changed.
6597 clearcmdentry(int firstchange)
6599 struct tblentry **tblp;
6600 struct tblentry **pp;
6601 struct tblentry *cmdp;
6604 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6606 while ((cmdp = *pp) != NULL) {
6607 if ((cmdp->cmdtype == CMDNORMAL &&
6608 cmdp->param.index >= firstchange)
6609 || (cmdp->cmdtype == CMDBUILTIN &&
6610 builtinloc >= firstchange)
6623 * Locate a command in the command hash table. If "add" is nonzero,
6624 * add the command to the table if it is not already present. The
6625 * variable "lastcmdentry" is set to point to the address of the link
6626 * pointing to the entry, so that delete_cmd_entry can delete the
6629 * Interrupts must be off if called with add != 0.
6631 static struct tblentry **lastcmdentry;
6633 static struct tblentry *
6634 cmdlookup(const char *name, int add)
6636 unsigned int hashval;
6638 struct tblentry *cmdp;
6639 struct tblentry **pp;
6642 hashval = (unsigned char)*p << 4;
6644 hashval += (unsigned char)*p++;
6646 pp = &cmdtable[hashval % CMDTABLESIZE];
6647 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6648 if (strcmp(cmdp->cmdname, name) == 0)
6652 if (add && cmdp == NULL) {
6653 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6654 + strlen(name) + 1);
6656 cmdp->cmdtype = CMDUNKNOWN;
6657 strcpy(cmdp->cmdname, name);
6664 * Delete the command entry returned on the last lookup.
6667 delete_cmd_entry(void)
6669 struct tblentry *cmdp;
6672 cmdp = *lastcmdentry;
6673 *lastcmdentry = cmdp->next;
6674 if (cmdp->cmdtype == CMDFUNCTION)
6675 freefunc(cmdp->param.func);
6681 * Add a new command entry, replacing any existing command entry for
6682 * the same name - except special builtins.
6685 addcmdentry(char *name, struct cmdentry *entry)
6687 struct tblentry *cmdp;
6689 cmdp = cmdlookup(name, 1);
6690 if (cmdp->cmdtype == CMDFUNCTION) {
6691 freefunc(cmdp->param.func);
6693 cmdp->cmdtype = entry->cmdtype;
6694 cmdp->param = entry->u;
6699 hashcmd(int argc, char **argv)
6701 struct tblentry **pp;
6702 struct tblentry *cmdp;
6704 struct cmdentry entry;
6707 while ((c = nextopt("r")) != '\0') {
6711 if (*argptr == NULL) {
6712 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6713 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6714 if (cmdp->cmdtype == CMDNORMAL)
6721 while ((name = *argptr) != NULL) {
6722 cmdp = cmdlookup(name, 0);
6724 && (cmdp->cmdtype == CMDNORMAL
6725 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6727 find_command(name, &entry, DO_ERR, pathval());
6728 if (entry.cmdtype == CMDUNKNOWN)
6736 * Called when a cd is done. Marks all commands so the next time they
6737 * are executed they will be rehashed.
6742 struct tblentry **pp;
6743 struct tblentry *cmdp;
6745 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6746 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6747 if (cmdp->cmdtype == CMDNORMAL || (
6748 cmdp->cmdtype == CMDBUILTIN &&
6749 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6758 * Fix command hash table when PATH changed.
6759 * Called before PATH is changed. The argument is the new value of PATH;
6760 * pathval() still returns the old value at this point.
6761 * Called with interrupts off.
6764 changepath(const char *newval)
6766 const char *old, *new;
6773 firstchange = 9999; /* assume no change */
6779 if ((*old == '\0' && *new == ':')
6780 || (*old == ':' && *new == '\0'))
6782 old = new; /* ignore subsequent differences */
6786 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6793 if (builtinloc < 0 && idx_bltin >= 0)
6794 builtinloc = idx_bltin; /* zap builtins */
6795 if (builtinloc >= 0 && idx_bltin < 0)
6797 clearcmdentry(firstchange);
6798 builtinloc = idx_bltin;
6813 #define TENDBQUOTE 12
6831 /* first char is indicating which tokens mark the end of a list */
6832 static const char *const tokname_array[] = {
6846 #define KWDOFFSET 13
6847 /* the following are keywords */
6869 static char buf[16];
6872 //if (tok < TSEMI) return tokname_array[tok] + 1;
6873 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6878 sprintf(buf + (tok >= TSEMI), "%s%c",
6879 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6883 /* Wrapper around strcmp for qsort/bsearch/... */
6885 pstrcmp(const void *a, const void *b)
6887 return strcmp((char*) a, (*(char**) b) + 1);
6890 static const char *const *
6891 findkwd(const char *s)
6893 return bsearch(s, tokname_array + KWDOFFSET,
6894 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6895 sizeof(tokname_array[0]), pstrcmp);
6899 * Locate and print what a word is...
6902 describe_command(char *command, int describe_command_verbose)
6904 struct cmdentry entry;
6905 struct tblentry *cmdp;
6906 #if ENABLE_ASH_ALIAS
6907 const struct alias *ap;
6909 const char *path = pathval();
6911 if (describe_command_verbose) {
6915 /* First look at the keywords */
6916 if (findkwd(command)) {
6917 out1str(describe_command_verbose ? " is a shell keyword" : command);
6921 #if ENABLE_ASH_ALIAS
6922 /* Then look at the aliases */
6923 ap = lookupalias(command, 0);
6925 if (!describe_command_verbose) {
6930 out1fmt(" is an alias for %s", ap->val);
6934 /* Then check if it is a tracked alias */
6935 cmdp = cmdlookup(command, 0);
6937 entry.cmdtype = cmdp->cmdtype;
6938 entry.u = cmdp->param;
6940 /* Finally use brute force */
6941 find_command(command, &entry, DO_ABS, path);
6944 switch (entry.cmdtype) {
6946 int j = entry.u.index;
6952 p = padvance(&path, command);
6956 if (describe_command_verbose) {
6958 (cmdp ? " a tracked alias for" : nullstr), p
6967 if (describe_command_verbose) {
6968 out1str(" is a shell function");
6975 if (describe_command_verbose) {
6976 out1fmt(" is a %sshell builtin",
6977 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
6978 "special " : nullstr
6986 if (describe_command_verbose) {
6987 out1str(": not found\n");
6992 outstr("\n", stdout);
6997 typecmd(int argc, char **argv)
7003 /* type -p ... ? (we don't bother checking for 'p') */
7004 if (argv[1] && argv[1][0] == '-') {
7009 err |= describe_command(argv[i++], verbose);
7014 #if ENABLE_ASH_CMDCMD
7016 commandcmd(int argc, char **argv)
7024 while ((c = nextopt("pvV")) != '\0')
7026 verify |= VERIFY_VERBOSE;
7028 verify |= VERIFY_BRIEF;
7034 return describe_command(*argptr, verify - VERIFY_BRIEF);
7041 /* ============ eval.c */
7043 static int funcblocksize; /* size of structures in function */
7044 static int funcstringsize; /* size of strings in node */
7045 static void *funcblock; /* block to allocate function from */
7046 static char *funcstring; /* block to allocate strings from */
7048 /* flags in argument to evaltree */
7049 #define EV_EXIT 01 /* exit after evaluating tree */
7050 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7051 #define EV_BACKCMD 04 /* command executing within back quotes */
7053 static const short nodesize[26] = {
7054 SHELL_ALIGN(sizeof(struct ncmd)),
7055 SHELL_ALIGN(sizeof(struct npipe)),
7056 SHELL_ALIGN(sizeof(struct nredir)),
7057 SHELL_ALIGN(sizeof(struct nredir)),
7058 SHELL_ALIGN(sizeof(struct nredir)),
7059 SHELL_ALIGN(sizeof(struct nbinary)),
7060 SHELL_ALIGN(sizeof(struct nbinary)),
7061 SHELL_ALIGN(sizeof(struct nbinary)),
7062 SHELL_ALIGN(sizeof(struct nif)),
7063 SHELL_ALIGN(sizeof(struct nbinary)),
7064 SHELL_ALIGN(sizeof(struct nbinary)),
7065 SHELL_ALIGN(sizeof(struct nfor)),
7066 SHELL_ALIGN(sizeof(struct ncase)),
7067 SHELL_ALIGN(sizeof(struct nclist)),
7068 SHELL_ALIGN(sizeof(struct narg)),
7069 SHELL_ALIGN(sizeof(struct narg)),
7070 SHELL_ALIGN(sizeof(struct nfile)),
7071 SHELL_ALIGN(sizeof(struct nfile)),
7072 SHELL_ALIGN(sizeof(struct nfile)),
7073 SHELL_ALIGN(sizeof(struct nfile)),
7074 SHELL_ALIGN(sizeof(struct nfile)),
7075 SHELL_ALIGN(sizeof(struct ndup)),
7076 SHELL_ALIGN(sizeof(struct ndup)),
7077 SHELL_ALIGN(sizeof(struct nhere)),
7078 SHELL_ALIGN(sizeof(struct nhere)),
7079 SHELL_ALIGN(sizeof(struct nnot)),
7082 static void calcsize(union node *n);
7085 sizenodelist(struct nodelist *lp)
7088 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7095 calcsize(union node *n)
7099 funcblocksize += nodesize[n->type];
7102 calcsize(n->ncmd.redirect);
7103 calcsize(n->ncmd.args);
7104 calcsize(n->ncmd.assign);
7107 sizenodelist(n->npipe.cmdlist);
7112 calcsize(n->nredir.redirect);
7113 calcsize(n->nredir.n);
7120 calcsize(n->nbinary.ch2);
7121 calcsize(n->nbinary.ch1);
7124 calcsize(n->nif.elsepart);
7125 calcsize(n->nif.ifpart);
7126 calcsize(n->nif.test);
7129 funcstringsize += strlen(n->nfor.var) + 1;
7130 calcsize(n->nfor.body);
7131 calcsize(n->nfor.args);
7134 calcsize(n->ncase.cases);
7135 calcsize(n->ncase.expr);
7138 calcsize(n->nclist.body);
7139 calcsize(n->nclist.pattern);
7140 calcsize(n->nclist.next);
7144 sizenodelist(n->narg.backquote);
7145 funcstringsize += strlen(n->narg.text) + 1;
7146 calcsize(n->narg.next);
7153 calcsize(n->nfile.fname);
7154 calcsize(n->nfile.next);
7158 calcsize(n->ndup.vname);
7159 calcsize(n->ndup.next);
7163 calcsize(n->nhere.doc);
7164 calcsize(n->nhere.next);
7167 calcsize(n->nnot.com);
7173 nodeckstrdup(char *s)
7175 char *rtn = funcstring;
7177 strcpy(funcstring, s);
7178 funcstring += strlen(s) + 1;
7182 static union node *copynode(union node *);
7184 static struct nodelist *
7185 copynodelist(struct nodelist *lp)
7187 struct nodelist *start;
7188 struct nodelist **lpp;
7193 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7194 (*lpp)->n = copynode(lp->n);
7196 lpp = &(*lpp)->next;
7203 copynode(union node *n)
7210 funcblock = (char *) funcblock + nodesize[n->type];
7214 new->ncmd.redirect = copynode(n->ncmd.redirect);
7215 new->ncmd.args = copynode(n->ncmd.args);
7216 new->ncmd.assign = copynode(n->ncmd.assign);
7219 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7220 new->npipe.backgnd = n->npipe.backgnd;
7225 new->nredir.redirect = copynode(n->nredir.redirect);
7226 new->nredir.n = copynode(n->nredir.n);
7233 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7234 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7237 new->nif.elsepart = copynode(n->nif.elsepart);
7238 new->nif.ifpart = copynode(n->nif.ifpart);
7239 new->nif.test = copynode(n->nif.test);
7242 new->nfor.var = nodeckstrdup(n->nfor.var);
7243 new->nfor.body = copynode(n->nfor.body);
7244 new->nfor.args = copynode(n->nfor.args);
7247 new->ncase.cases = copynode(n->ncase.cases);
7248 new->ncase.expr = copynode(n->ncase.expr);
7251 new->nclist.body = copynode(n->nclist.body);
7252 new->nclist.pattern = copynode(n->nclist.pattern);
7253 new->nclist.next = copynode(n->nclist.next);
7257 new->narg.backquote = copynodelist(n->narg.backquote);
7258 new->narg.text = nodeckstrdup(n->narg.text);
7259 new->narg.next = copynode(n->narg.next);
7266 new->nfile.fname = copynode(n->nfile.fname);
7267 new->nfile.fd = n->nfile.fd;
7268 new->nfile.next = copynode(n->nfile.next);
7272 new->ndup.vname = copynode(n->ndup.vname);
7273 new->ndup.dupfd = n->ndup.dupfd;
7274 new->ndup.fd = n->ndup.fd;
7275 new->ndup.next = copynode(n->ndup.next);
7279 new->nhere.doc = copynode(n->nhere.doc);
7280 new->nhere.fd = n->nhere.fd;
7281 new->nhere.next = copynode(n->nhere.next);
7284 new->nnot.com = copynode(n->nnot.com);
7287 new->type = n->type;
7292 * Make a copy of a parse tree.
7294 static struct funcnode *
7295 copyfunc(union node *n)
7300 funcblocksize = offsetof(struct funcnode, n);
7303 blocksize = funcblocksize;
7304 f = ckmalloc(blocksize + funcstringsize);
7305 funcblock = (char *) f + offsetof(struct funcnode, n);
7306 funcstring = (char *) f + blocksize;
7313 * Define a shell function.
7316 defun(char *name, union node *func)
7318 struct cmdentry entry;
7321 entry.cmdtype = CMDFUNCTION;
7322 entry.u.func = copyfunc(func);
7323 addcmdentry(name, &entry);
7327 static int evalskip; /* set if we are skipping commands */
7328 /* reasons for skipping commands (see comment on breakcmd routine) */
7329 #define SKIPBREAK (1 << 0)
7330 #define SKIPCONT (1 << 1)
7331 #define SKIPFUNC (1 << 2)
7332 #define SKIPFILE (1 << 3)
7333 #define SKIPEVAL (1 << 4)
7334 static int skipcount; /* number of levels to skip */
7335 static int funcnest; /* depth of function calls */
7337 /* forward decl way out to parsing code - dotrap needs it */
7338 static int evalstring(char *s, int mask);
7341 * Called to execute a trap. Perhaps we should avoid entering new trap
7342 * handlers while we are executing a trap handler.
7353 savestatus = exitstatus;
7357 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7365 skip = evalstring(p, SKIPEVAL);
7366 exitstatus = savestatus;
7374 /* forward declarations - evaluation is fairly recursive business... */
7375 static void evalloop(union node *, int);
7376 static void evalfor(union node *, int);
7377 static void evalcase(union node *, int);
7378 static void evalsubshell(union node *, int);
7379 static void expredir(union node *);
7380 static void evalpipe(union node *, int);
7381 static void evalcommand(union node *, int);
7382 static int evalbltin(const struct builtincmd *, int, char **);
7383 static void prehash(union node *);
7386 * Evaluate a parse tree. The value is left in the global variable
7390 evaltree(union node *n, int flags)
7393 void (*evalfn)(union node *, int);
7397 TRACE(("evaltree(NULL) called\n"));
7400 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7401 getpid(), n, n->type, flags));
7405 out1fmt("Node type = %d\n", n->type);
7410 evaltree(n->nnot.com, EV_TESTED);
7411 status = !exitstatus;
7414 expredir(n->nredir.redirect);
7415 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7417 evaltree(n->nredir.n, flags & EV_TESTED);
7418 status = exitstatus;
7423 evalfn = evalcommand;
7425 if (eflag && !(flags & EV_TESTED))
7437 evalfn = evalsubshell;
7449 #error NAND + 1 != NOR
7451 #if NOR + 1 != NSEMI
7452 #error NOR + 1 != NSEMI
7454 isor = n->type - NAND;
7457 (flags | ((isor >> 1) - 1)) & EV_TESTED
7459 if (!exitstatus == isor)
7471 evaltree(n->nif.test, EV_TESTED);
7474 if (exitstatus == 0) {
7477 } else if (n->nif.elsepart) {
7478 n = n->nif.elsepart;
7483 defun(n->narg.text, n->narg.next);
7487 exitstatus = status;
7491 if ((checkexit & exitstatus))
7492 evalskip |= SKIPEVAL;
7493 else if (pendingsig && dotrap())
7496 if (flags & EV_EXIT) {
7498 raise_exception(EXEXIT);
7502 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7505 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7507 static int loopnest; /* current loop nesting level */
7510 evalloop(union node *n, int flags)
7520 evaltree(n->nbinary.ch1, EV_TESTED);
7523 if (evalskip == SKIPCONT && --skipcount <= 0) {
7527 if (evalskip == SKIPBREAK && --skipcount <= 0)
7532 if (n->type != NWHILE)
7536 evaltree(n->nbinary.ch2, flags);
7537 status = exitstatus;
7542 exitstatus = status;
7546 evalfor(union node *n, int flags)
7548 struct arglist arglist;
7551 struct stackmark smark;
7553 setstackmark(&smark);
7554 arglist.lastp = &arglist.list;
7555 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7556 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7561 *arglist.lastp = NULL;
7566 for (sp = arglist.list; sp; sp = sp->next) {
7567 setvar(n->nfor.var, sp->text, 0);
7568 evaltree(n->nfor.body, flags);
7570 if (evalskip == SKIPCONT && --skipcount <= 0) {
7574 if (evalskip == SKIPBREAK && --skipcount <= 0)
7581 popstackmark(&smark);
7585 evalcase(union node *n, int flags)
7589 struct arglist arglist;
7590 struct stackmark smark;
7592 setstackmark(&smark);
7593 arglist.lastp = &arglist.list;
7594 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7596 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7597 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7598 if (casematch(patp, arglist.list->text)) {
7599 if (evalskip == 0) {
7600 evaltree(cp->nclist.body, flags);
7607 popstackmark(&smark);
7611 * Kick off a subshell to evaluate a tree.
7614 evalsubshell(union node *n, int flags)
7617 int backgnd = (n->type == NBACKGND);
7620 expredir(n->nredir.redirect);
7621 if (!backgnd && flags & EV_EXIT && !trap[0])
7625 if (forkshell(jp, n, backgnd) == 0) {
7629 flags &=~ EV_TESTED;
7631 redirect(n->nredir.redirect, 0);
7632 evaltreenr(n->nredir.n, flags);
7637 status = waitforjob(jp);
7638 exitstatus = status;
7643 * Compute the names of the files in a redirection list.
7645 static void fixredir(union node *, const char *, int);
7647 expredir(union node *n)
7651 for (redir = n; redir; redir = redir->nfile.next) {
7654 memset(&fn, 0, sizeof(fn));
7655 fn.lastp = &fn.list;
7656 switch (redir->type) {
7662 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7663 redir->nfile.expfname = fn.list->text;
7667 if (redir->ndup.vname) {
7668 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7669 if (fn.list == NULL)
7670 ash_msg_and_raise_error("redir error");
7671 fixredir(redir, fn.list->text, 1);
7679 * Evaluate a pipeline. All the processes in the pipeline are children
7680 * of the process creating the pipeline. (This differs from some versions
7681 * of the shell, which make the last process in a pipeline the parent
7685 evalpipe(union node *n, int flags)
7688 struct nodelist *lp;
7693 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7695 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7699 jp = makejob(n, pipelen);
7701 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7705 if (pipe(pip) < 0) {
7707 ash_msg_and_raise_error("pipe call failed");
7710 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7723 evaltreenr(lp->n, flags);
7731 if (n->npipe.backgnd == 0) {
7732 exitstatus = waitforjob(jp);
7733 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7739 * Controls whether the shell is interactive or not.
7742 setinteractive(int on)
7744 static int is_interactive;
7746 if (++on == is_interactive)
7748 is_interactive = on;
7752 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7753 if (is_interactive > 1) {
7754 /* Looks like they want an interactive shell */
7755 static smallint did_banner;
7760 "%s built-in shell (ash)\n"
7761 "Enter 'help' for a list of built-in commands."
7770 #if ENABLE_FEATURE_EDITING_VI
7771 #define setvimode(on) do { \
7772 if (on) line_input_state->flags |= VI_MODE; \
7773 else line_input_state->flags &= ~VI_MODE; \
7776 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7785 setinteractive(iflag);
7790 static struct localvar *localvars;
7793 * Called after a function returns.
7794 * Interrupts must be off.
7799 struct localvar *lvp;
7802 while ((lvp = localvars) != NULL) {
7803 localvars = lvp->next;
7805 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7806 if (vp == NULL) { /* $- saved */
7807 memcpy(optlist, lvp->text, sizeof(optlist));
7808 free((char*)lvp->text);
7810 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7814 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7815 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7816 free((char*)vp->text);
7817 vp->flags = lvp->flags;
7818 vp->text = lvp->text;
7825 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7827 volatile struct shparam saveparam;
7828 struct localvar *volatile savelocalvars;
7829 struct jmploc *volatile savehandler;
7830 struct jmploc jmploc;
7833 saveparam = shellparam;
7834 savelocalvars = localvars;
7835 e = setjmp(jmploc.loc);
7840 savehandler = exception_handler;
7841 exception_handler = &jmploc;
7843 shellparam.malloc = 0;
7847 shellparam.nparam = argc - 1;
7848 shellparam.p = argv + 1;
7849 #if ENABLE_ASH_GETOPTS
7850 shellparam.optind = 1;
7851 shellparam.optoff = -1;
7853 evaltree(&func->n, flags & EV_TESTED);
7859 localvars = savelocalvars;
7860 freeparam(&shellparam);
7861 shellparam = saveparam;
7862 exception_handler = savehandler;
7864 evalskip &= ~SKIPFUNC;
7868 #if ENABLE_ASH_CMDCMD
7870 parse_command_args(char **argv, const char **path)
7883 if (c == '-' && !*cp) {
7890 *path = bb_default_path;
7893 /* run 'typecmd' for other options */
7904 * Make a variable a local variable. When a variable is made local, it's
7905 * value and flags are saved in a localvar structure. The saved values
7906 * will be restored when the shell function returns. We handle the name
7907 * "-" as a special case.
7912 struct localvar *lvp;
7917 lvp = ckmalloc(sizeof(struct localvar));
7918 if (LONE_DASH(name)) {
7920 p = ckmalloc(sizeof(optlist));
7921 lvp->text = memcpy(p, optlist, sizeof(optlist));
7926 vpp = hashvar(name);
7927 vp = *findvar(vpp, name);
7928 eq = strchr(name, '=');
7931 setvareq(name, VSTRFIXED);
7933 setvar(name, NULL, VSTRFIXED);
7934 vp = *vpp; /* the new variable */
7935 lvp->flags = VUNSET;
7937 lvp->text = vp->text;
7938 lvp->flags = vp->flags;
7939 vp->flags |= VSTRFIXED|VTEXTFIXED;
7945 lvp->next = localvars;
7951 * The "local" command.
7954 localcmd(int argc, char **argv)
7959 while ((name = *argv++) != NULL) {
7966 falsecmd(int argc, char **argv)
7972 truecmd(int argc, char **argv)
7978 execcmd(int argc, char **argv)
7981 iflag = 0; /* exit on error */
7984 shellexec(argv + 1, pathval(), 0);
7990 * The return command.
7993 returncmd(int argc, char **argv)
7996 * If called outside a function, do what ksh does;
7997 * skip the rest of the file.
7999 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8000 return argv[1] ? number(argv[1]) : exitstatus;
8003 /* Forward declarations for builtintab[] */
8004 static int breakcmd(int, char **);
8005 static int dotcmd(int, char **);
8006 static int evalcmd(int, char **);
8007 #if ENABLE_ASH_BUILTIN_ECHO
8008 static int echocmd(int, char **);
8010 #if ENABLE_ASH_BUILTIN_TEST
8011 static int testcmd(int, char **);
8013 static int exitcmd(int, char **);
8014 static int exportcmd(int, char **);
8015 #if ENABLE_ASH_GETOPTS
8016 static int getoptscmd(int, char **);
8018 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8019 static int helpcmd(int argc, char **argv);
8021 #if ENABLE_ASH_MATH_SUPPORT
8022 static int letcmd(int, char **);
8024 static int readcmd(int, char **);
8025 static int setcmd(int, char **);
8026 static int shiftcmd(int, char **);
8027 static int timescmd(int, char **);
8028 static int trapcmd(int, char **);
8029 static int umaskcmd(int, char **);
8030 static int unsetcmd(int, char **);
8031 static int ulimitcmd(int, char **);
8033 #define BUILTIN_NOSPEC "0"
8034 #define BUILTIN_SPECIAL "1"
8035 #define BUILTIN_REGULAR "2"
8036 #define BUILTIN_SPEC_REG "3"
8037 #define BUILTIN_ASSIGN "4"
8038 #define BUILTIN_SPEC_ASSG "5"
8039 #define BUILTIN_REG_ASSG "6"
8040 #define BUILTIN_SPEC_REG_ASSG "7"
8042 /* make sure to keep these in proper order since it is searched via bsearch() */
8043 static const struct builtincmd builtintab[] = {
8044 { BUILTIN_SPEC_REG ".", dotcmd },
8045 { BUILTIN_SPEC_REG ":", truecmd },
8046 #if ENABLE_ASH_BUILTIN_TEST
8047 { BUILTIN_REGULAR "[", testcmd },
8048 { BUILTIN_REGULAR "[[", testcmd },
8050 #if ENABLE_ASH_ALIAS
8051 { BUILTIN_REG_ASSG "alias", aliascmd },
8054 { BUILTIN_REGULAR "bg", fg_bgcmd },
8056 { BUILTIN_SPEC_REG "break", breakcmd },
8057 { BUILTIN_REGULAR "cd", cdcmd },
8058 { BUILTIN_NOSPEC "chdir", cdcmd },
8059 #if ENABLE_ASH_CMDCMD
8060 { BUILTIN_REGULAR "command", commandcmd },
8062 { BUILTIN_SPEC_REG "continue", breakcmd },
8063 #if ENABLE_ASH_BUILTIN_ECHO
8064 { BUILTIN_REGULAR "echo", echocmd },
8066 { BUILTIN_SPEC_REG "eval", evalcmd },
8067 { BUILTIN_SPEC_REG "exec", execcmd },
8068 { BUILTIN_SPEC_REG "exit", exitcmd },
8069 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8070 { BUILTIN_REGULAR "false", falsecmd },
8072 { BUILTIN_REGULAR "fg", fg_bgcmd },
8074 #if ENABLE_ASH_GETOPTS
8075 { BUILTIN_REGULAR "getopts", getoptscmd },
8077 { BUILTIN_NOSPEC "hash", hashcmd },
8078 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8079 { BUILTIN_NOSPEC "help", helpcmd },
8082 { BUILTIN_REGULAR "jobs", jobscmd },
8083 { BUILTIN_REGULAR "kill", killcmd },
8085 #if ENABLE_ASH_MATH_SUPPORT
8086 { BUILTIN_NOSPEC "let", letcmd },
8088 { BUILTIN_ASSIGN "local", localcmd },
8089 { BUILTIN_NOSPEC "pwd", pwdcmd },
8090 { BUILTIN_REGULAR "read", readcmd },
8091 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8092 { BUILTIN_SPEC_REG "return", returncmd },
8093 { BUILTIN_SPEC_REG "set", setcmd },
8094 { BUILTIN_SPEC_REG "shift", shiftcmd },
8095 { BUILTIN_SPEC_REG "source", dotcmd },
8096 #if ENABLE_ASH_BUILTIN_TEST
8097 { BUILTIN_REGULAR "test", testcmd },
8099 { BUILTIN_SPEC_REG "times", timescmd },
8100 { BUILTIN_SPEC_REG "trap", trapcmd },
8101 { BUILTIN_REGULAR "true", truecmd },
8102 { BUILTIN_NOSPEC "type", typecmd },
8103 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8104 { BUILTIN_REGULAR "umask", umaskcmd },
8105 #if ENABLE_ASH_ALIAS
8106 { BUILTIN_REGULAR "unalias", unaliascmd },
8108 { BUILTIN_SPEC_REG "unset", unsetcmd },
8109 { BUILTIN_REGULAR "wait", waitcmd },
8113 #define COMMANDCMD (builtintab + 5 + \
8114 2 * ENABLE_ASH_BUILTIN_TEST + \
8115 ENABLE_ASH_ALIAS + \
8116 ENABLE_ASH_JOB_CONTROL)
8117 #define EXECCMD (builtintab + 7 + \
8118 2 * ENABLE_ASH_BUILTIN_TEST + \
8119 ENABLE_ASH_ALIAS + \
8120 ENABLE_ASH_JOB_CONTROL + \
8121 ENABLE_ASH_CMDCMD + \
8122 ENABLE_ASH_BUILTIN_ECHO)
8125 * Search the table of builtin commands.
8127 static struct builtincmd *
8128 find_builtin(const char *name)
8130 struct builtincmd *bp;
8133 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8140 * Execute a simple command.
8142 static int back_exitstatus; /* exit status of backquoted command */
8144 isassignment(const char *p)
8146 const char *q = endofname(p);
8152 bltincmd(int argc, char **argv)
8154 /* Preserve exitstatus of a previous possible redirection
8155 * as POSIX mandates */
8156 return back_exitstatus;
8159 evalcommand(union node *cmd, int flags)
8161 static const struct builtincmd bltin = {
8164 struct stackmark smark;
8166 struct arglist arglist;
8167 struct arglist varlist;
8170 const struct strlist *sp;
8171 struct cmdentry cmdentry;
8179 struct builtincmd *bcmd;
8180 int pseudovarflag = 0;
8182 /* First expand the arguments. */
8183 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8184 setstackmark(&smark);
8185 back_exitstatus = 0;
8187 cmdentry.cmdtype = CMDBUILTIN;
8188 cmdentry.u.cmd = &bltin;
8189 varlist.lastp = &varlist.list;
8190 *varlist.lastp = NULL;
8191 arglist.lastp = &arglist.list;
8192 *arglist.lastp = NULL;
8195 if (cmd->ncmd.args) {
8196 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8197 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8200 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8201 struct strlist **spp;
8203 spp = arglist.lastp;
8204 if (pseudovarflag && isassignment(argp->narg.text))
8205 expandarg(argp, &arglist, EXP_VARTILDE);
8207 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8209 for (sp = *spp; sp; sp = sp->next)
8213 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8214 for (sp = arglist.list; sp; sp = sp->next) {
8215 TRACE(("evalcommand arg: %s\n", sp->text));
8216 *nargv++ = sp->text;
8221 if (iflag && funcnest == 0 && argc > 0)
8222 lastarg = nargv[-1];
8225 expredir(cmd->ncmd.redirect);
8226 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8229 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8230 struct strlist **spp;
8233 spp = varlist.lastp;
8234 expandarg(argp, &varlist, EXP_VARTILDE);
8237 * Modify the command lookup path, if a PATH= assignment
8241 if (varequal(p, path))
8245 /* Print the command if xflag is set. */
8248 const char *p = " %s";
8251 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8254 for (n = 0; n < 2; n++) {
8256 fdprintf(preverrout_fd, p, sp->text);
8264 full_write(preverrout_fd, "\n", 1);
8270 /* Now locate the command. */
8272 const char *oldpath;
8273 int cmd_flag = DO_ERR;
8278 find_command(argv[0], &cmdentry, cmd_flag, path);
8279 if (cmdentry.cmdtype == CMDUNKNOWN) {
8285 /* implement bltin and command here */
8286 if (cmdentry.cmdtype != CMDBUILTIN)
8289 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8290 if (cmdentry.u.cmd == EXECCMD)
8292 #if ENABLE_ASH_CMDCMD
8293 if (cmdentry.u.cmd == COMMANDCMD) {
8295 nargv = parse_command_args(argv, &path);
8298 argc -= nargv - argv;
8300 cmd_flag |= DO_NOFUNC;
8308 /* We have a redirection error. */
8310 raise_exception(EXERROR);
8312 exitstatus = status;
8316 /* Execute the command. */
8317 switch (cmdentry.cmdtype) {
8319 /* Fork off a child process if necessary. */
8320 if (!(flags & EV_EXIT) || trap[0]) {
8322 jp = makejob(cmd, 1);
8323 if (forkshell(jp, cmd, FORK_FG) != 0) {
8324 exitstatus = waitforjob(jp);
8330 listsetvar(varlist.list, VEXPORT|VSTACK);
8331 shellexec(argv, path, cmdentry.u.index);
8335 cmdenviron = varlist.list;
8337 struct strlist *list = cmdenviron;
8339 if (spclbltin > 0 || argc == 0) {
8341 if (cmd_is_exec && argc > 1)
8344 listsetvar(list, i);
8346 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8361 exit_status = j + 128;
8362 exitstatus = exit_status;
8364 if (i == EXINT || spclbltin > 0) {
8366 longjmp(exception_handler->loc, 1);
8373 listsetvar(varlist.list, 0);
8374 if (evalfun(cmdentry.u.func, argc, argv, flags))
8380 popredir(cmd_is_exec);
8382 /* dsl: I think this is intended to be used to support
8383 * '_' in 'vi' command mode during line editing...
8384 * However I implemented that within libedit itself.
8386 setvar("_", lastarg, 0);
8387 popstackmark(&smark);
8391 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8393 char *volatile savecmdname;
8394 struct jmploc *volatile savehandler;
8395 struct jmploc jmploc;
8398 savecmdname = commandname;
8399 i = setjmp(jmploc.loc);
8402 savehandler = exception_handler;
8403 exception_handler = &jmploc;
8404 commandname = argv[0];
8406 optptr = NULL; /* initialize nextopt */
8407 exitstatus = (*cmd->builtin)(argc, argv);
8408 flush_stdout_stderr();
8410 exitstatus |= ferror(stdout);
8412 commandname = savecmdname;
8414 exception_handler = savehandler;
8420 goodname(const char *p)
8422 return !*endofname(p);
8427 * Search for a command. This is called before we fork so that the
8428 * location of the command will be available in the parent as well as
8429 * the child. The check for "goodname" is an overly conservative
8430 * check that the name will not be subject to expansion.
8433 prehash(union node *n)
8435 struct cmdentry entry;
8437 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8438 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8442 /* ============ Builtin commands
8444 * Builtin commands whose functions are closely tied to evaluation
8445 * are implemented here.
8449 * Handle break and continue commands. Break, continue, and return are
8450 * all handled by setting the evalskip flag. The evaluation routines
8451 * above all check this flag, and if it is set they start skipping
8452 * commands rather than executing them. The variable skipcount is
8453 * the number of loops to break/continue, or the number of function
8454 * levels to return. (The latter is always 1.) It should probably
8455 * be an error to break out of more loops than exist, but it isn't
8456 * in the standard shell so we don't make it one here.
8459 breakcmd(int argc, char **argv)
8461 int n = argc > 1 ? number(argv[1]) : 1;
8464 ash_msg_and_raise_error(illnum, argv[1]);
8468 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8475 /* ============ input.c
8477 * This implements the input routines used by the parser.
8480 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8483 INPUT_PUSH_FILE = 1,
8484 INPUT_NOFILE_OK = 2,
8487 static int plinno = 1; /* input line number */
8488 /* number of characters left in input buffer */
8489 static int parsenleft; /* copy of parsefile->nleft */
8490 static int parselleft; /* copy of parsefile->lleft */
8491 /* next character in input buffer */
8492 static char *parsenextc; /* copy of parsefile->nextc */
8494 static int checkkwd;
8495 /* values of checkkwd variable */
8496 #define CHKALIAS 0x1
8503 struct strpush *sp = parsefile->strpush;
8506 #if ENABLE_ASH_ALIAS
8508 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8509 checkkwd |= CHKALIAS;
8511 if (sp->string != sp->ap->val) {
8514 sp->ap->flag &= ~ALIASINUSE;
8515 if (sp->ap->flag & ALIASDEAD) {
8516 unalias(sp->ap->name);
8520 parsenextc = sp->prevstring;
8521 parsenleft = sp->prevnleft;
8522 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8523 parsefile->strpush = sp->prev;
8524 if (sp != &(parsefile->basestrpush))
8533 char *buf = parsefile->buf;
8537 #if ENABLE_FEATURE_EDITING
8538 if (!iflag || parsefile->fd)
8539 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8541 #if ENABLE_FEATURE_TAB_COMPLETION
8542 line_input_state->path_lookup = pathval();
8544 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8546 /* Ctrl+C pressed */
8555 if (nr < 0 && errno == 0) {
8556 /* Ctrl+D presend */
8561 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8565 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8566 int flags = fcntl(0, F_GETFL);
8567 if (flags >= 0 && flags & O_NONBLOCK) {
8568 flags &=~ O_NONBLOCK;
8569 if (fcntl(0, F_SETFL, flags) >= 0) {
8570 out2str("sh: turning off NDELAY mode\n");
8580 * Refill the input buffer and return the next input character:
8582 * 1) If a string was pushed back on the input, pop it;
8583 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8584 * from a string so we can't refill the buffer, return EOF.
8585 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8586 * 4) Process input up to the next newline, deleting nul characters.
8595 while (parsefile->strpush) {
8596 #if ENABLE_ASH_ALIAS
8597 if (parsenleft == -1 && parsefile->strpush->ap &&
8598 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8603 if (--parsenleft >= 0)
8604 return signed_char2int(*parsenextc++);
8606 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8608 flush_stdout_stderr();
8615 parselleft = parsenleft = EOF_NLEFT;
8622 /* delete nul characters */
8630 memmove(q, q + 1, more);
8634 parsenleft = q - parsenextc - 1;
8640 parsenleft = q - parsenextc - 1;
8652 out2str(parsenextc);
8657 return signed_char2int(*parsenextc++);
8660 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8664 return pgetc_as_macro();
8667 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8668 #define pgetc_macro() pgetc()
8670 #define pgetc_macro() pgetc_as_macro()
8674 * Same as pgetc(), but ignores PEOA.
8676 #if ENABLE_ASH_ALIAS
8684 } while (c == PEOA);
8691 return pgetc_macro();
8696 * Read a line from the script.
8699 pfgets(char *line, int len)
8705 while (--nleft > 0) {
8721 * Undo the last call to pgetc. Only one character may be pushed back.
8722 * PEOF may be pushed back.
8732 * Push a string back onto the input at this current parsefile level.
8733 * We handle aliases this way.
8736 pushstring(char *s, void *ap)
8743 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8744 if (parsefile->strpush) {
8745 sp = ckmalloc(sizeof(struct strpush));
8746 sp->prev = parsefile->strpush;
8747 parsefile->strpush = sp;
8749 sp = parsefile->strpush = &(parsefile->basestrpush);
8750 sp->prevstring = parsenextc;
8751 sp->prevnleft = parsenleft;
8752 #if ENABLE_ASH_ALIAS
8753 sp->ap = (struct alias *)ap;
8755 ((struct alias *)ap)->flag |= ALIASINUSE;
8765 * To handle the "." command, a stack of input files is used. Pushfile
8766 * adds a new entry to the stack and popfile restores the previous level.
8771 struct parsefile *pf;
8773 parsefile->nleft = parsenleft;
8774 parsefile->lleft = parselleft;
8775 parsefile->nextc = parsenextc;
8776 parsefile->linno = plinno;
8777 pf = ckmalloc(sizeof(*pf));
8778 pf->prev = parsefile;
8781 pf->basestrpush.prev = NULL;
8788 struct parsefile *pf = parsefile;
8796 parsefile = pf->prev;
8798 parsenleft = parsefile->nleft;
8799 parselleft = parsefile->lleft;
8800 parsenextc = parsefile->nextc;
8801 plinno = parsefile->linno;
8806 * Return to top level.
8811 while (parsefile != &basepf)
8816 * Close the file(s) that the shell is reading commands from. Called
8817 * after a fork is done.
8823 if (parsefile->fd > 0) {
8824 close(parsefile->fd);
8830 * Like setinputfile, but takes an open file descriptor. Call this with
8834 setinputfd(int fd, int push)
8836 close_on_exec_on(fd);
8842 if (parsefile->buf == NULL)
8843 parsefile->buf = ckmalloc(IBUFSIZ);
8844 parselleft = parsenleft = 0;
8849 * Set the input to take input from a file. If push is set, push the
8850 * old input onto the stack first.
8853 setinputfile(const char *fname, int flags)
8859 fd = open(fname, O_RDONLY);
8861 if (flags & INPUT_NOFILE_OK)
8863 ash_msg_and_raise_error("can't open %s", fname);
8866 fd2 = copyfd(fd, 10);
8869 ash_msg_and_raise_error("out of file descriptors");
8872 setinputfd(fd, flags & INPUT_PUSH_FILE);
8879 * Like setinputfile, but takes input from a string.
8882 setinputstring(char *string)
8886 parsenextc = string;
8887 parsenleft = strlen(string);
8888 parsefile->buf = NULL;
8894 /* ============ mail.c
8896 * Routines to check for mail.
8901 #define MAXMBOXES 10
8903 /* times of mailboxes */
8904 static time_t mailtime[MAXMBOXES];
8905 /* Set if MAIL or MAILPATH is changed. */
8906 static smallint mail_var_path_changed;
8909 * Print appropriate message(s) if mail has arrived.
8910 * If mail_var_path_changed is set,
8911 * then the value of MAIL has mail_var_path_changed,
8912 * so we just update the values.
8921 struct stackmark smark;
8924 setstackmark(&smark);
8925 mpath = mpathset() ? mpathval() : mailval();
8926 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8927 p = padvance(&mpath, nullstr);
8932 for (q = p; *q; q++);
8937 q[-1] = '\0'; /* delete trailing '/' */
8938 if (stat(p, &statb) < 0) {
8942 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
8945 pathopt ? pathopt : "you have mail"
8948 *mtp = statb.st_mtime;
8950 mail_var_path_changed = 0;
8951 popstackmark(&smark);
8955 changemail(const char *val)
8957 mail_var_path_changed = 1;
8960 #endif /* ASH_MAIL */
8963 /* ============ ??? */
8966 * Set the shell parameters.
8969 setparam(char **argv)
8975 for (nparam = 0; argv[nparam]; nparam++);
8976 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
8978 *ap++ = ckstrdup(*argv++);
8981 freeparam(&shellparam);
8982 shellparam.malloc = 1;
8983 shellparam.nparam = nparam;
8984 shellparam.p = newparam;
8985 #if ENABLE_ASH_GETOPTS
8986 shellparam.optind = 1;
8987 shellparam.optoff = -1;
8992 * Process shell options. The global variable argptr contains a pointer
8993 * to the argument list; we advance it past the options.
8996 minus_o(char *name, int val)
9001 for (i = 0; i < NOPTS; i++) {
9002 if (strcmp(name, optnames(i)) == 0) {
9007 ash_msg_and_raise_error("illegal option -o %s", name);
9009 out1str("Current option settings\n");
9010 for (i = 0; i < NOPTS; i++)
9011 out1fmt("%-16s%s\n", optnames(i),
9012 optlist[i] ? "on" : "off");
9015 setoption(int flag, int val)
9019 for (i = 0; i < NOPTS; i++) {
9020 if (optletters(i) == flag) {
9025 ash_msg_and_raise_error("illegal option -%c", flag);
9029 options(int cmdline)
9037 while ((p = *argptr) != NULL) {
9039 if (c != '-' && c != '+')
9042 val = 0; /* val = 0 if c == '+' */
9045 if (p[0] == '\0' || LONE_DASH(p)) {
9047 /* "-" means turn off -x and -v */
9050 /* "--" means reset params */
9051 else if (*argptr == NULL)
9054 break; /* "-" or "--" terminates options */
9057 /* first char was + or - */
9058 while ((c = *p++) != '\0') {
9059 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9060 if (c == 'c' && cmdline) {
9061 minusc = p; /* command is after shell args */
9062 } else if (c == 'o') {
9063 minus_o(*argptr, val);
9066 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9068 /* bash does not accept +-login, we also won't */
9069 } else if (cmdline && val && (c == '-')) { /* long options */
9070 if (strcmp(p, "login") == 0)
9081 * The shift builtin command.
9084 shiftcmd(int argc, char **argv)
9091 n = number(argv[1]);
9092 if (n > shellparam.nparam)
9093 ash_msg_and_raise_error("can't shift that many");
9095 shellparam.nparam -= n;
9096 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9097 if (shellparam.malloc)
9101 while ((*ap2++ = *ap1++) != NULL);
9102 #if ENABLE_ASH_GETOPTS
9103 shellparam.optind = 1;
9104 shellparam.optoff = -1;
9111 * POSIX requires that 'set' (but not export or readonly) output the
9112 * variables in lexicographic order - by the locale's collating order (sigh).
9113 * Maybe we could keep them in an ordered balanced binary tree
9114 * instead of hashed lists.
9115 * For now just roll 'em through qsort for printing...
9118 showvars(const char *sep_prefix, int on, int off)
9123 ep = listvars(on, off, &epend);
9124 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9126 sep = *sep_prefix ? " " : sep_prefix;
9128 for (; ep < epend; ep++) {
9132 p = strchrnul(*ep, '=');
9135 q = single_quote(++p);
9136 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9142 * The set command builtin.
9145 setcmd(int argc, char **argv)
9148 return showvars(nullstr, 0, VUNSET);
9152 if (*argptr != NULL) {
9159 #if ENABLE_ASH_RANDOM_SUPPORT
9160 /* Roughly copied from bash.. */
9162 change_random(const char *value)
9164 if (value == NULL) {
9165 /* "get", generate */
9168 rseed = rseed * 1103515245 + 12345;
9169 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9170 /* set without recursion */
9171 setvar(vrandom.text, buf, VNOFUNC);
9172 vrandom.flags &= ~VNOFUNC;
9175 rseed = strtoul(value, (char **)NULL, 10);
9180 #if ENABLE_ASH_GETOPTS
9182 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9191 if (*param_optind < 1)
9193 optnext = optfirst + *param_optind - 1;
9195 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9198 p = optnext[-1] + *optoff;
9199 if (p == NULL || *p == '\0') {
9200 /* Current word is done, advance */
9202 if (p == NULL || *p != '-' || *++p == '\0') {
9209 if (LONE_DASH(p)) /* check for "--" */
9214 for (q = optstr; *q != c; ) {
9216 if (optstr[0] == ':') {
9219 err |= setvarsafe("OPTARG", s, 0);
9221 fprintf(stderr, "Illegal option -%c\n", c);
9232 if (*p == '\0' && (p = *optnext) == NULL) {
9233 if (optstr[0] == ':') {
9236 err |= setvarsafe("OPTARG", s, 0);
9239 fprintf(stderr, "No arg for -%c option\n", c);
9248 err |= setvarsafe("OPTARG", p, 0);
9251 err |= setvarsafe("OPTARG", nullstr, 0);
9253 *optoff = p ? p - *(optnext - 1) : -1;
9254 *param_optind = optnext - optfirst + 1;
9255 fmtstr(s, sizeof(s), "%d", *param_optind);
9256 err |= setvarsafe("OPTIND", s, VNOFUNC);
9259 err |= setvarsafe(optvar, s, 0);
9263 flush_stdout_stderr();
9264 raise_exception(EXERROR);
9270 * The getopts builtin. Shellparam.optnext points to the next argument
9271 * to be processed. Shellparam.optptr points to the next character to
9272 * be processed in the current argument. If shellparam.optnext is NULL,
9273 * then it's the first time getopts has been called.
9276 getoptscmd(int argc, char **argv)
9281 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9283 optbase = shellparam.p;
9284 if (shellparam.optind > shellparam.nparam + 1) {
9285 shellparam.optind = 1;
9286 shellparam.optoff = -1;
9290 if (shellparam.optind > argc - 2) {
9291 shellparam.optind = 1;
9292 shellparam.optoff = -1;
9296 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9297 &shellparam.optoff);
9299 #endif /* ASH_GETOPTS */
9302 /* ============ Shell parser */
9305 * NEOF is returned by parsecmd when it encounters an end of file. It
9306 * must be distinct from NULL, so we use the address of a variable that
9307 * happens to be handy.
9309 static smallint tokpushback; /* last token pushed back */
9310 #define NEOF ((union node *)&tokpushback)
9311 static smallint parsebackquote; /* nonzero if we are inside backquotes */
9312 static int lasttoken; /* last token read */
9313 static char *wordtext; /* text of last word returned by readtoken */
9314 static struct nodelist *backquotelist;
9315 static union node *redirnode;
9316 static struct heredoc *heredoc;
9317 static smallint quoteflag; /* set if (part of) last token was quoted */
9319 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9321 raise_error_syntax(const char *msg)
9323 ash_msg_and_raise_error("syntax error: %s", msg);
9328 * Called when an unexpected token is read during the parse. The argument
9329 * is the token that is expected, or -1 if more than one type of token can
9330 * occur at this point.
9332 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9334 raise_error_unexpected_syntax(int token)
9339 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9341 sprintf(msg + l, " (expecting %s)", tokname(token));
9342 raise_error_syntax(msg);
9346 #define EOFMARKLEN 79
9349 struct heredoc *next; /* next here document in list */
9350 union node *here; /* redirection node */
9351 char *eofmark; /* string indicating end of input */
9352 int striptabs; /* if set, strip leading tabs */
9355 static struct heredoc *heredoclist; /* list of here documents to read */
9357 /* parsing is heavily cross-recursive, need these forward decls */
9358 static union node *andor(void);
9359 static union node *pipeline(void);
9360 static union node *parse_command(void);
9361 static void parseheredoc(void);
9362 static char peektoken(void);
9363 static int readtoken(void);
9368 union node *n1, *n2, *n3;
9371 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9372 if (nlflag == 2 && peektoken())
9378 if (tok == TBACKGND) {
9379 if (n2->type == NPIPE) {
9380 n2->npipe.backgnd = 1;
9382 if (n2->type != NREDIR) {
9383 n3 = stalloc(sizeof(struct nredir));
9385 n3->nredir.redirect = NULL;
9388 n2->type = NBACKGND;
9394 n3 = stalloc(sizeof(struct nbinary));
9396 n3->nbinary.ch1 = n1;
9397 n3->nbinary.ch2 = n2;
9413 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9421 pungetc(); /* push back EOF on input */
9425 raise_error_unexpected_syntax(-1);
9435 union node *n1, *n2, *n3;
9443 } else if (t == TOR) {
9449 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9451 n3 = stalloc(sizeof(struct nbinary));
9453 n3->nbinary.ch1 = n1;
9454 n3->nbinary.ch2 = n2;
9462 union node *n1, *n2, *pipenode;
9463 struct nodelist *lp, *prev;
9467 TRACE(("pipeline: entered\n"));
9468 if (readtoken() == TNOT) {
9470 checkkwd = CHKKWD | CHKALIAS;
9473 n1 = parse_command();
9474 if (readtoken() == TPIPE) {
9475 pipenode = stalloc(sizeof(struct npipe));
9476 pipenode->type = NPIPE;
9477 pipenode->npipe.backgnd = 0;
9478 lp = stalloc(sizeof(struct nodelist));
9479 pipenode->npipe.cmdlist = lp;
9483 lp = stalloc(sizeof(struct nodelist));
9484 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9485 lp->n = parse_command();
9487 } while (readtoken() == TPIPE);
9493 n2 = stalloc(sizeof(struct nnot));
9506 n = stalloc(sizeof(struct narg));
9508 n->narg.next = NULL;
9509 n->narg.text = wordtext;
9510 n->narg.backquote = backquotelist;
9515 fixredir(union node *n, const char *text, int err)
9517 TRACE(("Fix redir %s %d\n", text, err));
9519 n->ndup.vname = NULL;
9521 if (isdigit(text[0]) && text[1] == '\0')
9522 n->ndup.dupfd = text[0] - '0';
9523 else if (LONE_DASH(text))
9527 raise_error_syntax("Bad fd number");
9528 n->ndup.vname = makename();
9533 * Returns true if the text contains nothing to expand (no dollar signs
9537 noexpand(char *text)
9543 while ((c = *p++) != '\0') {
9544 if (c == CTLQUOTEMARK)
9548 else if (SIT(c, BASESYNTAX) == CCTL)
9557 union node *n = redirnode;
9559 if (readtoken() != TWORD)
9560 raise_error_unexpected_syntax(-1);
9561 if (n->type == NHERE) {
9562 struct heredoc *here = heredoc;
9568 TRACE(("Here document %d\n", n->type));
9569 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9570 raise_error_syntax("Illegal eof marker for << redirection");
9571 rmescapes(wordtext);
9572 here->eofmark = wordtext;
9574 if (heredoclist == NULL)
9577 for (p = heredoclist; p->next; p = p->next);
9580 } else if (n->type == NTOFD || n->type == NFROMFD) {
9581 fixredir(n, wordtext, 0);
9583 n->nfile.fname = makename();
9590 union node *args, **app;
9591 union node *n = NULL;
9592 union node *vars, **vpp;
9593 union node **rpp, *redir;
9603 savecheckkwd = CHKALIAS;
9605 checkkwd = savecheckkwd;
9606 switch (readtoken()) {
9608 n = stalloc(sizeof(struct narg));
9610 n->narg.text = wordtext;
9611 n->narg.backquote = backquotelist;
9612 if (savecheckkwd && isassignment(wordtext)) {
9614 vpp = &n->narg.next;
9617 app = &n->narg.next;
9622 *rpp = n = redirnode;
9623 rpp = &n->nfile.next;
9624 parsefname(); /* read name of redirection file */
9627 if (args && app == &args->narg.next
9630 struct builtincmd *bcmd;
9633 /* We have a function */
9634 if (readtoken() != TRP)
9635 raise_error_unexpected_syntax(TRP);
9636 name = n->narg.text;
9638 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9640 raise_error_syntax("Bad function name");
9643 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9644 n->narg.next = parse_command();
9657 n = stalloc(sizeof(struct ncmd));
9659 n->ncmd.args = args;
9660 n->ncmd.assign = vars;
9661 n->ncmd.redirect = redir;
9668 union node *n1, *n2;
9669 union node *ap, **app;
9670 union node *cp, **cpp;
9671 union node *redir, **rpp;
9678 switch (readtoken()) {
9680 raise_error_unexpected_syntax(-1);
9683 n1 = stalloc(sizeof(struct nif));
9685 n1->nif.test = list(0);
9686 if (readtoken() != TTHEN)
9687 raise_error_unexpected_syntax(TTHEN);
9688 n1->nif.ifpart = list(0);
9690 while (readtoken() == TELIF) {
9691 n2->nif.elsepart = stalloc(sizeof(struct nif));
9692 n2 = n2->nif.elsepart;
9694 n2->nif.test = list(0);
9695 if (readtoken() != TTHEN)
9696 raise_error_unexpected_syntax(TTHEN);
9697 n2->nif.ifpart = list(0);
9699 if (lasttoken == TELSE)
9700 n2->nif.elsepart = list(0);
9702 n2->nif.elsepart = NULL;
9710 n1 = stalloc(sizeof(struct nbinary));
9711 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9712 n1->nbinary.ch1 = list(0);
9715 TRACE(("expecting DO got %s %s\n", tokname(got),
9716 got == TWORD ? wordtext : ""));
9717 raise_error_unexpected_syntax(TDO);
9719 n1->nbinary.ch2 = list(0);
9724 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9725 raise_error_syntax("Bad for loop variable");
9726 n1 = stalloc(sizeof(struct nfor));
9728 n1->nfor.var = wordtext;
9729 checkkwd = CHKKWD | CHKALIAS;
9730 if (readtoken() == TIN) {
9732 while (readtoken() == TWORD) {
9733 n2 = stalloc(sizeof(struct narg));
9735 n2->narg.text = wordtext;
9736 n2->narg.backquote = backquotelist;
9738 app = &n2->narg.next;
9742 if (lasttoken != TNL && lasttoken != TSEMI)
9743 raise_error_unexpected_syntax(-1);
9745 n2 = stalloc(sizeof(struct narg));
9747 n2->narg.text = (char *)dolatstr;
9748 n2->narg.backquote = NULL;
9749 n2->narg.next = NULL;
9752 * Newline or semicolon here is optional (but note
9753 * that the original Bourne shell only allowed NL).
9755 if (lasttoken != TNL && lasttoken != TSEMI)
9758 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9759 if (readtoken() != TDO)
9760 raise_error_unexpected_syntax(TDO);
9761 n1->nfor.body = list(0);
9765 n1 = stalloc(sizeof(struct ncase));
9767 if (readtoken() != TWORD)
9768 raise_error_unexpected_syntax(TWORD);
9769 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9771 n2->narg.text = wordtext;
9772 n2->narg.backquote = backquotelist;
9773 n2->narg.next = NULL;
9775 checkkwd = CHKKWD | CHKALIAS;
9776 } while (readtoken() == TNL);
9777 if (lasttoken != TIN)
9778 raise_error_unexpected_syntax(TIN);
9779 cpp = &n1->ncase.cases;
9781 checkkwd = CHKNL | CHKKWD;
9783 while (t != TESAC) {
9784 if (lasttoken == TLP)
9786 *cpp = cp = stalloc(sizeof(struct nclist));
9788 app = &cp->nclist.pattern;
9790 *app = ap = stalloc(sizeof(struct narg));
9792 ap->narg.text = wordtext;
9793 ap->narg.backquote = backquotelist;
9794 if (readtoken() != TPIPE)
9796 app = &ap->narg.next;
9799 ap->narg.next = NULL;
9800 if (lasttoken != TRP)
9801 raise_error_unexpected_syntax(TRP);
9802 cp->nclist.body = list(2);
9804 cpp = &cp->nclist.next;
9806 checkkwd = CHKNL | CHKKWD;
9810 raise_error_unexpected_syntax(TENDCASE);
9817 n1 = stalloc(sizeof(struct nredir));
9818 n1->type = NSUBSHELL;
9819 n1->nredir.n = list(0);
9820 n1->nredir.redirect = NULL;
9833 if (readtoken() != t)
9834 raise_error_unexpected_syntax(t);
9837 /* Now check for redirection which may follow command */
9838 checkkwd = CHKKWD | CHKALIAS;
9840 while (readtoken() == TREDIR) {
9841 *rpp = n2 = redirnode;
9842 rpp = &n2->nfile.next;
9848 if (n1->type != NSUBSHELL) {
9849 n2 = stalloc(sizeof(struct nredir));
9854 n1->nredir.redirect = redir;
9860 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9861 * is not NULL, read a here document. In the latter case, eofmark is the
9862 * word which marks the end of the document and striptabs is true if
9863 * leading tabs should be stripped from the document. The argument firstc
9864 * is the first character of the input token or document.
9866 * Because C does not have internal subroutines, I have simulated them
9867 * using goto's to implement the subroutine linkage. The following macros
9868 * will run code that appears at the end of readtoken1.
9871 #define CHECKEND() {goto checkend; checkend_return:;}
9872 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9873 #define PARSESUB() {goto parsesub; parsesub_return:;}
9874 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9875 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9876 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9879 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9881 /* NB: syntax parameter fits into smallint */
9885 char line[EOFMARKLEN + 1];
9886 struct nodelist *bqlist;
9890 smallint prevsyntax; /* syntax before arithmetic */
9891 #if ENABLE_ASH_EXPAND_PRMT
9892 smallint pssyntax; /* we are expanding a prompt string */
9894 int varnest; /* levels of variables expansion */
9895 int arinest; /* levels of arithmetic expansion */
9896 int parenlevel; /* levels of parens in arithmetic */
9897 int dqvarnest; /* levels of variables expansion within double quotes */
9900 /* Avoid longjmp clobbering */
9912 startlinno = plinno;
9917 #if ENABLE_ASH_EXPAND_PRMT
9918 pssyntax = (syntax == PSSYNTAX);
9922 dblquote = (syntax == DQSYNTAX);
9929 loop: { /* for each line, until end of word */
9930 CHECKEND(); /* set c to PEOF if at end of here document */
9931 for (;;) { /* until end of line or end of word */
9932 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9933 switch (SIT(c, syntax)) {
9934 case CNL: /* '\n' */
9935 if (syntax == BASESYNTAX)
9936 goto endword; /* exit outer loop */
9942 goto loop; /* continue outer loop */
9947 if (eofmark == NULL || dblquote)
9948 USTPUTC(CTLESC, out);
9951 case CBACK: /* backslash */
9954 USTPUTC(CTLESC, out);
9957 } else if (c == '\n') {
9961 #if ENABLE_ASH_EXPAND_PRMT
9962 if (c == '$' && pssyntax) {
9963 USTPUTC(CTLESC, out);
9968 c != '\\' && c != '`' &&
9973 USTPUTC(CTLESC, out);
9976 if (SIT(c, SQSYNTAX) == CCTL)
9977 USTPUTC(CTLESC, out);
9985 if (eofmark == NULL) {
9986 USTPUTC(CTLQUOTEMARK, out);
9994 if (eofmark != NULL && arinest == 0
9999 if (dqvarnest == 0) {
10000 syntax = BASESYNTAX;
10007 case CVAR: /* '$' */
10008 PARSESUB(); /* parse substitution */
10010 case CENDVAR: /* '}' */
10013 if (dqvarnest > 0) {
10016 USTPUTC(CTLENDVAR, out);
10021 #if ENABLE_ASH_MATH_SUPPORT
10022 case CLP: /* '(' in arithmetic */
10026 case CRP: /* ')' in arithmetic */
10027 if (parenlevel > 0) {
10031 if (pgetc() == ')') {
10032 if (--arinest == 0) {
10033 USTPUTC(CTLENDARI, out);
10034 syntax = prevsyntax;
10035 dblquote = (syntax == DQSYNTAX);
10040 * unbalanced parens
10041 * (don't 2nd guess - no error)
10049 case CBQUOTE: /* '`' */
10053 goto endword; /* exit outer loop */
10058 goto endword; /* exit outer loop */
10059 #if ENABLE_ASH_ALIAS
10069 #if ENABLE_ASH_MATH_SUPPORT
10070 if (syntax == ARISYNTAX)
10071 raise_error_syntax("Missing '))'");
10073 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10074 raise_error_syntax("Unterminated quoted string");
10075 if (varnest != 0) {
10076 startlinno = plinno;
10078 raise_error_syntax("Missing '}'");
10080 USTPUTC('\0', out);
10081 len = out - (char *)stackblock();
10082 out = stackblock();
10083 if (eofmark == NULL) {
10084 if ((c == '>' || c == '<')
10087 && (*out == '\0' || isdigit(*out))) {
10089 return lasttoken = TREDIR;
10094 quoteflag = quotef;
10095 backquotelist = bqlist;
10096 grabstackblock(len);
10100 /* end of readtoken routine */
10103 * Check to see whether we are at the end of the here document. When this
10104 * is called, c is set to the first character of the next input line. If
10105 * we are at the end of the here document, this routine sets the c to PEOF.
10109 #if ENABLE_ASH_ALIAS
10115 while (c == '\t') {
10119 if (c == *eofmark) {
10120 if (pfgets(line, sizeof(line)) != NULL) {
10124 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10125 if (*p == '\n' && *q == '\0') {
10128 needprompt = doprompt;
10130 pushstring(line, NULL);
10135 goto checkend_return;
10139 * Parse a redirection operator. The variable "out" points to a string
10140 * specifying the fd to be redirected. The variable "c" contains the
10141 * first character of the redirection operator.
10147 np = stalloc(sizeof(struct nfile));
10152 np->type = NAPPEND;
10154 np->type = NCLOBBER;
10161 } else { /* c == '<' */
10166 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10167 np = stalloc(sizeof(struct nhere));
10171 heredoc = stalloc(sizeof(struct heredoc));
10172 heredoc->here = np;
10175 heredoc->striptabs = 1;
10177 heredoc->striptabs = 0;
10183 np->type = NFROMFD;
10187 np->type = NFROMTO;
10197 np->nfile.fd = fd - '0';
10199 goto parseredir_return;
10203 * Parse a substitution. At this point, we have read the dollar sign
10204 * and nothing else.
10207 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10208 * (assuming ascii char codes, as the original implementation did) */
10209 #define is_special(c) \
10210 ((((unsigned int)c) - 33 < 32) \
10211 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10217 static const char types[] ALIGN1 = "}-+?=";
10221 c <= PEOA_OR_PEOF ||
10222 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10226 } else if (c == '(') { /* $(command) or $((arith)) */
10227 if (pgetc() == '(') {
10228 #if ENABLE_ASH_MATH_SUPPORT
10231 raise_error_syntax("We unsupport $((arith))");
10238 USTPUTC(CTLVAR, out);
10239 typeloc = out - (char *)stackblock();
10240 USTPUTC(VSNORMAL, out);
10241 subtype = VSNORMAL;
10249 subtype = VSLENGTH;
10253 if (c > PEOA_OR_PEOF && is_name(c)) {
10257 } while (c > PEOA_OR_PEOF && is_in_name(c));
10258 } else if (isdigit(c)) {
10262 } while (isdigit(c));
10263 } else if (is_special(c)) {
10267 badsub: raise_error_syntax("Bad substitution");
10271 if (subtype == 0) {
10278 p = strchr(types, c);
10281 subtype = p - types + VSNORMAL;
10287 subtype = c == '#' ? VSTRIMLEFT :
10300 if (dblquote || arinest)
10302 *((char *)stackblock() + typeloc) = subtype | flags;
10303 if (subtype != VSNORMAL) {
10305 if (dblquote || arinest) {
10310 goto parsesub_return;
10314 * Called to parse command substitutions. Newstyle is set if the command
10315 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10316 * list of commands (passed by reference), and savelen is the number of
10317 * characters on the top of the stack which must be preserved.
10320 struct nodelist **nlpp;
10323 char *volatile str;
10324 struct jmploc jmploc;
10325 struct jmploc *volatile savehandler;
10327 smallint saveprompt = 0;
10330 (void) &saveprompt;
10332 savepbq = parsebackquote;
10333 if (setjmp(jmploc.loc)) {
10335 parsebackquote = 0;
10336 exception_handler = savehandler;
10337 longjmp(exception_handler->loc, 1);
10341 savelen = out - (char *)stackblock();
10343 str = ckmalloc(savelen);
10344 memcpy(str, stackblock(), savelen);
10346 savehandler = exception_handler;
10347 exception_handler = &jmploc;
10350 /* We must read until the closing backquote, giving special
10351 treatment to some slashes, and then push the string and
10352 reread it as input, interpreting it normally. */
10359 STARTSTACKSTR(pout);
10376 * If eating a newline, avoid putting
10377 * the newline into the new character
10378 * stream (via the STPUTC after the
10383 if (pc != '\\' && pc != '`' && pc != '$'
10384 && (!dblquote || pc != '"'))
10385 STPUTC('\\', pout);
10386 if (pc > PEOA_OR_PEOF) {
10392 #if ENABLE_ASH_ALIAS
10395 startlinno = plinno;
10396 raise_error_syntax("EOF in backquote substitution");
10400 needprompt = doprompt;
10409 STPUTC('\0', pout);
10410 psavelen = pout - (char *)stackblock();
10411 if (psavelen > 0) {
10412 pstr = grabstackstr(pout);
10413 setinputstring(pstr);
10418 nlpp = &(*nlpp)->next;
10419 *nlpp = stalloc(sizeof(**nlpp));
10420 (*nlpp)->next = NULL;
10421 parsebackquote = oldstyle;
10424 saveprompt = doprompt;
10431 doprompt = saveprompt;
10432 else if (readtoken() != TRP)
10433 raise_error_unexpected_syntax(TRP);
10438 * Start reading from old file again, ignoring any pushed back
10439 * tokens left from the backquote parsing
10444 while (stackblocksize() <= savelen)
10446 STARTSTACKSTR(out);
10448 memcpy(out, str, savelen);
10449 STADJUST(savelen, out);
10455 parsebackquote = savepbq;
10456 exception_handler = savehandler;
10457 if (arinest || dblquote)
10458 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10460 USTPUTC(CTLBACKQ, out);
10462 goto parsebackq_oldreturn;
10463 goto parsebackq_newreturn;
10466 #if ENABLE_ASH_MATH_SUPPORT
10468 * Parse an arithmetic expansion (indicate start of one and set state)
10471 if (++arinest == 1) {
10472 prevsyntax = syntax;
10473 syntax = ARISYNTAX;
10474 USTPUTC(CTLARI, out);
10481 * we collapse embedded arithmetic expansion to
10482 * parenthesis, which should be equivalent
10486 goto parsearith_return;
10490 } /* end of readtoken */
10493 * Read the next input token.
10494 * If the token is a word, we set backquotelist to the list of cmds in
10495 * backquotes. We set quoteflag to true if any part of the word was
10497 * If the token is TREDIR, then we set redirnode to a structure containing
10499 * In all cases, the variable startlinno is set to the number of the line
10500 * on which the token starts.
10502 * [Change comment: here documents and internal procedures]
10503 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10504 * word parsing code into a separate routine. In this case, readtoken
10505 * doesn't need to have any internal procedures, but parseword does.
10506 * We could also make parseoperator in essence the main routine, and
10507 * have parseword (readtoken1?) handle both words and redirection.]
10509 #define NEW_xxreadtoken
10510 #ifdef NEW_xxreadtoken
10511 /* singles must be first! */
10512 static const char xxreadtoken_chars[7] ALIGN1 = {
10513 '\n', '(', ')', '&', '|', ';', 0
10516 static const char xxreadtoken_tokens[] ALIGN1 = {
10517 TNL, TLP, TRP, /* only single occurrence allowed */
10518 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10519 TEOF, /* corresponds to trailing nul */
10520 TAND, TOR, TENDCASE /* if double occurrence */
10523 #define xxreadtoken_doubles \
10524 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10525 #define xxreadtoken_singles \
10526 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10540 startlinno = plinno;
10541 for (;;) { /* until token or start of word found */
10544 if ((c != ' ') && (c != '\t')
10545 #if ENABLE_ASH_ALIAS
10550 while ((c = pgetc()) != '\n' && c != PEOF);
10552 } else if (c == '\\') {
10553 if (pgetc() != '\n') {
10557 startlinno = ++plinno;
10562 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10567 needprompt = doprompt;
10570 p = strchr(xxreadtoken_chars, c);
10573 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10576 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10577 if (pgetc() == *p) { /* double occurrence? */
10578 p += xxreadtoken_doubles + 1;
10584 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10590 #define RETURN(token) return lasttoken = token
10603 startlinno = plinno;
10604 for (;;) { /* until token or start of word found */
10607 case ' ': case '\t':
10608 #if ENABLE_ASH_ALIAS
10613 while ((c = pgetc()) != '\n' && c != PEOF);
10617 if (pgetc() == '\n') {
10618 startlinno = ++plinno;
10627 needprompt = doprompt;
10632 if (pgetc() == '&')
10637 if (pgetc() == '|')
10642 if (pgetc() == ';')
10655 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10658 #endif /* NEW_xxreadtoken */
10665 smallint alreadyseen = tokpushback;
10668 #if ENABLE_ASH_ALIAS
10677 if (checkkwd & CHKNL) {
10684 if (t != TWORD || quoteflag) {
10689 * check for keywords
10691 if (checkkwd & CHKKWD) {
10692 const char *const *pp;
10694 pp = findkwd(wordtext);
10696 lasttoken = t = pp - tokname_array;
10697 TRACE(("keyword %s recognized\n", tokname(t)));
10702 if (checkkwd & CHKALIAS) {
10703 #if ENABLE_ASH_ALIAS
10705 ap = lookupalias(wordtext, 1);
10708 pushstring(ap->val, ap);
10718 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10720 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10732 return tokname_array[t][0];
10736 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10737 * valid parse tree indicating a blank line.)
10739 static union node *
10740 parsecmd(int interact)
10745 doprompt = interact;
10747 setprompt(doprompt);
10759 * Input any here documents.
10764 struct heredoc *here;
10767 here = heredoclist;
10774 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10775 here->eofmark, here->striptabs);
10776 n = stalloc(sizeof(struct narg));
10777 n->narg.type = NARG;
10778 n->narg.next = NULL;
10779 n->narg.text = wordtext;
10780 n->narg.backquote = backquotelist;
10781 here->here->nhere.doc = n;
10788 * called by editline -- any expansions to the prompt should be added here.
10790 #if ENABLE_ASH_EXPAND_PRMT
10791 static const char *
10792 expandstr(const char *ps)
10796 /* XXX Fix (char *) cast. */
10797 setinputstring((char *)ps);
10798 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
10801 n.narg.type = NARG;
10802 n.narg.next = NULL;
10803 n.narg.text = wordtext;
10804 n.narg.backquote = backquotelist;
10806 expandarg(&n, NULL, 0);
10807 return stackblock();
10812 * Execute a command or commands contained in a string.
10815 evalstring(char *s, int mask)
10818 struct stackmark smark;
10822 setstackmark(&smark);
10825 while ((n = parsecmd(0)) != NEOF) {
10827 popstackmark(&smark);
10840 * The eval command.
10843 evalcmd(int argc, char **argv)
10852 STARTSTACKSTR(concat);
10855 concat = stack_putstr(p, concat);
10859 STPUTC(' ', concat);
10861 STPUTC('\0', concat);
10862 p = grabstackstr(concat);
10864 evalstring(p, ~SKIPEVAL);
10871 * Read and execute commands. "Top" is nonzero for the top level command
10872 * loop; it turns on prompting if the shell is interactive.
10878 struct stackmark smark;
10882 TRACE(("cmdloop(%d) called\n", top));
10886 setstackmark(&smark);
10889 showjobs(stderr, SHOW_CHANGED);
10892 if (iflag && top) {
10894 #if ENABLE_ASH_MAIL
10898 n = parsecmd(inter);
10899 /* showtree(n); DEBUG */
10901 if (!top || numeof >= 50)
10903 if (!stoppedjobs()) {
10906 out2str("\nUse \"exit\" to leave shell.\n");
10909 } else if (nflag == 0) {
10910 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
10915 popstackmark(&smark);
10920 return skip & SKIPEVAL;
10927 * Take commands from a file. To be compatible we should do a path
10928 * search for the file, which is necessary to find sub-commands.
10931 find_dot_file(char *name)
10934 const char *path = pathval();
10937 /* don't try this for absolute or relative paths */
10938 if (strchr(name, '/'))
10941 while ((fullname = padvance(&path, name)) != NULL) {
10942 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
10944 * Don't bother freeing here, since it will
10945 * be freed by the caller.
10949 stunalloc(fullname);
10952 /* not found in the PATH */
10953 ash_msg_and_raise_error("%s: not found", name);
10958 dotcmd(int argc, char **argv)
10960 struct strlist *sp;
10961 volatile struct shparam saveparam;
10964 for (sp = cmdenviron; sp; sp = sp->next)
10965 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
10967 if (argc >= 2) { /* That's what SVR2 does */
10970 fullname = find_dot_file(argv[1]);
10973 saveparam = shellparam;
10974 shellparam.malloc = 0;
10975 shellparam.nparam = argc - 2;
10976 shellparam.p = argv + 2;
10979 setinputfile(fullname, INPUT_PUSH_FILE);
10980 commandname = fullname;
10985 freeparam(&shellparam);
10986 shellparam = saveparam;
10988 status = exitstatus;
10994 exitcmd(int argc, char **argv)
10999 exitstatus = number(argv[1]);
11000 raise_exception(EXEXIT);
11004 #if ENABLE_ASH_BUILTIN_ECHO
11006 echocmd(int argc, char **argv)
11008 return echo_main(argc, argv);
11012 #if ENABLE_ASH_BUILTIN_TEST
11014 testcmd(int argc, char **argv)
11016 return test_main(argc, argv);
11021 * Read a file containing shell functions.
11024 readcmdfile(char *name)
11026 setinputfile(name, INPUT_PUSH_FILE);
11032 /* ============ find_command inplementation */
11035 * Resolve a command name. If you change this routine, you may have to
11036 * change the shellexec routine as well.
11039 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11041 struct tblentry *cmdp;
11048 struct builtincmd *bcmd;
11050 /* If name contains a slash, don't use PATH or hash table */
11051 if (strchr(name, '/') != NULL) {
11052 entry->u.index = -1;
11053 if (act & DO_ABS) {
11054 while (stat(name, &statb) < 0) {
11056 if (errno == EINTR)
11059 entry->cmdtype = CMDUNKNOWN;
11063 entry->cmdtype = CMDNORMAL;
11067 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11069 updatetbl = (path == pathval());
11072 if (strstr(path, "%builtin") != NULL)
11073 act |= DO_ALTBLTIN;
11076 /* If name is in the table, check answer will be ok */
11077 cmdp = cmdlookup(name, 0);
11078 if (cmdp != NULL) {
11081 switch (cmdp->cmdtype) {
11099 } else if (cmdp->rehash == 0)
11100 /* if not invalidated by cd, we're done */
11104 /* If %builtin not in path, check for builtin next */
11105 bcmd = find_builtin(name);
11107 if (IS_BUILTIN_REGULAR(bcmd))
11108 goto builtin_success;
11109 if (act & DO_ALTPATH) {
11110 if (!(act & DO_ALTBLTIN))
11111 goto builtin_success;
11112 } else if (builtinloc <= 0) {
11113 goto builtin_success;
11117 #if ENABLE_FEATURE_SH_STANDALONE
11118 if (find_applet_by_name(name) >= 0) {
11119 entry->cmdtype = CMDNORMAL;
11120 entry->u.index = -1;
11125 /* We have to search path. */
11126 prev = -1; /* where to start */
11127 if (cmdp && cmdp->rehash) { /* doing a rehash */
11128 if (cmdp->cmdtype == CMDBUILTIN)
11131 prev = cmdp->param.index;
11137 while ((fullname = padvance(&path, name)) != NULL) {
11138 stunalloc(fullname);
11139 /* NB: code below will still use fullname
11140 * despite it being "unallocated" */
11143 if (prefix(pathopt, "builtin")) {
11145 goto builtin_success;
11147 } else if (!(act & DO_NOFUNC)
11148 && prefix(pathopt, "func")) {
11149 /* handled below */
11151 /* ignore unimplemented options */
11155 /* if rehash, don't redo absolute path names */
11156 if (fullname[0] == '/' && idx <= prev) {
11159 TRACE(("searchexec \"%s\": no change\n", name));
11162 while (stat(fullname, &statb) < 0) {
11164 if (errno == EINTR)
11167 if (errno != ENOENT && errno != ENOTDIR)
11171 e = EACCES; /* if we fail, this will be the error */
11172 if (!S_ISREG(statb.st_mode))
11174 if (pathopt) { /* this is a %func directory */
11175 stalloc(strlen(fullname) + 1);
11176 /* NB: stalloc will return space pointed by fullname
11177 * (because we don't have any intervening allocations
11178 * between stunalloc above and this stalloc) */
11179 readcmdfile(fullname);
11180 cmdp = cmdlookup(name, 0);
11181 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11182 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11183 stunalloc(fullname);
11186 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11188 entry->cmdtype = CMDNORMAL;
11189 entry->u.index = idx;
11193 cmdp = cmdlookup(name, 1);
11194 cmdp->cmdtype = CMDNORMAL;
11195 cmdp->param.index = idx;
11200 /* We failed. If there was an entry for this command, delete it */
11201 if (cmdp && updatetbl)
11202 delete_cmd_entry();
11204 ash_msg("%s: %s", name, errmsg(e, "not found"));
11205 entry->cmdtype = CMDUNKNOWN;
11210 entry->cmdtype = CMDBUILTIN;
11211 entry->u.cmd = bcmd;
11215 cmdp = cmdlookup(name, 1);
11216 cmdp->cmdtype = CMDBUILTIN;
11217 cmdp->param.cmd = bcmd;
11221 entry->cmdtype = cmdp->cmdtype;
11222 entry->u = cmdp->param;
11226 /* ============ trap.c */
11229 * The trap builtin.
11232 trapcmd(int argc, char **argv)
11241 for (signo = 0; signo < NSIG; signo++) {
11242 if (trap[signo] != NULL) {
11245 sn = get_signame(signo);
11246 out1fmt("trap -- %s %s\n",
11247 single_quote(trap[signo]), sn);
11257 signo = get_signum(*ap);
11259 ash_msg_and_raise_error("%s: bad trap", *ap);
11262 if (LONE_DASH(action))
11265 action = ckstrdup(action);
11268 trap[signo] = action;
11278 /* ============ Builtins */
11280 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11282 * Lists available builtins
11285 helpcmd(int argc, char **argv)
11289 out1fmt("\nBuilt-in commands:\n-------------------\n");
11290 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11291 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11292 builtintab[i].name + 1);
11298 #if ENABLE_FEATURE_SH_STANDALONE
11300 const char *a = applet_names;
11302 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11307 a += strlen(a) + 1;
11312 return EXIT_SUCCESS;
11314 #endif /* FEATURE_SH_EXTRA_QUIET */
11317 * The export and readonly commands.
11320 exportcmd(int argc, char **argv)
11326 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11328 if (nextopt("p") != 'p') {
11333 p = strchr(name, '=');
11337 vp = *findvar(hashvar(name), name);
11343 setvar(name, p, flag);
11344 } while ((name = *++aptr) != NULL);
11348 showvars(argv[0], flag, 0);
11353 * Delete a function if it exists.
11356 unsetfunc(const char *name)
11358 struct tblentry *cmdp;
11360 cmdp = cmdlookup(name, 0);
11361 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11362 delete_cmd_entry();
11366 * The unset builtin command. We unset the function before we unset the
11367 * variable to allow a function to be unset when there is a readonly variable
11368 * with the same name.
11371 unsetcmd(int argc, char **argv)
11378 while ((i = nextopt("vf")) != '\0') {
11382 for (ap = argptr; *ap; ap++) {
11398 #include <sys/times.h>
11400 static const unsigned char timescmd_str[] ALIGN1 = {
11401 ' ', offsetof(struct tms, tms_utime),
11402 '\n', offsetof(struct tms, tms_stime),
11403 ' ', offsetof(struct tms, tms_cutime),
11404 '\n', offsetof(struct tms, tms_cstime),
11409 timescmd(int ac, char **av)
11411 long clk_tck, s, t;
11412 const unsigned char *p;
11415 clk_tck = sysconf(_SC_CLK_TCK);
11420 t = *(clock_t *)(((char *) &buf) + p[1]);
11422 out1fmt("%ldm%ld.%.3lds%c",
11424 ((t - s * clk_tck) * 1000) / clk_tck,
11426 } while (*(p += 2));
11431 #if ENABLE_ASH_MATH_SUPPORT
11433 dash_arith(const char *s)
11439 result = arith(s, &errcode);
11442 ash_msg_and_raise_error("exponent less than 0");
11444 ash_msg_and_raise_error("divide by zero");
11446 ash_msg_and_raise_error("expression recursion loop detected");
11447 raise_error_syntax(s);
11455 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11456 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11458 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11461 letcmd(int argc, char **argv)
11468 ash_msg_and_raise_error("expression expected");
11469 for (ap = argv + 1; *ap; ap++) {
11470 i = dash_arith(*ap);
11475 #endif /* ASH_MATH_SUPPORT */
11478 /* ============ miscbltin.c
11480 * Miscellaneous builtins.
11485 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11486 typedef enum __rlimit_resource rlim_t;
11490 * The read builtin. The -e option causes backslashes to escape the
11491 * following character.
11493 * This uses unbuffered input, which may be avoidable in some cases.
11496 readcmd(int argc, char **argv)
11508 #if ENABLE_ASH_READ_NCHARS
11512 struct termios tty, old_tty;
11514 #if ENABLE_ASH_READ_TIMEOUT
11518 ts.tv_sec = ts.tv_usec = 0;
11523 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11524 while ((i = nextopt("p:rt:n:s")) != '\0')
11525 #elif ENABLE_ASH_READ_NCHARS
11526 while ((i = nextopt("p:rn:s")) != '\0')
11527 #elif ENABLE_ASH_READ_TIMEOUT
11528 while ((i = nextopt("p:rt:")) != '\0')
11530 while ((i = nextopt("p:r")) != '\0')
11535 prompt = optionarg;
11537 #if ENABLE_ASH_READ_NCHARS
11539 nchars = bb_strtou(optionarg, NULL, 10);
11540 if (nchars < 0 || errno)
11541 ash_msg_and_raise_error("invalid count");
11542 n_flag = nchars; /* just a flag "nchars is nonzero" */
11548 #if ENABLE_ASH_READ_TIMEOUT
11550 ts.tv_sec = bb_strtou(optionarg, &p, 10);
11552 /* EINVAL means number is ok, but not terminated by NUL */
11553 if (*p == '.' && errno == EINVAL) {
11557 ts.tv_usec = bb_strtou(p, &p2, 10);
11559 ash_msg_and_raise_error("invalid timeout");
11561 /* normalize to usec */
11563 ash_msg_and_raise_error("invalid timeout");
11564 while (scale++ < 6)
11567 } else if (ts.tv_sec < 0 || errno) {
11568 ash_msg_and_raise_error("invalid timeout");
11570 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
11571 ash_msg_and_raise_error("invalid timeout");
11582 if (prompt && isatty(0)) {
11587 ash_msg_and_raise_error("arg count");
11588 ifs = bltinlookup("IFS");
11591 #if ENABLE_ASH_READ_NCHARS
11592 if (n_flag || silent) {
11593 if (tcgetattr(0, &tty) != 0) {
11600 tty.c_lflag &= ~ICANON;
11601 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
11604 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
11606 tcsetattr(0, TCSANOW, &tty);
11610 #if ENABLE_ASH_READ_TIMEOUT
11611 if (ts.tv_sec || ts.tv_usec) {
11615 /* poll-based wait produces bigger code, using select */
11616 i = select(1, &set, NULL, NULL, &ts);
11617 if (!i) { /* timed out! */
11618 #if ENABLE_ASH_READ_NCHARS
11620 tcsetattr(0, TCSANOW, &old_tty);
11631 if (read(0, &c, 1) != 1) {
11643 if (!rflag && c == '\\') {
11649 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11653 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11655 setvar(*ap, stackblock(), 0);
11664 /* end of do {} while: */
11665 #if ENABLE_ASH_READ_NCHARS
11666 while (!n_flag || --nchars);
11671 #if ENABLE_ASH_READ_NCHARS
11672 if (n_flag || silent)
11673 tcsetattr(0, TCSANOW, &old_tty);
11677 /* Remove trailing blanks */
11678 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11680 setvar(*ap, stackblock(), 0);
11681 while (*++ap != NULL)
11682 setvar(*ap, nullstr, 0);
11687 umaskcmd(int argc, char **argv)
11689 static const char permuser[3] ALIGN1 = "ugo";
11690 static const char permmode[3] ALIGN1 = "rwx";
11691 static const short permmask[] ALIGN2 = {
11692 S_IRUSR, S_IWUSR, S_IXUSR,
11693 S_IRGRP, S_IWGRP, S_IXGRP,
11694 S_IROTH, S_IWOTH, S_IXOTH
11700 int symbolic_mode = 0;
11702 while (nextopt("S") != '\0') {
11713 if (symbolic_mode) {
11717 for (i = 0; i < 3; i++) {
11720 *p++ = permuser[i];
11722 for (j = 0; j < 3; j++) {
11723 if ((mask & permmask[3 * i + j]) == 0) {
11724 *p++ = permmode[j];
11732 out1fmt("%.4o\n", mask);
11735 if (isdigit((unsigned char) *ap)) {
11738 if (*ap >= '8' || *ap < '0')
11739 ash_msg_and_raise_error(illnum, argv[1]);
11740 mask = (mask << 3) + (*ap - '0');
11741 } while (*++ap != '\0');
11744 mask = ~mask & 0777;
11745 if (!bb_parse_mode(ap, &mask)) {
11746 ash_msg_and_raise_error("illegal mode: %s", ap);
11748 umask(~mask & 0777);
11757 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11758 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11759 * ash by J.T. Conklin.
11765 uint8_t cmd; /* RLIMIT_xxx fit into it */
11766 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
11770 static const struct limits limits_tbl[] = {
11772 { RLIMIT_CPU, 0, 't' },
11774 #ifdef RLIMIT_FSIZE
11775 { RLIMIT_FSIZE, 9, 'f' },
11778 { RLIMIT_DATA, 10, 'd' },
11780 #ifdef RLIMIT_STACK
11781 { RLIMIT_STACK, 10, 's' },
11784 { RLIMIT_CORE, 9, 'c' },
11787 { RLIMIT_RSS, 10, 'm' },
11789 #ifdef RLIMIT_MEMLOCK
11790 { RLIMIT_MEMLOCK, 10, 'l' },
11792 #ifdef RLIMIT_NPROC
11793 { RLIMIT_NPROC, 0, 'p' },
11795 #ifdef RLIMIT_NOFILE
11796 { RLIMIT_NOFILE, 0, 'n' },
11799 { RLIMIT_AS, 10, 'v' },
11801 #ifdef RLIMIT_LOCKS
11802 { RLIMIT_LOCKS, 0, 'w' },
11805 static const char limits_name[] =
11807 "time(seconds)" "\0"
11809 #ifdef RLIMIT_FSIZE
11810 "file(blocks)" "\0"
11815 #ifdef RLIMIT_STACK
11819 "coredump(blocks)" "\0"
11824 #ifdef RLIMIT_MEMLOCK
11825 "locked memory(kb)" "\0"
11827 #ifdef RLIMIT_NPROC
11830 #ifdef RLIMIT_NOFILE
11836 #ifdef RLIMIT_LOCKS
11841 enum limtype { SOFT = 0x1, HARD = 0x2 };
11844 printlim(enum limtype how, const struct rlimit *limit,
11845 const struct limits *l)
11849 val = limit->rlim_max;
11851 val = limit->rlim_cur;
11853 if (val == RLIM_INFINITY)
11854 out1fmt("unlimited\n");
11856 val >>= l->factor_shift;
11857 out1fmt("%lld\n", (long long) val);
11862 ulimitcmd(int argc, char **argv)
11866 enum limtype how = SOFT | HARD;
11867 const struct limits *l;
11870 struct rlimit limit;
11873 while ((optc = nextopt("HSa"
11877 #ifdef RLIMIT_FSIZE
11883 #ifdef RLIMIT_STACK
11892 #ifdef RLIMIT_MEMLOCK
11895 #ifdef RLIMIT_NPROC
11898 #ifdef RLIMIT_NOFILE
11904 #ifdef RLIMIT_LOCKS
11922 for (l = limits_tbl; l->option != what; l++)
11925 set = *argptr ? 1 : 0;
11929 if (all || argptr[1])
11930 ash_msg_and_raise_error("too many arguments");
11931 if (strncmp(p, "unlimited\n", 9) == 0)
11932 val = RLIM_INFINITY;
11936 while ((c = *p++) >= '0' && c <= '9') {
11937 val = (val * 10) + (long)(c - '0');
11938 if (val < (rlim_t) 0)
11942 ash_msg_and_raise_error("bad number");
11943 val <<= l->factor_shift;
11947 const char *lname = limits_name;
11948 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
11949 getrlimit(l->cmd, &limit);
11950 out1fmt("%-20s ", lname);
11951 lname += strlen(lname) + 1;
11952 printlim(how, &limit, l);
11957 getrlimit(l->cmd, &limit);
11960 limit.rlim_max = val;
11962 limit.rlim_cur = val;
11963 if (setrlimit(l->cmd, &limit) < 0)
11964 ash_msg_and_raise_error("error setting limit (%m)");
11966 printlim(how, &limit, l);
11972 /* ============ Math support */
11974 #if ENABLE_ASH_MATH_SUPPORT
11976 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11978 Permission is hereby granted, free of charge, to any person obtaining
11979 a copy of this software and associated documentation files (the
11980 "Software"), to deal in the Software without restriction, including
11981 without limitation the rights to use, copy, modify, merge, publish,
11982 distribute, sublicense, and/or sell copies of the Software, and to
11983 permit persons to whom the Software is furnished to do so, subject to
11984 the following conditions:
11986 The above copyright notice and this permission notice shall be
11987 included in all copies or substantial portions of the Software.
11989 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11990 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11991 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
11992 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
11993 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11994 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11995 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11998 /* This is my infix parser/evaluator. It is optimized for size, intended
11999 * as a replacement for yacc-based parsers. However, it may well be faster
12000 * than a comparable parser written in yacc. The supported operators are
12001 * listed in #defines below. Parens, order of operations, and error handling
12002 * are supported. This code is thread safe. The exact expression format should
12003 * be that which POSIX specifies for shells. */
12005 /* The code uses a simple two-stack algorithm. See
12006 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12007 * for a detailed explanation of the infix-to-postfix algorithm on which
12008 * this is based (this code differs in that it applies operators immediately
12009 * to the stack instead of adding them to a queue to end up with an
12012 /* To use the routine, call it with an expression string and error return
12016 * Aug 24, 2001 Manuel Novoa III
12018 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12020 * 1) In arith_apply():
12021 * a) Cached values of *numptr and &(numptr[-1]).
12022 * b) Removed redundant test for zero denominator.
12025 * a) Eliminated redundant code for processing operator tokens by moving
12026 * to a table-based implementation. Also folded handling of parens
12028 * b) Combined all 3 loops which called arith_apply to reduce generated
12029 * code size at the cost of speed.
12031 * 3) The following expressions were treated as valid by the original code:
12032 * 1() , 0! , 1 ( *3 ) .
12033 * These bugs have been fixed by internally enclosing the expression in
12034 * parens and then checking that all binary ops and right parens are
12035 * preceded by a valid expression (NUM_TOKEN).
12037 * Note: It may be desirable to replace Aaron's test for whitespace with
12038 * ctype's isspace() if it is used by another busybox applet or if additional
12039 * whitespace chars should be considered. Look below the "#include"s for a
12040 * precompiler test.
12044 * Aug 26, 2001 Manuel Novoa III
12046 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12048 * Merge in Aaron's comments previously posted to the busybox list,
12049 * modified slightly to take account of my changes to the code.
12054 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12056 * - allow access to variable,
12057 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12058 * - realize assign syntax (VAR=expr, +=, *= etc)
12059 * - realize exponentiation (** operator)
12060 * - realize comma separated - expr, expr
12061 * - realise ++expr --expr expr++ expr--
12062 * - realise expr ? expr : expr (but, second expr calculate always)
12063 * - allow hexadecimal and octal numbers
12064 * - was restored loses XOR operator
12065 * - remove one goto label, added three ;-)
12066 * - protect $((num num)) as true zero expr (Manuel`s error)
12067 * - always use special isspace(), see comment from bash ;-)
12070 #define arith_isspace(arithval) \
12071 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12073 typedef unsigned char operator;
12075 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12076 * precedence, and 3 high bits are an ID unique across operators of that
12077 * precedence. The ID portion is so that multiple operators can have the
12078 * same precedence, ensuring that the leftmost one is evaluated first.
12079 * Consider * and /. */
12081 #define tok_decl(prec,id) (((id)<<5)|(prec))
12082 #define PREC(op) ((op) & 0x1F)
12084 #define TOK_LPAREN tok_decl(0,0)
12086 #define TOK_COMMA tok_decl(1,0)
12088 #define TOK_ASSIGN tok_decl(2,0)
12089 #define TOK_AND_ASSIGN tok_decl(2,1)
12090 #define TOK_OR_ASSIGN tok_decl(2,2)
12091 #define TOK_XOR_ASSIGN tok_decl(2,3)
12092 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12093 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12094 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12095 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12097 #define TOK_MUL_ASSIGN tok_decl(3,0)
12098 #define TOK_DIV_ASSIGN tok_decl(3,1)
12099 #define TOK_REM_ASSIGN tok_decl(3,2)
12101 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12102 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12104 /* conditional is right associativity too */
12105 #define TOK_CONDITIONAL tok_decl(4,0)
12106 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12108 #define TOK_OR tok_decl(5,0)
12110 #define TOK_AND tok_decl(6,0)
12112 #define TOK_BOR tok_decl(7,0)
12114 #define TOK_BXOR tok_decl(8,0)
12116 #define TOK_BAND tok_decl(9,0)
12118 #define TOK_EQ tok_decl(10,0)
12119 #define TOK_NE tok_decl(10,1)
12121 #define TOK_LT tok_decl(11,0)
12122 #define TOK_GT tok_decl(11,1)
12123 #define TOK_GE tok_decl(11,2)
12124 #define TOK_LE tok_decl(11,3)
12126 #define TOK_LSHIFT tok_decl(12,0)
12127 #define TOK_RSHIFT tok_decl(12,1)
12129 #define TOK_ADD tok_decl(13,0)
12130 #define TOK_SUB tok_decl(13,1)
12132 #define TOK_MUL tok_decl(14,0)
12133 #define TOK_DIV tok_decl(14,1)
12134 #define TOK_REM tok_decl(14,2)
12136 /* exponent is right associativity */
12137 #define TOK_EXPONENT tok_decl(15,1)
12139 /* For now unary operators. */
12140 #define UNARYPREC 16
12141 #define TOK_BNOT tok_decl(UNARYPREC,0)
12142 #define TOK_NOT tok_decl(UNARYPREC,1)
12144 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12145 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12147 #define PREC_PRE (UNARYPREC+2)
12149 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12150 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12152 #define PREC_POST (UNARYPREC+3)
12154 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12155 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12157 #define SPEC_PREC (UNARYPREC+4)
12159 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12160 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12162 #define NUMPTR (*numstackptr)
12165 tok_have_assign(operator op)
12167 operator prec = PREC(op);
12169 convert_prec_is_assing(prec);
12170 return (prec == PREC(TOK_ASSIGN) ||
12171 prec == PREC_PRE || prec == PREC_POST);
12175 is_right_associativity(operator prec)
12177 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12178 || prec == PREC(TOK_CONDITIONAL));
12181 typedef struct ARITCH_VAR_NUM {
12183 arith_t contidional_second_val;
12184 char contidional_second_val_initialized;
12185 char *var; /* if NULL then is regular number,
12186 else is variable name */
12189 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12191 struct CHK_VAR_RECURSIVE_LOOPED *next;
12192 } chk_var_recursive_looped_t;
12194 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12197 arith_lookup_val(v_n_t *t)
12200 const char * p = lookupvar(t->var);
12205 /* recursive try as expression */
12206 chk_var_recursive_looped_t *cur;
12207 chk_var_recursive_looped_t cur_save;
12209 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12210 if (strcmp(cur->var, t->var) == 0) {
12211 /* expression recursion loop detected */
12215 /* save current lookuped var name */
12216 cur = prev_chk_var_recursive;
12217 cur_save.var = t->var;
12218 cur_save.next = cur;
12219 prev_chk_var_recursive = &cur_save;
12221 t->val = arith (p, &errcode);
12222 /* restore previous ptr after recursiving */
12223 prev_chk_var_recursive = cur;
12226 /* allow undefined var as 0 */
12232 /* "applying" a token means performing it on the top elements on the integer
12233 * stack. For a unary operator it will only change the top element, but a
12234 * binary operator will pop two arguments and push a result */
12236 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12239 arith_t numptr_val, rez;
12240 int ret_arith_lookup_val;
12242 /* There is no operator that can work without arguments */
12243 if (NUMPTR == numstack) goto err;
12244 numptr_m1 = NUMPTR - 1;
12246 /* check operand is var with noninteger value */
12247 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12248 if (ret_arith_lookup_val)
12249 return ret_arith_lookup_val;
12251 rez = numptr_m1->val;
12252 if (op == TOK_UMINUS)
12254 else if (op == TOK_NOT)
12256 else if (op == TOK_BNOT)
12258 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12260 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12262 else if (op != TOK_UPLUS) {
12263 /* Binary operators */
12265 /* check and binary operators need two arguments */
12266 if (numptr_m1 == numstack) goto err;
12268 /* ... and they pop one */
12271 if (op == TOK_CONDITIONAL) {
12272 if (! numptr_m1->contidional_second_val_initialized) {
12273 /* protect $((expr1 ? expr2)) without ": expr" */
12276 rez = numptr_m1->contidional_second_val;
12277 } else if (numptr_m1->contidional_second_val_initialized) {
12278 /* protect $((expr1 : expr2)) without "expr ? " */
12281 numptr_m1 = NUMPTR - 1;
12282 if (op != TOK_ASSIGN) {
12283 /* check operand is var with noninteger value for not '=' */
12284 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12285 if (ret_arith_lookup_val)
12286 return ret_arith_lookup_val;
12288 if (op == TOK_CONDITIONAL) {
12289 numptr_m1->contidional_second_val = rez;
12291 rez = numptr_m1->val;
12292 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12294 else if (op == TOK_OR)
12295 rez = numptr_val || rez;
12296 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12298 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12300 else if (op == TOK_AND)
12301 rez = rez && numptr_val;
12302 else if (op == TOK_EQ)
12303 rez = (rez == numptr_val);
12304 else if (op == TOK_NE)
12305 rez = (rez != numptr_val);
12306 else if (op == TOK_GE)
12307 rez = (rez >= numptr_val);
12308 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12309 rez >>= numptr_val;
12310 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12311 rez <<= numptr_val;
12312 else if (op == TOK_GT)
12313 rez = (rez > numptr_val);
12314 else if (op == TOK_LT)
12315 rez = (rez < numptr_val);
12316 else if (op == TOK_LE)
12317 rez = (rez <= numptr_val);
12318 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12320 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12322 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12324 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12326 else if (op == TOK_CONDITIONAL_SEP) {
12327 if (numptr_m1 == numstack) {
12328 /* protect $((expr : expr)) without "expr ? " */
12331 numptr_m1->contidional_second_val_initialized = op;
12332 numptr_m1->contidional_second_val = numptr_val;
12333 } else if (op == TOK_CONDITIONAL) {
12335 numptr_val : numptr_m1->contidional_second_val;
12336 } else if (op == TOK_EXPONENT) {
12337 if (numptr_val < 0)
12338 return -3; /* exponent less than 0 */
12343 while (numptr_val--)
12347 } else if (numptr_val==0) /* zero divisor check */
12349 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12351 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12354 if (tok_have_assign(op)) {
12355 char buf[sizeof(arith_t_type)*3 + 2];
12357 if (numptr_m1->var == NULL) {
12361 /* save to shell variable */
12362 #if ENABLE_ASH_MATH_SUPPORT_64
12363 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12365 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12367 setvar(numptr_m1->var, buf, 0);
12368 /* after saving, make previous value for v++ or v-- */
12369 if (op == TOK_POST_INC)
12371 else if (op == TOK_POST_DEC)
12374 numptr_m1->val = rez;
12375 /* protect geting var value, is number now */
12376 numptr_m1->var = NULL;
12382 /* longest must be first */
12383 static const char op_tokens[] ALIGN1 = {
12384 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12385 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12386 '<','<', 0, TOK_LSHIFT,
12387 '>','>', 0, TOK_RSHIFT,
12388 '|','|', 0, TOK_OR,
12389 '&','&', 0, TOK_AND,
12390 '!','=', 0, TOK_NE,
12391 '<','=', 0, TOK_LE,
12392 '>','=', 0, TOK_GE,
12393 '=','=', 0, TOK_EQ,
12394 '|','=', 0, TOK_OR_ASSIGN,
12395 '&','=', 0, TOK_AND_ASSIGN,
12396 '*','=', 0, TOK_MUL_ASSIGN,
12397 '/','=', 0, TOK_DIV_ASSIGN,
12398 '%','=', 0, TOK_REM_ASSIGN,
12399 '+','=', 0, TOK_PLUS_ASSIGN,
12400 '-','=', 0, TOK_MINUS_ASSIGN,
12401 '-','-', 0, TOK_POST_DEC,
12402 '^','=', 0, TOK_XOR_ASSIGN,
12403 '+','+', 0, TOK_POST_INC,
12404 '*','*', 0, TOK_EXPONENT,
12408 '=', 0, TOK_ASSIGN,
12420 '?', 0, TOK_CONDITIONAL,
12421 ':', 0, TOK_CONDITIONAL_SEP,
12422 ')', 0, TOK_RPAREN,
12423 '(', 0, TOK_LPAREN,
12427 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12430 arith(const char *expr, int *perrcode)
12432 char arithval; /* Current character under analysis */
12433 operator lasttok, op;
12436 const char *p = endexpression;
12439 size_t datasizes = strlen(expr) + 2;
12441 /* Stack of integers */
12442 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12443 * in any given correct or incorrect expression is left as an exercise to
12445 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12446 *numstackptr = numstack;
12447 /* Stack of operator tokens */
12448 operator *stack = alloca((datasizes) * sizeof(operator)),
12451 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12452 *perrcode = errcode = 0;
12456 if (arithval == 0) {
12457 if (p == endexpression) {
12458 /* Null expression. */
12462 /* This is only reached after all tokens have been extracted from the
12463 * input stream. If there are still tokens on the operator stack, they
12464 * are to be applied in order. At the end, there should be a final
12465 * result on the integer stack */
12467 if (expr != endexpression + 1) {
12468 /* If we haven't done so already, */
12469 /* append a closing right paren */
12470 expr = endexpression;
12471 /* and let the loop process it. */
12474 /* At this point, we're done with the expression. */
12475 if (numstackptr != numstack+1) {
12476 /* ... but if there isn't, it's bad */
12478 return (*perrcode = -1);
12480 if (numstack->var) {
12481 /* expression is $((var)) only, lookup now */
12482 errcode = arith_lookup_val(numstack);
12485 *perrcode = errcode;
12486 return numstack->val;
12489 /* Continue processing the expression. */
12490 if (arith_isspace(arithval)) {
12491 /* Skip whitespace */
12494 p = endofname(expr);
12496 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12498 numstackptr->var = alloca(var_name_size);
12499 safe_strncpy(numstackptr->var, expr, var_name_size);
12502 numstackptr->contidional_second_val_initialized = 0;
12507 if (isdigit(arithval)) {
12508 numstackptr->var = NULL;
12509 #if ENABLE_ASH_MATH_SUPPORT_64
12510 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12512 numstackptr->val = strtol(expr, (char **) &expr, 0);
12516 for (p = op_tokens; ; p++) {
12520 /* strange operator not found */
12523 for (o = expr; *p && *o == *p; p++)
12530 /* skip tail uncompared token */
12533 /* skip zero delim */
12538 /* post grammar: a++ reduce to num */
12539 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12542 /* Plus and minus are binary (not unary) _only_ if the last
12543 * token was as number, or a right paren (which pretends to be
12544 * a number, since it evaluates to one). Think about it.
12545 * It makes sense. */
12546 if (lasttok != TOK_NUM) {
12562 /* We don't want a unary operator to cause recursive descent on the
12563 * stack, because there can be many in a row and it could cause an
12564 * operator to be evaluated before its argument is pushed onto the
12565 * integer stack. */
12566 /* But for binary operators, "apply" everything on the operator
12567 * stack until we find an operator with a lesser priority than the
12568 * one we have just extracted. */
12569 /* Left paren is given the lowest priority so it will never be
12570 * "applied" in this way.
12571 * if associativity is right and priority eq, applied also skip
12574 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12575 /* not left paren or unary */
12576 if (lasttok != TOK_NUM) {
12577 /* binary op must be preceded by a num */
12580 while (stackptr != stack) {
12581 if (op == TOK_RPAREN) {
12582 /* The algorithm employed here is simple: while we don't
12583 * hit an open paren nor the bottom of the stack, pop
12584 * tokens and apply them */
12585 if (stackptr[-1] == TOK_LPAREN) {
12587 /* Any operator directly after a */
12589 /* close paren should consider itself binary */
12593 operator prev_prec = PREC(stackptr[-1]);
12595 convert_prec_is_assing(prec);
12596 convert_prec_is_assing(prev_prec);
12597 if (prev_prec < prec)
12599 /* check right assoc */
12600 if (prev_prec == prec && is_right_associativity(prec))
12603 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12604 if (errcode) goto ret;
12606 if (op == TOK_RPAREN) {
12611 /* Push this operator to the stack and remember it. */
12612 *stackptr++ = lasttok = op;
12617 #endif /* ASH_MATH_SUPPORT */
12620 /* ============ main() and helpers */
12623 * Called to exit the shell.
12625 static void exitshell(void) ATTRIBUTE_NORETURN;
12633 status = exitstatus;
12634 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12635 if (setjmp(loc.loc)) {
12636 if (exception == EXEXIT)
12637 /* dash bug: it just does _exit(exitstatus) here
12638 * but we have to do setjobctl(0) first!
12639 * (bug is still not fixed in dash-0.5.3 - if you run dash
12640 * under Midnight Commander, on exit from dash MC is backgrounded) */
12641 status = exitstatus;
12644 exception_handler = &loc;
12650 flush_stdout_stderr();
12660 /* from input.c: */
12661 basepf.nextc = basepf.buf = basebuf;
12664 signal(SIGCHLD, SIG_DFL);
12669 char ppid[sizeof(int)*3 + 1];
12671 struct stat st1, st2;
12674 for (envp = environ; envp && *envp; envp++) {
12675 if (strchr(*envp, '=')) {
12676 setvareq(*envp, VEXPORT|VTEXTFIXED);
12680 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12681 setvar("PPID", ppid, 0);
12683 p = lookupvar("PWD");
12685 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12686 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12693 * Process the shell command line arguments.
12696 procargs(int argc, char **argv)
12699 const char *xminusc;
12706 for (i = 0; i < NOPTS; i++)
12712 if (*xargv == NULL) {
12714 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12717 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12721 for (i = 0; i < NOPTS; i++)
12722 if (optlist[i] == 2)
12727 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12732 } else if (!sflag) {
12733 setinputfile(*xargv, 0);
12736 commandname = arg0;
12739 shellparam.p = xargv;
12740 #if ENABLE_ASH_GETOPTS
12741 shellparam.optind = 1;
12742 shellparam.optoff = -1;
12744 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12746 shellparam.nparam++;
12753 * Read /etc/profile or .profile.
12756 read_profile(const char *name)
12760 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12769 * This routine is called when an error or an interrupt occurs in an
12770 * interactive shell and control is returned to the main command loop.
12778 /* from input.c: */
12779 parselleft = parsenleft = 0; /* clear input buffer */
12781 /* from parser.c: */
12784 /* from redir.c: */
12789 static short profile_buf[16384];
12790 extern int etext();
12794 * Main routine. We initialize things, parse the arguments, execute
12795 * profiles if we're a login shell, and then call cmdloop to execute
12796 * commands. The setjmp call sets up the location to jump to when an
12797 * exception occurs. When an exception occurs the variable "state"
12798 * is used to figure out how far we had gotten.
12800 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12801 int ash_main(int argc, char **argv)
12804 volatile int state;
12805 struct jmploc jmploc;
12806 struct stackmark smark;
12809 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12812 #if ENABLE_FEATURE_EDITING
12813 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12816 if (setjmp(jmploc.loc)) {
12826 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12830 outcslow('\n', stderr);
12832 popstackmark(&smark);
12833 FORCE_INT_ON; /* enable interrupts */
12842 exception_handler = &jmploc;
12845 trace_puts("Shell args: ");
12846 trace_puts_args(argv);
12848 rootpid = getpid();
12850 #if ENABLE_ASH_RANDOM_SUPPORT
12851 rseed = rootpid + time(NULL);
12854 setstackmark(&smark);
12855 procargs(argc, argv);
12856 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12858 const char *hp = lookupvar("HISTFILE");
12861 hp = lookupvar("HOME");
12863 char *defhp = concat_path_file(hp, ".ash_history");
12864 setvar("HISTFILE", defhp, 0);
12870 if (argv[0] && argv[0][0] == '-')
12874 read_profile("/etc/profile");
12877 read_profile(".profile");
12883 getuid() == geteuid() && getgid() == getegid() &&
12887 shinit = lookupvar("ENV");
12888 if (shinit != NULL && *shinit != '\0') {
12889 read_profile(shinit);
12895 evalstring(minusc, 0);
12897 if (sflag || minusc == NULL) {
12898 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12900 const char *hp = lookupvar("HISTFILE");
12903 line_input_state->hist_file = hp;
12906 state4: /* XXX ??? - why isn't this before the "if" statement */
12914 extern void _mcleanup(void);
12923 const char *applet_name = "debug stuff usage";
12924 int main(int argc, char **argv)
12926 return ash_main(argc, argv);
12932 * Copyright (c) 1989, 1991, 1993, 1994
12933 * The Regents of the University of California. All rights reserved.
12935 * This code is derived from software contributed to Berkeley by
12936 * Kenneth Almquist.
12938 * Redistribution and use in source and binary forms, with or without
12939 * modification, are permitted provided that the following conditions
12941 * 1. Redistributions of source code must retain the above copyright
12942 * notice, this list of conditions and the following disclaimer.
12943 * 2. Redistributions in binary form must reproduce the above copyright
12944 * notice, this list of conditions and the following disclaimer in the
12945 * documentation and/or other materials provided with the distribution.
12946 * 3. Neither the name of the University nor the names of its contributors
12947 * may be used to endorse or promote products derived from this software
12948 * without specific prior written permission.
12950 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12951 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12952 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12953 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12954 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12955 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12956 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12957 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12958 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12959 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF