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 struct bb_applet */
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 */
2498 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2499 #define USE_SIT_FUNCTION
2502 #if ENABLE_ASH_MATH_SUPPORT
2503 static const char S_I_T[][4] = {
2504 #if ENABLE_ASH_ALIAS
2505 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2507 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2508 { CNL, CNL, CNL, CNL }, /* 2, \n */
2509 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2510 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2511 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2512 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2513 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2514 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2515 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2516 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2517 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2518 #ifndef USE_SIT_FUNCTION
2519 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2520 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2521 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2525 static const char S_I_T[][3] = {
2526 #if ENABLE_ASH_ALIAS
2527 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2529 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2530 { CNL, CNL, CNL }, /* 2, \n */
2531 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2532 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2533 { CVAR, CVAR, CWORD }, /* 5, $ */
2534 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2535 { CSPCL, CWORD, CWORD }, /* 7, ( */
2536 { CSPCL, CWORD, CWORD }, /* 8, ) */
2537 { CBACK, CBACK, CCTL }, /* 9, \ */
2538 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2539 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2540 #ifndef USE_SIT_FUNCTION
2541 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2542 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2543 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2546 #endif /* ASH_MATH_SUPPORT */
2548 #ifdef USE_SIT_FUNCTION
2551 SIT(int c, int syntax)
2553 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2554 #if ENABLE_ASH_ALIAS
2555 static const char syntax_index_table[] ALIGN1 = {
2556 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2557 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2558 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2562 static const char syntax_index_table[] ALIGN1 = {
2563 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2564 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2565 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2572 if (c == PEOF) /* 2^8+2 */
2574 #if ENABLE_ASH_ALIAS
2575 if (c == PEOA) /* 2^8+1 */
2579 #define U_C(c) ((unsigned char)(c))
2581 if ((unsigned char)c >= (unsigned char)(CTLESC)
2582 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2586 s = strchr(spec_symbls, c);
2587 if (s == NULL || *s == '\0')
2589 indx = syntax_index_table[(s - spec_symbls)];
2591 return S_I_T[indx][syntax];
2594 #else /* !USE_SIT_FUNCTION */
2596 #if ENABLE_ASH_ALIAS
2597 #define CSPCL_CIGN_CIGN_CIGN 0
2598 #define CSPCL_CWORD_CWORD_CWORD 1
2599 #define CNL_CNL_CNL_CNL 2
2600 #define CWORD_CCTL_CCTL_CWORD 3
2601 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2602 #define CVAR_CVAR_CWORD_CVAR 5
2603 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2604 #define CSPCL_CWORD_CWORD_CLP 7
2605 #define CSPCL_CWORD_CWORD_CRP 8
2606 #define CBACK_CBACK_CCTL_CBACK 9
2607 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2608 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2609 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2610 #define CWORD_CWORD_CWORD_CWORD 13
2611 #define CCTL_CCTL_CCTL_CCTL 14
2613 #define CSPCL_CWORD_CWORD_CWORD 0
2614 #define CNL_CNL_CNL_CNL 1
2615 #define CWORD_CCTL_CCTL_CWORD 2
2616 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2617 #define CVAR_CVAR_CWORD_CVAR 4
2618 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2619 #define CSPCL_CWORD_CWORD_CLP 6
2620 #define CSPCL_CWORD_CWORD_CRP 7
2621 #define CBACK_CBACK_CCTL_CBACK 8
2622 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2623 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2624 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2625 #define CWORD_CWORD_CWORD_CWORD 12
2626 #define CCTL_CCTL_CCTL_CCTL 13
2629 static const char syntax_index_table[258] = {
2630 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2631 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2632 #if ENABLE_ASH_ALIAS
2633 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2635 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2636 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2637 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2638 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2639 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2640 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2641 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2642 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2643 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2644 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2645 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2646 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2647 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2648 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2649 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2773 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2774 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2796 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2797 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2798 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2800 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2802 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2803 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2804 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2805 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2806 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2808 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2809 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2810 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2811 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2823 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2824 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2825 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2826 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2827 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2856 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2857 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2860 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2861 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2888 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2889 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2893 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2895 #endif /* USE_SIT_FUNCTION */
2898 /* ============ Alias handling */
2900 #if ENABLE_ASH_ALIAS
2902 #define ALIASINUSE 1
2914 static struct alias *atab[ATABSIZE];
2916 static struct alias **
2917 __lookupalias(const char *name) {
2918 unsigned int hashval;
2925 ch = (unsigned char)*p;
2929 ch = (unsigned char)*++p;
2931 app = &atab[hashval % ATABSIZE];
2933 for (; *app; app = &(*app)->next) {
2934 if (strcmp(name, (*app)->name) == 0) {
2942 static struct alias *
2943 lookupalias(const char *name, int check)
2945 struct alias *ap = *__lookupalias(name);
2947 if (check && ap && (ap->flag & ALIASINUSE))
2952 static struct alias *
2953 freealias(struct alias *ap)
2957 if (ap->flag & ALIASINUSE) {
2958 ap->flag |= ALIASDEAD;
2970 setalias(const char *name, const char *val)
2972 struct alias *ap, **app;
2974 app = __lookupalias(name);
2978 if (!(ap->flag & ALIASINUSE)) {
2981 ap->val = ckstrdup(val);
2982 ap->flag &= ~ALIASDEAD;
2985 ap = ckmalloc(sizeof(struct alias));
2986 ap->name = ckstrdup(name);
2987 ap->val = ckstrdup(val);
2996 unalias(const char *name)
3000 app = __lookupalias(name);
3004 *app = freealias(*app);
3015 struct alias *ap, **app;
3019 for (i = 0; i < ATABSIZE; i++) {
3021 for (ap = *app; ap; ap = *app) {
3022 *app = freealias(*app);
3032 printalias(const struct alias *ap)
3034 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3038 * TODO - sort output
3041 aliascmd(int argc, char **argv)
3050 for (i = 0; i < ATABSIZE; i++)
3051 for (ap = atab[i]; ap; ap = ap->next) {
3056 while ((n = *++argv) != NULL) {
3057 v = strchr(n+1, '=');
3058 if (v == NULL) { /* n+1: funny ksh stuff */
3059 ap = *__lookupalias(n);
3061 fprintf(stderr, "%s: %s not found\n", "alias", n);
3075 unaliascmd(int argc, char **argv)
3079 while ((i = nextopt("a")) != '\0') {
3085 for (i = 0; *argptr; argptr++) {
3086 if (unalias(*argptr)) {
3087 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3095 #endif /* ASH_ALIAS */
3098 /* ============ jobs.c */
3100 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3103 #define FORK_NOJOB 2
3105 /* mode flags for showjob(s) */
3106 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3107 #define SHOW_PID 0x04 /* include process pid */
3108 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3111 * A job structure contains information about a job. A job is either a
3112 * single process or a set of processes contained in a pipeline. In the
3113 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3118 pid_t pid; /* process id */
3119 int status; /* last process status from wait() */
3120 char *cmd; /* text of command being run */
3124 struct procstat ps0; /* status of process */
3125 struct procstat *ps; /* status or processes when more than one */
3127 int stopstatus; /* status of a stopped job */
3130 nprocs: 16, /* number of processes */
3132 #define JOBRUNNING 0 /* at least one proc running */
3133 #define JOBSTOPPED 1 /* all procs are stopped */
3134 #define JOBDONE 2 /* all procs are completed */
3136 sigint: 1, /* job was killed by SIGINT */
3137 jobctl: 1, /* job running under job control */
3139 waited: 1, /* true if this entry has been waited for */
3140 used: 1, /* true if this entry is in used */
3141 changed: 1; /* true if status has changed */
3142 struct job *prev_job; /* previous job */
3145 static pid_t backgndpid; /* pid of last background process */
3146 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3148 static struct job *makejob(union node *, int);
3149 static int forkshell(struct job *, union node *, int);
3150 static int waitforjob(struct job *);
3153 enum { jobctl = 0 };
3154 #define setjobctl(on) do {} while (0)
3156 static smallint jobctl; /* true if doing job control */
3157 static void setjobctl(int);
3161 * Set the signal handler for the specified signal. The routine figures
3162 * out what it should be set to.
3165 setsignal(int signo)
3169 struct sigaction act;
3174 else if (*t != '\0')
3178 if (rootshell && action == S_DFL) {
3181 if (iflag || minusc || sflag == 0)
3204 t = &sigmode[signo - 1];
3208 * current setting unknown
3210 if (sigaction(signo, 0, &act) == -1) {
3212 * Pretend it worked; maybe we should give a warning
3213 * here, but other shells don't. We don't alter
3214 * sigmode, so that we retry every time.
3218 if (act.sa_handler == SIG_IGN) {
3220 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3222 tsig = S_IGN; /* don't hard ignore these */
3226 tsig = S_RESET; /* force to be set */
3229 if (tsig == S_HARD_IGN || tsig == action)
3233 act.sa_handler = onsig;
3236 act.sa_handler = SIG_IGN;
3239 act.sa_handler = SIG_DFL;
3243 sigfillset(&act.sa_mask);
3244 sigaction(signo, &act, 0);
3247 /* mode flags for set_curjob */
3248 #define CUR_DELETE 2
3249 #define CUR_RUNNING 1
3250 #define CUR_STOPPED 0
3252 /* mode flags for dowait */
3253 #define DOWAIT_NORMAL 0
3254 #define DOWAIT_BLOCK 1
3257 /* pgrp of shell on invocation */
3258 static int initialpgrp;
3259 static int ttyfd = -1;
3262 static struct job *jobtab;
3264 static unsigned njobs;
3266 static struct job *curjob;
3267 /* number of presumed living untracked jobs */
3271 set_curjob(struct job *jp, unsigned mode)
3274 struct job **jpp, **curp;
3276 /* first remove from list */
3277 jpp = curp = &curjob;
3282 jpp = &jp1->prev_job;
3284 *jpp = jp1->prev_job;
3286 /* Then re-insert in correct position */
3294 /* job being deleted */
3297 /* newly created job or backgrounded job,
3298 put after all stopped jobs. */
3302 if (!jp1 || jp1->state != JOBSTOPPED)
3305 jpp = &jp1->prev_job;
3311 /* newly stopped job - becomes curjob */
3312 jp->prev_job = *jpp;
3320 jobno(const struct job *jp)
3322 return jp - jobtab + 1;
3327 * Convert a job name to a job structure.
3330 getjob(const char *name, int getctl)
3334 const char *err_msg = "No such job: %s";
3338 char *(*match)(const char *, const char *);
3353 if (c == '+' || c == '%') {
3355 err_msg = "No current job";
3361 err_msg = "No previous job";
3372 jp = jobtab + num - 1;
3389 if (match(jp->ps[0].cmd, p)) {
3393 err_msg = "%s: ambiguous";
3400 err_msg = "job %s not created under job control";
3401 if (getctl && jp->jobctl == 0)
3406 ash_msg_and_raise_error(err_msg, name);
3410 * Mark a job structure as unused.
3413 freejob(struct job *jp)
3415 struct procstat *ps;
3419 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3420 if (ps->cmd != nullstr)
3423 if (jp->ps != &jp->ps0)
3426 set_curjob(jp, CUR_DELETE);
3432 xtcsetpgrp(int fd, pid_t pgrp)
3434 if (tcsetpgrp(fd, pgrp))
3435 ash_msg_and_raise_error("cannot set tty process group (%m)");
3439 * Turn job control on and off.
3441 * Note: This code assumes that the third arg to ioctl is a character
3442 * pointer, which is true on Berkeley systems but not System V. Since
3443 * System V doesn't have job control yet, this isn't a problem now.
3445 * Called with interrupts off.
3453 if (on == jobctl || rootshell == 0)
3457 ofd = fd = open(_PATH_TTY, O_RDWR);
3459 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3460 * That sometimes helps to acquire controlling tty.
3461 * Obviously, a workaround for bugs when someone
3462 * failed to provide a controlling tty to bash! :) */
3464 while (!isatty(fd) && --fd >= 0)
3467 fd = fcntl(fd, F_DUPFD, 10);
3471 fcntl(fd, F_SETFD, FD_CLOEXEC);
3472 do { /* while we are in the background */
3473 pgrp = tcgetpgrp(fd);
3476 ash_msg("can't access tty; job control turned off");
3480 if (pgrp == getpgrp())
3491 xtcsetpgrp(fd, pgrp);
3493 /* turning job control off */
3496 /* was xtcsetpgrp, but this can make exiting ash
3497 * with pty already deleted loop forever */
3498 tcsetpgrp(fd, pgrp);
3512 killcmd(int argc, char **argv)
3514 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3517 if (argv[i][0] == '%') {
3518 struct job *jp = getjob(argv[i], 0);
3519 unsigned pid = jp->ps[0].pid;
3520 /* Enough space for ' -NNN<nul>' */
3521 argv[i] = alloca(sizeof(int)*3 + 3);
3522 /* kill_main has matching code to expect
3523 * leading space. Needed to not confuse
3524 * negative pids with "kill -SIGNAL_NO" syntax */
3525 sprintf(argv[i], " -%u", pid);
3527 } while (argv[++i]);
3529 return kill_main(argc, argv);
3533 showpipe(struct job *jp, FILE *out)
3535 struct procstat *sp;
3536 struct procstat *spend;
3538 spend = jp->ps + jp->nprocs;
3539 for (sp = jp->ps + 1; sp < spend; sp++)
3540 fprintf(out, " | %s", sp->cmd);
3541 outcslow('\n', out);
3542 flush_stdout_stderr();
3547 restartjob(struct job *jp, int mode)
3549 struct procstat *ps;
3555 if (jp->state == JOBDONE)
3557 jp->state = JOBRUNNING;
3559 if (mode == FORK_FG)
3560 xtcsetpgrp(ttyfd, pgid);
3561 killpg(pgid, SIGCONT);
3565 if (WIFSTOPPED(ps->status)) {
3571 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3577 fg_bgcmd(int argc, char **argv)
3584 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3589 jp = getjob(*argv, 1);
3590 if (mode == FORK_BG) {
3591 set_curjob(jp, CUR_RUNNING);
3592 fprintf(out, "[%d] ", jobno(jp));
3594 outstr(jp->ps->cmd, out);
3596 retval = restartjob(jp, mode);
3597 } while (*argv && *++argv);
3603 sprint_status(char *s, int status, int sigonly)
3609 if (!WIFEXITED(status)) {
3611 if (WIFSTOPPED(status))
3612 st = WSTOPSIG(status);
3615 st = WTERMSIG(status);
3617 if (st == SIGINT || st == SIGPIPE)
3620 if (WIFSTOPPED(status))
3625 col = fmtstr(s, 32, strsignal(st));
3626 if (WCOREDUMP(status)) {
3627 col += fmtstr(s + col, 16, " (core dumped)");
3629 } else if (!sigonly) {
3630 st = WEXITSTATUS(status);
3632 col = fmtstr(s, 16, "Done(%d)", st);
3634 col = fmtstr(s, 16, "Done");
3641 * Do a wait system call. If job control is compiled in, we accept
3642 * stopped processes. If block is zero, we return a value of zero
3643 * rather than blocking.
3645 * System V doesn't have a non-blocking wait system call. It does
3646 * have a SIGCLD signal that is sent to a process when one of it's
3647 * children dies. The obvious way to use SIGCLD would be to install
3648 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3649 * was received, and have waitproc bump another counter when it got
3650 * the status of a process. Waitproc would then know that a wait
3651 * system call would not block if the two counters were different.
3652 * This approach doesn't work because if a process has children that
3653 * have not been waited for, System V will send it a SIGCLD when it
3654 * installs a signal handler for SIGCLD. What this means is that when
3655 * a child exits, the shell will be sent SIGCLD signals continuously
3656 * until is runs out of stack space, unless it does a wait call before
3657 * restoring the signal handler. The code below takes advantage of
3658 * this (mis)feature by installing a signal handler for SIGCLD and
3659 * then checking to see whether it was called. If there are any
3660 * children to be waited for, it will be.
3662 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3663 * waits at all. In this case, the user will not be informed when
3664 * a background process until the next time she runs a real program
3665 * (as opposed to running a builtin command or just typing return),
3666 * and the jobs command may give out of date information.
3669 waitproc(int block, int *status)
3679 return wait3(status, flags, (struct rusage *)NULL);
3683 * Wait for a process to terminate.
3686 dowait(int block, struct job *job)
3691 struct job *thisjob;
3694 TRACE(("dowait(%d) called\n", block));
3695 pid = waitproc(block, &status);
3696 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3701 for (jp = curjob; jp; jp = jp->prev_job) {
3702 struct procstat *sp;
3703 struct procstat *spend;
3704 if (jp->state == JOBDONE)
3707 spend = jp->ps + jp->nprocs;
3710 if (sp->pid == pid) {
3711 TRACE(("Job %d: changing status of proc %d "
3712 "from 0x%x to 0x%x\n",
3713 jobno(jp), pid, sp->status, status));
3714 sp->status = status;
3717 if (sp->status == -1)
3720 if (state == JOBRUNNING)
3722 if (WIFSTOPPED(sp->status)) {
3723 jp->stopstatus = sp->status;
3727 } while (++sp < spend);
3732 if (!WIFSTOPPED(status))
3739 if (state != JOBRUNNING) {
3740 thisjob->changed = 1;
3742 if (thisjob->state != state) {
3743 TRACE(("Job %d: changing state from %d to %d\n",
3744 jobno(thisjob), thisjob->state, state));
3745 thisjob->state = state;
3747 if (state == JOBSTOPPED) {
3748 set_curjob(thisjob, CUR_STOPPED);
3757 if (thisjob && thisjob == job) {
3761 len = sprint_status(s, status, 1);
3773 showjob(FILE *out, struct job *jp, int mode)
3775 struct procstat *ps;
3776 struct procstat *psend;
3783 if (mode & SHOW_PGID) {
3784 /* just output process (group) id of pipeline */
3785 fprintf(out, "%d\n", ps->pid);
3789 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3794 else if (curjob && jp == curjob->prev_job)
3797 if (mode & SHOW_PID)
3798 col += fmtstr(s + col, 16, "%d ", ps->pid);
3800 psend = ps + jp->nprocs;
3802 if (jp->state == JOBRUNNING) {
3803 strcpy(s + col, "Running");
3804 col += sizeof("Running") - 1;
3806 int status = psend[-1].status;
3807 if (jp->state == JOBSTOPPED)
3808 status = jp->stopstatus;
3809 col += sprint_status(s + col, status, 0);
3815 /* for each process */
3816 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3818 fprintf(out, "%s%*c%s",
3819 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3821 if (!(mode & SHOW_PID)) {
3825 if (++ps == psend) {
3826 outcslow('\n', out);
3833 if (jp->state == JOBDONE) {
3834 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3840 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3841 * statuses have changed since the last call to showjobs.
3844 showjobs(FILE *out, int mode)
3848 TRACE(("showjobs(%x) called\n", mode));
3850 /* If not even one one job changed, there is nothing to do */
3851 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3854 for (jp = curjob; jp; jp = jp->prev_job) {
3855 if (!(mode & SHOW_CHANGED) || jp->changed) {
3856 showjob(out, jp, mode);
3862 jobscmd(int argc, char **argv)
3867 while ((m = nextopt("lp"))) {
3877 showjob(stdout, getjob(*argv,0), mode);
3880 showjobs(stdout, mode);
3887 getstatus(struct job *job)
3892 status = job->ps[job->nprocs - 1].status;
3893 retval = WEXITSTATUS(status);
3894 if (!WIFEXITED(status)) {
3896 retval = WSTOPSIG(status);
3897 if (!WIFSTOPPED(status))
3900 /* XXX: limits number of signals */
3901 retval = WTERMSIG(status);
3903 if (retval == SIGINT)
3909 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3910 jobno(job), job->nprocs, status, retval));
3915 waitcmd(int argc, char **argv)
3928 /* wait for all jobs */
3933 /* no running procs */
3936 if (jp->state == JOBRUNNING)
3941 dowait(DOWAIT_BLOCK, 0);
3947 if (**argv != '%') {
3948 pid_t pid = number(*argv);
3952 if (job->ps[job->nprocs - 1].pid == pid)
3954 job = job->prev_job;
3960 job = getjob(*argv, 0);
3961 /* loop until process terminated or stopped */
3962 while (job->state == JOBRUNNING)
3963 dowait(DOWAIT_BLOCK, 0);
3965 retval = getstatus(job);
3979 struct job *jp, *jq;
3981 len = njobs * sizeof(*jp);
3983 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
3985 offset = (char *)jp - (char *)jq;
3987 /* Relocate pointers */
3990 jq = (struct job *)((char *)jq + l);
3994 #define joff(p) ((struct job *)((char *)(p) + l))
3995 #define jmove(p) (p) = (void *)((char *)(p) + offset)
3996 if (joff(jp)->ps == &jq->ps0)
3997 jmove(joff(jp)->ps);
3998 if (joff(jp)->prev_job)
3999 jmove(joff(jp)->prev_job);
4009 jp = (struct job *)((char *)jp + len);
4013 } while (--jq >= jp);
4018 * Return a new job structure.
4019 * Called with interrupts off.
4022 makejob(union node *node, int nprocs)
4027 for (i = njobs, jp = jobtab; ; jp++) {
4034 if (jp->state != JOBDONE || !jp->waited)
4043 memset(jp, 0, sizeof(*jp));
4045 /* jp->jobctl is a bitfield.
4046 * "jp->jobctl |= jobctl" likely to give awful code */
4050 jp->prev_job = curjob;
4055 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4057 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4064 * Return a string identifying a command (to be printed by the
4067 static char *cmdnextc;
4070 cmdputs(const char *s)
4072 const char *p, *str;
4073 char c, cc[2] = " ";
4077 static const char vstype[VSTYPE + 1][4] = {
4078 "", "}", "-", "+", "?", "=",
4079 "%", "%%", "#", "##"
4082 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4084 while ((c = *p++) != 0) {
4092 if ((subtype & VSTYPE) == VSLENGTH)
4096 if (!(subtype & VSQUOTE) == !(quoted & 1))
4102 str = "\"}" + !(quoted & 1);
4109 case CTLBACKQ+CTLQUOTE:
4112 #if ENABLE_ASH_MATH_SUPPORT
4127 if ((subtype & VSTYPE) != VSNORMAL)
4129 str = vstype[subtype & VSTYPE];
4130 if (subtype & VSNUL)
4139 /* These can only happen inside quotes */
4152 while ((c = *str++)) {
4157 USTPUTC('"', nextc);
4163 /* cmdtxt() and cmdlist() call each other */
4164 static void cmdtxt(union node *n);
4167 cmdlist(union node *np, int sep)
4169 for (; np; np = np->narg.next) {
4173 if (sep && np->narg.next)
4179 cmdtxt(union node *n)
4182 struct nodelist *lp;
4194 lp = n->npipe.cmdlist;
4212 cmdtxt(n->nbinary.ch1);
4228 cmdtxt(n->nif.test);
4231 if (n->nif.elsepart) {
4234 n = n->nif.elsepart;
4250 cmdtxt(n->nbinary.ch1);
4260 cmdputs(n->nfor.var);
4262 cmdlist(n->nfor.args, 1);
4267 cmdputs(n->narg.text);
4271 cmdlist(n->ncmd.args, 1);
4272 cmdlist(n->ncmd.redirect, 0);
4285 cmdputs(n->ncase.expr->narg.text);
4287 for (np = n->ncase.cases; np; np = np->nclist.next) {
4288 cmdtxt(np->nclist.pattern);
4290 cmdtxt(np->nclist.body);
4316 s[0] = n->nfile.fd + '0';
4320 if (n->type == NTOFD || n->type == NFROMFD) {
4321 s[0] = n->ndup.dupfd + '0';
4331 commandtext(union node *n)
4335 STARTSTACKSTR(cmdnextc);
4337 name = stackblock();
4338 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4339 name, cmdnextc, cmdnextc));
4340 return ckstrdup(name);
4345 * Fork off a subshell. If we are doing job control, give the subshell its
4346 * own process group. Jp is a job structure that the job is to be added to.
4347 * N is the command that will be evaluated by the child. Both jp and n may
4348 * be NULL. The mode parameter can be one of the following:
4349 * FORK_FG - Fork off a foreground process.
4350 * FORK_BG - Fork off a background process.
4351 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4352 * process group even if job control is on.
4354 * When job control is turned off, background processes have their standard
4355 * input redirected to /dev/null (except for the second and later processes
4358 * Called with interrupts off.
4361 * Clear traps on a fork.
4368 for (tp = trap; tp < &trap[NSIG]; tp++) {
4369 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4374 setsignal(tp - trap);
4380 /* Lives far away from here, needed for forkchild */
4381 static void closescript(void);
4382 /* Called after fork(), in child */
4384 forkchild(struct job *jp, union node *n, int mode)
4388 TRACE(("Child shell %d\n", getpid()));
4395 /* do job control only in root shell */
4397 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4400 if (jp->nprocs == 0)
4403 pgrp = jp->ps[0].pid;
4404 /* This can fail because we are doing it in the parent also */
4405 (void)setpgid(0, pgrp);
4406 if (mode == FORK_FG)
4407 xtcsetpgrp(ttyfd, pgrp);
4412 if (mode == FORK_BG) {
4415 if (jp->nprocs == 0) {
4417 if (open(bb_dev_null, O_RDONLY) != 0)
4418 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4421 if (!oldlvl && iflag) {
4427 /* For "jobs | cat" to work like in bash, we must retain list of jobs
4428 * in child, but we do need to remove ourself */
4432 for (jp = curjob; jp; jp = jp->prev_job)
4438 /* Called after fork(), in parent */
4440 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4442 TRACE(("In parent shell: child = %d\n", pid));
4444 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4449 if (mode != FORK_NOJOB && jp->jobctl) {
4452 if (jp->nprocs == 0)
4455 pgrp = jp->ps[0].pid;
4456 /* This can fail because we are doing it in the child also */
4460 if (mode == FORK_BG) {
4461 backgndpid = pid; /* set $! */
4462 set_curjob(jp, CUR_RUNNING);
4465 struct procstat *ps = &jp->ps[jp->nprocs++];
4471 ps->cmd = commandtext(n);
4477 forkshell(struct job *jp, union node *n, int mode)
4481 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4484 TRACE(("Fork failed, errno=%d", errno));
4487 ash_msg_and_raise_error("cannot fork");
4490 forkchild(jp, n, mode);
4492 forkparent(jp, n, mode, pid);
4497 * Wait for job to finish.
4499 * Under job control we have the problem that while a child process is
4500 * running interrupts generated by the user are sent to the child but not
4501 * to the shell. This means that an infinite loop started by an inter-
4502 * active user may be hard to kill. With job control turned off, an
4503 * interactive user may place an interactive program inside a loop. If
4504 * the interactive program catches interrupts, the user doesn't want
4505 * these interrupts to also abort the loop. The approach we take here
4506 * is to have the shell ignore interrupt signals while waiting for a
4507 * foreground process to terminate, and then send itself an interrupt
4508 * signal if the child process was terminated by an interrupt signal.
4509 * Unfortunately, some programs want to do a bit of cleanup and then
4510 * exit on interrupt; unless these processes terminate themselves by
4511 * sending a signal to themselves (instead of calling exit) they will
4512 * confuse this approach.
4514 * Called with interrupts off.
4517 waitforjob(struct job *jp)
4521 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4522 while (jp->state == JOBRUNNING) {
4523 dowait(DOWAIT_BLOCK, jp);
4528 xtcsetpgrp(ttyfd, rootpid);
4530 * This is truly gross.
4531 * If we're doing job control, then we did a TIOCSPGRP which
4532 * caused us (the shell) to no longer be in the controlling
4533 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4534 * intuit from the subprocess exit status whether a SIGINT
4535 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4540 if (jp->state == JOBDONE)
4547 * return 1 if there are stopped jobs, otherwise 0
4559 if (jp && jp->state == JOBSTOPPED) {
4560 out2str("You have stopped jobs.\n");
4569 /* ============ redir.c
4571 * Code for dealing with input/output redirection.
4574 #define EMPTY -2 /* marks an unused slot in redirtab */
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) {
4808 q = ckmalloc(sizeof(struct redirtab));
4809 q->next = redirlist;
4811 q->nullredirs = nullredirs - 1;
4812 for (i = 0; i < 10; i++)
4813 q->renamed[i] = EMPTY;
4820 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4821 && n->ndup.dupfd == fd)
4822 continue; /* redirect from/to same file descriptor */
4824 newfd = openredirect(n);
4827 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4828 i = fcntl(fd, F_DUPFD, 10);
4835 ash_msg_and_raise_error("%d: %m", fd);
4845 dupredirect(n, newfd);
4846 } while ((n = n->nfile.next));
4848 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4849 preverrout_fd = sv->renamed[2];
4853 * Undo the effects of the last redirection.
4858 struct redirtab *rp;
4861 if (--nullredirs >= 0)
4865 for (i = 0; i < 10; i++) {
4866 if (rp->renamed[i] != EMPTY) {
4869 copyfd(rp->renamed[i], i);
4871 close(rp->renamed[i]);
4874 redirlist = rp->next;
4875 nullredirs = rp->nullredirs;
4881 * Undo all redirections. Called on error or interrupt.
4885 * Discard all saved file descriptors.
4888 clearredir(int drop)
4899 redirectsafe(union node *redir, int flags)
4902 volatile int saveint;
4903 struct jmploc *volatile savehandler = exception_handler;
4904 struct jmploc jmploc;
4907 err = setjmp(jmploc.loc) * 2;
4909 exception_handler = &jmploc;
4910 redirect(redir, flags);
4912 exception_handler = savehandler;
4913 if (err && exception != EXERROR)
4914 longjmp(exception_handler->loc, 1);
4915 RESTORE_INT(saveint);
4920 /* ============ Routines to expand arguments to commands
4922 * We have to deal with backquotes, shell variables, and file metacharacters.
4928 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4929 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4930 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4931 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4932 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4933 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4934 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4935 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4936 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
4940 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4941 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4942 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4943 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4944 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4947 * Structure specifying which parts of the string should be searched
4948 * for IFS characters.
4951 struct ifsregion *next; /* next region in list */
4952 int begoff; /* offset of start of region */
4953 int endoff; /* offset of end of region */
4954 int nulonly; /* search for nul bytes only */
4958 struct strlist *list;
4959 struct strlist **lastp;
4962 /* output of current string */
4963 static char *expdest;
4964 /* list of back quote expressions */
4965 static struct nodelist *argbackq;
4966 /* first struct in list of ifs regions */
4967 static struct ifsregion ifsfirst;
4968 /* last struct in list */
4969 static struct ifsregion *ifslastp;
4970 /* holds expanded arg list */
4971 static struct arglist exparg;
4981 expdest = makestrspace(32, expdest);
4982 #if ENABLE_ASH_MATH_SUPPORT_64
4983 len = fmtstr(expdest, 32, "%lld", (long long) num);
4985 len = fmtstr(expdest, 32, "%ld", num);
4987 STADJUST(len, expdest);
4992 esclen(const char *start, const char *p)
4996 while (p > start && *--p == CTLESC) {
5003 * Remove any CTLESC characters from a string.
5006 _rmescapes(char *str, int flag)
5008 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5015 p = strpbrk(str, qchars);
5021 if (flag & RMESCAPE_ALLOC) {
5022 size_t len = p - str;
5023 size_t fulllen = len + strlen(p) + 1;
5025 if (flag & RMESCAPE_GROW) {
5026 r = makestrspace(fulllen, expdest);
5027 } else if (flag & RMESCAPE_HEAP) {
5028 r = ckmalloc(fulllen);
5030 r = stalloc(fulllen);
5034 q = memcpy(q, str, len) + len;
5037 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5038 globbing = flag & RMESCAPE_GLOB;
5039 notescaped = globbing;
5041 if (*p == CTLQUOTEMARK) {
5042 inquotes = ~inquotes;
5044 notescaped = globbing;
5048 /* naked back slash */
5054 if (notescaped && inquotes && *p != '/') {
5058 notescaped = globbing;
5063 if (flag & RMESCAPE_GROW) {
5065 STADJUST(q - r + 1, expdest);
5069 #define rmescapes(p) _rmescapes((p), 0)
5071 #define pmatch(a, b) !fnmatch((a), (b), 0)
5074 * Prepare a pattern for a expmeta (internal glob(3)) call.
5076 * Returns an stalloced string.
5079 preglob(const char *pattern, int quoted, int flag)
5081 flag |= RMESCAPE_GLOB;
5083 flag |= RMESCAPE_QUOTED;
5085 return _rmescapes((char *)pattern, flag);
5089 * Put a string on the stack.
5092 memtodest(const char *p, size_t len, int syntax, int quotes)
5096 q = makestrspace(len * 2, q);
5099 int c = signed_char2int(*p++);
5102 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5111 strtodest(const char *p, int syntax, int quotes)
5113 memtodest(p, strlen(p), syntax, quotes);
5117 * Record the fact that we have to scan this region of the
5118 * string for IFS characters.
5121 recordregion(int start, int end, int nulonly)
5123 struct ifsregion *ifsp;
5125 if (ifslastp == NULL) {
5129 ifsp = ckmalloc(sizeof(*ifsp));
5131 ifslastp->next = ifsp;
5135 ifslastp->begoff = start;
5136 ifslastp->endoff = end;
5137 ifslastp->nulonly = nulonly;
5141 removerecordregions(int endoff)
5143 if (ifslastp == NULL)
5146 if (ifsfirst.endoff > endoff) {
5147 while (ifsfirst.next != NULL) {
5148 struct ifsregion *ifsp;
5150 ifsp = ifsfirst.next->next;
5151 free(ifsfirst.next);
5152 ifsfirst.next = ifsp;
5155 if (ifsfirst.begoff > endoff)
5158 ifslastp = &ifsfirst;
5159 ifsfirst.endoff = endoff;
5164 ifslastp = &ifsfirst;
5165 while (ifslastp->next && ifslastp->next->begoff < endoff)
5166 ifslastp=ifslastp->next;
5167 while (ifslastp->next != NULL) {
5168 struct ifsregion *ifsp;
5170 ifsp = ifslastp->next->next;
5171 free(ifslastp->next);
5172 ifslastp->next = ifsp;
5175 if (ifslastp->endoff > endoff)
5176 ifslastp->endoff = endoff;
5180 exptilde(char *startp, char *p, int flag)
5186 int quotes = flag & (EXP_FULL | EXP_CASE);
5191 while ((c = *++p) != '\0') {
5198 if (flag & EXP_VARTILDE)
5208 if (*name == '\0') {
5209 home = lookupvar(homestr);
5211 pw = getpwnam(name);
5216 if (!home || !*home)
5219 startloc = expdest - (char *)stackblock();
5220 strtodest(home, SQSYNTAX, quotes);
5221 recordregion(startloc, expdest - (char *)stackblock(), 0);
5229 * Execute a command inside back quotes. If it's a builtin command, we
5230 * want to save its output in a block obtained from malloc. Otherwise
5231 * we fork off a subprocess and get the output of the command via a pipe.
5232 * Should be called with interrupts off.
5234 struct backcmd { /* result of evalbackcmd */
5235 int fd; /* file descriptor to read from */
5236 char *buf; /* buffer */
5237 int nleft; /* number of chars in buffer */
5238 struct job *jp; /* job structure for command */
5241 /* These forward decls are needed to use "eval" code for backticks handling: */
5242 static int back_exitstatus; /* exit status of backquoted command */
5243 #define EV_EXIT 01 /* exit after evaluating tree */
5244 static void evaltree(union node *, int);
5247 evalbackcmd(union node *n, struct backcmd *result)
5259 saveherefd = herefd;
5267 ash_msg_and_raise_error("pipe call failed");
5269 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5278 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5282 result->fd = pip[0];
5285 herefd = saveherefd;
5287 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5288 result->fd, result->buf, result->nleft, result->jp));
5292 * Expand stuff in backwards quotes.
5295 expbackq(union node *cmd, int quoted, int quotes)
5303 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5304 struct stackmark smark;
5307 setstackmark(&smark);
5309 startloc = dest - (char *)stackblock();
5311 evalbackcmd(cmd, &in);
5312 popstackmark(&smark);
5319 memtodest(p, i, syntax, quotes);
5323 i = safe_read(in.fd, buf, sizeof(buf));
5324 TRACE(("expbackq: read returns %d\n", i));
5334 back_exitstatus = waitforjob(in.jp);
5338 /* Eat all trailing newlines */
5340 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5345 recordregion(startloc, dest - (char *)stackblock(), 0);
5346 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5347 (dest - (char *)stackblock()) - startloc,
5348 (dest - (char *)stackblock()) - startloc,
5349 stackblock() + startloc));
5352 #if ENABLE_ASH_MATH_SUPPORT
5354 * Expand arithmetic expression. Backup to start of expression,
5355 * evaluate, place result in (backed up) result, adjust string position.
5368 * This routine is slightly over-complicated for
5369 * efficiency. Next we scan backwards looking for the
5370 * start of arithmetic.
5372 start = stackblock();
5379 while (*p != CTLARI) {
5383 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5388 esc = esclen(start, p);
5398 removerecordregions(begoff);
5407 len = cvtnum(dash_arith(p + 2));
5410 recordregion(begoff, begoff + len, 0);
5414 /* argstr needs it */
5415 static char *evalvar(char *p, int flag);
5418 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5419 * characters to allow for further processing. Otherwise treat
5420 * $@ like $* since no splitting will be performed.
5423 argstr(char *p, int flag)
5425 static const char spclchars[] ALIGN1 = {
5433 CTLBACKQ | CTLQUOTE,
5434 #if ENABLE_ASH_MATH_SUPPORT
5439 const char *reject = spclchars;
5441 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5442 int breakall = flag & EXP_WORD;
5447 if (!(flag & EXP_VARTILDE)) {
5449 } else if (flag & EXP_VARTILDE2) {
5454 if (flag & EXP_TILDE) {
5460 if (*q == CTLESC && (flag & EXP_QWORD))
5463 p = exptilde(p, q, flag);
5466 startloc = expdest - (char *)stackblock();
5468 length += strcspn(p + length, reject);
5470 if (c && (!(c & 0x80)
5471 #if ENABLE_ASH_MATH_SUPPORT
5475 /* c == '=' || c == ':' || c == CTLENDARI */
5480 expdest = stack_nputstr(p, length, expdest);
5481 newloc = expdest - (char *)stackblock();
5482 if (breakall && !inquotes && newloc > startloc) {
5483 recordregion(startloc, newloc, 0);
5494 if (flag & EXP_VARTILDE2) {
5498 flag |= EXP_VARTILDE2;
5503 * sort of a hack - expand tildes in variable
5504 * assignments (after the first '=' and after ':'s).
5513 case CTLENDVAR: /* ??? */
5516 /* "$@" syntax adherence hack */
5519 !memcmp(p, dolatstr, 4) &&
5520 (p[4] == CTLQUOTEMARK || (
5521 p[4] == CTLENDVAR &&
5522 p[5] == CTLQUOTEMARK
5525 p = evalvar(p + 1, flag) + 1;
5528 inquotes = !inquotes;
5541 p = evalvar(p, flag);
5545 case CTLBACKQ|CTLQUOTE:
5546 expbackq(argbackq->n, c, quotes);
5547 argbackq = argbackq->next;
5549 #if ENABLE_ASH_MATH_SUPPORT
5562 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5573 const char *s = loc2;
5579 match = pmatch(str, s);
5583 if (quotes && *loc == CTLESC)
5592 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5599 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5602 const char *s = loc2;
5607 match = pmatch(str, s);
5614 esc = esclen(startp, loc);
5625 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5627 varunset(const char *end, const char *var, const char *umsg, int varflags)
5633 msg = "parameter not set";
5635 if (*end == CTLENDVAR) {
5636 if (varflags & VSNUL)
5641 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5645 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5649 int saveherefd = herefd;
5650 struct nodelist *saveargbackq = argbackq;
5652 char *rmesc, *rmescend;
5654 char *(*scan)(char *, char *, char *, char *, int , int);
5657 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5658 STPUTC('\0', expdest);
5659 herefd = saveherefd;
5660 argbackq = saveargbackq;
5661 startp = stackblock() + startloc;
5665 setvar(str, startp, 0);
5666 amount = startp - expdest;
5667 STADJUST(amount, expdest);
5671 varunset(p, str, startp, varflags);
5675 subtype -= VSTRIMRIGHT;
5677 if (subtype < 0 || subtype > 3)
5682 rmescend = stackblock() + strloc;
5684 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5685 if (rmesc != startp) {
5687 startp = stackblock() + startloc;
5691 str = stackblock() + strloc;
5692 preglob(str, varflags & VSQUOTE, 0);
5694 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5695 zero = subtype >> 1;
5696 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5697 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5699 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5702 memmove(startp, loc, str - loc);
5703 loc = startp + (str - loc) - 1;
5706 amount = loc - expdest;
5707 STADJUST(amount, expdest);
5713 * Add the value of a specialized variable to the stack string.
5716 varvalue(char *name, int varflags, int flags)
5726 int quoted = varflags & VSQUOTE;
5727 int subtype = varflags & VSTYPE;
5728 int quotes = flags & (EXP_FULL | EXP_CASE);
5730 if (quoted && (flags & EXP_FULL))
5731 sep = 1 << CHAR_BIT;
5733 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5742 num = shellparam.nparam;
5752 p = makestrspace(NOPTS, expdest);
5753 for (i = NOPTS - 1; i >= 0; i--) {
5755 USTPUTC(optletters(i), p);
5766 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5767 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5773 while ((p = *ap++)) {
5776 partlen = strlen(p);
5779 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5780 memtodest(p, partlen, syntax, quotes);
5786 if (subtype == VSPLUS || subtype == VSLENGTH) {
5808 if (num < 0 || num > shellparam.nparam)
5810 p = num ? shellparam.p[num - 1] : arg0;
5813 p = lookupvar(name);
5819 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5820 memtodest(p, len, syntax, quotes);
5824 if (subtype == VSPLUS || subtype == VSLENGTH)
5825 STADJUST(-len, expdest);
5830 * Expand a variable, and return a pointer to the next character in the
5834 evalvar(char *p, int flag)
5847 quotes = flag & (EXP_FULL | EXP_CASE);
5849 subtype = varflags & VSTYPE;
5850 quoted = varflags & VSQUOTE;
5852 easy = (!quoted || (*var == '@' && shellparam.nparam));
5853 startloc = expdest - (char *)stackblock();
5854 p = strchr(p, '=') + 1;
5857 varlen = varvalue(var, varflags, flag);
5858 if (varflags & VSNUL)
5861 if (subtype == VSPLUS) {
5862 varlen = -1 - varlen;
5866 if (subtype == VSMINUS) {
5870 p, flag | EXP_TILDE |
5871 (quoted ? EXP_QWORD : EXP_WORD)
5880 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5882 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5885 * Remove any recorded regions beyond
5888 removerecordregions(startloc);
5898 if (varlen < 0 && uflag)
5899 varunset(p, var, 0, 0);
5901 if (subtype == VSLENGTH) {
5902 cvtnum(varlen > 0 ? varlen : 0);
5906 if (subtype == VSNORMAL) {
5910 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5919 case VSTRIMRIGHTMAX:
5928 * Terminate the string and start recording the pattern
5931 STPUTC('\0', expdest);
5932 patloc = expdest - (char *)stackblock();
5933 if (subevalvar(p, NULL, patloc, subtype,
5934 startloc, varflags, quotes) == 0) {
5935 int amount = expdest - (
5936 (char *)stackblock() + patloc - 1
5938 STADJUST(-amount, expdest);
5940 /* Remove any recorded regions beyond start of variable */
5941 removerecordregions(startloc);
5946 if (subtype != VSNORMAL) { /* skip to end of alternative */
5952 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5954 argbackq = argbackq->next;
5955 } else if (c == CTLVAR) {
5956 if ((*p++ & VSTYPE) != VSNORMAL)
5958 } else if (c == CTLENDVAR) {
5968 * Break the argument string into pieces based upon IFS and add the
5969 * strings to the argument list. The regions of the string to be
5970 * searched for IFS characters have been stored by recordregion.
5973 ifsbreakup(char *string, struct arglist *arglist)
5975 struct ifsregion *ifsp;
5980 const char *ifs, *realifs;
5985 if (ifslastp != NULL) {
5988 realifs = ifsset() ? ifsval() : defifs;
5991 p = string + ifsp->begoff;
5992 nulonly = ifsp->nulonly;
5993 ifs = nulonly ? nullstr : realifs;
5995 while (p < string + ifsp->endoff) {
5999 if (!strchr(ifs, *p)) {
6004 ifsspc = (strchr(defifs, *p) != NULL);
6005 /* Ignore IFS whitespace at start */
6006 if (q == start && ifsspc) {
6012 sp = stalloc(sizeof(*sp));
6014 *arglist->lastp = sp;
6015 arglist->lastp = &sp->next;
6019 if (p >= string + ifsp->endoff) {
6025 if (strchr(ifs, *p) == NULL ) {
6028 } else if (strchr(defifs, *p) == NULL) {
6043 } while (ifsp != NULL);
6052 sp = stalloc(sizeof(*sp));
6054 *arglist->lastp = sp;
6055 arglist->lastp = &sp->next;
6061 struct ifsregion *p;
6066 struct ifsregion *ifsp;
6072 ifsfirst.next = NULL;
6077 * Add a file name to the list.
6080 addfname(const char *name)
6084 sp = stalloc(sizeof(*sp));
6085 sp->text = ststrdup(name);
6087 exparg.lastp = &sp->next;
6090 static char *expdir;
6093 * Do metacharacter (i.e. *, ?, [...]) expansion.
6096 expmeta(char *enddir, char *name)
6111 for (p = name; *p; p++) {
6112 if (*p == '*' || *p == '?')
6114 else if (*p == '[') {
6121 if (*q == '/' || *q == '\0')
6128 } else if (*p == '\\')
6130 else if (*p == '/') {
6137 if (metaflag == 0) { /* we've reached the end of the file name */
6138 if (enddir != expdir)
6146 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6157 } while (p < start);
6159 if (enddir == expdir) {
6161 } else if (enddir == expdir + 1 && *expdir == '/') {
6170 if (enddir != expdir)
6172 if (*endname == 0) {
6184 while (! intpending && (dp = readdir(dirp)) != NULL) {
6185 if (dp->d_name[0] == '.' && ! matchdot)
6187 if (pmatch(start, dp->d_name)) {
6189 strcpy(enddir, dp->d_name);
6192 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6195 expmeta(p, endname);
6204 static struct strlist *
6205 msort(struct strlist *list, int len)
6207 struct strlist *p, *q = NULL;
6208 struct strlist **lpp;
6216 for (n = half; --n >= 0; ) {
6220 q->next = NULL; /* terminate first half of list */
6221 q = msort(list, half); /* sort first half of list */
6222 p = msort(p, len - half); /* sort second half */
6225 #if ENABLE_LOCALE_SUPPORT
6226 if (strcoll(p->text, q->text) < 0)
6228 if (strcmp(p->text, q->text) < 0)
6252 * Sort the results of file name expansion. It calculates the number of
6253 * strings to sort and then calls msort (short for merge sort) to do the
6256 static struct strlist *
6257 expsort(struct strlist *str)
6263 for (sp = str; sp; sp = sp->next)
6265 return msort(str, len);
6269 expandmeta(struct strlist *str, int flag)
6271 static const char metachars[] ALIGN1 = {
6274 /* TODO - EXP_REDIR */
6277 struct strlist **savelastp;
6283 if (!strpbrk(str->text, metachars))
6285 savelastp = exparg.lastp;
6288 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6290 int i = strlen(str->text);
6291 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6299 if (exparg.lastp == savelastp) {
6304 *exparg.lastp = str;
6305 rmescapes(str->text);
6306 exparg.lastp = &str->next;
6308 *exparg.lastp = NULL;
6309 *savelastp = sp = expsort(*savelastp);
6310 while (sp->next != NULL)
6312 exparg.lastp = &sp->next;
6319 * Perform variable substitution and command substitution on an argument,
6320 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6321 * perform splitting and file name expansion. When arglist is NULL, perform
6322 * here document expansion.
6325 expandarg(union node *arg, struct arglist *arglist, int flag)
6330 argbackq = arg->narg.backquote;
6331 STARTSTACKSTR(expdest);
6332 ifsfirst.next = NULL;
6334 argstr(arg->narg.text, flag);
6335 p = _STPUTC('\0', expdest);
6337 if (arglist == NULL) {
6338 return; /* here document expanded */
6340 p = grabstackstr(p);
6341 exparg.lastp = &exparg.list;
6345 if (flag & EXP_FULL) {
6346 ifsbreakup(p, &exparg);
6347 *exparg.lastp = NULL;
6348 exparg.lastp = &exparg.list;
6349 expandmeta(exparg.list, flag);
6351 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6353 sp = stalloc(sizeof(*sp));
6356 exparg.lastp = &sp->next;
6360 *exparg.lastp = NULL;
6362 *arglist->lastp = exparg.list;
6363 arglist->lastp = exparg.lastp;
6368 * Expand shell variables and backquotes inside a here document.
6371 expandhere(union node *arg, int fd)
6374 expandarg(arg, (struct arglist *)NULL, 0);
6375 full_write(fd, stackblock(), expdest - (char *)stackblock());
6379 * Returns true if the pattern matches the string.
6382 patmatch(char *pattern, const char *string)
6384 return pmatch(preglob(pattern, 0, 0), string);
6388 * See if a pattern matches in a case statement.
6391 casematch(union node *pattern, char *val)
6393 struct stackmark smark;
6396 setstackmark(&smark);
6397 argbackq = pattern->narg.backquote;
6398 STARTSTACKSTR(expdest);
6400 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6401 STACKSTRNUL(expdest);
6402 result = patmatch(stackblock(), val);
6403 popstackmark(&smark);
6408 /* ============ find_command */
6412 int (*builtin)(int, char **);
6413 /* unsigned flags; */
6415 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6416 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6417 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6423 const struct builtincmd *cmd;
6424 struct funcnode *func;
6427 /* values of cmdtype */
6428 #define CMDUNKNOWN -1 /* no entry in table for command */
6429 #define CMDNORMAL 0 /* command is an executable program */
6430 #define CMDFUNCTION 1 /* command is a shell function */
6431 #define CMDBUILTIN 2 /* command is a shell builtin */
6433 /* action to find_command() */
6434 #define DO_ERR 0x01 /* prints errors */
6435 #define DO_ABS 0x02 /* checks absolute paths */
6436 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6437 #define DO_ALTPATH 0x08 /* using alternate path */
6438 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6440 static void find_command(char *, struct cmdentry *, int, const char *);
6443 /* ============ Hashing commands */
6446 * When commands are first encountered, they are entered in a hash table.
6447 * This ensures that a full path search will not have to be done for them
6448 * on each invocation.
6450 * We should investigate converting to a linear search, even though that
6451 * would make the command name "hash" a misnomer.
6454 #define CMDTABLESIZE 31 /* should be prime */
6455 #define ARB 1 /* actual size determined at run time */
6458 struct tblentry *next; /* next entry in hash chain */
6459 union param param; /* definition of builtin function */
6460 short cmdtype; /* index identifying command */
6461 char rehash; /* if set, cd done since entry created */
6462 char cmdname[ARB]; /* name of command */
6465 static struct tblentry *cmdtable[CMDTABLESIZE];
6466 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6469 tryexec(char *cmd, char **argv, char **envp)
6473 #if ENABLE_FEATURE_SH_STANDALONE
6474 if (strchr(cmd, '/') == NULL) {
6475 const struct bb_applet *a;
6477 a = find_applet_by_name(cmd);
6481 run_current_applet_and_exit(argv);
6483 /* re-exec ourselves with the new arguments */
6484 execve(bb_busybox_exec_path, argv, envp);
6485 /* If they called chroot or otherwise made the binary no longer
6486 * executable, fall through */
6494 execve(cmd, argv, envp);
6495 } while (errno == EINTR);
6497 execve(cmd, argv, envp);
6501 } else if (errno == ENOEXEC) {
6505 for (ap = argv; *ap; ap++)
6507 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6509 ap[0] = cmd = (char *)DEFAULT_SHELL;
6512 while ((*ap++ = *argv++))
6520 * Exec a program. Never returns. If you change this routine, you may
6521 * have to change the find_command routine as well.
6523 #define environment() listvars(VEXPORT, VUNSET, 0)
6524 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6526 shellexec(char **argv, const char *path, int idx)
6534 envp = environment();
6535 if (strchr(argv[0], '/')
6536 #if ENABLE_FEATURE_SH_STANDALONE
6537 || find_applet_by_name(argv[0])
6540 tryexec(argv[0], argv, envp);
6544 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6545 if (--idx < 0 && pathopt == NULL) {
6546 tryexec(cmdname, argv, envp);
6547 if (errno != ENOENT && errno != ENOTDIR)
6554 /* Map to POSIX errors */
6566 exitstatus = exerrno;
6567 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6568 argv[0], e, suppressint ));
6569 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6574 printentry(struct tblentry *cmdp)
6580 idx = cmdp->param.index;
6583 name = padvance(&path, cmdp->cmdname);
6585 } while (--idx >= 0);
6586 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6590 * Clear out command entries. The argument specifies the first entry in
6591 * PATH which has changed.
6594 clearcmdentry(int firstchange)
6596 struct tblentry **tblp;
6597 struct tblentry **pp;
6598 struct tblentry *cmdp;
6601 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6603 while ((cmdp = *pp) != NULL) {
6604 if ((cmdp->cmdtype == CMDNORMAL &&
6605 cmdp->param.index >= firstchange)
6606 || (cmdp->cmdtype == CMDBUILTIN &&
6607 builtinloc >= firstchange)
6620 * Locate a command in the command hash table. If "add" is nonzero,
6621 * add the command to the table if it is not already present. The
6622 * variable "lastcmdentry" is set to point to the address of the link
6623 * pointing to the entry, so that delete_cmd_entry can delete the
6626 * Interrupts must be off if called with add != 0.
6628 static struct tblentry **lastcmdentry;
6630 static struct tblentry *
6631 cmdlookup(const char *name, int add)
6633 unsigned int hashval;
6635 struct tblentry *cmdp;
6636 struct tblentry **pp;
6639 hashval = (unsigned char)*p << 4;
6641 hashval += (unsigned char)*p++;
6643 pp = &cmdtable[hashval % CMDTABLESIZE];
6644 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6645 if (strcmp(cmdp->cmdname, name) == 0)
6649 if (add && cmdp == NULL) {
6650 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6651 + strlen(name) + 1);
6653 cmdp->cmdtype = CMDUNKNOWN;
6654 strcpy(cmdp->cmdname, name);
6661 * Delete the command entry returned on the last lookup.
6664 delete_cmd_entry(void)
6666 struct tblentry *cmdp;
6669 cmdp = *lastcmdentry;
6670 *lastcmdentry = cmdp->next;
6671 if (cmdp->cmdtype == CMDFUNCTION)
6672 freefunc(cmdp->param.func);
6678 * Add a new command entry, replacing any existing command entry for
6679 * the same name - except special builtins.
6682 addcmdentry(char *name, struct cmdentry *entry)
6684 struct tblentry *cmdp;
6686 cmdp = cmdlookup(name, 1);
6687 if (cmdp->cmdtype == CMDFUNCTION) {
6688 freefunc(cmdp->param.func);
6690 cmdp->cmdtype = entry->cmdtype;
6691 cmdp->param = entry->u;
6696 hashcmd(int argc, char **argv)
6698 struct tblentry **pp;
6699 struct tblentry *cmdp;
6701 struct cmdentry entry;
6704 while ((c = nextopt("r")) != '\0') {
6708 if (*argptr == NULL) {
6709 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6710 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6711 if (cmdp->cmdtype == CMDNORMAL)
6718 while ((name = *argptr) != NULL) {
6719 cmdp = cmdlookup(name, 0);
6721 && (cmdp->cmdtype == CMDNORMAL
6722 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6724 find_command(name, &entry, DO_ERR, pathval());
6725 if (entry.cmdtype == CMDUNKNOWN)
6733 * Called when a cd is done. Marks all commands so the next time they
6734 * are executed they will be rehashed.
6739 struct tblentry **pp;
6740 struct tblentry *cmdp;
6742 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6743 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6744 if (cmdp->cmdtype == CMDNORMAL || (
6745 cmdp->cmdtype == CMDBUILTIN &&
6746 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6755 * Fix command hash table when PATH changed.
6756 * Called before PATH is changed. The argument is the new value of PATH;
6757 * pathval() still returns the old value at this point.
6758 * Called with interrupts off.
6761 changepath(const char *newval)
6763 const char *old, *new;
6770 firstchange = 9999; /* assume no change */
6776 if ((*old == '\0' && *new == ':')
6777 || (*old == ':' && *new == '\0'))
6779 old = new; /* ignore subsequent differences */
6783 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6790 if (builtinloc < 0 && idx_bltin >= 0)
6791 builtinloc = idx_bltin; /* zap builtins */
6792 if (builtinloc >= 0 && idx_bltin < 0)
6794 clearcmdentry(firstchange);
6795 builtinloc = idx_bltin;
6810 #define TENDBQUOTE 12
6828 /* first char is indicating which tokens mark the end of a list */
6829 static const char *const tokname_array[] = {
6843 #define KWDOFFSET 13
6844 /* the following are keywords */
6866 static char buf[16];
6869 //if (tok < TSEMI) return tokname_array[tok] + 1;
6870 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6875 sprintf(buf + (tok >= TSEMI), "%s%c",
6876 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6880 /* Wrapper around strcmp for qsort/bsearch/... */
6882 pstrcmp(const void *a, const void *b)
6884 return strcmp((char*) a, (*(char**) b) + 1);
6887 static const char *const *
6888 findkwd(const char *s)
6890 return bsearch(s, tokname_array + KWDOFFSET,
6891 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6892 sizeof(tokname_array[0]), pstrcmp);
6896 * Locate and print what a word is...
6899 describe_command(char *command, int describe_command_verbose)
6901 struct cmdentry entry;
6902 struct tblentry *cmdp;
6903 #if ENABLE_ASH_ALIAS
6904 const struct alias *ap;
6906 const char *path = pathval();
6908 if (describe_command_verbose) {
6912 /* First look at the keywords */
6913 if (findkwd(command)) {
6914 out1str(describe_command_verbose ? " is a shell keyword" : command);
6918 #if ENABLE_ASH_ALIAS
6919 /* Then look at the aliases */
6920 ap = lookupalias(command, 0);
6922 if (!describe_command_verbose) {
6927 out1fmt(" is an alias for %s", ap->val);
6931 /* Then check if it is a tracked alias */
6932 cmdp = cmdlookup(command, 0);
6934 entry.cmdtype = cmdp->cmdtype;
6935 entry.u = cmdp->param;
6937 /* Finally use brute force */
6938 find_command(command, &entry, DO_ABS, path);
6941 switch (entry.cmdtype) {
6943 int j = entry.u.index;
6949 p = padvance(&path, command);
6953 if (describe_command_verbose) {
6955 (cmdp ? " a tracked alias for" : nullstr), p
6964 if (describe_command_verbose) {
6965 out1str(" is a shell function");
6972 if (describe_command_verbose) {
6973 out1fmt(" is a %sshell builtin",
6974 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
6975 "special " : nullstr
6983 if (describe_command_verbose) {
6984 out1str(": not found\n");
6989 outstr("\n", stdout);
6994 typecmd(int argc, char **argv)
7000 /* type -p ... ? (we don't bother checking for 'p') */
7001 if (argv[1] && argv[1][0] == '-') {
7006 err |= describe_command(argv[i++], verbose);
7011 #if ENABLE_ASH_CMDCMD
7013 commandcmd(int argc, char **argv)
7021 while ((c = nextopt("pvV")) != '\0')
7023 verify |= VERIFY_VERBOSE;
7025 verify |= VERIFY_BRIEF;
7031 return describe_command(*argptr, verify - VERIFY_BRIEF);
7038 /* ============ eval.c */
7040 static int funcblocksize; /* size of structures in function */
7041 static int funcstringsize; /* size of strings in node */
7042 static void *funcblock; /* block to allocate function from */
7043 static char *funcstring; /* block to allocate strings from */
7045 /* flags in argument to evaltree */
7046 #define EV_EXIT 01 /* exit after evaluating tree */
7047 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7048 #define EV_BACKCMD 04 /* command executing within back quotes */
7050 static const short nodesize[26] = {
7051 SHELL_ALIGN(sizeof(struct ncmd)),
7052 SHELL_ALIGN(sizeof(struct npipe)),
7053 SHELL_ALIGN(sizeof(struct nredir)),
7054 SHELL_ALIGN(sizeof(struct nredir)),
7055 SHELL_ALIGN(sizeof(struct nredir)),
7056 SHELL_ALIGN(sizeof(struct nbinary)),
7057 SHELL_ALIGN(sizeof(struct nbinary)),
7058 SHELL_ALIGN(sizeof(struct nbinary)),
7059 SHELL_ALIGN(sizeof(struct nif)),
7060 SHELL_ALIGN(sizeof(struct nbinary)),
7061 SHELL_ALIGN(sizeof(struct nbinary)),
7062 SHELL_ALIGN(sizeof(struct nfor)),
7063 SHELL_ALIGN(sizeof(struct ncase)),
7064 SHELL_ALIGN(sizeof(struct nclist)),
7065 SHELL_ALIGN(sizeof(struct narg)),
7066 SHELL_ALIGN(sizeof(struct narg)),
7067 SHELL_ALIGN(sizeof(struct nfile)),
7068 SHELL_ALIGN(sizeof(struct nfile)),
7069 SHELL_ALIGN(sizeof(struct nfile)),
7070 SHELL_ALIGN(sizeof(struct nfile)),
7071 SHELL_ALIGN(sizeof(struct nfile)),
7072 SHELL_ALIGN(sizeof(struct ndup)),
7073 SHELL_ALIGN(sizeof(struct ndup)),
7074 SHELL_ALIGN(sizeof(struct nhere)),
7075 SHELL_ALIGN(sizeof(struct nhere)),
7076 SHELL_ALIGN(sizeof(struct nnot)),
7079 static void calcsize(union node *n);
7082 sizenodelist(struct nodelist *lp)
7085 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7092 calcsize(union node *n)
7096 funcblocksize += nodesize[n->type];
7099 calcsize(n->ncmd.redirect);
7100 calcsize(n->ncmd.args);
7101 calcsize(n->ncmd.assign);
7104 sizenodelist(n->npipe.cmdlist);
7109 calcsize(n->nredir.redirect);
7110 calcsize(n->nredir.n);
7117 calcsize(n->nbinary.ch2);
7118 calcsize(n->nbinary.ch1);
7121 calcsize(n->nif.elsepart);
7122 calcsize(n->nif.ifpart);
7123 calcsize(n->nif.test);
7126 funcstringsize += strlen(n->nfor.var) + 1;
7127 calcsize(n->nfor.body);
7128 calcsize(n->nfor.args);
7131 calcsize(n->ncase.cases);
7132 calcsize(n->ncase.expr);
7135 calcsize(n->nclist.body);
7136 calcsize(n->nclist.pattern);
7137 calcsize(n->nclist.next);
7141 sizenodelist(n->narg.backquote);
7142 funcstringsize += strlen(n->narg.text) + 1;
7143 calcsize(n->narg.next);
7150 calcsize(n->nfile.fname);
7151 calcsize(n->nfile.next);
7155 calcsize(n->ndup.vname);
7156 calcsize(n->ndup.next);
7160 calcsize(n->nhere.doc);
7161 calcsize(n->nhere.next);
7164 calcsize(n->nnot.com);
7170 nodeckstrdup(char *s)
7172 char *rtn = funcstring;
7174 strcpy(funcstring, s);
7175 funcstring += strlen(s) + 1;
7179 static union node *copynode(union node *);
7181 static struct nodelist *
7182 copynodelist(struct nodelist *lp)
7184 struct nodelist *start;
7185 struct nodelist **lpp;
7190 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7191 (*lpp)->n = copynode(lp->n);
7193 lpp = &(*lpp)->next;
7200 copynode(union node *n)
7207 funcblock = (char *) funcblock + nodesize[n->type];
7211 new->ncmd.redirect = copynode(n->ncmd.redirect);
7212 new->ncmd.args = copynode(n->ncmd.args);
7213 new->ncmd.assign = copynode(n->ncmd.assign);
7216 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7217 new->npipe.backgnd = n->npipe.backgnd;
7222 new->nredir.redirect = copynode(n->nredir.redirect);
7223 new->nredir.n = copynode(n->nredir.n);
7230 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7231 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7234 new->nif.elsepart = copynode(n->nif.elsepart);
7235 new->nif.ifpart = copynode(n->nif.ifpart);
7236 new->nif.test = copynode(n->nif.test);
7239 new->nfor.var = nodeckstrdup(n->nfor.var);
7240 new->nfor.body = copynode(n->nfor.body);
7241 new->nfor.args = copynode(n->nfor.args);
7244 new->ncase.cases = copynode(n->ncase.cases);
7245 new->ncase.expr = copynode(n->ncase.expr);
7248 new->nclist.body = copynode(n->nclist.body);
7249 new->nclist.pattern = copynode(n->nclist.pattern);
7250 new->nclist.next = copynode(n->nclist.next);
7254 new->narg.backquote = copynodelist(n->narg.backquote);
7255 new->narg.text = nodeckstrdup(n->narg.text);
7256 new->narg.next = copynode(n->narg.next);
7263 new->nfile.fname = copynode(n->nfile.fname);
7264 new->nfile.fd = n->nfile.fd;
7265 new->nfile.next = copynode(n->nfile.next);
7269 new->ndup.vname = copynode(n->ndup.vname);
7270 new->ndup.dupfd = n->ndup.dupfd;
7271 new->ndup.fd = n->ndup.fd;
7272 new->ndup.next = copynode(n->ndup.next);
7276 new->nhere.doc = copynode(n->nhere.doc);
7277 new->nhere.fd = n->nhere.fd;
7278 new->nhere.next = copynode(n->nhere.next);
7281 new->nnot.com = copynode(n->nnot.com);
7284 new->type = n->type;
7289 * Make a copy of a parse tree.
7291 static struct funcnode *
7292 copyfunc(union node *n)
7297 funcblocksize = offsetof(struct funcnode, n);
7300 blocksize = funcblocksize;
7301 f = ckmalloc(blocksize + funcstringsize);
7302 funcblock = (char *) f + offsetof(struct funcnode, n);
7303 funcstring = (char *) f + blocksize;
7310 * Define a shell function.
7313 defun(char *name, union node *func)
7315 struct cmdentry entry;
7318 entry.cmdtype = CMDFUNCTION;
7319 entry.u.func = copyfunc(func);
7320 addcmdentry(name, &entry);
7324 static int evalskip; /* set if we are skipping commands */
7325 /* reasons for skipping commands (see comment on breakcmd routine) */
7326 #define SKIPBREAK (1 << 0)
7327 #define SKIPCONT (1 << 1)
7328 #define SKIPFUNC (1 << 2)
7329 #define SKIPFILE (1 << 3)
7330 #define SKIPEVAL (1 << 4)
7331 static int skipcount; /* number of levels to skip */
7332 static int funcnest; /* depth of function calls */
7334 /* forward decl way out to parsing code - dotrap needs it */
7335 static int evalstring(char *s, int mask);
7338 * Called to execute a trap. Perhaps we should avoid entering new trap
7339 * handlers while we are executing a trap handler.
7350 savestatus = exitstatus;
7354 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7362 skip = evalstring(p, SKIPEVAL);
7363 exitstatus = savestatus;
7371 /* forward declarations - evaluation is fairly recursive business... */
7372 static void evalloop(union node *, int);
7373 static void evalfor(union node *, int);
7374 static void evalcase(union node *, int);
7375 static void evalsubshell(union node *, int);
7376 static void expredir(union node *);
7377 static void evalpipe(union node *, int);
7378 static void evalcommand(union node *, int);
7379 static int evalbltin(const struct builtincmd *, int, char **);
7380 static void prehash(union node *);
7383 * Evaluate a parse tree. The value is left in the global variable
7387 evaltree(union node *n, int flags)
7390 void (*evalfn)(union node *, int);
7394 TRACE(("evaltree(NULL) called\n"));
7397 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7398 getpid(), n, n->type, flags));
7402 out1fmt("Node type = %d\n", n->type);
7407 evaltree(n->nnot.com, EV_TESTED);
7408 status = !exitstatus;
7411 expredir(n->nredir.redirect);
7412 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7414 evaltree(n->nredir.n, flags & EV_TESTED);
7415 status = exitstatus;
7420 evalfn = evalcommand;
7422 if (eflag && !(flags & EV_TESTED))
7434 evalfn = evalsubshell;
7446 #error NAND + 1 != NOR
7448 #if NOR + 1 != NSEMI
7449 #error NOR + 1 != NSEMI
7451 isor = n->type - NAND;
7454 (flags | ((isor >> 1) - 1)) & EV_TESTED
7456 if (!exitstatus == isor)
7468 evaltree(n->nif.test, EV_TESTED);
7471 if (exitstatus == 0) {
7474 } else if (n->nif.elsepart) {
7475 n = n->nif.elsepart;
7480 defun(n->narg.text, n->narg.next);
7484 exitstatus = status;
7488 if ((checkexit & exitstatus))
7489 evalskip |= SKIPEVAL;
7490 else if (pendingsig && dotrap())
7493 if (flags & EV_EXIT) {
7495 raise_exception(EXEXIT);
7499 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7502 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7504 static int loopnest; /* current loop nesting level */
7507 evalloop(union node *n, int flags)
7517 evaltree(n->nbinary.ch1, EV_TESTED);
7520 if (evalskip == SKIPCONT && --skipcount <= 0) {
7524 if (evalskip == SKIPBREAK && --skipcount <= 0)
7529 if (n->type != NWHILE)
7533 evaltree(n->nbinary.ch2, flags);
7534 status = exitstatus;
7539 exitstatus = status;
7543 evalfor(union node *n, int flags)
7545 struct arglist arglist;
7548 struct stackmark smark;
7550 setstackmark(&smark);
7551 arglist.lastp = &arglist.list;
7552 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7553 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7558 *arglist.lastp = NULL;
7563 for (sp = arglist.list; sp; sp = sp->next) {
7564 setvar(n->nfor.var, sp->text, 0);
7565 evaltree(n->nfor.body, flags);
7567 if (evalskip == SKIPCONT && --skipcount <= 0) {
7571 if (evalskip == SKIPBREAK && --skipcount <= 0)
7578 popstackmark(&smark);
7582 evalcase(union node *n, int flags)
7586 struct arglist arglist;
7587 struct stackmark smark;
7589 setstackmark(&smark);
7590 arglist.lastp = &arglist.list;
7591 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7593 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7594 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7595 if (casematch(patp, arglist.list->text)) {
7596 if (evalskip == 0) {
7597 evaltree(cp->nclist.body, flags);
7604 popstackmark(&smark);
7608 * Kick off a subshell to evaluate a tree.
7611 evalsubshell(union node *n, int flags)
7614 int backgnd = (n->type == NBACKGND);
7617 expredir(n->nredir.redirect);
7618 if (!backgnd && flags & EV_EXIT && !trap[0])
7622 if (forkshell(jp, n, backgnd) == 0) {
7626 flags &=~ EV_TESTED;
7628 redirect(n->nredir.redirect, 0);
7629 evaltreenr(n->nredir.n, flags);
7634 status = waitforjob(jp);
7635 exitstatus = status;
7640 * Compute the names of the files in a redirection list.
7642 static void fixredir(union node *, const char *, int);
7644 expredir(union node *n)
7648 for (redir = n; redir; redir = redir->nfile.next) {
7651 memset(&fn, 0, sizeof(fn));
7652 fn.lastp = &fn.list;
7653 switch (redir->type) {
7659 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7660 redir->nfile.expfname = fn.list->text;
7664 if (redir->ndup.vname) {
7665 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7666 if (fn.list == NULL)
7667 ash_msg_and_raise_error("redir error");
7668 fixredir(redir, fn.list->text, 1);
7676 * Evaluate a pipeline. All the processes in the pipeline are children
7677 * of the process creating the pipeline. (This differs from some versions
7678 * of the shell, which make the last process in a pipeline the parent
7682 evalpipe(union node *n, int flags)
7685 struct nodelist *lp;
7690 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7692 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7696 jp = makejob(n, pipelen);
7698 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7702 if (pipe(pip) < 0) {
7704 ash_msg_and_raise_error("pipe call failed");
7707 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7720 evaltreenr(lp->n, flags);
7728 if (n->npipe.backgnd == 0) {
7729 exitstatus = waitforjob(jp);
7730 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7736 * Controls whether the shell is interactive or not.
7739 setinteractive(int on)
7741 static int is_interactive;
7743 if (++on == is_interactive)
7745 is_interactive = on;
7749 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7750 if (is_interactive > 1) {
7751 /* Looks like they want an interactive shell */
7752 static smallint did_banner;
7757 "%s built-in shell (ash)\n"
7758 "Enter 'help' for a list of built-in commands."
7767 #if ENABLE_FEATURE_EDITING_VI
7768 #define setvimode(on) do { \
7769 if (on) line_input_state->flags |= VI_MODE; \
7770 else line_input_state->flags &= ~VI_MODE; \
7773 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7782 setinteractive(iflag);
7787 static struct localvar *localvars;
7790 * Called after a function returns.
7791 * Interrupts must be off.
7796 struct localvar *lvp;
7799 while ((lvp = localvars) != NULL) {
7800 localvars = lvp->next;
7802 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7803 if (vp == NULL) { /* $- saved */
7804 memcpy(optlist, lvp->text, sizeof(optlist));
7805 free((char*)lvp->text);
7807 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7811 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7812 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7813 free((char*)vp->text);
7814 vp->flags = lvp->flags;
7815 vp->text = lvp->text;
7822 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7824 volatile struct shparam saveparam;
7825 struct localvar *volatile savelocalvars;
7826 struct jmploc *volatile savehandler;
7827 struct jmploc jmploc;
7830 saveparam = shellparam;
7831 savelocalvars = localvars;
7832 e = setjmp(jmploc.loc);
7837 savehandler = exception_handler;
7838 exception_handler = &jmploc;
7840 shellparam.malloc = 0;
7844 shellparam.nparam = argc - 1;
7845 shellparam.p = argv + 1;
7846 #if ENABLE_ASH_GETOPTS
7847 shellparam.optind = 1;
7848 shellparam.optoff = -1;
7850 evaltree(&func->n, flags & EV_TESTED);
7856 localvars = savelocalvars;
7857 freeparam(&shellparam);
7858 shellparam = saveparam;
7859 exception_handler = savehandler;
7861 evalskip &= ~SKIPFUNC;
7865 #if ENABLE_ASH_CMDCMD
7867 parse_command_args(char **argv, const char **path)
7880 if (c == '-' && !*cp) {
7887 *path = bb_default_path;
7890 /* run 'typecmd' for other options */
7901 * Make a variable a local variable. When a variable is made local, it's
7902 * value and flags are saved in a localvar structure. The saved values
7903 * will be restored when the shell function returns. We handle the name
7904 * "-" as a special case.
7909 struct localvar *lvp;
7914 lvp = ckmalloc(sizeof(struct localvar));
7915 if (LONE_DASH(name)) {
7917 p = ckmalloc(sizeof(optlist));
7918 lvp->text = memcpy(p, optlist, sizeof(optlist));
7923 vpp = hashvar(name);
7924 vp = *findvar(vpp, name);
7925 eq = strchr(name, '=');
7928 setvareq(name, VSTRFIXED);
7930 setvar(name, NULL, VSTRFIXED);
7931 vp = *vpp; /* the new variable */
7932 lvp->flags = VUNSET;
7934 lvp->text = vp->text;
7935 lvp->flags = vp->flags;
7936 vp->flags |= VSTRFIXED|VTEXTFIXED;
7942 lvp->next = localvars;
7948 * The "local" command.
7951 localcmd(int argc, char **argv)
7956 while ((name = *argv++) != NULL) {
7963 falsecmd(int argc, char **argv)
7969 truecmd(int argc, char **argv)
7975 execcmd(int argc, char **argv)
7978 iflag = 0; /* exit on error */
7981 shellexec(argv + 1, pathval(), 0);
7987 * The return command.
7990 returncmd(int argc, char **argv)
7993 * If called outside a function, do what ksh does;
7994 * skip the rest of the file.
7996 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
7997 return argv[1] ? number(argv[1]) : exitstatus;
8000 /* Forward declarations for builtintab[] */
8001 static int breakcmd(int, char **);
8002 static int dotcmd(int, char **);
8003 static int evalcmd(int, char **);
8004 #if ENABLE_ASH_BUILTIN_ECHO
8005 static int echocmd(int, char **);
8007 #if ENABLE_ASH_BUILTIN_TEST
8008 static int testcmd(int, char **);
8010 static int exitcmd(int, char **);
8011 static int exportcmd(int, char **);
8012 #if ENABLE_ASH_GETOPTS
8013 static int getoptscmd(int, char **);
8015 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8016 static int helpcmd(int argc, char **argv);
8018 #if ENABLE_ASH_MATH_SUPPORT
8019 static int letcmd(int, char **);
8021 static int readcmd(int, char **);
8022 static int setcmd(int, char **);
8023 static int shiftcmd(int, char **);
8024 static int timescmd(int, char **);
8025 static int trapcmd(int, char **);
8026 static int umaskcmd(int, char **);
8027 static int unsetcmd(int, char **);
8028 static int ulimitcmd(int, char **);
8030 #define BUILTIN_NOSPEC "0"
8031 #define BUILTIN_SPECIAL "1"
8032 #define BUILTIN_REGULAR "2"
8033 #define BUILTIN_SPEC_REG "3"
8034 #define BUILTIN_ASSIGN "4"
8035 #define BUILTIN_SPEC_ASSG "5"
8036 #define BUILTIN_REG_ASSG "6"
8037 #define BUILTIN_SPEC_REG_ASSG "7"
8039 /* make sure to keep these in proper order since it is searched via bsearch() */
8040 static const struct builtincmd builtintab[] = {
8041 { BUILTIN_SPEC_REG ".", dotcmd },
8042 { BUILTIN_SPEC_REG ":", truecmd },
8043 #if ENABLE_ASH_BUILTIN_TEST
8044 { BUILTIN_REGULAR "[", testcmd },
8045 { BUILTIN_REGULAR "[[", testcmd },
8047 #if ENABLE_ASH_ALIAS
8048 { BUILTIN_REG_ASSG "alias", aliascmd },
8051 { BUILTIN_REGULAR "bg", fg_bgcmd },
8053 { BUILTIN_SPEC_REG "break", breakcmd },
8054 { BUILTIN_REGULAR "cd", cdcmd },
8055 { BUILTIN_NOSPEC "chdir", cdcmd },
8056 #if ENABLE_ASH_CMDCMD
8057 { BUILTIN_REGULAR "command", commandcmd },
8059 { BUILTIN_SPEC_REG "continue", breakcmd },
8060 #if ENABLE_ASH_BUILTIN_ECHO
8061 { BUILTIN_REGULAR "echo", echocmd },
8063 { BUILTIN_SPEC_REG "eval", evalcmd },
8064 { BUILTIN_SPEC_REG "exec", execcmd },
8065 { BUILTIN_SPEC_REG "exit", exitcmd },
8066 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8067 { BUILTIN_REGULAR "false", falsecmd },
8069 { BUILTIN_REGULAR "fg", fg_bgcmd },
8071 #if ENABLE_ASH_GETOPTS
8072 { BUILTIN_REGULAR "getopts", getoptscmd },
8074 { BUILTIN_NOSPEC "hash", hashcmd },
8075 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8076 { BUILTIN_NOSPEC "help", helpcmd },
8079 { BUILTIN_REGULAR "jobs", jobscmd },
8080 { BUILTIN_REGULAR "kill", killcmd },
8082 #if ENABLE_ASH_MATH_SUPPORT
8083 { BUILTIN_NOSPEC "let", letcmd },
8085 { BUILTIN_ASSIGN "local", localcmd },
8086 { BUILTIN_NOSPEC "pwd", pwdcmd },
8087 { BUILTIN_REGULAR "read", readcmd },
8088 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8089 { BUILTIN_SPEC_REG "return", returncmd },
8090 { BUILTIN_SPEC_REG "set", setcmd },
8091 { BUILTIN_SPEC_REG "shift", shiftcmd },
8092 { BUILTIN_SPEC_REG "source", dotcmd },
8093 #if ENABLE_ASH_BUILTIN_TEST
8094 { BUILTIN_REGULAR "test", testcmd },
8096 { BUILTIN_SPEC_REG "times", timescmd },
8097 { BUILTIN_SPEC_REG "trap", trapcmd },
8098 { BUILTIN_REGULAR "true", truecmd },
8099 { BUILTIN_NOSPEC "type", typecmd },
8100 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8101 { BUILTIN_REGULAR "umask", umaskcmd },
8102 #if ENABLE_ASH_ALIAS
8103 { BUILTIN_REGULAR "unalias", unaliascmd },
8105 { BUILTIN_SPEC_REG "unset", unsetcmd },
8106 { BUILTIN_REGULAR "wait", waitcmd },
8110 #define COMMANDCMD (builtintab + 5 + \
8111 2 * ENABLE_ASH_BUILTIN_TEST + \
8112 ENABLE_ASH_ALIAS + \
8113 ENABLE_ASH_JOB_CONTROL)
8114 #define EXECCMD (builtintab + 7 + \
8115 2 * ENABLE_ASH_BUILTIN_TEST + \
8116 ENABLE_ASH_ALIAS + \
8117 ENABLE_ASH_JOB_CONTROL + \
8118 ENABLE_ASH_CMDCMD + \
8119 ENABLE_ASH_BUILTIN_ECHO)
8122 * Search the table of builtin commands.
8124 static struct builtincmd *
8125 find_builtin(const char *name)
8127 struct builtincmd *bp;
8130 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8137 * Execute a simple command.
8139 static int back_exitstatus; /* exit status of backquoted command */
8141 isassignment(const char *p)
8143 const char *q = endofname(p);
8149 bltincmd(int argc, char **argv)
8151 /* Preserve exitstatus of a previous possible redirection
8152 * as POSIX mandates */
8153 return back_exitstatus;
8156 evalcommand(union node *cmd, int flags)
8158 static const struct builtincmd bltin = {
8161 struct stackmark smark;
8163 struct arglist arglist;
8164 struct arglist varlist;
8167 const struct strlist *sp;
8168 struct cmdentry cmdentry;
8176 struct builtincmd *bcmd;
8177 int pseudovarflag = 0;
8179 /* First expand the arguments. */
8180 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8181 setstackmark(&smark);
8182 back_exitstatus = 0;
8184 cmdentry.cmdtype = CMDBUILTIN;
8185 cmdentry.u.cmd = &bltin;
8186 varlist.lastp = &varlist.list;
8187 *varlist.lastp = NULL;
8188 arglist.lastp = &arglist.list;
8189 *arglist.lastp = NULL;
8192 if (cmd->ncmd.args) {
8193 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8194 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8197 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8198 struct strlist **spp;
8200 spp = arglist.lastp;
8201 if (pseudovarflag && isassignment(argp->narg.text))
8202 expandarg(argp, &arglist, EXP_VARTILDE);
8204 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8206 for (sp = *spp; sp; sp = sp->next)
8210 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8211 for (sp = arglist.list; sp; sp = sp->next) {
8212 TRACE(("evalcommand arg: %s\n", sp->text));
8213 *nargv++ = sp->text;
8218 if (iflag && funcnest == 0 && argc > 0)
8219 lastarg = nargv[-1];
8222 expredir(cmd->ncmd.redirect);
8223 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8226 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8227 struct strlist **spp;
8230 spp = varlist.lastp;
8231 expandarg(argp, &varlist, EXP_VARTILDE);
8234 * Modify the command lookup path, if a PATH= assignment
8238 if (varequal(p, path))
8242 /* Print the command if xflag is set. */
8245 const char *p = " %s";
8248 dprintf(preverrout_fd, p, expandstr(ps4val()));
8251 for (n = 0; n < 2; n++) {
8253 dprintf(preverrout_fd, p, sp->text);
8261 full_write(preverrout_fd, "\n", 1);
8267 /* Now locate the command. */
8269 const char *oldpath;
8270 int cmd_flag = DO_ERR;
8275 find_command(argv[0], &cmdentry, cmd_flag, path);
8276 if (cmdentry.cmdtype == CMDUNKNOWN) {
8282 /* implement bltin and command here */
8283 if (cmdentry.cmdtype != CMDBUILTIN)
8286 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8287 if (cmdentry.u.cmd == EXECCMD)
8289 #if ENABLE_ASH_CMDCMD
8290 if (cmdentry.u.cmd == COMMANDCMD) {
8292 nargv = parse_command_args(argv, &path);
8295 argc -= nargv - argv;
8297 cmd_flag |= DO_NOFUNC;
8305 /* We have a redirection error. */
8307 raise_exception(EXERROR);
8309 exitstatus = status;
8313 /* Execute the command. */
8314 switch (cmdentry.cmdtype) {
8316 /* Fork off a child process if necessary. */
8317 if (!(flags & EV_EXIT) || trap[0]) {
8319 jp = makejob(cmd, 1);
8320 if (forkshell(jp, cmd, FORK_FG) != 0) {
8321 exitstatus = waitforjob(jp);
8327 listsetvar(varlist.list, VEXPORT|VSTACK);
8328 shellexec(argv, path, cmdentry.u.index);
8332 cmdenviron = varlist.list;
8334 struct strlist *list = cmdenviron;
8336 if (spclbltin > 0 || argc == 0) {
8338 if (cmd_is_exec && argc > 1)
8341 listsetvar(list, i);
8343 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8358 exit_status = j + 128;
8359 exitstatus = exit_status;
8361 if (i == EXINT || spclbltin > 0) {
8363 longjmp(exception_handler->loc, 1);
8370 listsetvar(varlist.list, 0);
8371 if (evalfun(cmdentry.u.func, argc, argv, flags))
8377 popredir(cmd_is_exec);
8379 /* dsl: I think this is intended to be used to support
8380 * '_' in 'vi' command mode during line editing...
8381 * However I implemented that within libedit itself.
8383 setvar("_", lastarg, 0);
8384 popstackmark(&smark);
8388 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8390 char *volatile savecmdname;
8391 struct jmploc *volatile savehandler;
8392 struct jmploc jmploc;
8395 savecmdname = commandname;
8396 i = setjmp(jmploc.loc);
8399 savehandler = exception_handler;
8400 exception_handler = &jmploc;
8401 commandname = argv[0];
8403 optptr = NULL; /* initialize nextopt */
8404 exitstatus = (*cmd->builtin)(argc, argv);
8405 flush_stdout_stderr();
8407 exitstatus |= ferror(stdout);
8409 commandname = savecmdname;
8411 exception_handler = savehandler;
8417 goodname(const char *p)
8419 return !*endofname(p);
8424 * Search for a command. This is called before we fork so that the
8425 * location of the command will be available in the parent as well as
8426 * the child. The check for "goodname" is an overly conservative
8427 * check that the name will not be subject to expansion.
8430 prehash(union node *n)
8432 struct cmdentry entry;
8434 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8435 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8439 /* ============ Builtin commands
8441 * Builtin commands whose functions are closely tied to evaluation
8442 * are implemented here.
8446 * Handle break and continue commands. Break, continue, and return are
8447 * all handled by setting the evalskip flag. The evaluation routines
8448 * above all check this flag, and if it is set they start skipping
8449 * commands rather than executing them. The variable skipcount is
8450 * the number of loops to break/continue, or the number of function
8451 * levels to return. (The latter is always 1.) It should probably
8452 * be an error to break out of more loops than exist, but it isn't
8453 * in the standard shell so we don't make it one here.
8456 breakcmd(int argc, char **argv)
8458 int n = argc > 1 ? number(argv[1]) : 1;
8461 ash_msg_and_raise_error(illnum, argv[1]);
8465 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8472 /* ============ input.c
8474 * This implements the input routines used by the parser.
8477 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8480 INPUT_PUSH_FILE = 1,
8481 INPUT_NOFILE_OK = 2,
8484 static int plinno = 1; /* input line number */
8485 /* number of characters left in input buffer */
8486 static int parsenleft; /* copy of parsefile->nleft */
8487 static int parselleft; /* copy of parsefile->lleft */
8488 /* next character in input buffer */
8489 static char *parsenextc; /* copy of parsefile->nextc */
8491 static int checkkwd;
8492 /* values of checkkwd variable */
8493 #define CHKALIAS 0x1
8500 struct strpush *sp = parsefile->strpush;
8503 #if ENABLE_ASH_ALIAS
8505 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8506 checkkwd |= CHKALIAS;
8508 if (sp->string != sp->ap->val) {
8511 sp->ap->flag &= ~ALIASINUSE;
8512 if (sp->ap->flag & ALIASDEAD) {
8513 unalias(sp->ap->name);
8517 parsenextc = sp->prevstring;
8518 parsenleft = sp->prevnleft;
8519 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8520 parsefile->strpush = sp->prev;
8521 if (sp != &(parsefile->basestrpush))
8530 char *buf = parsefile->buf;
8534 #if ENABLE_FEATURE_EDITING
8535 if (!iflag || parsefile->fd)
8536 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8538 #if ENABLE_FEATURE_TAB_COMPLETION
8539 line_input_state->path_lookup = pathval();
8541 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8543 /* Ctrl+C pressed */
8552 if (nr < 0 && errno == 0) {
8553 /* Ctrl+D presend */
8558 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8562 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8563 int flags = fcntl(0, F_GETFL);
8564 if (flags >= 0 && flags & O_NONBLOCK) {
8565 flags &=~ O_NONBLOCK;
8566 if (fcntl(0, F_SETFL, flags) >= 0) {
8567 out2str("sh: turning off NDELAY mode\n");
8577 * Refill the input buffer and return the next input character:
8579 * 1) If a string was pushed back on the input, pop it;
8580 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8581 * from a string so we can't refill the buffer, return EOF.
8582 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8583 * 4) Process input up to the next newline, deleting nul characters.
8592 while (parsefile->strpush) {
8593 #if ENABLE_ASH_ALIAS
8594 if (parsenleft == -1 && parsefile->strpush->ap &&
8595 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8600 if (--parsenleft >= 0)
8601 return signed_char2int(*parsenextc++);
8603 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8605 flush_stdout_stderr();
8612 parselleft = parsenleft = EOF_NLEFT;
8619 /* delete nul characters */
8627 memmove(q, q + 1, more);
8631 parsenleft = q - parsenextc - 1;
8637 parsenleft = q - parsenextc - 1;
8649 out2str(parsenextc);
8654 return signed_char2int(*parsenextc++);
8657 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8661 return pgetc_as_macro();
8664 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8665 #define pgetc_macro() pgetc()
8667 #define pgetc_macro() pgetc_as_macro()
8671 * Same as pgetc(), but ignores PEOA.
8673 #if ENABLE_ASH_ALIAS
8681 } while (c == PEOA);
8688 return pgetc_macro();
8693 * Read a line from the script.
8696 pfgets(char *line, int len)
8702 while (--nleft > 0) {
8718 * Undo the last call to pgetc. Only one character may be pushed back.
8719 * PEOF may be pushed back.
8729 * Push a string back onto the input at this current parsefile level.
8730 * We handle aliases this way.
8733 pushstring(char *s, void *ap)
8740 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8741 if (parsefile->strpush) {
8742 sp = ckmalloc(sizeof(struct strpush));
8743 sp->prev = parsefile->strpush;
8744 parsefile->strpush = sp;
8746 sp = parsefile->strpush = &(parsefile->basestrpush);
8747 sp->prevstring = parsenextc;
8748 sp->prevnleft = parsenleft;
8749 #if ENABLE_ASH_ALIAS
8750 sp->ap = (struct alias *)ap;
8752 ((struct alias *)ap)->flag |= ALIASINUSE;
8762 * To handle the "." command, a stack of input files is used. Pushfile
8763 * adds a new entry to the stack and popfile restores the previous level.
8768 struct parsefile *pf;
8770 parsefile->nleft = parsenleft;
8771 parsefile->lleft = parselleft;
8772 parsefile->nextc = parsenextc;
8773 parsefile->linno = plinno;
8774 pf = ckmalloc(sizeof(*pf));
8775 pf->prev = parsefile;
8778 pf->basestrpush.prev = NULL;
8785 struct parsefile *pf = parsefile;
8794 parsefile = pf->prev;
8796 parsenleft = parsefile->nleft;
8797 parselleft = parsefile->lleft;
8798 parsenextc = parsefile->nextc;
8799 plinno = parsefile->linno;
8804 * Return to top level.
8809 while (parsefile != &basepf)
8814 * Close the file(s) that the shell is reading commands from. Called
8815 * after a fork is done.
8821 if (parsefile->fd > 0) {
8822 close(parsefile->fd);
8828 * Like setinputfile, but takes an open file descriptor. Call this with
8832 setinputfd(int fd, int push)
8834 fcntl(fd, F_SETFD, FD_CLOEXEC);
8840 if (parsefile->buf == NULL)
8841 parsefile->buf = ckmalloc(IBUFSIZ);
8842 parselleft = parsenleft = 0;
8847 * Set the input to take input from a file. If push is set, push the
8848 * old input onto the stack first.
8851 setinputfile(const char *fname, int flags)
8857 fd = open(fname, O_RDONLY);
8859 if (flags & INPUT_NOFILE_OK)
8861 ash_msg_and_raise_error("can't open %s", fname);
8864 fd2 = copyfd(fd, 10);
8867 ash_msg_and_raise_error("out of file descriptors");
8870 setinputfd(fd, flags & INPUT_PUSH_FILE);
8877 * Like setinputfile, but takes input from a string.
8880 setinputstring(char *string)
8884 parsenextc = string;
8885 parsenleft = strlen(string);
8886 parsefile->buf = NULL;
8892 /* ============ mail.c
8894 * Routines to check for mail.
8899 #define MAXMBOXES 10
8901 /* times of mailboxes */
8902 static time_t mailtime[MAXMBOXES];
8903 /* Set if MAIL or MAILPATH is changed. */
8904 static smallint mail_var_path_changed;
8907 * Print appropriate message(s) if mail has arrived.
8908 * If mail_var_path_changed is set,
8909 * then the value of MAIL has mail_var_path_changed,
8910 * so we just update the values.
8919 struct stackmark smark;
8922 setstackmark(&smark);
8923 mpath = mpathset() ? mpathval() : mailval();
8924 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8925 p = padvance(&mpath, nullstr);
8930 for (q = p; *q; q++);
8935 q[-1] = '\0'; /* delete trailing '/' */
8936 if (stat(p, &statb) < 0) {
8940 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
8943 pathopt ? pathopt : "you have mail"
8946 *mtp = statb.st_mtime;
8948 mail_var_path_changed = 0;
8949 popstackmark(&smark);
8953 changemail(const char *val)
8955 mail_var_path_changed = 1;
8958 #endif /* ASH_MAIL */
8961 /* ============ ??? */
8964 * Set the shell parameters.
8967 setparam(char **argv)
8973 for (nparam = 0; argv[nparam]; nparam++);
8974 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
8976 *ap++ = ckstrdup(*argv++);
8979 freeparam(&shellparam);
8980 shellparam.malloc = 1;
8981 shellparam.nparam = nparam;
8982 shellparam.p = newparam;
8983 #if ENABLE_ASH_GETOPTS
8984 shellparam.optind = 1;
8985 shellparam.optoff = -1;
8990 * Process shell options. The global variable argptr contains a pointer
8991 * to the argument list; we advance it past the options.
8994 minus_o(char *name, int val)
8999 for (i = 0; i < NOPTS; i++) {
9000 if (strcmp(name, optnames(i)) == 0) {
9005 ash_msg_and_raise_error("illegal option -o %s", name);
9007 out1str("Current option settings\n");
9008 for (i = 0; i < NOPTS; i++)
9009 out1fmt("%-16s%s\n", optnames(i),
9010 optlist[i] ? "on" : "off");
9013 setoption(int flag, int val)
9017 for (i = 0; i < NOPTS; i++) {
9018 if (optletters(i) == flag) {
9023 ash_msg_and_raise_error("illegal option -%c", flag);
9027 options(int cmdline)
9035 while ((p = *argptr) != NULL) {
9037 if (c != '-' && c != '+')
9040 val = 0; /* val = 0 if c == '+' */
9043 if (p[0] == '\0' || LONE_DASH(p)) {
9045 /* "-" means turn off -x and -v */
9048 /* "--" means reset params */
9049 else if (*argptr == NULL)
9052 break; /* "-" or "--" terminates options */
9055 /* first char was + or - */
9056 while ((c = *p++) != '\0') {
9057 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9058 if (c == 'c' && cmdline) {
9059 minusc = p; /* command is after shell args */
9060 } else if (c == 'o') {
9061 minus_o(*argptr, val);
9064 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9066 /* bash does not accept +-login, we also won't */
9067 } else if (cmdline && val && (c == '-')) { /* long options */
9068 if (strcmp(p, "login") == 0)
9079 * The shift builtin command.
9082 shiftcmd(int argc, char **argv)
9089 n = number(argv[1]);
9090 if (n > shellparam.nparam)
9091 ash_msg_and_raise_error("can't shift that many");
9093 shellparam.nparam -= n;
9094 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9095 if (shellparam.malloc)
9099 while ((*ap2++ = *ap1++) != NULL);
9100 #if ENABLE_ASH_GETOPTS
9101 shellparam.optind = 1;
9102 shellparam.optoff = -1;
9109 * POSIX requires that 'set' (but not export or readonly) output the
9110 * variables in lexicographic order - by the locale's collating order (sigh).
9111 * Maybe we could keep them in an ordered balanced binary tree
9112 * instead of hashed lists.
9113 * For now just roll 'em through qsort for printing...
9116 showvars(const char *sep_prefix, int on, int off)
9121 ep = listvars(on, off, &epend);
9122 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9124 sep = *sep_prefix ? " " : sep_prefix;
9126 for (; ep < epend; ep++) {
9130 p = strchrnul(*ep, '=');
9133 q = single_quote(++p);
9134 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9140 * The set command builtin.
9143 setcmd(int argc, char **argv)
9146 return showvars(nullstr, 0, VUNSET);
9150 if (*argptr != NULL) {
9157 #if ENABLE_ASH_RANDOM_SUPPORT
9158 /* Roughly copied from bash.. */
9160 change_random(const char *value)
9162 if (value == NULL) {
9163 /* "get", generate */
9166 rseed = rseed * 1103515245 + 12345;
9167 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9168 /* set without recursion */
9169 setvar(vrandom.text, buf, VNOFUNC);
9170 vrandom.flags &= ~VNOFUNC;
9173 rseed = strtoul(value, (char **)NULL, 10);
9178 #if ENABLE_ASH_GETOPTS
9180 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9189 if (*param_optind < 1)
9191 optnext = optfirst + *param_optind - 1;
9193 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9196 p = optnext[-1] + *optoff;
9197 if (p == NULL || *p == '\0') {
9198 /* Current word is done, advance */
9200 if (p == NULL || *p != '-' || *++p == '\0') {
9207 if (LONE_DASH(p)) /* check for "--" */
9212 for (q = optstr; *q != c; ) {
9214 if (optstr[0] == ':') {
9217 err |= setvarsafe("OPTARG", s, 0);
9219 fprintf(stderr, "Illegal option -%c\n", c);
9230 if (*p == '\0' && (p = *optnext) == NULL) {
9231 if (optstr[0] == ':') {
9234 err |= setvarsafe("OPTARG", s, 0);
9237 fprintf(stderr, "No arg for -%c option\n", c);
9246 err |= setvarsafe("OPTARG", p, 0);
9249 err |= setvarsafe("OPTARG", nullstr, 0);
9251 *optoff = p ? p - *(optnext - 1) : -1;
9252 *param_optind = optnext - optfirst + 1;
9253 fmtstr(s, sizeof(s), "%d", *param_optind);
9254 err |= setvarsafe("OPTIND", s, VNOFUNC);
9257 err |= setvarsafe(optvar, s, 0);
9261 flush_stdout_stderr();
9262 raise_exception(EXERROR);
9268 * The getopts builtin. Shellparam.optnext points to the next argument
9269 * to be processed. Shellparam.optptr points to the next character to
9270 * be processed in the current argument. If shellparam.optnext is NULL,
9271 * then it's the first time getopts has been called.
9274 getoptscmd(int argc, char **argv)
9279 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9281 optbase = shellparam.p;
9282 if (shellparam.optind > shellparam.nparam + 1) {
9283 shellparam.optind = 1;
9284 shellparam.optoff = -1;
9288 if (shellparam.optind > argc - 2) {
9289 shellparam.optind = 1;
9290 shellparam.optoff = -1;
9294 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9295 &shellparam.optoff);
9297 #endif /* ASH_GETOPTS */
9300 /* ============ Shell parser */
9303 * NEOF is returned by parsecmd when it encounters an end of file. It
9304 * must be distinct from NULL, so we use the address of a variable that
9305 * happens to be handy.
9307 static smallint tokpushback; /* last token pushed back */
9308 #define NEOF ((union node *)&tokpushback)
9309 static smallint parsebackquote; /* nonzero if we are inside backquotes */
9310 static int lasttoken; /* last token read */
9311 static char *wordtext; /* text of last word returned by readtoken */
9312 static struct nodelist *backquotelist;
9313 static union node *redirnode;
9314 static struct heredoc *heredoc;
9315 static smallint quoteflag; /* set if (part of) last token was quoted */
9317 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9319 raise_error_syntax(const char *msg)
9321 ash_msg_and_raise_error("syntax error: %s", msg);
9326 * Called when an unexpected token is read during the parse. The argument
9327 * is the token that is expected, or -1 if more than one type of token can
9328 * occur at this point.
9330 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9332 raise_error_unexpected_syntax(int token)
9337 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9339 sprintf(msg + l, " (expecting %s)", tokname(token));
9340 raise_error_syntax(msg);
9344 #define EOFMARKLEN 79
9347 struct heredoc *next; /* next here document in list */
9348 union node *here; /* redirection node */
9349 char *eofmark; /* string indicating end of input */
9350 int striptabs; /* if set, strip leading tabs */
9353 static struct heredoc *heredoclist; /* list of here documents to read */
9355 /* parsing is heavily cross-recursive, need these forward decls */
9356 static union node *andor(void);
9357 static union node *pipeline(void);
9358 static union node *parse_command(void);
9359 static void parseheredoc(void);
9360 static char peektoken(void);
9361 static int readtoken(void);
9366 union node *n1, *n2, *n3;
9369 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9370 if (nlflag == 2 && peektoken())
9376 if (tok == TBACKGND) {
9377 if (n2->type == NPIPE) {
9378 n2->npipe.backgnd = 1;
9380 if (n2->type != NREDIR) {
9381 n3 = stalloc(sizeof(struct nredir));
9383 n3->nredir.redirect = NULL;
9386 n2->type = NBACKGND;
9392 n3 = stalloc(sizeof(struct nbinary));
9394 n3->nbinary.ch1 = n1;
9395 n3->nbinary.ch2 = n2;
9411 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9419 pungetc(); /* push back EOF on input */
9423 raise_error_unexpected_syntax(-1);
9433 union node *n1, *n2, *n3;
9441 } else if (t == TOR) {
9447 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9449 n3 = stalloc(sizeof(struct nbinary));
9451 n3->nbinary.ch1 = n1;
9452 n3->nbinary.ch2 = n2;
9460 union node *n1, *n2, *pipenode;
9461 struct nodelist *lp, *prev;
9465 TRACE(("pipeline: entered\n"));
9466 if (readtoken() == TNOT) {
9468 checkkwd = CHKKWD | CHKALIAS;
9471 n1 = parse_command();
9472 if (readtoken() == TPIPE) {
9473 pipenode = stalloc(sizeof(struct npipe));
9474 pipenode->type = NPIPE;
9475 pipenode->npipe.backgnd = 0;
9476 lp = stalloc(sizeof(struct nodelist));
9477 pipenode->npipe.cmdlist = lp;
9481 lp = stalloc(sizeof(struct nodelist));
9482 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9483 lp->n = parse_command();
9485 } while (readtoken() == TPIPE);
9491 n2 = stalloc(sizeof(struct nnot));
9504 n = stalloc(sizeof(struct narg));
9506 n->narg.next = NULL;
9507 n->narg.text = wordtext;
9508 n->narg.backquote = backquotelist;
9513 fixredir(union node *n, const char *text, int err)
9515 TRACE(("Fix redir %s %d\n", text, err));
9517 n->ndup.vname = NULL;
9519 if (isdigit(text[0]) && text[1] == '\0')
9520 n->ndup.dupfd = text[0] - '0';
9521 else if (LONE_DASH(text))
9525 raise_error_syntax("Bad fd number");
9526 n->ndup.vname = makename();
9531 * Returns true if the text contains nothing to expand (no dollar signs
9535 noexpand(char *text)
9541 while ((c = *p++) != '\0') {
9542 if (c == CTLQUOTEMARK)
9546 else if (SIT(c, BASESYNTAX) == CCTL)
9555 union node *n = redirnode;
9557 if (readtoken() != TWORD)
9558 raise_error_unexpected_syntax(-1);
9559 if (n->type == NHERE) {
9560 struct heredoc *here = heredoc;
9566 TRACE(("Here document %d\n", n->type));
9567 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9568 raise_error_syntax("Illegal eof marker for << redirection");
9569 rmescapes(wordtext);
9570 here->eofmark = wordtext;
9572 if (heredoclist == NULL)
9575 for (p = heredoclist; p->next; p = p->next);
9578 } else if (n->type == NTOFD || n->type == NFROMFD) {
9579 fixredir(n, wordtext, 0);
9581 n->nfile.fname = makename();
9588 union node *args, **app;
9589 union node *n = NULL;
9590 union node *vars, **vpp;
9591 union node **rpp, *redir;
9601 savecheckkwd = CHKALIAS;
9603 checkkwd = savecheckkwd;
9604 switch (readtoken()) {
9606 n = stalloc(sizeof(struct narg));
9608 n->narg.text = wordtext;
9609 n->narg.backquote = backquotelist;
9610 if (savecheckkwd && isassignment(wordtext)) {
9612 vpp = &n->narg.next;
9615 app = &n->narg.next;
9620 *rpp = n = redirnode;
9621 rpp = &n->nfile.next;
9622 parsefname(); /* read name of redirection file */
9625 if (args && app == &args->narg.next
9628 struct builtincmd *bcmd;
9631 /* We have a function */
9632 if (readtoken() != TRP)
9633 raise_error_unexpected_syntax(TRP);
9634 name = n->narg.text;
9636 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9638 raise_error_syntax("Bad function name");
9641 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9642 n->narg.next = parse_command();
9655 n = stalloc(sizeof(struct ncmd));
9657 n->ncmd.args = args;
9658 n->ncmd.assign = vars;
9659 n->ncmd.redirect = redir;
9666 union node *n1, *n2;
9667 union node *ap, **app;
9668 union node *cp, **cpp;
9669 union node *redir, **rpp;
9676 switch (readtoken()) {
9678 raise_error_unexpected_syntax(-1);
9681 n1 = stalloc(sizeof(struct nif));
9683 n1->nif.test = list(0);
9684 if (readtoken() != TTHEN)
9685 raise_error_unexpected_syntax(TTHEN);
9686 n1->nif.ifpart = list(0);
9688 while (readtoken() == TELIF) {
9689 n2->nif.elsepart = stalloc(sizeof(struct nif));
9690 n2 = n2->nif.elsepart;
9692 n2->nif.test = list(0);
9693 if (readtoken() != TTHEN)
9694 raise_error_unexpected_syntax(TTHEN);
9695 n2->nif.ifpart = list(0);
9697 if (lasttoken == TELSE)
9698 n2->nif.elsepart = list(0);
9700 n2->nif.elsepart = NULL;
9708 n1 = stalloc(sizeof(struct nbinary));
9709 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9710 n1->nbinary.ch1 = list(0);
9713 TRACE(("expecting DO got %s %s\n", tokname(got),
9714 got == TWORD ? wordtext : ""));
9715 raise_error_unexpected_syntax(TDO);
9717 n1->nbinary.ch2 = list(0);
9722 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9723 raise_error_syntax("Bad for loop variable");
9724 n1 = stalloc(sizeof(struct nfor));
9726 n1->nfor.var = wordtext;
9727 checkkwd = CHKKWD | CHKALIAS;
9728 if (readtoken() == TIN) {
9730 while (readtoken() == TWORD) {
9731 n2 = stalloc(sizeof(struct narg));
9733 n2->narg.text = wordtext;
9734 n2->narg.backquote = backquotelist;
9736 app = &n2->narg.next;
9740 if (lasttoken != TNL && lasttoken != TSEMI)
9741 raise_error_unexpected_syntax(-1);
9743 n2 = stalloc(sizeof(struct narg));
9745 n2->narg.text = (char *)dolatstr;
9746 n2->narg.backquote = NULL;
9747 n2->narg.next = NULL;
9750 * Newline or semicolon here is optional (but note
9751 * that the original Bourne shell only allowed NL).
9753 if (lasttoken != TNL && lasttoken != TSEMI)
9756 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9757 if (readtoken() != TDO)
9758 raise_error_unexpected_syntax(TDO);
9759 n1->nfor.body = list(0);
9763 n1 = stalloc(sizeof(struct ncase));
9765 if (readtoken() != TWORD)
9766 raise_error_unexpected_syntax(TWORD);
9767 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9769 n2->narg.text = wordtext;
9770 n2->narg.backquote = backquotelist;
9771 n2->narg.next = NULL;
9773 checkkwd = CHKKWD | CHKALIAS;
9774 } while (readtoken() == TNL);
9775 if (lasttoken != TIN)
9776 raise_error_unexpected_syntax(TIN);
9777 cpp = &n1->ncase.cases;
9779 checkkwd = CHKNL | CHKKWD;
9781 while (t != TESAC) {
9782 if (lasttoken == TLP)
9784 *cpp = cp = stalloc(sizeof(struct nclist));
9786 app = &cp->nclist.pattern;
9788 *app = ap = stalloc(sizeof(struct narg));
9790 ap->narg.text = wordtext;
9791 ap->narg.backquote = backquotelist;
9792 if (readtoken() != TPIPE)
9794 app = &ap->narg.next;
9797 ap->narg.next = NULL;
9798 if (lasttoken != TRP)
9799 raise_error_unexpected_syntax(TRP);
9800 cp->nclist.body = list(2);
9802 cpp = &cp->nclist.next;
9804 checkkwd = CHKNL | CHKKWD;
9808 raise_error_unexpected_syntax(TENDCASE);
9815 n1 = stalloc(sizeof(struct nredir));
9816 n1->type = NSUBSHELL;
9817 n1->nredir.n = list(0);
9818 n1->nredir.redirect = NULL;
9831 if (readtoken() != t)
9832 raise_error_unexpected_syntax(t);
9835 /* Now check for redirection which may follow command */
9836 checkkwd = CHKKWD | CHKALIAS;
9838 while (readtoken() == TREDIR) {
9839 *rpp = n2 = redirnode;
9840 rpp = &n2->nfile.next;
9846 if (n1->type != NSUBSHELL) {
9847 n2 = stalloc(sizeof(struct nredir));
9852 n1->nredir.redirect = redir;
9858 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9859 * is not NULL, read a here document. In the latter case, eofmark is the
9860 * word which marks the end of the document and striptabs is true if
9861 * leading tabs should be stripped from the document. The argument firstc
9862 * is the first character of the input token or document.
9864 * Because C does not have internal subroutines, I have simulated them
9865 * using goto's to implement the subroutine linkage. The following macros
9866 * will run code that appears at the end of readtoken1.
9869 #define CHECKEND() {goto checkend; checkend_return:;}
9870 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9871 #define PARSESUB() {goto parsesub; parsesub_return:;}
9872 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9873 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9874 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9877 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9879 /* NB: syntax parameter fits into smallint */
9883 char line[EOFMARKLEN + 1];
9884 struct nodelist *bqlist;
9888 smallint prevsyntax; /* syntax before arithmetic */
9889 int varnest; /* levels of variables expansion */
9890 int arinest; /* levels of arithmetic expansion */
9891 int parenlevel; /* levels of parens in arithmetic */
9892 int dqvarnest; /* levels of variables expansion within double quotes */
9895 /* Avoid longjmp clobbering */
9907 startlinno = plinno;
9910 dblquote = (syntax == DQSYNTAX);
9919 loop: { /* for each line, until end of word */
9920 CHECKEND(); /* set c to PEOF if at end of here document */
9921 for (;;) { /* until end of line or end of word */
9922 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9923 switch (SIT(c, syntax)) {
9924 case CNL: /* '\n' */
9925 if (syntax == BASESYNTAX)
9926 goto endword; /* exit outer loop */
9932 goto loop; /* continue outer loop */
9937 if (eofmark == NULL || dblquote)
9938 USTPUTC(CTLESC, out);
9941 case CBACK: /* backslash */
9944 USTPUTC(CTLESC, out);
9947 } else if (c == '\n') {
9952 c != '\\' && c != '`' &&
9957 USTPUTC(CTLESC, out);
9960 if (SIT(c, SQSYNTAX) == CCTL)
9961 USTPUTC(CTLESC, out);
9969 if (eofmark == NULL) {
9970 USTPUTC(CTLQUOTEMARK, out);
9978 if (eofmark != NULL && arinest == 0
9983 if (dqvarnest == 0) {
9984 syntax = BASESYNTAX;
9991 case CVAR: /* '$' */
9992 PARSESUB(); /* parse substitution */
9994 case CENDVAR: /* '}' */
9997 if (dqvarnest > 0) {
10000 USTPUTC(CTLENDVAR, out);
10005 #if ENABLE_ASH_MATH_SUPPORT
10006 case CLP: /* '(' in arithmetic */
10010 case CRP: /* ')' in arithmetic */
10011 if (parenlevel > 0) {
10015 if (pgetc() == ')') {
10016 if (--arinest == 0) {
10017 USTPUTC(CTLENDARI, out);
10018 syntax = prevsyntax;
10019 dblquote = (syntax == DQSYNTAX);
10024 * unbalanced parens
10025 * (don't 2nd guess - no error)
10033 case CBQUOTE: /* '`' */
10037 goto endword; /* exit outer loop */
10042 goto endword; /* exit outer loop */
10043 #if ENABLE_ASH_ALIAS
10053 #if ENABLE_ASH_MATH_SUPPORT
10054 if (syntax == ARISYNTAX)
10055 raise_error_syntax("Missing '))'");
10057 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10058 raise_error_syntax("Unterminated quoted string");
10059 if (varnest != 0) {
10060 startlinno = plinno;
10062 raise_error_syntax("Missing '}'");
10064 USTPUTC('\0', out);
10065 len = out - (char *)stackblock();
10066 out = stackblock();
10067 if (eofmark == NULL) {
10068 if ((c == '>' || c == '<')
10071 && (*out == '\0' || isdigit(*out))) {
10073 return lasttoken = TREDIR;
10078 quoteflag = quotef;
10079 backquotelist = bqlist;
10080 grabstackblock(len);
10084 /* end of readtoken routine */
10087 * Check to see whether we are at the end of the here document. When this
10088 * is called, c is set to the first character of the next input line. If
10089 * we are at the end of the here document, this routine sets the c to PEOF.
10093 #if ENABLE_ASH_ALIAS
10099 while (c == '\t') {
10103 if (c == *eofmark) {
10104 if (pfgets(line, sizeof(line)) != NULL) {
10108 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10109 if (*p == '\n' && *q == '\0') {
10112 needprompt = doprompt;
10114 pushstring(line, NULL);
10119 goto checkend_return;
10123 * Parse a redirection operator. The variable "out" points to a string
10124 * specifying the fd to be redirected. The variable "c" contains the
10125 * first character of the redirection operator.
10131 np = stalloc(sizeof(struct nfile));
10136 np->type = NAPPEND;
10138 np->type = NCLOBBER;
10145 } else { /* c == '<' */
10150 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10151 np = stalloc(sizeof(struct nhere));
10155 heredoc = stalloc(sizeof(struct heredoc));
10156 heredoc->here = np;
10159 heredoc->striptabs = 1;
10161 heredoc->striptabs = 0;
10167 np->type = NFROMFD;
10171 np->type = NFROMTO;
10181 np->nfile.fd = fd - '0';
10183 goto parseredir_return;
10187 * Parse a substitution. At this point, we have read the dollar sign
10188 * and nothing else.
10191 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10192 * (assuming ascii char codes, as the original implementation did) */
10193 #define is_special(c) \
10194 ((((unsigned int)c) - 33 < 32) \
10195 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10201 static const char types[] ALIGN1 = "}-+?=";
10205 c <= PEOA_OR_PEOF ||
10206 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10210 } else if (c == '(') { /* $(command) or $((arith)) */
10211 if (pgetc() == '(') {
10212 #if ENABLE_ASH_MATH_SUPPORT
10215 raise_error_syntax("We unsupport $((arith))");
10222 USTPUTC(CTLVAR, out);
10223 typeloc = out - (char *)stackblock();
10224 USTPUTC(VSNORMAL, out);
10225 subtype = VSNORMAL;
10233 subtype = VSLENGTH;
10237 if (c > PEOA_OR_PEOF && is_name(c)) {
10241 } while (c > PEOA_OR_PEOF && is_in_name(c));
10242 } else if (isdigit(c)) {
10246 } while (isdigit(c));
10247 } else if (is_special(c)) {
10251 badsub: raise_error_syntax("Bad substitution");
10255 if (subtype == 0) {
10262 p = strchr(types, c);
10265 subtype = p - types + VSNORMAL;
10271 subtype = c == '#' ? VSTRIMLEFT :
10284 if (dblquote || arinest)
10286 *((char *)stackblock() + typeloc) = subtype | flags;
10287 if (subtype != VSNORMAL) {
10289 if (dblquote || arinest) {
10294 goto parsesub_return;
10298 * Called to parse command substitutions. Newstyle is set if the command
10299 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10300 * list of commands (passed by reference), and savelen is the number of
10301 * characters on the top of the stack which must be preserved.
10304 struct nodelist **nlpp;
10307 char *volatile str;
10308 struct jmploc jmploc;
10309 struct jmploc *volatile savehandler;
10311 smallint saveprompt = 0;
10314 (void) &saveprompt;
10316 savepbq = parsebackquote;
10317 if (setjmp(jmploc.loc)) {
10320 parsebackquote = 0;
10321 exception_handler = savehandler;
10322 longjmp(exception_handler->loc, 1);
10326 savelen = out - (char *)stackblock();
10328 str = ckmalloc(savelen);
10329 memcpy(str, stackblock(), savelen);
10331 savehandler = exception_handler;
10332 exception_handler = &jmploc;
10335 /* We must read until the closing backquote, giving special
10336 treatment to some slashes, and then push the string and
10337 reread it as input, interpreting it normally. */
10344 STARTSTACKSTR(pout);
10361 * If eating a newline, avoid putting
10362 * the newline into the new character
10363 * stream (via the STPUTC after the
10368 if (pc != '\\' && pc != '`' && pc != '$'
10369 && (!dblquote || pc != '"'))
10370 STPUTC('\\', pout);
10371 if (pc > PEOA_OR_PEOF) {
10377 #if ENABLE_ASH_ALIAS
10380 startlinno = plinno;
10381 raise_error_syntax("EOF in backquote substitution");
10385 needprompt = doprompt;
10394 STPUTC('\0', pout);
10395 psavelen = pout - (char *)stackblock();
10396 if (psavelen > 0) {
10397 pstr = grabstackstr(pout);
10398 setinputstring(pstr);
10403 nlpp = &(*nlpp)->next;
10404 *nlpp = stalloc(sizeof(**nlpp));
10405 (*nlpp)->next = NULL;
10406 parsebackquote = oldstyle;
10409 saveprompt = doprompt;
10416 doprompt = saveprompt;
10417 else if (readtoken() != TRP)
10418 raise_error_unexpected_syntax(TRP);
10423 * Start reading from old file again, ignoring any pushed back
10424 * tokens left from the backquote parsing
10429 while (stackblocksize() <= savelen)
10431 STARTSTACKSTR(out);
10433 memcpy(out, str, savelen);
10434 STADJUST(savelen, out);
10440 parsebackquote = savepbq;
10441 exception_handler = savehandler;
10442 if (arinest || dblquote)
10443 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10445 USTPUTC(CTLBACKQ, out);
10447 goto parsebackq_oldreturn;
10448 goto parsebackq_newreturn;
10451 #if ENABLE_ASH_MATH_SUPPORT
10453 * Parse an arithmetic expansion (indicate start of one and set state)
10456 if (++arinest == 1) {
10457 prevsyntax = syntax;
10458 syntax = ARISYNTAX;
10459 USTPUTC(CTLARI, out);
10466 * we collapse embedded arithmetic expansion to
10467 * parenthesis, which should be equivalent
10471 goto parsearith_return;
10475 } /* end of readtoken */
10478 * Read the next input token.
10479 * If the token is a word, we set backquotelist to the list of cmds in
10480 * backquotes. We set quoteflag to true if any part of the word was
10482 * If the token is TREDIR, then we set redirnode to a structure containing
10484 * In all cases, the variable startlinno is set to the number of the line
10485 * on which the token starts.
10487 * [Change comment: here documents and internal procedures]
10488 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10489 * word parsing code into a separate routine. In this case, readtoken
10490 * doesn't need to have any internal procedures, but parseword does.
10491 * We could also make parseoperator in essence the main routine, and
10492 * have parseword (readtoken1?) handle both words and redirection.]
10494 #define NEW_xxreadtoken
10495 #ifdef NEW_xxreadtoken
10496 /* singles must be first! */
10497 static const char xxreadtoken_chars[7] ALIGN1 = {
10498 '\n', '(', ')', '&', '|', ';', 0
10501 static const char xxreadtoken_tokens[] ALIGN1 = {
10502 TNL, TLP, TRP, /* only single occurrence allowed */
10503 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10504 TEOF, /* corresponds to trailing nul */
10505 TAND, TOR, TENDCASE /* if double occurrence */
10508 #define xxreadtoken_doubles \
10509 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10510 #define xxreadtoken_singles \
10511 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10525 startlinno = plinno;
10526 for (;;) { /* until token or start of word found */
10529 if ((c != ' ') && (c != '\t')
10530 #if ENABLE_ASH_ALIAS
10535 while ((c = pgetc()) != '\n' && c != PEOF);
10537 } else if (c == '\\') {
10538 if (pgetc() != '\n') {
10542 startlinno = ++plinno;
10547 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10552 needprompt = doprompt;
10555 p = strchr(xxreadtoken_chars, c);
10558 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10561 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10562 if (pgetc() == *p) { /* double occurrence? */
10563 p += xxreadtoken_doubles + 1;
10569 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10575 #define RETURN(token) return lasttoken = token
10588 startlinno = plinno;
10589 for (;;) { /* until token or start of word found */
10592 case ' ': case '\t':
10593 #if ENABLE_ASH_ALIAS
10598 while ((c = pgetc()) != '\n' && c != PEOF);
10602 if (pgetc() == '\n') {
10603 startlinno = ++plinno;
10612 needprompt = doprompt;
10617 if (pgetc() == '&')
10622 if (pgetc() == '|')
10627 if (pgetc() == ';')
10640 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10643 #endif /* NEW_xxreadtoken */
10650 smallint alreadyseen = tokpushback;
10653 #if ENABLE_ASH_ALIAS
10662 if (checkkwd & CHKNL) {
10669 if (t != TWORD || quoteflag) {
10674 * check for keywords
10676 if (checkkwd & CHKKWD) {
10677 const char *const *pp;
10679 pp = findkwd(wordtext);
10681 lasttoken = t = pp - tokname_array;
10682 TRACE(("keyword %s recognized\n", tokname(t)));
10687 if (checkkwd & CHKALIAS) {
10688 #if ENABLE_ASH_ALIAS
10690 ap = lookupalias(wordtext, 1);
10693 pushstring(ap->val, ap);
10703 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10705 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10717 return tokname_array[t][0];
10721 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10722 * valid parse tree indicating a blank line.)
10724 static union node *
10725 parsecmd(int interact)
10730 doprompt = interact;
10732 setprompt(doprompt);
10744 * Input any here documents.
10749 struct heredoc *here;
10752 here = heredoclist;
10759 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10760 here->eofmark, here->striptabs);
10761 n = stalloc(sizeof(struct narg));
10762 n->narg.type = NARG;
10763 n->narg.next = NULL;
10764 n->narg.text = wordtext;
10765 n->narg.backquote = backquotelist;
10766 here->here->nhere.doc = n;
10773 * called by editline -- any expansions to the prompt should be added here.
10775 #if ENABLE_ASH_EXPAND_PRMT
10776 static const char *
10777 expandstr(const char *ps)
10781 /* XXX Fix (char *) cast. */
10782 setinputstring((char *)ps);
10783 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10786 n.narg.type = NARG;
10787 n.narg.next = NULL;
10788 n.narg.text = wordtext;
10789 n.narg.backquote = backquotelist;
10791 expandarg(&n, NULL, 0);
10792 return stackblock();
10797 * Execute a command or commands contained in a string.
10800 evalstring(char *s, int mask)
10803 struct stackmark smark;
10807 setstackmark(&smark);
10810 while ((n = parsecmd(0)) != NEOF) {
10812 popstackmark(&smark);
10825 * The eval command.
10828 evalcmd(int argc, char **argv)
10837 STARTSTACKSTR(concat);
10840 concat = stack_putstr(p, concat);
10844 STPUTC(' ', concat);
10846 STPUTC('\0', concat);
10847 p = grabstackstr(concat);
10849 evalstring(p, ~SKIPEVAL);
10856 * Read and execute commands. "Top" is nonzero for the top level command
10857 * loop; it turns on prompting if the shell is interactive.
10863 struct stackmark smark;
10867 TRACE(("cmdloop(%d) called\n", top));
10871 setstackmark(&smark);
10874 showjobs(stderr, SHOW_CHANGED);
10877 if (iflag && top) {
10879 #if ENABLE_ASH_MAIL
10883 n = parsecmd(inter);
10884 /* showtree(n); DEBUG */
10886 if (!top || numeof >= 50)
10888 if (!stoppedjobs()) {
10891 out2str("\nUse \"exit\" to leave shell.\n");
10894 } else if (nflag == 0) {
10895 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
10900 popstackmark(&smark);
10905 return skip & SKIPEVAL;
10912 * Take commands from a file. To be compatible we should do a path
10913 * search for the file, which is necessary to find sub-commands.
10916 find_dot_file(char *name)
10919 const char *path = pathval();
10922 /* don't try this for absolute or relative paths */
10923 if (strchr(name, '/'))
10926 while ((fullname = padvance(&path, name)) != NULL) {
10927 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
10929 * Don't bother freeing here, since it will
10930 * be freed by the caller.
10934 stunalloc(fullname);
10937 /* not found in the PATH */
10938 ash_msg_and_raise_error("%s: not found", name);
10943 dotcmd(int argc, char **argv)
10945 struct strlist *sp;
10946 volatile struct shparam saveparam;
10949 for (sp = cmdenviron; sp; sp = sp->next)
10950 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
10952 if (argc >= 2) { /* That's what SVR2 does */
10955 fullname = find_dot_file(argv[1]);
10958 saveparam = shellparam;
10959 shellparam.malloc = 0;
10960 shellparam.nparam = argc - 2;
10961 shellparam.p = argv + 2;
10964 setinputfile(fullname, INPUT_PUSH_FILE);
10965 commandname = fullname;
10970 freeparam(&shellparam);
10971 shellparam = saveparam;
10973 status = exitstatus;
10979 exitcmd(int argc, char **argv)
10984 exitstatus = number(argv[1]);
10985 raise_exception(EXEXIT);
10989 #if ENABLE_ASH_BUILTIN_ECHO
10991 echocmd(int argc, char **argv)
10993 return bb_echo(argv);
10997 #if ENABLE_ASH_BUILTIN_TEST
10999 testcmd(int argc, char **argv)
11001 return test_main(argc, argv);
11006 * Read a file containing shell functions.
11009 readcmdfile(char *name)
11011 setinputfile(name, INPUT_PUSH_FILE);
11017 /* ============ find_command inplementation */
11020 * Resolve a command name. If you change this routine, you may have to
11021 * change the shellexec routine as well.
11024 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11026 struct tblentry *cmdp;
11033 struct builtincmd *bcmd;
11035 /* If name contains a slash, don't use PATH or hash table */
11036 if (strchr(name, '/') != NULL) {
11037 entry->u.index = -1;
11038 if (act & DO_ABS) {
11039 while (stat(name, &statb) < 0) {
11041 if (errno == EINTR)
11044 entry->cmdtype = CMDUNKNOWN;
11048 entry->cmdtype = CMDNORMAL;
11052 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11054 updatetbl = (path == pathval());
11057 if (strstr(path, "%builtin") != NULL)
11058 act |= DO_ALTBLTIN;
11061 /* If name is in the table, check answer will be ok */
11062 cmdp = cmdlookup(name, 0);
11063 if (cmdp != NULL) {
11066 switch (cmdp->cmdtype) {
11084 } else if (cmdp->rehash == 0)
11085 /* if not invalidated by cd, we're done */
11089 /* If %builtin not in path, check for builtin next */
11090 bcmd = find_builtin(name);
11092 if (IS_BUILTIN_REGULAR(bcmd))
11093 goto builtin_success;
11094 if (act & DO_ALTPATH) {
11095 if (!(act & DO_ALTBLTIN))
11096 goto builtin_success;
11097 } else if (builtinloc <= 0) {
11098 goto builtin_success;
11102 #if ENABLE_FEATURE_SH_STANDALONE
11103 if (find_applet_by_name(name)) {
11104 entry->cmdtype = CMDNORMAL;
11105 entry->u.index = -1;
11110 /* We have to search path. */
11111 prev = -1; /* where to start */
11112 if (cmdp && cmdp->rehash) { /* doing a rehash */
11113 if (cmdp->cmdtype == CMDBUILTIN)
11116 prev = cmdp->param.index;
11122 while ((fullname = padvance(&path, name)) != NULL) {
11123 stunalloc(fullname);
11124 /* NB: code below will still use fullname
11125 * despite it being "unallocated" */
11128 if (prefix(pathopt, "builtin")) {
11130 goto builtin_success;
11132 } else if (!(act & DO_NOFUNC)
11133 && prefix(pathopt, "func")) {
11134 /* handled below */
11136 /* ignore unimplemented options */
11140 /* if rehash, don't redo absolute path names */
11141 if (fullname[0] == '/' && idx <= prev) {
11144 TRACE(("searchexec \"%s\": no change\n", name));
11147 while (stat(fullname, &statb) < 0) {
11149 if (errno == EINTR)
11152 if (errno != ENOENT && errno != ENOTDIR)
11156 e = EACCES; /* if we fail, this will be the error */
11157 if (!S_ISREG(statb.st_mode))
11159 if (pathopt) { /* this is a %func directory */
11160 stalloc(strlen(fullname) + 1);
11161 /* NB: stalloc will return space pointed by fullname
11162 * (because we don't have any intervening allocations
11163 * between stunalloc above and this stalloc) */
11164 readcmdfile(fullname);
11165 cmdp = cmdlookup(name, 0);
11166 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11167 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11168 stunalloc(fullname);
11171 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11173 entry->cmdtype = CMDNORMAL;
11174 entry->u.index = idx;
11178 cmdp = cmdlookup(name, 1);
11179 cmdp->cmdtype = CMDNORMAL;
11180 cmdp->param.index = idx;
11185 /* We failed. If there was an entry for this command, delete it */
11186 if (cmdp && updatetbl)
11187 delete_cmd_entry();
11189 ash_msg("%s: %s", name, errmsg(e, "not found"));
11190 entry->cmdtype = CMDUNKNOWN;
11195 entry->cmdtype = CMDBUILTIN;
11196 entry->u.cmd = bcmd;
11200 cmdp = cmdlookup(name, 1);
11201 cmdp->cmdtype = CMDBUILTIN;
11202 cmdp->param.cmd = bcmd;
11206 entry->cmdtype = cmdp->cmdtype;
11207 entry->u = cmdp->param;
11211 /* ============ trap.c */
11214 * The trap builtin.
11217 trapcmd(int argc, char **argv)
11226 for (signo = 0; signo < NSIG; signo++) {
11227 if (trap[signo] != NULL) {
11230 sn = get_signame(signo);
11231 out1fmt("trap -- %s %s\n",
11232 single_quote(trap[signo]), sn);
11242 signo = get_signum(*ap);
11244 ash_msg_and_raise_error("%s: bad trap", *ap);
11247 if (LONE_DASH(action))
11250 action = ckstrdup(action);
11254 trap[signo] = action;
11264 /* ============ Builtins */
11266 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11268 * Lists available builtins
11271 helpcmd(int argc, char **argv)
11275 out1fmt("\nBuilt-in commands:\n-------------------\n");
11276 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11277 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11278 builtintab[i].name + 1);
11284 #if ENABLE_FEATURE_SH_STANDALONE
11285 for (i = 0; i < NUM_APPLETS; i++) {
11286 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11294 return EXIT_SUCCESS;
11296 #endif /* FEATURE_SH_EXTRA_QUIET */
11299 * The export and readonly commands.
11302 exportcmd(int argc, char **argv)
11308 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11310 if (nextopt("p") != 'p') {
11315 p = strchr(name, '=');
11319 vp = *findvar(hashvar(name), name);
11325 setvar(name, p, flag);
11326 } while ((name = *++aptr) != NULL);
11330 showvars(argv[0], flag, 0);
11335 * Delete a function if it exists.
11338 unsetfunc(const char *name)
11340 struct tblentry *cmdp;
11342 cmdp = cmdlookup(name, 0);
11343 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11344 delete_cmd_entry();
11348 * The unset builtin command. We unset the function before we unset the
11349 * variable to allow a function to be unset when there is a readonly variable
11350 * with the same name.
11353 unsetcmd(int argc, char **argv)
11360 while ((i = nextopt("vf")) != '\0') {
11364 for (ap = argptr; *ap; ap++) {
11380 #include <sys/times.h>
11382 static const unsigned char timescmd_str[] ALIGN1 = {
11383 ' ', offsetof(struct tms, tms_utime),
11384 '\n', offsetof(struct tms, tms_stime),
11385 ' ', offsetof(struct tms, tms_cutime),
11386 '\n', offsetof(struct tms, tms_cstime),
11391 timescmd(int ac, char **av)
11393 long clk_tck, s, t;
11394 const unsigned char *p;
11397 clk_tck = sysconf(_SC_CLK_TCK);
11402 t = *(clock_t *)(((char *) &buf) + p[1]);
11404 out1fmt("%ldm%ld.%.3lds%c",
11406 ((t - s * clk_tck) * 1000) / clk_tck,
11408 } while (*(p += 2));
11413 #if ENABLE_ASH_MATH_SUPPORT
11415 dash_arith(const char *s)
11421 result = arith(s, &errcode);
11424 ash_msg_and_raise_error("exponent less than 0");
11426 ash_msg_and_raise_error("divide by zero");
11428 ash_msg_and_raise_error("expression recursion loop detected");
11429 raise_error_syntax(s);
11437 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11438 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11440 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11443 letcmd(int argc, char **argv)
11450 ash_msg_and_raise_error("expression expected");
11451 for (ap = argv + 1; *ap; ap++) {
11452 i = dash_arith(*ap);
11457 #endif /* ASH_MATH_SUPPORT */
11460 /* ============ miscbltin.c
11462 * Miscellaneous builtins.
11467 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11468 typedef enum __rlimit_resource rlim_t;
11472 * The read builtin. The -e option causes backslashes to escape the
11473 * following character.
11475 * This uses unbuffered input, which may be avoidable in some cases.
11478 readcmd(int argc, char **argv)
11490 #if ENABLE_ASH_READ_NCHARS
11494 struct termios tty, old_tty;
11496 #if ENABLE_ASH_READ_TIMEOUT
11500 ts.tv_sec = ts.tv_usec = 0;
11505 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11506 while ((i = nextopt("p:rt:n:s")) != '\0')
11507 #elif ENABLE_ASH_READ_NCHARS
11508 while ((i = nextopt("p:rn:s")) != '\0')
11509 #elif ENABLE_ASH_READ_TIMEOUT
11510 while ((i = nextopt("p:rt:")) != '\0')
11512 while ((i = nextopt("p:r")) != '\0')
11517 prompt = optionarg;
11519 #if ENABLE_ASH_READ_NCHARS
11521 nchars = strtol(optionarg, &p, 10);
11523 ash_msg_and_raise_error("invalid count");
11524 nch_flag = (nchars > 0);
11530 #if ENABLE_ASH_READ_TIMEOUT
11532 ts.tv_sec = strtol(optionarg, &p, 10);
11538 ts.tv_usec = strtol(p, &p2, 10);
11540 ash_msg_and_raise_error("invalid timeout");
11542 /* normalize to usec */
11544 ash_msg_and_raise_error("invalid timeout");
11545 while (scale++ < 6)
11549 ash_msg_and_raise_error("invalid timeout");
11551 if ( ! ts.tv_sec && ! ts.tv_usec)
11552 ash_msg_and_raise_error("invalid timeout");
11562 if (prompt && isatty(0)) {
11567 ash_msg_and_raise_error("arg count");
11568 ifs = bltinlookup("IFS");
11571 #if ENABLE_ASH_READ_NCHARS
11572 if (nch_flag || silent) {
11573 tcgetattr(0, &tty);
11576 tty.c_lflag &= ~ICANON;
11577 tty.c_cc[VMIN] = nchars;
11580 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11583 tcsetattr(0, TCSANOW, &tty);
11586 #if ENABLE_ASH_READ_TIMEOUT
11587 if (ts.tv_sec || ts.tv_usec) {
11588 // TODO: replace with poll, it is smaller
11592 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11594 #if ENABLE_ASH_READ_NCHARS
11596 tcsetattr(0, TCSANOW, &old_tty);
11606 #if ENABLE_ASH_READ_NCHARS
11607 while (!nch_flag || nchars--)
11612 if (read(0, &c, 1) != 1) {
11624 if (!rflag && c == '\\') {
11630 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11634 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11636 setvar(*ap, stackblock(), 0);
11645 #if ENABLE_ASH_READ_NCHARS
11646 if (nch_flag || silent)
11647 tcsetattr(0, TCSANOW, &old_tty);
11651 /* Remove trailing blanks */
11652 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11654 setvar(*ap, stackblock(), 0);
11655 while (*++ap != NULL)
11656 setvar(*ap, nullstr, 0);
11661 umaskcmd(int argc, char **argv)
11663 static const char permuser[3] ALIGN1 = "ugo";
11664 static const char permmode[3] ALIGN1 = "rwx";
11665 static const short permmask[] ALIGN2 = {
11666 S_IRUSR, S_IWUSR, S_IXUSR,
11667 S_IRGRP, S_IWGRP, S_IXGRP,
11668 S_IROTH, S_IWOTH, S_IXOTH
11674 int symbolic_mode = 0;
11676 while (nextopt("S") != '\0') {
11687 if (symbolic_mode) {
11691 for (i = 0; i < 3; i++) {
11694 *p++ = permuser[i];
11696 for (j = 0; j < 3; j++) {
11697 if ((mask & permmask[3 * i + j]) == 0) {
11698 *p++ = permmode[j];
11706 out1fmt("%.4o\n", mask);
11709 if (isdigit((unsigned char) *ap)) {
11712 if (*ap >= '8' || *ap < '0')
11713 ash_msg_and_raise_error(illnum, argv[1]);
11714 mask = (mask << 3) + (*ap - '0');
11715 } while (*++ap != '\0');
11718 mask = ~mask & 0777;
11719 if (!bb_parse_mode(ap, &mask)) {
11720 ash_msg_and_raise_error("illegal mode: %s", ap);
11722 umask(~mask & 0777);
11731 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11732 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11733 * ash by J.T. Conklin.
11741 int factor; /* multiply by to get rlim_{cur,max} values */
11745 static const struct limits limits[] = {
11747 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11749 #ifdef RLIMIT_FSIZE
11750 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11753 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11755 #ifdef RLIMIT_STACK
11756 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11759 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11762 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11764 #ifdef RLIMIT_MEMLOCK
11765 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11767 #ifdef RLIMIT_NPROC
11768 { "process", RLIMIT_NPROC, 1, 'p' },
11770 #ifdef RLIMIT_NOFILE
11771 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11774 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11776 #ifdef RLIMIT_LOCKS
11777 { "locks", RLIMIT_LOCKS, 1, 'w' },
11779 { NULL, 0, 0, '\0' }
11782 enum limtype { SOFT = 0x1, HARD = 0x2 };
11785 printlim(enum limtype how, const struct rlimit *limit,
11786 const struct limits *l)
11790 val = limit->rlim_max;
11792 val = limit->rlim_cur;
11794 if (val == RLIM_INFINITY)
11795 out1fmt("unlimited\n");
11798 out1fmt("%lld\n", (long long) val);
11803 ulimitcmd(int argc, char **argv)
11807 enum limtype how = SOFT | HARD;
11808 const struct limits *l;
11811 struct rlimit limit;
11814 while ((optc = nextopt("HSa"
11818 #ifdef RLIMIT_FSIZE
11824 #ifdef RLIMIT_STACK
11833 #ifdef RLIMIT_MEMLOCK
11836 #ifdef RLIMIT_NPROC
11839 #ifdef RLIMIT_NOFILE
11845 #ifdef RLIMIT_LOCKS
11863 for (l = limits; l->option != what; l++)
11866 set = *argptr ? 1 : 0;
11870 if (all || argptr[1])
11871 ash_msg_and_raise_error("too many arguments");
11872 if (strncmp(p, "unlimited\n", 9) == 0)
11873 val = RLIM_INFINITY;
11877 while ((c = *p++) >= '0' && c <= '9') {
11878 val = (val * 10) + (long)(c - '0');
11879 if (val < (rlim_t) 0)
11883 ash_msg_and_raise_error("bad number");
11888 for (l = limits; l->name; l++) {
11889 getrlimit(l->cmd, &limit);
11890 out1fmt("%-20s ", l->name);
11891 printlim(how, &limit, l);
11896 getrlimit(l->cmd, &limit);
11899 limit.rlim_max = val;
11901 limit.rlim_cur = val;
11902 if (setrlimit(l->cmd, &limit) < 0)
11903 ash_msg_and_raise_error("error setting limit (%m)");
11905 printlim(how, &limit, l);
11911 /* ============ Math support */
11913 #if ENABLE_ASH_MATH_SUPPORT
11915 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11917 Permission is hereby granted, free of charge, to any person obtaining
11918 a copy of this software and associated documentation files (the
11919 "Software"), to deal in the Software without restriction, including
11920 without limitation the rights to use, copy, modify, merge, publish,
11921 distribute, sublicense, and/or sell copies of the Software, and to
11922 permit persons to whom the Software is furnished to do so, subject to
11923 the following conditions:
11925 The above copyright notice and this permission notice shall be
11926 included in all copies or substantial portions of the Software.
11928 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11929 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11930 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
11931 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
11932 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11933 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11934 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11937 /* This is my infix parser/evaluator. It is optimized for size, intended
11938 * as a replacement for yacc-based parsers. However, it may well be faster
11939 * than a comparable parser written in yacc. The supported operators are
11940 * listed in #defines below. Parens, order of operations, and error handling
11941 * are supported. This code is thread safe. The exact expression format should
11942 * be that which POSIX specifies for shells. */
11944 /* The code uses a simple two-stack algorithm. See
11945 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
11946 * for a detailed explanation of the infix-to-postfix algorithm on which
11947 * this is based (this code differs in that it applies operators immediately
11948 * to the stack instead of adding them to a queue to end up with an
11951 /* To use the routine, call it with an expression string and error return
11955 * Aug 24, 2001 Manuel Novoa III
11957 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
11959 * 1) In arith_apply():
11960 * a) Cached values of *numptr and &(numptr[-1]).
11961 * b) Removed redundant test for zero denominator.
11964 * a) Eliminated redundant code for processing operator tokens by moving
11965 * to a table-based implementation. Also folded handling of parens
11967 * b) Combined all 3 loops which called arith_apply to reduce generated
11968 * code size at the cost of speed.
11970 * 3) The following expressions were treated as valid by the original code:
11971 * 1() , 0! , 1 ( *3 ) .
11972 * These bugs have been fixed by internally enclosing the expression in
11973 * parens and then checking that all binary ops and right parens are
11974 * preceded by a valid expression (NUM_TOKEN).
11976 * Note: It may be desirable to replace Aaron's test for whitespace with
11977 * ctype's isspace() if it is used by another busybox applet or if additional
11978 * whitespace chars should be considered. Look below the "#include"s for a
11979 * precompiler test.
11983 * Aug 26, 2001 Manuel Novoa III
11985 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
11987 * Merge in Aaron's comments previously posted to the busybox list,
11988 * modified slightly to take account of my changes to the code.
11993 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11995 * - allow access to variable,
11996 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
11997 * - realize assign syntax (VAR=expr, +=, *= etc)
11998 * - realize exponentiation (** operator)
11999 * - realize comma separated - expr, expr
12000 * - realise ++expr --expr expr++ expr--
12001 * - realise expr ? expr : expr (but, second expr calculate always)
12002 * - allow hexadecimal and octal numbers
12003 * - was restored loses XOR operator
12004 * - remove one goto label, added three ;-)
12005 * - protect $((num num)) as true zero expr (Manuel`s error)
12006 * - always use special isspace(), see comment from bash ;-)
12009 #define arith_isspace(arithval) \
12010 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12012 typedef unsigned char operator;
12014 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12015 * precedence, and 3 high bits are an ID unique across operators of that
12016 * precedence. The ID portion is so that multiple operators can have the
12017 * same precedence, ensuring that the leftmost one is evaluated first.
12018 * Consider * and /. */
12020 #define tok_decl(prec,id) (((id)<<5)|(prec))
12021 #define PREC(op) ((op) & 0x1F)
12023 #define TOK_LPAREN tok_decl(0,0)
12025 #define TOK_COMMA tok_decl(1,0)
12027 #define TOK_ASSIGN tok_decl(2,0)
12028 #define TOK_AND_ASSIGN tok_decl(2,1)
12029 #define TOK_OR_ASSIGN tok_decl(2,2)
12030 #define TOK_XOR_ASSIGN tok_decl(2,3)
12031 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12032 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12033 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12034 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12036 #define TOK_MUL_ASSIGN tok_decl(3,0)
12037 #define TOK_DIV_ASSIGN tok_decl(3,1)
12038 #define TOK_REM_ASSIGN tok_decl(3,2)
12040 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12041 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12043 /* conditional is right associativity too */
12044 #define TOK_CONDITIONAL tok_decl(4,0)
12045 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12047 #define TOK_OR tok_decl(5,0)
12049 #define TOK_AND tok_decl(6,0)
12051 #define TOK_BOR tok_decl(7,0)
12053 #define TOK_BXOR tok_decl(8,0)
12055 #define TOK_BAND tok_decl(9,0)
12057 #define TOK_EQ tok_decl(10,0)
12058 #define TOK_NE tok_decl(10,1)
12060 #define TOK_LT tok_decl(11,0)
12061 #define TOK_GT tok_decl(11,1)
12062 #define TOK_GE tok_decl(11,2)
12063 #define TOK_LE tok_decl(11,3)
12065 #define TOK_LSHIFT tok_decl(12,0)
12066 #define TOK_RSHIFT tok_decl(12,1)
12068 #define TOK_ADD tok_decl(13,0)
12069 #define TOK_SUB tok_decl(13,1)
12071 #define TOK_MUL tok_decl(14,0)
12072 #define TOK_DIV tok_decl(14,1)
12073 #define TOK_REM tok_decl(14,2)
12075 /* exponent is right associativity */
12076 #define TOK_EXPONENT tok_decl(15,1)
12078 /* For now unary operators. */
12079 #define UNARYPREC 16
12080 #define TOK_BNOT tok_decl(UNARYPREC,0)
12081 #define TOK_NOT tok_decl(UNARYPREC,1)
12083 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12084 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12086 #define PREC_PRE (UNARYPREC+2)
12088 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12089 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12091 #define PREC_POST (UNARYPREC+3)
12093 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12094 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12096 #define SPEC_PREC (UNARYPREC+4)
12098 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12099 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12101 #define NUMPTR (*numstackptr)
12104 tok_have_assign(operator op)
12106 operator prec = PREC(op);
12108 convert_prec_is_assing(prec);
12109 return (prec == PREC(TOK_ASSIGN) ||
12110 prec == PREC_PRE || prec == PREC_POST);
12114 is_right_associativity(operator prec)
12116 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12117 || prec == PREC(TOK_CONDITIONAL));
12120 typedef struct ARITCH_VAR_NUM {
12122 arith_t contidional_second_val;
12123 char contidional_second_val_initialized;
12124 char *var; /* if NULL then is regular number,
12125 else is variable name */
12128 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12130 struct CHK_VAR_RECURSIVE_LOOPED *next;
12131 } chk_var_recursive_looped_t;
12133 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12136 arith_lookup_val(v_n_t *t)
12139 const char * p = lookupvar(t->var);
12144 /* recursive try as expression */
12145 chk_var_recursive_looped_t *cur;
12146 chk_var_recursive_looped_t cur_save;
12148 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12149 if (strcmp(cur->var, t->var) == 0) {
12150 /* expression recursion loop detected */
12154 /* save current lookuped var name */
12155 cur = prev_chk_var_recursive;
12156 cur_save.var = t->var;
12157 cur_save.next = cur;
12158 prev_chk_var_recursive = &cur_save;
12160 t->val = arith (p, &errcode);
12161 /* restore previous ptr after recursiving */
12162 prev_chk_var_recursive = cur;
12165 /* allow undefined var as 0 */
12171 /* "applying" a token means performing it on the top elements on the integer
12172 * stack. For a unary operator it will only change the top element, but a
12173 * binary operator will pop two arguments and push a result */
12175 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12178 arith_t numptr_val, rez;
12179 int ret_arith_lookup_val;
12181 /* There is no operator that can work without arguments */
12182 if (NUMPTR == numstack) goto err;
12183 numptr_m1 = NUMPTR - 1;
12185 /* check operand is var with noninteger value */
12186 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12187 if (ret_arith_lookup_val)
12188 return ret_arith_lookup_val;
12190 rez = numptr_m1->val;
12191 if (op == TOK_UMINUS)
12193 else if (op == TOK_NOT)
12195 else if (op == TOK_BNOT)
12197 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12199 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12201 else if (op != TOK_UPLUS) {
12202 /* Binary operators */
12204 /* check and binary operators need two arguments */
12205 if (numptr_m1 == numstack) goto err;
12207 /* ... and they pop one */
12210 if (op == TOK_CONDITIONAL) {
12211 if (! numptr_m1->contidional_second_val_initialized) {
12212 /* protect $((expr1 ? expr2)) without ": expr" */
12215 rez = numptr_m1->contidional_second_val;
12216 } else if (numptr_m1->contidional_second_val_initialized) {
12217 /* protect $((expr1 : expr2)) without "expr ? " */
12220 numptr_m1 = NUMPTR - 1;
12221 if (op != TOK_ASSIGN) {
12222 /* check operand is var with noninteger value for not '=' */
12223 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12224 if (ret_arith_lookup_val)
12225 return ret_arith_lookup_val;
12227 if (op == TOK_CONDITIONAL) {
12228 numptr_m1->contidional_second_val = rez;
12230 rez = numptr_m1->val;
12231 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12233 else if (op == TOK_OR)
12234 rez = numptr_val || rez;
12235 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12237 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12239 else if (op == TOK_AND)
12240 rez = rez && numptr_val;
12241 else if (op == TOK_EQ)
12242 rez = (rez == numptr_val);
12243 else if (op == TOK_NE)
12244 rez = (rez != numptr_val);
12245 else if (op == TOK_GE)
12246 rez = (rez >= numptr_val);
12247 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12248 rez >>= numptr_val;
12249 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12250 rez <<= numptr_val;
12251 else if (op == TOK_GT)
12252 rez = (rez > numptr_val);
12253 else if (op == TOK_LT)
12254 rez = (rez < numptr_val);
12255 else if (op == TOK_LE)
12256 rez = (rez <= numptr_val);
12257 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12259 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12261 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12263 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12265 else if (op == TOK_CONDITIONAL_SEP) {
12266 if (numptr_m1 == numstack) {
12267 /* protect $((expr : expr)) without "expr ? " */
12270 numptr_m1->contidional_second_val_initialized = op;
12271 numptr_m1->contidional_second_val = numptr_val;
12272 } else if (op == TOK_CONDITIONAL) {
12274 numptr_val : numptr_m1->contidional_second_val;
12275 } else if (op == TOK_EXPONENT) {
12276 if (numptr_val < 0)
12277 return -3; /* exponent less than 0 */
12282 while (numptr_val--)
12286 } else if (numptr_val==0) /* zero divisor check */
12288 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12290 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12293 if (tok_have_assign(op)) {
12294 char buf[sizeof(arith_t_type)*3 + 2];
12296 if (numptr_m1->var == NULL) {
12300 /* save to shell variable */
12301 #if ENABLE_ASH_MATH_SUPPORT_64
12302 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12304 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12306 setvar(numptr_m1->var, buf, 0);
12307 /* after saving, make previous value for v++ or v-- */
12308 if (op == TOK_POST_INC)
12310 else if (op == TOK_POST_DEC)
12313 numptr_m1->val = rez;
12314 /* protect geting var value, is number now */
12315 numptr_m1->var = NULL;
12321 /* longest must be first */
12322 static const char op_tokens[] ALIGN1 = {
12323 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12324 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12325 '<','<', 0, TOK_LSHIFT,
12326 '>','>', 0, TOK_RSHIFT,
12327 '|','|', 0, TOK_OR,
12328 '&','&', 0, TOK_AND,
12329 '!','=', 0, TOK_NE,
12330 '<','=', 0, TOK_LE,
12331 '>','=', 0, TOK_GE,
12332 '=','=', 0, TOK_EQ,
12333 '|','=', 0, TOK_OR_ASSIGN,
12334 '&','=', 0, TOK_AND_ASSIGN,
12335 '*','=', 0, TOK_MUL_ASSIGN,
12336 '/','=', 0, TOK_DIV_ASSIGN,
12337 '%','=', 0, TOK_REM_ASSIGN,
12338 '+','=', 0, TOK_PLUS_ASSIGN,
12339 '-','=', 0, TOK_MINUS_ASSIGN,
12340 '-','-', 0, TOK_POST_DEC,
12341 '^','=', 0, TOK_XOR_ASSIGN,
12342 '+','+', 0, TOK_POST_INC,
12343 '*','*', 0, TOK_EXPONENT,
12347 '=', 0, TOK_ASSIGN,
12359 '?', 0, TOK_CONDITIONAL,
12360 ':', 0, TOK_CONDITIONAL_SEP,
12361 ')', 0, TOK_RPAREN,
12362 '(', 0, TOK_LPAREN,
12366 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12369 arith(const char *expr, int *perrcode)
12371 char arithval; /* Current character under analysis */
12372 operator lasttok, op;
12375 const char *p = endexpression;
12378 size_t datasizes = strlen(expr) + 2;
12380 /* Stack of integers */
12381 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12382 * in any given correct or incorrect expression is left as an exercise to
12384 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12385 *numstackptr = numstack;
12386 /* Stack of operator tokens */
12387 operator *stack = alloca((datasizes) * sizeof(operator)),
12390 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12391 *perrcode = errcode = 0;
12395 if (arithval == 0) {
12396 if (p == endexpression) {
12397 /* Null expression. */
12401 /* This is only reached after all tokens have been extracted from the
12402 * input stream. If there are still tokens on the operator stack, they
12403 * are to be applied in order. At the end, there should be a final
12404 * result on the integer stack */
12406 if (expr != endexpression + 1) {
12407 /* If we haven't done so already, */
12408 /* append a closing right paren */
12409 expr = endexpression;
12410 /* and let the loop process it. */
12413 /* At this point, we're done with the expression. */
12414 if (numstackptr != numstack+1) {
12415 /* ... but if there isn't, it's bad */
12417 return (*perrcode = -1);
12419 if (numstack->var) {
12420 /* expression is $((var)) only, lookup now */
12421 errcode = arith_lookup_val(numstack);
12424 *perrcode = errcode;
12425 return numstack->val;
12428 /* Continue processing the expression. */
12429 if (arith_isspace(arithval)) {
12430 /* Skip whitespace */
12433 p = endofname(expr);
12435 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12437 numstackptr->var = alloca(var_name_size);
12438 safe_strncpy(numstackptr->var, expr, var_name_size);
12441 numstackptr->contidional_second_val_initialized = 0;
12446 if (isdigit(arithval)) {
12447 numstackptr->var = NULL;
12448 #if ENABLE_ASH_MATH_SUPPORT_64
12449 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12451 numstackptr->val = strtol(expr, (char **) &expr, 0);
12455 for (p = op_tokens; ; p++) {
12459 /* strange operator not found */
12462 for (o = expr; *p && *o == *p; p++)
12469 /* skip tail uncompared token */
12472 /* skip zero delim */
12477 /* post grammar: a++ reduce to num */
12478 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12481 /* Plus and minus are binary (not unary) _only_ if the last
12482 * token was as number, or a right paren (which pretends to be
12483 * a number, since it evaluates to one). Think about it.
12484 * It makes sense. */
12485 if (lasttok != TOK_NUM) {
12501 /* We don't want a unary operator to cause recursive descent on the
12502 * stack, because there can be many in a row and it could cause an
12503 * operator to be evaluated before its argument is pushed onto the
12504 * integer stack. */
12505 /* But for binary operators, "apply" everything on the operator
12506 * stack until we find an operator with a lesser priority than the
12507 * one we have just extracted. */
12508 /* Left paren is given the lowest priority so it will never be
12509 * "applied" in this way.
12510 * if associativity is right and priority eq, applied also skip
12513 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12514 /* not left paren or unary */
12515 if (lasttok != TOK_NUM) {
12516 /* binary op must be preceded by a num */
12519 while (stackptr != stack) {
12520 if (op == TOK_RPAREN) {
12521 /* The algorithm employed here is simple: while we don't
12522 * hit an open paren nor the bottom of the stack, pop
12523 * tokens and apply them */
12524 if (stackptr[-1] == TOK_LPAREN) {
12526 /* Any operator directly after a */
12528 /* close paren should consider itself binary */
12532 operator prev_prec = PREC(stackptr[-1]);
12534 convert_prec_is_assing(prec);
12535 convert_prec_is_assing(prev_prec);
12536 if (prev_prec < prec)
12538 /* check right assoc */
12539 if (prev_prec == prec && is_right_associativity(prec))
12542 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12543 if (errcode) goto ret;
12545 if (op == TOK_RPAREN) {
12550 /* Push this operator to the stack and remember it. */
12551 *stackptr++ = lasttok = op;
12556 #endif /* ASH_MATH_SUPPORT */
12559 /* ============ main() and helpers */
12562 * Called to exit the shell.
12564 static void exitshell(void) ATTRIBUTE_NORETURN;
12572 status = exitstatus;
12573 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12574 if (setjmp(loc.loc)) {
12575 if (exception == EXEXIT)
12576 /* dash bug: it just does _exit(exitstatus) here
12577 * but we have to do setjobctl(0) first!
12578 * (bug is still not fixed in dash-0.5.3 - if you run dash
12579 * under Midnight Commander, on exit from dash MC is backgrounded) */
12580 status = exitstatus;
12583 exception_handler = &loc;
12589 flush_stdout_stderr();
12599 /* from input.c: */
12600 basepf.nextc = basepf.buf = basebuf;
12603 signal(SIGCHLD, SIG_DFL);
12608 char ppid[sizeof(int)*3 + 1];
12610 struct stat st1, st2;
12613 for (envp = environ; envp && *envp; envp++) {
12614 if (strchr(*envp, '=')) {
12615 setvareq(*envp, VEXPORT|VTEXTFIXED);
12619 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12620 setvar("PPID", ppid, 0);
12622 p = lookupvar("PWD");
12624 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12625 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12632 * Process the shell command line arguments.
12635 procargs(int argc, char **argv)
12638 const char *xminusc;
12645 for (i = 0; i < NOPTS; i++)
12651 if (*xargv == NULL) {
12653 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12656 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12660 for (i = 0; i < NOPTS; i++)
12661 if (optlist[i] == 2)
12666 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12671 } else if (!sflag) {
12672 setinputfile(*xargv, 0);
12675 commandname = arg0;
12678 shellparam.p = xargv;
12679 #if ENABLE_ASH_GETOPTS
12680 shellparam.optind = 1;
12681 shellparam.optoff = -1;
12683 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12685 shellparam.nparam++;
12692 * Read /etc/profile or .profile.
12695 read_profile(const char *name)
12699 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12708 * This routine is called when an error or an interrupt occurs in an
12709 * interactive shell and control is returned to the main command loop.
12717 /* from input.c: */
12718 parselleft = parsenleft = 0; /* clear input buffer */
12720 /* from parser.c: */
12723 /* from redir.c: */
12728 static short profile_buf[16384];
12729 extern int etext();
12733 * Main routine. We initialize things, parse the arguments, execute
12734 * profiles if we're a login shell, and then call cmdloop to execute
12735 * commands. The setjmp call sets up the location to jump to when an
12736 * exception occurs. When an exception occurs the variable "state"
12737 * is used to figure out how far we had gotten.
12739 int ash_main(int argc, char **argv);
12740 int ash_main(int argc, char **argv)
12743 volatile int state;
12744 struct jmploc jmploc;
12745 struct stackmark smark;
12748 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12751 #if ENABLE_FEATURE_EDITING
12752 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12755 if (setjmp(jmploc.loc)) {
12765 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12769 outcslow('\n', stderr);
12771 popstackmark(&smark);
12772 FORCE_INT_ON; /* enable interrupts */
12781 exception_handler = &jmploc;
12784 trace_puts("Shell args: ");
12785 trace_puts_args(argv);
12787 rootpid = getpid();
12789 #if ENABLE_ASH_RANDOM_SUPPORT
12790 rseed = rootpid + time(NULL);
12793 setstackmark(&smark);
12794 procargs(argc, argv);
12795 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12797 const char *hp = lookupvar("HISTFILE");
12800 hp = lookupvar("HOME");
12802 char *defhp = concat_path_file(hp, ".ash_history");
12803 setvar("HISTFILE", defhp, 0);
12809 if (argv[0] && argv[0][0] == '-')
12813 read_profile("/etc/profile");
12816 read_profile(".profile");
12822 getuid() == geteuid() && getgid() == getegid() &&
12826 shinit = lookupvar("ENV");
12827 if (shinit != NULL && *shinit != '\0') {
12828 read_profile(shinit);
12834 evalstring(minusc, 0);
12836 if (sflag || minusc == NULL) {
12837 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12839 const char *hp = lookupvar("HISTFILE");
12842 line_input_state->hist_file = hp;
12845 state4: /* XXX ??? - why isn't this before the "if" statement */
12853 extern void _mcleanup(void);
12862 const char *applet_name = "debug stuff usage";
12863 int main(int argc, char **argv)
12865 return ash_main(argc, argv);
12871 * Copyright (c) 1989, 1991, 1993, 1994
12872 * The Regents of the University of California. All rights reserved.
12874 * This code is derived from software contributed to Berkeley by
12875 * Kenneth Almquist.
12877 * Redistribution and use in source and binary forms, with or without
12878 * modification, are permitted provided that the following conditions
12880 * 1. Redistributions of source code must retain the above copyright
12881 * notice, this list of conditions and the following disclaimer.
12882 * 2. Redistributions in binary form must reproduce the above copyright
12883 * notice, this list of conditions and the following disclaimer in the
12884 * documentation and/or other materials provided with the distribution.
12885 * 3. Neither the name of the University nor the names of its contributors
12886 * may be used to endorse or promote products derived from this software
12887 * without specific prior written permission.
12889 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12890 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12891 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12892 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12893 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12894 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12895 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12896 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12897 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12898 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF