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
60 #if JOBS || ENABLE_ASH_READ_NCHARS
64 #if defined(__uClinux__)
65 #error "Do not even bother, ash will not run on uClinux"
69 /* ============ Misc helpers */
71 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
73 /* C99 say: "char" declaration may be signed or unsigned default */
74 #define signed_char2int(sc) ((int)((signed char)sc))
77 /* ============ Shell options */
79 static const char *const optletters_optnames[] = {
100 #define optletters(n) optletters_optnames[(n)][0]
101 #define optnames(n) (&optletters_optnames[(n)][1])
103 #define NOPTS (sizeof(optletters_optnames)/sizeof(optletters_optnames[0]))
105 static char optlist[NOPTS];
107 #define eflag optlist[0]
108 #define fflag optlist[1]
109 #define Iflag optlist[2]
110 #define iflag optlist[3]
111 #define mflag optlist[4]
112 #define nflag optlist[5]
113 #define sflag optlist[6]
114 #define xflag optlist[7]
115 #define vflag optlist[8]
116 #define Cflag optlist[9]
117 #define aflag optlist[10]
118 #define bflag optlist[11]
119 #define uflag optlist[12]
120 #define viflag optlist[13]
122 #define nolog optlist[14]
123 #define debug optlist[15]
127 /* ============ Misc data */
131 static int *dash_errno;
133 #define errno (*dash_errno)
136 static char nullstr[1]; /* zero length string */
137 static const char homestr[] = "HOME";
138 static const char snlfmt[] = "%s\n";
139 static const char illnum[] = "Illegal number: %s";
141 static char *minusc; /* argument to -c option */
143 static int isloginsh;
144 /* pid of main shell */
146 /* shell level: 0 for the main shell, 1 for its children, and so on */
148 #define rootshell (!shlvl)
149 /* trap handler commands */
150 static char *trap[NSIG];
151 /* current value of signal */
152 static char sigmode[NSIG - 1];
153 /* indicates specified signal received */
154 static char gotsig[NSIG - 1];
155 static char *arg0; /* value of $0 */
158 /* ============ Interrupts / exceptions
160 * We enclose jmp_buf in a structure so that we can declare pointers to
161 * jump locations. The global variable handler contains the location to
162 * jump to when an exception occurs, and the global variable exception
163 * contains a code identifying the exception. To implement nested
164 * exception handlers, the user should save the value of handler on entry
165 * to an inner scope, set handler to point to a jmploc structure for the
166 * inner scope, and restore handler on exit from the scope.
171 static struct jmploc *exception_handler;
172 static int exception;
174 #define EXINT 0 /* SIGINT received */
175 #define EXERROR 1 /* a generic error */
176 #define EXSHELLPROC 2 /* execute a shell procedure */
177 #define EXEXEC 3 /* command execution failed */
178 #define EXEXIT 4 /* exit the shell */
179 #define EXSIG 5 /* trapped signal in wait(1) */
180 static volatile int suppressint;
181 static volatile sig_atomic_t intpending;
182 /* do we generate EXSIG events */
184 /* last pending signal */
185 static volatile sig_atomic_t pendingsigs;
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
197 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
200 * These macros allow the user to suspend the handling of interrupt signals
201 * over a period of time. This is similar to SIGHOLD to or sigblock, but
202 * much more efficient and portable. (But hacking the kernel is so much
203 * more fun than worrying about efficiency and portability. :-))
212 * Called to raise an exception. Since C doesn't include exceptions, we
213 * just do a longjmp to the exception handler. The type of exception is
214 * stored in the global variable "exception".
216 static void raise_exception(int) ATTRIBUTE_NORETURN;
218 raise_exception(int e)
221 if (exception_handler == NULL)
226 longjmp(exception_handler->loc, 1);
230 * Called from trap.c when a SIGINT is received. (If the user specifies
231 * that SIGINT is to be trapped or ignored using the trap builtin, then
232 * this routine is not called.) Suppressint is nonzero when interrupts
233 * are held using the INT_OFF macro. (The test for iflag is just
234 * defensive programming.)
236 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
238 raise_interrupt(void)
244 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
245 if (!(rootshell && iflag)) {
246 signal(SIGINT, SIG_DFL);
255 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
259 if (--suppressint == 0 && intpending) {
263 #define INT_ON int_on()
271 #define FORCE_INT_ON force_int_on()
276 if (--suppressint == 0 && intpending) \
279 #define FORCE_INT_ON \
286 #endif /* ASH_OPTIMIZE_FOR_SIZE */
288 #define SAVE_INT(v) ((v) = suppressint)
290 #define RESTORE_INT(v) \
294 if (suppressint == 0 && intpending) \
303 raise_exception(EXSIG); \
305 /* EXSIG is turned off by evalbltin(). */
308 * Ignore a signal. Only one usage site - in forkchild()
313 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
314 signal(signo, SIG_IGN);
316 sigmode[signo - 1] = S_HARD_IGN;
320 * Signal handler. Only one usage site - in setsignal()
325 gotsig[signo - 1] = 1;
328 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
336 /* ============ Stdout/stderr output */
339 outstr(const char *p, FILE *file)
347 flush_stdout_stderr(void)
364 outcslow(int c, FILE *dest)
372 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
374 out1fmt(const char *fmt, ...)
381 r = vprintf(fmt, ap);
387 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
389 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
396 ret = vsnprintf(outbuf, length, fmt, ap);
403 out1str(const char *p)
409 out2str(const char *p)
416 /* ============ Parser structures */
418 /* control characters in argument strings */
419 #define CTLESC '\201' /* escape next character */
420 #define CTLVAR '\202' /* variable defn */
421 #define CTLENDVAR '\203'
422 #define CTLBACKQ '\204'
423 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
424 /* CTLBACKQ | CTLQUOTE == '\205' */
425 #define CTLARI '\206' /* arithmetic expression */
426 #define CTLENDARI '\207'
427 #define CTLQUOTEMARK '\210'
429 /* variable substitution byte (follows CTLVAR) */
430 #define VSTYPE 0x0f /* type of variable substitution */
431 #define VSNUL 0x10 /* colon--treat the empty string as unset */
432 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
434 /* values of VSTYPE field */
435 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
436 #define VSMINUS 0x2 /* ${var-text} */
437 #define VSPLUS 0x3 /* ${var+text} */
438 #define VSQUESTION 0x4 /* ${var?message} */
439 #define VSASSIGN 0x5 /* ${var=text} */
440 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
441 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
442 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
443 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
444 #define VSLENGTH 0xa /* ${#var} */
446 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
481 union node *redirect;
487 struct nodelist *cmdlist;
493 union node *redirect;
506 union node *elsepart;
533 struct nodelist *backquote;
568 struct nredir nredir;
569 struct nbinary nbinary;
573 struct nclist nclist;
582 struct nodelist *next;
595 freefunc(struct funcnode *f)
597 if (f && --f->count < 0)
602 /* ============ Debugging output */
606 static FILE *tracefile;
609 trace_printf(const char *fmt, ...)
616 vfprintf(tracefile, fmt, va);
621 trace_vprintf(const char *fmt, va_list va)
625 vfprintf(tracefile, fmt, va);
629 trace_puts(const char *s)
637 trace_puts_quoted(char *s)
644 putc('"', tracefile);
645 for (p = s; *p; p++) {
647 case '\n': c = 'n'; goto backslash;
648 case '\t': c = 't'; goto backslash;
649 case '\r': c = 'r'; goto backslash;
650 case '"': c = '"'; goto backslash;
651 case '\\': c = '\\'; goto backslash;
652 case CTLESC: c = 'e'; goto backslash;
653 case CTLVAR: c = 'v'; goto backslash;
654 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
655 case CTLBACKQ: c = 'q'; goto backslash;
656 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
658 putc('\\', tracefile);
662 if (*p >= ' ' && *p <= '~')
665 putc('\\', tracefile);
666 putc(*p >> 6 & 03, tracefile);
667 putc(*p >> 3 & 07, tracefile);
668 putc(*p & 07, tracefile);
673 putc('"', tracefile);
677 trace_puts_args(char **ap)
684 trace_puts_quoted(*ap);
686 putc('\n', tracefile);
689 putc(' ', tracefile);
704 /* leave open because libedit might be using it */
707 strcpy(s, "./trace");
709 if (!freopen(s, "a", tracefile)) {
710 fprintf(stderr, "Can't re-open %s\n", s);
715 tracefile = fopen(s, "a");
716 if (tracefile == NULL) {
717 fprintf(stderr, "Can't open %s\n", s);
723 flags = fcntl(fileno(tracefile), F_GETFL, 0);
725 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
727 setlinebuf(tracefile);
728 fputs("\nTracing started.\n", tracefile);
732 indent(int amount, char *pfx, FILE *fp)
736 for (i = 0; i < amount; i++) {
737 if (pfx && i == amount - 1)
743 /* little circular references here... */
744 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
747 sharg(union node *arg, FILE *fp)
750 struct nodelist *bqlist;
753 if (arg->type != NARG) {
754 out1fmt("<node type %d>\n", arg->type);
757 bqlist = arg->narg.backquote;
758 for (p = arg->narg.text; *p; p++) {
767 if (subtype == VSLENGTH)
776 switch (subtype & VSTYPE) {
809 out1fmt("<subtype %d>", subtype);
816 case CTLBACKQ|CTLQUOTE:
819 shtree(bqlist->n, -1, NULL, fp);
830 shcmd(union node *cmd, FILE *fp)
838 for (np = cmd->ncmd.args; np; np = np->narg.next) {
844 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
847 switch (np->nfile.type) {
848 case NTO: s = ">"; dftfd = 1; break;
849 case NCLOBBER: s = ">|"; dftfd = 1; break;
850 case NAPPEND: s = ">>"; dftfd = 1; break;
851 case NTOFD: s = ">&"; dftfd = 1; break;
852 case NFROM: s = "<"; dftfd = 0; break;
853 case NFROMFD: s = "<&"; dftfd = 0; break;
854 case NFROMTO: s = "<>"; dftfd = 0; break;
855 default: s = "*error*"; dftfd = 0; break;
857 if (np->nfile.fd != dftfd)
858 fprintf(fp, "%d", np->nfile.fd);
860 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
861 fprintf(fp, "%d", np->ndup.dupfd);
863 sharg(np->nfile.fname, fp);
870 shtree(union node *n, int ind, char *pfx, FILE *fp)
878 indent(ind, pfx, fp);
889 shtree(n->nbinary.ch1, ind, NULL, fp);
892 shtree(n->nbinary.ch2, ind, NULL, fp);
900 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
905 if (n->npipe.backgnd)
911 fprintf(fp, "<node type %d>", n->type);
919 showtree(union node *n)
921 trace_puts("showtree called\n");
922 shtree(n, 1, NULL, stdout);
925 #define TRACE(param) trace_printf param
926 #define TRACEV(param) trace_vprintf param
931 #define TRACEV(param)
936 /* ============ Parser data */
939 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
942 struct strlist *next;
951 struct strpush *prev; /* preceding string on stack */
955 struct alias *ap; /* if push was associated with an alias */
957 char *string; /* remember the string since it may change */
961 struct parsefile *prev; /* preceding file on stack */
962 int linno; /* current line */
963 int fd; /* file descriptor (or -1 if string) */
964 int nleft; /* number of chars left in this line */
965 int lleft; /* number of chars left in this buffer */
966 char *nextc; /* next char in buffer */
967 char *buf; /* input buffer */
968 struct strpush *strpush; /* for pushing strings at this level */
969 struct strpush basestrpush; /* so pushing one is fast */
972 static struct parsefile basepf; /* top level input file */
973 static struct parsefile *parsefile = &basepf; /* current input file */
974 static int startlinno; /* line # where last token started */
975 static char *commandname; /* currently executing command */
976 static struct strlist *cmdenviron; /* environment for builtin command */
977 static int exitstatus; /* exit status of last command */
980 /* ============ Message printing */
983 ash_vmsg(const char *msg, va_list ap)
985 fprintf(stderr, "%s: ", arg0);
987 const char *fmt = (!iflag || parsefile->fd) ?
989 fprintf(stderr, fmt, commandname, startlinno);
991 vfprintf(stderr, msg, ap);
992 outcslow('\n', stderr);
996 * Exverror is called to raise the error exception. If the second argument
997 * is not NULL then error prints an error message using printf style
998 * formatting. It then raises the error exception.
1000 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1002 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1006 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1008 TRACE(("\") pid=%d\n", getpid()));
1010 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1015 flush_stdout_stderr();
1016 raise_exception(cond);
1020 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1022 ash_msg_and_raise_error(const char *msg, ...)
1027 ash_vmsg_and_raise(EXERROR, msg, ap);
1032 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1034 ash_msg_and_raise(int cond, const char *msg, ...)
1039 ash_vmsg_and_raise(cond, msg, ap);
1045 * error/warning routines for external builtins
1048 ash_msg(const char *fmt, ...)
1058 * Return a string describing an error. The returned string may be a
1059 * pointer to a static buffer that will be overwritten on the next call.
1060 * Action describes the operation that got the error.
1063 errmsg(int e, const char *em)
1065 if (e == ENOENT || e == ENOTDIR) {
1072 /* ============ Memory allocation */
1075 * It appears that grabstackstr() will barf with such alignments
1076 * because stalloc() will return a string allocated in a new stackblock.
1078 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1080 /* Most machines require the value returned from malloc to be aligned
1081 * in some way. The following macro will get this right
1082 * on many machines. */
1083 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1084 /* Minimum size of a block */
1085 MINSIZE = SHELL_ALIGN(504),
1088 struct stack_block {
1089 struct stack_block *prev;
1090 char space[MINSIZE];
1094 struct stack_block *stackp;
1097 struct stackmark *marknext;
1100 static struct stack_block stackbase;
1101 static struct stack_block *stackp = &stackbase;
1102 static struct stackmark *markp;
1103 static char *stacknxt = stackbase.space;
1104 static size_t stacknleft = MINSIZE;
1105 static char *sstrend = stackbase.space + MINSIZE;
1106 static int herefd = -1;
1108 #define stackblock() ((void *)stacknxt)
1109 #define stackblocksize() stacknleft
1112 ckrealloc(void * p, size_t nbytes)
1114 p = realloc(p, nbytes);
1116 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1121 ckmalloc(size_t nbytes)
1123 return ckrealloc(NULL, nbytes);
1127 * Make a copy of a string in safe storage.
1130 ckstrdup(const char *s)
1132 char *p = strdup(s);
1134 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1139 * Parse trees for commands are allocated in lifo order, so we use a stack
1140 * to make this more efficient, and also to avoid all sorts of exception
1141 * handling code to handle interrupts in the middle of a parse.
1143 * The size 504 was chosen because the Ultrix malloc handles that size
1147 stalloc(size_t nbytes)
1152 aligned = SHELL_ALIGN(nbytes);
1153 if (aligned > stacknleft) {
1156 struct stack_block *sp;
1158 blocksize = aligned;
1159 if (blocksize < MINSIZE)
1160 blocksize = MINSIZE;
1161 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1162 if (len < blocksize)
1163 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1167 stacknxt = sp->space;
1168 stacknleft = blocksize;
1169 sstrend = stacknxt + blocksize;
1174 stacknxt += aligned;
1175 stacknleft -= aligned;
1183 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1184 write(2, "stunalloc\n", 10);
1188 stacknleft += stacknxt - (char *)p;
1193 * Like strdup but works with the ash stack.
1196 ststrdup(const char *p)
1198 size_t len = strlen(p) + 1;
1199 return memcpy(stalloc(len), p, len);
1203 setstackmark(struct stackmark *mark)
1205 mark->stackp = stackp;
1206 mark->stacknxt = stacknxt;
1207 mark->stacknleft = stacknleft;
1208 mark->marknext = markp;
1213 popstackmark(struct stackmark *mark)
1215 struct stack_block *sp;
1218 markp = mark->marknext;
1219 while (stackp != mark->stackp) {
1224 stacknxt = mark->stacknxt;
1225 stacknleft = mark->stacknleft;
1226 sstrend = mark->stacknxt + mark->stacknleft;
1231 * When the parser reads in a string, it wants to stick the string on the
1232 * stack and only adjust the stack pointer when it knows how big the
1233 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1234 * of space on top of the stack and stackblocklen returns the length of
1235 * this block. Growstackblock will grow this space by at least one byte,
1236 * possibly moving it (like realloc). Grabstackblock actually allocates the
1237 * part of the block that has been used.
1240 growstackblock(void)
1244 newlen = stacknleft * 2;
1245 if (newlen < stacknleft)
1246 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1250 if (stacknxt == stackp->space && stackp != &stackbase) {
1251 struct stack_block *oldstackp;
1252 struct stackmark *xmark;
1253 struct stack_block *sp;
1254 struct stack_block *prevstackp;
1260 prevstackp = sp->prev;
1261 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1262 sp = ckrealloc(sp, grosslen);
1263 sp->prev = prevstackp;
1265 stacknxt = sp->space;
1266 stacknleft = newlen;
1267 sstrend = sp->space + newlen;
1270 * Stack marks pointing to the start of the old block
1271 * must be relocated to point to the new block
1274 while (xmark != NULL && xmark->stackp == oldstackp) {
1275 xmark->stackp = stackp;
1276 xmark->stacknxt = stacknxt;
1277 xmark->stacknleft = stacknleft;
1278 xmark = xmark->marknext;
1282 char *oldspace = stacknxt;
1283 int oldlen = stacknleft;
1284 char *p = stalloc(newlen);
1286 /* free the space we just allocated */
1287 stacknxt = memcpy(p, oldspace, oldlen);
1288 stacknleft += newlen;
1293 grabstackblock(size_t len)
1295 len = SHELL_ALIGN(len);
1301 * The following routines are somewhat easier to use than the above.
1302 * The user declares a variable of type STACKSTR, which may be declared
1303 * to be a register. The macro STARTSTACKSTR initializes things. Then
1304 * the user uses the macro STPUTC to add characters to the string. In
1305 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1306 * grown as necessary. When the user is done, she can just leave the
1307 * string there and refer to it using stackblock(). Or she can allocate
1308 * the space for it using grabstackstr(). If it is necessary to allow
1309 * someone else to use the stack temporarily and then continue to grow
1310 * the string, the user should use grabstack to allocate the space, and
1311 * then call ungrabstr(p) to return to the previous mode of operation.
1313 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1314 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1315 * is space for at least one character.
1320 size_t len = stackblocksize();
1321 if (herefd >= 0 && len >= 1024) {
1322 full_write(herefd, stackblock(), len);
1323 return stackblock();
1326 return stackblock() + len;
1330 * Called from CHECKSTRSPACE.
1333 makestrspace(size_t newlen, char *p)
1335 size_t len = p - stacknxt;
1336 size_t size = stackblocksize();
1341 size = stackblocksize();
1343 if (nleft >= newlen)
1347 return stackblock() + len;
1351 stack_nputstr(const char *s, size_t n, char *p)
1353 p = makestrspace(n, p);
1354 p = memcpy(p, s, n) + n;
1359 stack_putstr(const char *s, char *p)
1361 return stack_nputstr(s, strlen(s), p);
1365 _STPUTC(int c, char *p)
1373 #define STARTSTACKSTR(p) ((p) = stackblock())
1374 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1375 #define CHECKSTRSPACE(n, p) \
1379 size_t m = sstrend - q; \
1381 (p) = makestrspace(l, q); \
1383 #define USTPUTC(c, p) (*p++ = (c))
1384 #define STACKSTRNUL(p) \
1386 if ((p) == sstrend) \
1387 p = growstackstr(); \
1390 #define STUNPUTC(p) (--p)
1391 #define STTOPC(p) (p[-1])
1392 #define STADJUST(amount, p) (p += (amount))
1394 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1395 #define ungrabstackstr(s, p) stunalloc((s))
1396 #define stackstrend() ((void *)sstrend)
1399 /* ============ String helpers */
1402 * prefix -- see if pfx is a prefix of string.
1405 prefix(const char *string, const char *pfx)
1408 if (*pfx++ != *string++)
1411 return (char *) string;
1415 * Check for a valid number. This should be elsewhere.
1418 is_number(const char *p)
1423 } while (*++p != '\0');
1428 * Convert a string of digits to an integer, printing an error message on
1432 number(const char *s)
1435 ash_msg_and_raise_error(illnum, s);
1440 * Produce a possibly single quoted string suitable as input to the shell.
1441 * The return string is allocated on the stack.
1444 single_quote(const char *s)
1454 len = strchrnul(s, '\'') - s;
1456 q = p = makestrspace(len + 3, p);
1459 q = memcpy(q, s, len) + len;
1465 len = strspn(s, "'");
1469 q = p = makestrspace(len + 3, p);
1472 q = memcpy(q, s, len) + len;
1481 return stackblock();
1485 /* ============ nextopt */
1487 static char **argptr; /* argument list for builtin commands */
1488 static char *optionarg; /* set by nextopt (like getopt) */
1489 static char *optptr; /* used by nextopt */
1492 * XXX - should get rid of. have all builtins use getopt(3). the
1493 * library getopt must have the BSD extension static variable "optreset"
1494 * otherwise it can't be used within the shell safely.
1496 * Standard option processing (a la getopt) for builtin routines. The
1497 * only argument that is passed to nextopt is the option string; the
1498 * other arguments are unnecessary. It return the character, or '\0' on
1502 nextopt(const char *optstring)
1509 if (p == NULL || *p == '\0') {
1511 if (p == NULL || *p != '-' || *++p == '\0')
1514 if (LONE_DASH(p)) /* check for "--" */
1518 for (q = optstring; *q != c; ) {
1520 ash_msg_and_raise_error("Illegal option -%c", c);
1525 if (*p == '\0' && (p = *argptr++) == NULL)
1526 ash_msg_and_raise_error("No arg for -%c option", c);
1535 /* ============ Math support definitions */
1537 #if ENABLE_ASH_MATH_SUPPORT_64
1538 typedef int64_t arith_t;
1539 #define arith_t_type long long
1541 typedef long arith_t;
1542 #define arith_t_type long
1545 #if ENABLE_ASH_MATH_SUPPORT
1546 static arith_t dash_arith(const char *);
1547 static arith_t arith(const char *expr, int *perrcode);
1550 #if ENABLE_ASH_RANDOM_SUPPORT
1551 static unsigned long rseed;
1558 /* ============ Shell variables */
1561 #define VEXPORT 0x01 /* variable is exported */
1562 #define VREADONLY 0x02 /* variable cannot be modified */
1563 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1564 #define VTEXTFIXED 0x08 /* text is statically allocated */
1565 #define VSTACK 0x10 /* text is allocated on the stack */
1566 #define VUNSET 0x20 /* the variable is not set */
1567 #define VNOFUNC 0x40 /* don't call the callback function */
1568 #define VNOSET 0x80 /* do not set variable - just readonly test */
1569 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1571 # define VDYNAMIC 0x200 /* dynamic variable */
1576 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
1578 static const char defifsvar[] = "IFS= \t\n";
1579 #define defifs (defifsvar + 4)
1581 static const char defifs[] = " \t\n";
1585 int nparam; /* # of positional parameters (without $0) */
1586 unsigned char malloc; /* if parameter list dynamically allocated */
1587 char **p; /* parameter list */
1588 #if ENABLE_ASH_GETOPTS
1589 int optind; /* next parameter to be processed by getopts */
1590 int optoff; /* used by getopts */
1594 static struct shparam shellparam; /* $@ current positional parameters */
1597 * Free the list of positional parameters.
1600 freeparam(volatile struct shparam *param)
1604 if (param->malloc) {
1605 for (ap = param->p; *ap; ap++)
1611 #if ENABLE_ASH_GETOPTS
1613 getoptsreset(const char *value)
1615 shellparam.optind = number(value);
1616 shellparam.optoff = -1;
1621 struct var *next; /* next entry in hash list */
1622 int flags; /* flags are defined above */
1623 const char *text; /* name=value */
1624 void (*func)(const char *); /* function to be called when */
1625 /* the variable gets set/unset */
1629 struct localvar *next; /* next local variable in list */
1630 struct var *vp; /* the variable that was made local */
1631 int flags; /* saved flags */
1632 const char *text; /* saved text */
1635 /* Forward decls for varinit[] */
1636 #if ENABLE_LOCALE_SUPPORT
1638 change_lc_all(const char *value)
1640 if (value && *value != '\0')
1641 setlocale(LC_ALL, value);
1644 change_lc_ctype(const char *value)
1646 if (value && *value != '\0')
1647 setlocale(LC_CTYPE, value);
1651 static void chkmail(void);
1652 static void changemail(const char *);
1654 static void changepath(const char *);
1655 #if ENABLE_ASH_RANDOM_SUPPORT
1656 static void change_random(const char *);
1659 static struct var varinit[] = {
1661 { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
1663 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
1666 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1667 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1669 { NULL, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
1670 { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
1671 { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
1672 { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
1673 #if ENABLE_ASH_GETOPTS
1674 { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1676 #if ENABLE_ASH_RANDOM_SUPPORT
1677 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1679 #if ENABLE_LOCALE_SUPPORT
1680 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1681 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1683 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1684 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1688 #define vifs varinit[0]
1690 #define vmail (&vifs)[1]
1691 #define vmpath (&vmail)[1]
1695 #define vpath (&vmpath)[1]
1696 #define vps1 (&vpath)[1]
1697 #define vps2 (&vps1)[1]
1698 #define vps4 (&vps2)[1]
1699 #define voptind (&vps4)[1]
1700 #if ENABLE_ASH_GETOPTS
1701 #define vrandom (&voptind)[1]
1703 #define vrandom (&vps4)[1]
1705 #define defpath (defpathvar + 5)
1708 * The following macros access the values of the above variables.
1709 * They have to skip over the name. They return the null string
1710 * for unset variables.
1712 #define ifsval() (vifs.text + 4)
1713 #define ifsset() ((vifs.flags & VUNSET) == 0)
1714 #define mailval() (vmail.text + 5)
1715 #define mpathval() (vmpath.text + 9)
1716 #define pathval() (vpath.text + 5)
1717 #define ps1val() (vps1.text + 4)
1718 #define ps2val() (vps2.text + 4)
1719 #define ps4val() (vps4.text + 4)
1720 #define optindval() (voptind.text + 7)
1722 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1725 * The parsefile structure pointed to by the global variable parsefile
1726 * contains information about the current file being read.
1729 struct redirtab *next;
1734 static struct redirtab *redirlist;
1735 static int nullredirs;
1736 extern char **environ;
1737 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1741 static struct var *vartab[VTABSIZE];
1743 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1744 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1747 * Return of a legal variable name (a letter or underscore followed by zero or
1748 * more letters, underscores, and digits).
1751 endofname(const char *name)
1759 if (!is_in_name(*p))
1766 * Compares two strings up to the first = or '\0'. The first
1767 * string must be terminated by '='; the second may be terminated by
1768 * either '=' or '\0'.
1771 varcmp(const char *p, const char *q)
1775 while ((c = *p) == (d = *q)) {
1790 varequal(const char *a, const char *b)
1792 return !varcmp(a, b);
1796 * Find the appropriate entry in the hash table from the name.
1798 static struct var **
1799 hashvar(const char *p)
1803 hashval = ((unsigned char) *p) << 4;
1804 while (*p && *p != '=')
1805 hashval += (unsigned char) *p++;
1806 return &vartab[hashval % VTABSIZE];
1810 vpcmp(const void *a, const void *b)
1812 return varcmp(*(const char **)a, *(const char **)b);
1816 * This routine initializes the builtin variables.
1826 * PS1 depends on uid
1828 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1829 vps1.text = "PS1=\\w \\$ ";
1832 vps1.text = "PS1=# ";
1835 end = vp + sizeof(varinit) / sizeof(varinit[0]);
1837 vpp = hashvar(vp->text);
1840 } while (++vp < end);
1843 static struct var **
1844 findvar(struct var **vpp, const char *name)
1846 for (; *vpp; vpp = &(*vpp)->next) {
1847 if (varequal((*vpp)->text, name)) {
1855 * Find the value of a variable. Returns NULL if not set.
1858 lookupvar(const char *name)
1862 v = *findvar(hashvar(name), name);
1866 * Dynamic variables are implemented roughly the same way they are
1867 * in bash. Namely, they're "special" so long as they aren't unset.
1868 * As soon as they're unset, they're no longer dynamic, and dynamic
1869 * lookup will no longer happen at that point. -- PFM.
1871 if ((v->flags & VDYNAMIC))
1874 if (!(v->flags & VUNSET))
1875 return strchrnul(v->text, '=') + 1;
1881 * Search the environment of a builtin command.
1884 bltinlookup(const char *name)
1888 for (sp = cmdenviron; sp; sp = sp->next) {
1889 if (varequal(sp->text, name))
1890 return strchrnul(sp->text, '=') + 1;
1892 return lookupvar(name);
1896 * Same as setvar except that the variable and value are passed in
1897 * the first argument as name=value. Since the first argument will
1898 * be actually stored in the table, it should not be a string that
1900 * Called with interrupts off.
1903 setvareq(char *s, int flags)
1905 struct var *vp, **vpp;
1908 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1909 vp = *findvar(vpp, s);
1911 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1914 if (flags & VNOSAVE)
1917 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1923 if (vp->func && (flags & VNOFUNC) == 0)
1924 (*vp->func)(strchrnul(s, '=') + 1);
1926 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1927 free((char*)vp->text);
1929 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1934 vp = ckmalloc(sizeof(*vp));
1939 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1946 * Set the value of a variable. The flags argument is ored with the
1947 * flags of the variable. If val is NULL, the variable is unset.
1950 setvar(const char *name, const char *val, int flags)
1957 q = endofname(name);
1958 p = strchrnul(q, '=');
1960 if (!namelen || p != q)
1961 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1966 vallen = strlen(val);
1969 nameeq = ckmalloc(namelen + vallen + 2);
1970 p = memcpy(nameeq, name, namelen) + namelen;
1973 p = memcpy(p, val, vallen) + vallen;
1976 setvareq(nameeq, flags | VNOSAVE);
1980 #if ENABLE_ASH_GETOPTS
1982 * Safe version of setvar, returns 1 on success 0 on failure.
1985 setvarsafe(const char *name, const char *val, int flags)
1988 volatile int saveint;
1989 struct jmploc *volatile savehandler = exception_handler;
1990 struct jmploc jmploc;
1993 if (setjmp(jmploc.loc))
1996 exception_handler = &jmploc;
1997 setvar(name, val, flags);
2000 exception_handler = savehandler;
2001 RESTORE_INT(saveint);
2007 * Unset the specified variable.
2010 unsetvar(const char *s)
2016 vpp = findvar(hashvar(s), s);
2020 int flags = vp->flags;
2023 if (flags & VREADONLY)
2026 vp->flags &= ~VDYNAMIC;
2030 if ((flags & VSTRFIXED) == 0) {
2032 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2033 free((char*)vp->text);
2039 vp->flags &= ~VEXPORT;
2049 * Process a linked list of variable assignments.
2052 listsetvar(struct strlist *list_set_var, int flags)
2054 struct strlist *lp = list_set_var;
2060 setvareq(lp->text, flags);
2067 * Generate a list of variables satisfying the given conditions.
2070 listvars(int on, int off, char ***end)
2081 for (vp = *vpp; vp; vp = vp->next) {
2082 if ((vp->flags & mask) == on) {
2083 if (ep == stackstrend())
2084 ep = growstackstr();
2085 *ep++ = (char *) vp->text;
2088 } while (++vpp < vartab + VTABSIZE);
2089 if (ep == stackstrend())
2090 ep = growstackstr();
2094 return grabstackstr(ep);
2098 /* ============ Path search helper
2100 * The variable path (passed by reference) should be set to the start
2101 * of the path before the first call; padvance will update
2102 * this value as it proceeds. Successive calls to padvance will return
2103 * the possible path expansions in sequence. If an option (indicated by
2104 * a percent sign) appears in the path entry then the global variable
2105 * pathopt will be set to point to it; otherwise pathopt will be set to
2108 static const char *pathopt; /* set by padvance */
2111 padvance(const char **path, const char *name)
2121 for (p = start; *p && *p != ':' && *p != '%'; p++);
2122 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2123 while (stackblocksize() < len)
2127 memcpy(q, start, p - start);
2135 while (*p && *p != ':') p++;
2141 return stalloc(len);
2145 /* ============ Prompt */
2147 static int doprompt; /* if set, prompt the user */
2148 static int needprompt; /* true if interactive and at start of line */
2150 #if ENABLE_FEATURE_EDITING
2151 static line_input_t *line_input_state;
2152 static const char *cmdedit_prompt;
2154 putprompt(const char *s)
2156 if (ENABLE_ASH_EXPAND_PRMT) {
2157 free((char*)cmdedit_prompt);
2158 cmdedit_prompt = xstrdup(s);
2165 putprompt(const char *s)
2171 #if ENABLE_ASH_EXPAND_PRMT
2172 /* expandstr() needs parsing machinery, so it is far away ahead... */
2173 static const char *expandstr(const char *ps);
2175 #define expandstr(s) s
2179 setprompt(int whichprompt)
2182 #if ENABLE_ASH_EXPAND_PRMT
2183 struct stackmark smark;
2188 switch (whichprompt) {
2198 #if ENABLE_ASH_EXPAND_PRMT
2199 setstackmark(&smark);
2200 stalloc(stackblocksize());
2202 putprompt(expandstr(prompt));
2203 #if ENABLE_ASH_EXPAND_PRMT
2204 popstackmark(&smark);
2209 /* ============ The cd and pwd commands */
2211 #define CD_PHYSICAL 1
2214 static int docd(const char *, int);
2216 static char *curdir = nullstr; /* current working directory */
2217 static char *physdir = nullstr; /* physical working directory */
2226 while ((i = nextopt("LP"))) {
2228 flags ^= CD_PHYSICAL;
2237 * Update curdir (the name of the current directory) in response to a
2241 updatepwd(const char *dir)
2248 cdcomppath = ststrdup(dir);
2251 if (curdir == nullstr)
2253 new = stack_putstr(curdir, new);
2255 new = makestrspace(strlen(dir) + 2, new);
2256 lim = stackblock() + 1;
2260 if (new > lim && *lim == '/')
2265 if (dir[1] == '/' && dir[2] != '/') {
2271 p = strtok(cdcomppath, "/");
2275 if (p[1] == '.' && p[2] == '\0') {
2282 } else if (p[1] == '\0')
2286 new = stack_putstr(p, new);
2294 return stackblock();
2298 * Find out what the current directory is. If we already know the current
2299 * directory, this routine returns immediately.
2304 char *dir = getcwd(0, 0);
2305 return dir ? dir : nullstr;
2309 setpwd(const char *val, int setold)
2313 oldcur = dir = curdir;
2316 setvar("OLDPWD", oldcur, VEXPORT);
2319 if (physdir != nullstr) {
2320 if (physdir != oldcur)
2324 if (oldcur == val || !val) {
2330 dir = ckstrdup(val);
2331 if (oldcur != dir && oldcur != nullstr) {
2336 setvar("PWD", dir, VEXPORT);
2339 static void hashcd(void);
2342 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2343 * know that the current directory has changed.
2346 docd(const char *dest, int flags)
2348 const char *dir = 0;
2351 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2354 if (!(flags & CD_PHYSICAL)) {
2355 dir = updatepwd(dest);
2370 cdcmd(int argc, char **argv)
2382 dest = bltinlookup(homestr);
2383 else if (LONE_DASH(dest)) {
2384 dest = bltinlookup("OLDPWD");
2406 path = bltinlookup("CDPATH");
2415 p = padvance(&path, dest);
2416 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2420 if (!docd(p, flags))
2425 ash_msg_and_raise_error("can't cd to %s", dest);
2428 if (flags & CD_PRINT)
2429 out1fmt(snlfmt, curdir);
2434 pwdcmd(int argc, char **argv)
2437 const char *dir = curdir;
2441 if (physdir == nullstr)
2445 out1fmt(snlfmt, dir);
2450 /* ============ ... */
2452 #define IBUFSIZ (BUFSIZ + 1)
2453 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2455 /* Syntax classes */
2456 #define CWORD 0 /* character is nothing special */
2457 #define CNL 1 /* newline character */
2458 #define CBACK 2 /* a backslash character */
2459 #define CSQUOTE 3 /* single quote */
2460 #define CDQUOTE 4 /* double quote */
2461 #define CENDQUOTE 5 /* a terminating quote */
2462 #define CBQUOTE 6 /* backwards single quote */
2463 #define CVAR 7 /* a dollar sign */
2464 #define CENDVAR 8 /* a '}' character */
2465 #define CLP 9 /* a left paren in arithmetic */
2466 #define CRP 10 /* a right paren in arithmetic */
2467 #define CENDFILE 11 /* end of file */
2468 #define CCTL 12 /* like CWORD, except it must be escaped */
2469 #define CSPCL 13 /* these terminate a word */
2470 #define CIGN 14 /* character should be ignored */
2472 #if ENABLE_ASH_ALIAS
2476 #define PEOA_OR_PEOF PEOA
2480 #define PEOA_OR_PEOF PEOF
2483 /* number syntax index */
2484 #define BASESYNTAX 0 /* not in quotes */
2485 #define DQSYNTAX 1 /* in double quotes */
2486 #define SQSYNTAX 2 /* in single quotes */
2487 #define ARISYNTAX 3 /* in arithmetic */
2489 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2490 #define USE_SIT_FUNCTION
2493 #if ENABLE_ASH_MATH_SUPPORT
2494 static const char S_I_T[][4] = {
2495 #if ENABLE_ASH_ALIAS
2496 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2498 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2499 { CNL, CNL, CNL, CNL }, /* 2, \n */
2500 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2501 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2502 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2503 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2504 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2505 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2506 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2507 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2508 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2509 #ifndef USE_SIT_FUNCTION
2510 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2511 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2512 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2516 static const char S_I_T[][3] = {
2517 #if ENABLE_ASH_ALIAS
2518 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2520 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2521 { CNL, CNL, CNL }, /* 2, \n */
2522 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2523 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2524 { CVAR, CVAR, CWORD }, /* 5, $ */
2525 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2526 { CSPCL, CWORD, CWORD }, /* 7, ( */
2527 { CSPCL, CWORD, CWORD }, /* 8, ) */
2528 { CBACK, CBACK, CCTL }, /* 9, \ */
2529 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2530 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2531 #ifndef USE_SIT_FUNCTION
2532 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2533 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2534 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2537 #endif /* ASH_MATH_SUPPORT */
2539 #ifdef USE_SIT_FUNCTION
2542 SIT(int c, int syntax)
2544 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2545 #if ENABLE_ASH_ALIAS
2546 static const char syntax_index_table[] = {
2547 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2548 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2549 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2553 static const char syntax_index_table[] = {
2554 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2555 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2556 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2563 if (c == PEOF) /* 2^8+2 */
2565 #if ENABLE_ASH_ALIAS
2566 if (c == PEOA) /* 2^8+1 */
2570 #define U_C(c) ((unsigned char)(c))
2572 if ((unsigned char)c >= (unsigned char)(CTLESC)
2573 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2577 s = strchr(spec_symbls, c);
2578 if (s == NULL || *s == '\0')
2580 indx = syntax_index_table[(s - spec_symbls)];
2582 return S_I_T[indx][syntax];
2585 #else /* !USE_SIT_FUNCTION */
2587 #if ENABLE_ASH_ALIAS
2588 #define CSPCL_CIGN_CIGN_CIGN 0
2589 #define CSPCL_CWORD_CWORD_CWORD 1
2590 #define CNL_CNL_CNL_CNL 2
2591 #define CWORD_CCTL_CCTL_CWORD 3
2592 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2593 #define CVAR_CVAR_CWORD_CVAR 5
2594 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2595 #define CSPCL_CWORD_CWORD_CLP 7
2596 #define CSPCL_CWORD_CWORD_CRP 8
2597 #define CBACK_CBACK_CCTL_CBACK 9
2598 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2599 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2600 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2601 #define CWORD_CWORD_CWORD_CWORD 13
2602 #define CCTL_CCTL_CCTL_CCTL 14
2604 #define CSPCL_CWORD_CWORD_CWORD 0
2605 #define CNL_CNL_CNL_CNL 1
2606 #define CWORD_CCTL_CCTL_CWORD 2
2607 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2608 #define CVAR_CVAR_CWORD_CVAR 4
2609 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2610 #define CSPCL_CWORD_CWORD_CLP 6
2611 #define CSPCL_CWORD_CWORD_CRP 7
2612 #define CBACK_CBACK_CCTL_CBACK 8
2613 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2614 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2615 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2616 #define CWORD_CWORD_CWORD_CWORD 12
2617 #define CCTL_CCTL_CCTL_CCTL 13
2620 static const char syntax_index_table[258] = {
2621 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2622 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2623 #if ENABLE_ASH_ALIAS
2624 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2626 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2627 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2628 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2629 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2630 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2631 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2632 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2633 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2634 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2635 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2636 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2637 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2638 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2639 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2640 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2641 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2642 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2643 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2644 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2645 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2646 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2647 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2648 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2649 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2764 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2765 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2789 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2791 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2793 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2794 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2795 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2796 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2797 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2799 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2800 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2801 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2802 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2813 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2814 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2815 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2816 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2817 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2818 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2846 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2847 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2848 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2851 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2857 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2861 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2879 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2880 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2881 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2884 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2886 #endif /* USE_SIT_FUNCTION */
2889 /* ============ Alias handling */
2891 #if ENABLE_ASH_ALIAS
2893 #define ALIASINUSE 1
2905 static struct alias *atab[ATABSIZE];
2907 static struct alias **
2908 __lookupalias(const char *name) {
2909 unsigned int hashval;
2916 ch = (unsigned char)*p;
2920 ch = (unsigned char)*++p;
2922 app = &atab[hashval % ATABSIZE];
2924 for (; *app; app = &(*app)->next) {
2925 if (strcmp(name, (*app)->name) == 0) {
2933 static struct alias *
2934 lookupalias(const char *name, int check)
2936 struct alias *ap = *__lookupalias(name);
2938 if (check && ap && (ap->flag & ALIASINUSE))
2943 static struct alias *
2944 freealias(struct alias *ap)
2948 if (ap->flag & ALIASINUSE) {
2949 ap->flag |= ALIASDEAD;
2961 setalias(const char *name, const char *val)
2963 struct alias *ap, **app;
2965 app = __lookupalias(name);
2969 if (!(ap->flag & ALIASINUSE)) {
2972 ap->val = ckstrdup(val);
2973 ap->flag &= ~ALIASDEAD;
2976 ap = ckmalloc(sizeof(struct alias));
2977 ap->name = ckstrdup(name);
2978 ap->val = ckstrdup(val);
2987 unalias(const char *name)
2991 app = __lookupalias(name);
2995 *app = freealias(*app);
3006 struct alias *ap, **app;
3010 for (i = 0; i < ATABSIZE; i++) {
3012 for (ap = *app; ap; ap = *app) {
3013 *app = freealias(*app);
3023 printalias(const struct alias *ap)
3025 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3029 * TODO - sort output
3032 aliascmd(int argc, char **argv)
3041 for (i = 0; i < ATABSIZE; i++)
3042 for (ap = atab[i]; ap; ap = ap->next) {
3047 while ((n = *++argv) != NULL) {
3048 v = strchr(n+1, '=');
3049 if (v == NULL) { /* n+1: funny ksh stuff */
3050 ap = *__lookupalias(n);
3052 fprintf(stderr, "%s: %s not found\n", "alias", n);
3066 unaliascmd(int argc, char **argv)
3070 while ((i = nextopt("a")) != '\0') {
3076 for (i = 0; *argptr; argptr++) {
3077 if (unalias(*argptr)) {
3078 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3086 #endif /* ASH_ALIAS */
3089 /* ============ jobs.c */
3091 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3094 #define FORK_NOJOB 2
3096 /* mode flags for showjob(s) */
3097 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3098 #define SHOW_PID 0x04 /* include process pid */
3099 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3102 * A job structure contains information about a job. A job is either a
3103 * single process or a set of processes contained in a pipeline. In the
3104 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3109 pid_t pid; /* process id */
3110 int status; /* last process status from wait() */
3111 char *cmd; /* text of command being run */
3115 struct procstat ps0; /* status of process */
3116 struct procstat *ps; /* status or processes when more than one */
3118 int stopstatus; /* status of a stopped job */
3121 nprocs: 16, /* number of processes */
3123 #define JOBRUNNING 0 /* at least one proc running */
3124 #define JOBSTOPPED 1 /* all procs are stopped */
3125 #define JOBDONE 2 /* all procs are completed */
3127 sigint: 1, /* job was killed by SIGINT */
3128 jobctl: 1, /* job running under job control */
3130 waited: 1, /* true if this entry has been waited for */
3131 used: 1, /* true if this entry is in used */
3132 changed: 1; /* true if status has changed */
3133 struct job *prev_job; /* previous job */
3136 static pid_t backgndpid; /* pid of last background process */
3137 static int job_warning; /* user was warned about stopped jobs */
3139 static int jobctl; /* true if doing job control */
3142 static struct job *makejob(union node *, int);
3143 static int forkshell(struct job *, union node *, int);
3144 static int waitforjob(struct job *);
3147 #define setjobctl(on) /* do nothing */
3149 static void setjobctl(int);
3150 static void showjobs(FILE *, int);
3154 * Set the signal handler for the specified signal. The routine figures
3155 * out what it should be set to.
3158 setsignal(int signo)
3162 struct sigaction act;
3167 else if (*t != '\0')
3171 if (rootshell && action == S_DFL) {
3174 if (iflag || minusc || sflag == 0)
3197 t = &sigmode[signo - 1];
3201 * current setting unknown
3203 if (sigaction(signo, 0, &act) == -1) {
3205 * Pretend it worked; maybe we should give a warning
3206 * here, but other shells don't. We don't alter
3207 * sigmode, so that we retry every time.
3211 if (act.sa_handler == SIG_IGN) {
3213 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3215 tsig = S_IGN; /* don't hard ignore these */
3219 tsig = S_RESET; /* force to be set */
3222 if (tsig == S_HARD_IGN || tsig == action)
3226 act.sa_handler = onsig;
3229 act.sa_handler = SIG_IGN;
3232 act.sa_handler = SIG_DFL;
3236 sigfillset(&act.sa_mask);
3237 sigaction(signo, &act, 0);
3240 /* mode flags for set_curjob */
3241 #define CUR_DELETE 2
3242 #define CUR_RUNNING 1
3243 #define CUR_STOPPED 0
3245 /* mode flags for dowait */
3246 #define DOWAIT_NORMAL 0
3247 #define DOWAIT_BLOCK 1
3250 /* pgrp of shell on invocation */
3251 static int initialpgrp;
3252 static int ttyfd = -1;
3255 static struct job *jobtab;
3257 static unsigned njobs;
3259 static struct job *curjob;
3260 /* number of presumed living untracked jobs */
3264 set_curjob(struct job *jp, unsigned mode)
3267 struct job **jpp, **curp;
3269 /* first remove from list */
3270 jpp = curp = &curjob;
3275 jpp = &jp1->prev_job;
3277 *jpp = jp1->prev_job;
3279 /* Then re-insert in correct position */
3287 /* job being deleted */
3290 /* newly created job or backgrounded job,
3291 put after all stopped jobs. */
3295 if (!jp1 || jp1->state != JOBSTOPPED)
3298 jpp = &jp1->prev_job;
3304 /* newly stopped job - becomes curjob */
3305 jp->prev_job = *jpp;
3313 jobno(const struct job *jp)
3315 return jp - jobtab + 1;
3320 * Convert a job name to a job structure.
3323 getjob(const char *name, int getctl)
3327 const char *err_msg = "No such job: %s";
3331 char *(*match)(const char *, const char *);
3346 if (c == '+' || c == '%') {
3348 err_msg = "No current job";
3354 err_msg = "No previous job";
3365 jp = jobtab + num - 1;
3382 if (match(jp->ps[0].cmd, p)) {
3386 err_msg = "%s: ambiguous";
3393 err_msg = "job %s not created under job control";
3394 if (getctl && jp->jobctl == 0)
3399 ash_msg_and_raise_error(err_msg, name);
3403 * Mark a job structure as unused.
3406 freejob(struct job *jp)
3408 struct procstat *ps;
3412 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3413 if (ps->cmd != nullstr)
3416 if (jp->ps != &jp->ps0)
3419 set_curjob(jp, CUR_DELETE);
3425 xtcsetpgrp(int fd, pid_t pgrp)
3427 if (tcsetpgrp(fd, pgrp))
3428 ash_msg_and_raise_error("Cannot set tty process group (%m)");
3432 * Turn job control on and off.
3434 * Note: This code assumes that the third arg to ioctl is a character
3435 * pointer, which is true on Berkeley systems but not System V. Since
3436 * System V doesn't have job control yet, this isn't a problem now.
3438 * Called with interrupts off.
3446 if (on == jobctl || rootshell == 0)
3450 ofd = fd = open(_PATH_TTY, O_RDWR);
3452 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3453 * That sometimes helps to acquire controlling tty.
3454 * Obviously, a workaround for bugs when someone
3455 * failed to provide a controlling tty to bash! :) */
3457 while (!isatty(fd) && --fd >= 0)
3460 fd = fcntl(fd, F_DUPFD, 10);
3464 fcntl(fd, F_SETFD, FD_CLOEXEC);
3465 do { /* while we are in the background */
3466 pgrp = tcgetpgrp(fd);
3469 ash_msg("can't access tty; job control turned off");
3473 if (pgrp == getpgrp())
3484 xtcsetpgrp(fd, pgrp);
3486 /* turning job control off */
3489 xtcsetpgrp(fd, pgrp);
3503 killcmd(int argc, char **argv)
3513 ash_msg_and_raise_error(
3514 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
3515 "kill -l [exitstatus]"
3519 if (**++argv == '-') {
3520 signo = get_signum(*argv + 1);
3524 while ((c = nextopt("ls:")) != '\0') {
3534 signo = get_signum(optionarg);
3536 ash_msg_and_raise_error(
3537 "invalid signal number or name: %s",
3549 if (!list && signo < 0)
3552 if ((signo < 0 || !*argv) ^ list) {
3560 for (i = 1; i < NSIG; i++) {
3561 name = get_signame(i);
3563 out1fmt(snlfmt, name);
3567 name = get_signame(signo);
3568 if (!isdigit(*name))
3569 ash_msg_and_raise_error("invalid signal number or exit status: %s", *argptr);
3570 out1fmt(snlfmt, name);
3576 if (**argv == '%') {
3577 jp = getjob(*argv, 0);
3578 pid = -jp->ps[0].pid;
3580 pid = **argv == '-' ?
3581 -number(*argv + 1) : number(*argv);
3583 if (kill(pid, signo) != 0) {
3584 ash_msg("(%d) - %m", pid);
3593 showpipe(struct job *jp, FILE *out)
3595 struct procstat *sp;
3596 struct procstat *spend;
3598 spend = jp->ps + jp->nprocs;
3599 for (sp = jp->ps + 1; sp < spend; sp++)
3600 fprintf(out, " | %s", sp->cmd);
3601 outcslow('\n', out);
3602 flush_stdout_stderr();
3607 restartjob(struct job *jp, int mode)
3609 struct procstat *ps;
3615 if (jp->state == JOBDONE)
3617 jp->state = JOBRUNNING;
3619 if (mode == FORK_FG)
3620 xtcsetpgrp(ttyfd, pgid);
3621 killpg(pgid, SIGCONT);
3625 if (WIFSTOPPED(ps->status)) {
3628 } while (ps++, --i);
3630 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3636 fg_bgcmd(int argc, char **argv)
3643 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3648 jp = getjob(*argv, 1);
3649 if (mode == FORK_BG) {
3650 set_curjob(jp, CUR_RUNNING);
3651 fprintf(out, "[%d] ", jobno(jp));
3653 outstr(jp->ps->cmd, out);
3655 retval = restartjob(jp, mode);
3656 } while (*argv && *++argv);
3662 sprint_status(char *s, int status, int sigonly)
3668 if (!WIFEXITED(status)) {
3670 if (WIFSTOPPED(status))
3671 st = WSTOPSIG(status);
3674 st = WTERMSIG(status);
3676 if (st == SIGINT || st == SIGPIPE)
3679 if (WIFSTOPPED(status))
3684 col = fmtstr(s, 32, strsignal(st));
3685 if (WCOREDUMP(status)) {
3686 col += fmtstr(s + col, 16, " (core dumped)");
3688 } else if (!sigonly) {
3689 st = WEXITSTATUS(status);
3691 col = fmtstr(s, 16, "Done(%d)", st);
3693 col = fmtstr(s, 16, "Done");
3700 * Do a wait system call. If job control is compiled in, we accept
3701 * stopped processes. If block is zero, we return a value of zero
3702 * rather than blocking.
3704 * System V doesn't have a non-blocking wait system call. It does
3705 * have a SIGCLD signal that is sent to a process when one of it's
3706 * children dies. The obvious way to use SIGCLD would be to install
3707 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3708 * was received, and have waitproc bump another counter when it got
3709 * the status of a process. Waitproc would then know that a wait
3710 * system call would not block if the two counters were different.
3711 * This approach doesn't work because if a process has children that
3712 * have not been waited for, System V will send it a SIGCLD when it
3713 * installs a signal handler for SIGCLD. What this means is that when
3714 * a child exits, the shell will be sent SIGCLD signals continuously
3715 * until is runs out of stack space, unless it does a wait call before
3716 * restoring the signal handler. The code below takes advantage of
3717 * this (mis)feature by installing a signal handler for SIGCLD and
3718 * then checking to see whether it was called. If there are any
3719 * children to be waited for, it will be.
3721 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3722 * waits at all. In this case, the user will not be informed when
3723 * a background process until the next time she runs a real program
3724 * (as opposed to running a builtin command or just typing return),
3725 * and the jobs command may give out of date information.
3728 waitproc(int block, int *status)
3738 return wait3(status, flags, (struct rusage *)NULL);
3742 * Wait for a process to terminate.
3745 dowait(int block, struct job *job)
3750 struct job *thisjob;
3753 TRACE(("dowait(%d) called\n", block));
3754 pid = waitproc(block, &status);
3755 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3760 for (jp = curjob; jp; jp = jp->prev_job) {
3761 struct procstat *sp;
3762 struct procstat *spend;
3763 if (jp->state == JOBDONE)
3766 spend = jp->ps + jp->nprocs;
3769 if (sp->pid == pid) {
3770 TRACE(("Job %d: changing status of proc %d "
3771 "from 0x%x to 0x%x\n",
3772 jobno(jp), pid, sp->status, status));
3773 sp->status = status;
3776 if (sp->status == -1)
3779 if (state == JOBRUNNING)
3781 if (WIFSTOPPED(sp->status)) {
3782 jp->stopstatus = sp->status;
3786 } while (++sp < spend);
3791 if (!WIFSTOPPED(status))
3798 if (state != JOBRUNNING) {
3799 thisjob->changed = 1;
3801 if (thisjob->state != state) {
3802 TRACE(("Job %d: changing state from %d to %d\n",
3803 jobno(thisjob), thisjob->state, state));
3804 thisjob->state = state;
3806 if (state == JOBSTOPPED) {
3807 set_curjob(thisjob, CUR_STOPPED);
3816 if (thisjob && thisjob == job) {
3820 len = sprint_status(s, status, 1);
3832 showjob(FILE *out, struct job *jp, int mode)
3834 struct procstat *ps;
3835 struct procstat *psend;
3842 if (mode & SHOW_PGID) {
3843 /* just output process (group) id of pipeline */
3844 fprintf(out, "%d\n", ps->pid);
3848 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3853 else if (curjob && jp == curjob->prev_job)
3856 if (mode & SHOW_PID)
3857 col += fmtstr(s + col, 16, "%d ", ps->pid);
3859 psend = ps + jp->nprocs;
3861 if (jp->state == JOBRUNNING) {
3862 strcpy(s + col, "Running");
3863 col += sizeof("Running") - 1;
3865 int status = psend[-1].status;
3866 if (jp->state == JOBSTOPPED)
3867 status = jp->stopstatus;
3868 col += sprint_status(s + col, status, 0);
3874 /* for each process */
3875 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
3877 fprintf(out, "%s%*c%s",
3878 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3880 if (!(mode & SHOW_PID)) {
3884 if (++ps == psend) {
3885 outcslow('\n', out);
3892 if (jp->state == JOBDONE) {
3893 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3899 jobscmd(int argc, char **argv)
3905 while ((m = nextopt("lp"))) {
3916 showjob(out, getjob(*argv,0), mode);
3919 showjobs(out, mode);
3925 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3926 * statuses have changed since the last call to showjobs.
3929 showjobs(FILE *out, int mode)
3933 TRACE(("showjobs(%x) called\n", mode));
3935 /* If not even one one job changed, there is nothing to do */
3936 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3939 for (jp = curjob; jp; jp = jp->prev_job) {
3940 if (!(mode & SHOW_CHANGED) || jp->changed)
3941 showjob(out, jp, mode);
3947 getstatus(struct job *job)
3952 status = job->ps[job->nprocs - 1].status;
3953 retval = WEXITSTATUS(status);
3954 if (!WIFEXITED(status)) {
3956 retval = WSTOPSIG(status);
3957 if (!WIFSTOPPED(status))
3960 /* XXX: limits number of signals */
3961 retval = WTERMSIG(status);
3963 if (retval == SIGINT)
3969 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3970 jobno(job), job->nprocs, status, retval));
3975 waitcmd(int argc, char **argv)
3988 /* wait for all jobs */
3993 /* no running procs */
3996 if (jp->state == JOBRUNNING)
4001 dowait(DOWAIT_BLOCK, 0);
4007 if (**argv != '%') {
4008 pid_t pid = number(*argv);
4012 if (job->ps[job->nprocs - 1].pid == pid)
4014 job = job->prev_job;
4020 job = getjob(*argv, 0);
4021 /* loop until process terminated or stopped */
4022 while (job->state == JOBRUNNING)
4023 dowait(DOWAIT_BLOCK, 0);
4025 retval = getstatus(job);
4039 struct job *jp, *jq;
4041 len = njobs * sizeof(*jp);
4043 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4045 offset = (char *)jp - (char *)jq;
4047 /* Relocate pointers */
4050 jq = (struct job *)((char *)jq + l);
4054 #define joff(p) ((struct job *)((char *)(p) + l))
4055 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4056 if (joff(jp)->ps == &jq->ps0)
4057 jmove(joff(jp)->ps);
4058 if (joff(jp)->prev_job)
4059 jmove(joff(jp)->prev_job);
4069 jp = (struct job *)((char *)jp + len);
4073 } while (--jq >= jp);
4078 * Return a new job structure.
4079 * Called with interrupts off.
4082 makejob(union node *node, int nprocs)
4087 for (i = njobs, jp = jobtab; ; jp++) {
4094 if (jp->state != JOBDONE || !jp->waited)
4103 memset(jp, 0, sizeof(*jp));
4108 jp->prev_job = curjob;
4113 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4115 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4122 * Return a string identifying a command (to be printed by the
4125 static char *cmdnextc;
4128 cmdputs(const char *s)
4130 const char *p, *str;
4131 char c, cc[2] = " ";
4135 static const char vstype[VSTYPE + 1][4] = {
4136 "", "}", "-", "+", "?", "=",
4137 "%", "%%", "#", "##"
4140 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4142 while ((c = *p++) != 0) {
4150 if ((subtype & VSTYPE) == VSLENGTH)
4154 if (!(subtype & VSQUOTE) == !(quoted & 1))
4160 str = "\"}" + !(quoted & 1);
4167 case CTLBACKQ+CTLQUOTE:
4170 #if ENABLE_ASH_MATH_SUPPORT
4185 if ((subtype & VSTYPE) != VSNORMAL)
4187 str = vstype[subtype & VSTYPE];
4188 if (subtype & VSNUL)
4197 /* These can only happen inside quotes */
4210 while ((c = *str++)) {
4215 USTPUTC('"', nextc);
4221 /* cmdtxt() and cmdlist() call each other */
4222 static void cmdtxt(union node *n);
4225 cmdlist(union node *np, int sep)
4227 for (; np; np = np->narg.next) {
4231 if (sep && np->narg.next)
4237 cmdtxt(union node *n)
4240 struct nodelist *lp;
4252 lp = n->npipe.cmdlist;
4270 cmdtxt(n->nbinary.ch1);
4286 cmdtxt(n->nif.test);
4289 if (n->nif.elsepart) {
4292 n = n->nif.elsepart;
4308 cmdtxt(n->nbinary.ch1);
4318 cmdputs(n->nfor.var);
4320 cmdlist(n->nfor.args, 1);
4325 cmdputs(n->narg.text);
4329 cmdlist(n->ncmd.args, 1);
4330 cmdlist(n->ncmd.redirect, 0);
4343 cmdputs(n->ncase.expr->narg.text);
4345 for (np = n->ncase.cases; np; np = np->nclist.next) {
4346 cmdtxt(np->nclist.pattern);
4348 cmdtxt(np->nclist.body);
4374 s[0] = n->nfile.fd + '0';
4378 if (n->type == NTOFD || n->type == NFROMFD) {
4379 s[0] = n->ndup.dupfd + '0';
4389 commandtext(union node *n)
4393 STARTSTACKSTR(cmdnextc);
4395 name = stackblock();
4396 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4397 name, cmdnextc, cmdnextc));
4398 return ckstrdup(name);
4403 * Fork off a subshell. If we are doing job control, give the subshell its
4404 * own process group. Jp is a job structure that the job is to be added to.
4405 * N is the command that will be evaluated by the child. Both jp and n may
4406 * be NULL. The mode parameter can be one of the following:
4407 * FORK_FG - Fork off a foreground process.
4408 * FORK_BG - Fork off a background process.
4409 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4410 * process group even if job control is on.
4412 * When job control is turned off, background processes have their standard
4413 * input redirected to /dev/null (except for the second and later processes
4416 * Called with interrupts off.
4419 * Clear traps on a fork.
4426 for (tp = trap; tp < &trap[NSIG]; tp++) {
4427 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4432 setsignal(tp - trap);
4437 /* lives far away from here, needed for forkchild */
4438 static void closescript(void);
4440 forkchild(struct job *jp, union node *n, int mode)
4444 TRACE(("Child shell %d\n", getpid()));
4451 /* do job control only in root shell */
4453 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4456 if (jp->nprocs == 0)
4459 pgrp = jp->ps[0].pid;
4460 /* This can fail because we are doing it in the parent also */
4461 (void)setpgid(0, pgrp);
4462 if (mode == FORK_FG)
4463 xtcsetpgrp(ttyfd, pgrp);
4468 if (mode == FORK_BG) {
4471 if (jp->nprocs == 0) {
4473 if (open(bb_dev_null, O_RDONLY) != 0)
4474 ash_msg_and_raise_error("Can't open %s", bb_dev_null);
4477 if (!oldlvl && iflag) {
4482 for (jp = curjob; jp; jp = jp->prev_job)
4488 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4490 TRACE(("In parent shell: child = %d\n", pid));
4492 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4497 if (mode != FORK_NOJOB && jp->jobctl) {
4500 if (jp->nprocs == 0)
4503 pgrp = jp->ps[0].pid;
4504 /* This can fail because we are doing it in the child also */
4508 if (mode == FORK_BG) {
4509 backgndpid = pid; /* set $! */
4510 set_curjob(jp, CUR_RUNNING);
4513 struct procstat *ps = &jp->ps[jp->nprocs++];
4519 ps->cmd = commandtext(n);
4525 forkshell(struct job *jp, union node *n, int mode)
4529 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4532 TRACE(("Fork failed, errno=%d", errno));
4535 ash_msg_and_raise_error("Cannot fork");
4538 forkchild(jp, n, mode);
4540 forkparent(jp, n, mode, pid);
4545 * Wait for job to finish.
4547 * Under job control we have the problem that while a child process is
4548 * running interrupts generated by the user are sent to the child but not
4549 * to the shell. This means that an infinite loop started by an inter-
4550 * active user may be hard to kill. With job control turned off, an
4551 * interactive user may place an interactive program inside a loop. If
4552 * the interactive program catches interrupts, the user doesn't want
4553 * these interrupts to also abort the loop. The approach we take here
4554 * is to have the shell ignore interrupt signals while waiting for a
4555 * foreground process to terminate, and then send itself an interrupt
4556 * signal if the child process was terminated by an interrupt signal.
4557 * Unfortunately, some programs want to do a bit of cleanup and then
4558 * exit on interrupt; unless these processes terminate themselves by
4559 * sending a signal to themselves (instead of calling exit) they will
4560 * confuse this approach.
4562 * Called with interrupts off.
4565 waitforjob(struct job *jp)
4569 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4570 while (jp->state == JOBRUNNING) {
4571 dowait(DOWAIT_BLOCK, jp);
4576 xtcsetpgrp(ttyfd, rootpid);
4578 * This is truly gross.
4579 * If we're doing job control, then we did a TIOCSPGRP which
4580 * caused us (the shell) to no longer be in the controlling
4581 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4582 * intuit from the subprocess exit status whether a SIGINT
4583 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4588 if (jp->state == JOBDONE)
4595 * return 1 if there are stopped jobs, otherwise 0
4607 if (jp && jp->state == JOBSTOPPED) {
4608 out2str("You have stopped jobs.\n");
4617 /* ============ redir.c
4619 * Code for dealing with input/output redirection.
4622 #define EMPTY -2 /* marks an unused slot in redirtab */
4624 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4626 # define PIPESIZE PIPE_BUF
4630 * Open a file in noclobber mode.
4631 * The code was copied from bash.
4634 noclobberopen(const char *fname)
4637 struct stat finfo, finfo2;
4640 * If the file exists and is a regular file, return an error
4643 r = stat(fname, &finfo);
4644 if (r == 0 && S_ISREG(finfo.st_mode)) {
4650 * If the file was not present (r != 0), make sure we open it
4651 * exclusively so that if it is created before we open it, our open
4652 * will fail. Make sure that we do not truncate an existing file.
4653 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4654 * file was not a regular file, we leave O_EXCL off.
4657 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4658 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4660 /* If the open failed, return the file descriptor right away. */
4665 * OK, the open succeeded, but the file may have been changed from a
4666 * non-regular file to a regular file between the stat and the open.
4667 * We are assuming that the O_EXCL open handles the case where FILENAME
4668 * did not exist and is symlinked to an existing file between the stat
4673 * If we can open it and fstat the file descriptor, and neither check
4674 * revealed that it was a regular file, and the file has not been
4675 * replaced, return the file descriptor.
4677 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4678 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4681 /* The file has been replaced. badness. */
4688 * Handle here documents. Normally we fork off a process to write the
4689 * data to a pipe. If the document is short, we can stuff the data in
4690 * the pipe without forking.
4692 /* openhere needs this forward reference */
4693 static void expandhere(union node *arg, int fd);
4695 openhere(union node *redir)
4701 ash_msg_and_raise_error("Pipe call failed");
4702 if (redir->type == NHERE) {
4703 len = strlen(redir->nhere.doc->narg.text);
4704 if (len <= PIPESIZE) {
4705 full_write(pip[1], redir->nhere.doc->narg.text, len);
4709 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4711 signal(SIGINT, SIG_IGN);
4712 signal(SIGQUIT, SIG_IGN);
4713 signal(SIGHUP, SIG_IGN);
4715 signal(SIGTSTP, SIG_IGN);
4717 signal(SIGPIPE, SIG_DFL);
4718 if (redir->type == NHERE)
4719 full_write(pip[1], redir->nhere.doc->narg.text, len);
4721 expandhere(redir->nhere.doc, pip[1]);
4730 openredirect(union node *redir)
4735 switch (redir->nfile.type) {
4737 fname = redir->nfile.expfname;
4738 f = open(fname, O_RDONLY);
4743 fname = redir->nfile.expfname;
4744 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4749 /* Take care of noclobber mode. */
4751 fname = redir->nfile.expfname;
4752 f = noclobberopen(fname);
4759 fname = redir->nfile.expfname;
4760 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4765 fname = redir->nfile.expfname;
4766 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4774 /* Fall through to eliminate warning. */
4781 f = openhere(redir);
4787 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "Directory nonexistent"));
4789 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "No such file"));
4793 * Copy a file descriptor to be >= to. Returns -1
4794 * if the source file descriptor is closed, EMPTY if there are no unused
4795 * file descriptors left.
4798 copyfd(int from, int to)
4802 newfd = fcntl(from, F_DUPFD, to);
4804 if (errno == EMFILE)
4806 ash_msg_and_raise_error("%d: %m", from);
4812 dupredirect(union node *redir, int f)
4814 int fd = redir->nfile.fd;
4816 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4817 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4818 copyfd(redir->ndup.dupfd, fd);
4830 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4831 * old file descriptors are stashed away so that the redirection can be
4832 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4833 * standard output, and the standard error if it becomes a duplicate of
4834 * stdout, is saved in memory.
4836 /* flags passed to redirect */
4837 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4838 #define REDIR_SAVEFD2 03 /* set preverrout */
4840 redirect(union node *redir, int flags)
4843 struct redirtab *sv;
4854 if (flags & REDIR_PUSH) {
4856 q = ckmalloc(sizeof(struct redirtab));
4857 q->next = redirlist;
4859 q->nullredirs = nullredirs - 1;
4860 for (i = 0; i < 10; i++)
4861 q->renamed[i] = EMPTY;
4868 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4869 && n->ndup.dupfd == fd)
4870 continue; /* redirect from/to same file descriptor */
4872 newfd = openredirect(n);
4875 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4876 i = fcntl(fd, F_DUPFD, 10);
4883 ash_msg_and_raise_error("%d: %m", fd);
4893 dupredirect(n, newfd);
4894 } while ((n = n->nfile.next));
4896 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4897 preverrout_fd = sv->renamed[2];
4901 * Undo the effects of the last redirection.
4906 struct redirtab *rp;
4909 if (--nullredirs >= 0)
4913 for (i = 0; i < 10; i++) {
4914 if (rp->renamed[i] != EMPTY) {
4917 copyfd(rp->renamed[i], i);
4919 close(rp->renamed[i]);
4922 redirlist = rp->next;
4923 nullredirs = rp->nullredirs;
4929 * Undo all redirections. Called on error or interrupt.
4933 * Discard all saved file descriptors.
4936 clearredir(int drop)
4947 redirectsafe(union node *redir, int flags)
4950 volatile int saveint;
4951 struct jmploc *volatile savehandler = exception_handler;
4952 struct jmploc jmploc;
4955 err = setjmp(jmploc.loc) * 2;
4957 exception_handler = &jmploc;
4958 redirect(redir, flags);
4960 exception_handler = savehandler;
4961 if (err && exception != EXERROR)
4962 longjmp(exception_handler->loc, 1);
4963 RESTORE_INT(saveint);
4968 /* ============ Routines to expand arguments to commands
4970 * We have to deal with backquotes, shell variables, and file metacharacters.
4976 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4977 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4978 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4979 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4980 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4981 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4982 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4983 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4984 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
4988 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4989 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4990 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4991 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4992 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4995 * Structure specifying which parts of the string should be searched
4996 * for IFS characters.
4999 struct ifsregion *next; /* next region in list */
5000 int begoff; /* offset of start of region */
5001 int endoff; /* offset of end of region */
5002 int nulonly; /* search for nul bytes only */
5006 struct strlist *list;
5007 struct strlist **lastp;
5010 /* output of current string */
5011 static char *expdest;
5012 /* list of back quote expressions */
5013 static struct nodelist *argbackq;
5014 /* first struct in list of ifs regions */
5015 static struct ifsregion ifsfirst;
5016 /* last struct in list */
5017 static struct ifsregion *ifslastp;
5018 /* holds expanded arg list */
5019 static struct arglist exparg;
5029 expdest = makestrspace(32, expdest);
5030 #if ENABLE_ASH_MATH_SUPPORT_64
5031 len = fmtstr(expdest, 32, "%lld", (long long) num);
5033 len = fmtstr(expdest, 32, "%ld", num);
5035 STADJUST(len, expdest);
5040 esclen(const char *start, const char *p)
5044 while (p > start && *--p == CTLESC) {
5051 * Remove any CTLESC characters from a string.
5054 _rmescapes(char *str, int flag)
5057 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5062 p = strpbrk(str, qchars);
5068 if (flag & RMESCAPE_ALLOC) {
5069 size_t len = p - str;
5070 size_t fulllen = len + strlen(p) + 1;
5072 if (flag & RMESCAPE_GROW) {
5073 r = makestrspace(fulllen, expdest);
5074 } else if (flag & RMESCAPE_HEAP) {
5075 r = ckmalloc(fulllen);
5077 r = stalloc(fulllen);
5081 q = memcpy(q, str, len) + len;
5084 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5085 globbing = flag & RMESCAPE_GLOB;
5086 notescaped = globbing;
5088 if (*p == CTLQUOTEMARK) {
5089 inquotes = ~inquotes;
5091 notescaped = globbing;
5095 /* naked back slash */
5101 if (notescaped && inquotes && *p != '/') {
5105 notescaped = globbing;
5110 if (flag & RMESCAPE_GROW) {
5112 STADJUST(q - r + 1, expdest);
5116 #define rmescapes(p) _rmescapes((p), 0)
5118 #define pmatch(a, b) !fnmatch((a), (b), 0)
5121 * Prepare a pattern for a expmeta (internal glob(3)) call.
5123 * Returns an stalloced string.
5126 preglob(const char *pattern, int quoted, int flag)
5128 flag |= RMESCAPE_GLOB;
5130 flag |= RMESCAPE_QUOTED;
5132 return _rmescapes((char *)pattern, flag);
5136 * Put a string on the stack.
5139 memtodest(const char *p, size_t len, int syntax, int quotes)
5143 q = makestrspace(len * 2, q);
5146 int c = signed_char2int(*p++);
5149 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5158 strtodest(const char *p, int syntax, int quotes)
5160 memtodest(p, strlen(p), syntax, quotes);
5164 * Record the fact that we have to scan this region of the
5165 * string for IFS characters.
5168 recordregion(int start, int end, int nulonly)
5170 struct ifsregion *ifsp;
5172 if (ifslastp == NULL) {
5176 ifsp = ckmalloc(sizeof(*ifsp));
5178 ifslastp->next = ifsp;
5182 ifslastp->begoff = start;
5183 ifslastp->endoff = end;
5184 ifslastp->nulonly = nulonly;
5188 removerecordregions(int endoff)
5190 if (ifslastp == NULL)
5193 if (ifsfirst.endoff > endoff) {
5194 while (ifsfirst.next != NULL) {
5195 struct ifsregion *ifsp;
5197 ifsp = ifsfirst.next->next;
5198 free(ifsfirst.next);
5199 ifsfirst.next = ifsp;
5202 if (ifsfirst.begoff > endoff)
5205 ifslastp = &ifsfirst;
5206 ifsfirst.endoff = endoff;
5211 ifslastp = &ifsfirst;
5212 while (ifslastp->next && ifslastp->next->begoff < endoff)
5213 ifslastp=ifslastp->next;
5214 while (ifslastp->next != NULL) {
5215 struct ifsregion *ifsp;
5217 ifsp = ifslastp->next->next;
5218 free(ifslastp->next);
5219 ifslastp->next = ifsp;
5222 if (ifslastp->endoff > endoff)
5223 ifslastp->endoff = endoff;
5227 exptilde(char *startp, char *p, int flag)
5233 int quotes = flag & (EXP_FULL | EXP_CASE);
5238 while ((c = *++p) != '\0') {
5245 if (flag & EXP_VARTILDE)
5255 if (*name == '\0') {
5256 home = lookupvar(homestr);
5258 pw = getpwnam(name);
5263 if (!home || !*home)
5266 startloc = expdest - (char *)stackblock();
5267 strtodest(home, SQSYNTAX, quotes);
5268 recordregion(startloc, expdest - (char *)stackblock(), 0);
5276 * Execute a command inside back quotes. If it's a builtin command, we
5277 * want to save its output in a block obtained from malloc. Otherwise
5278 * we fork off a subprocess and get the output of the command via a pipe.
5279 * Should be called with interrupts off.
5281 struct backcmd { /* result of evalbackcmd */
5282 int fd; /* file descriptor to read from */
5283 char *buf; /* buffer */
5284 int nleft; /* number of chars in buffer */
5285 struct job *jp; /* job structure for command */
5288 /* These forward decls are needed to use "eval" code for backticks handling: */
5289 static int back_exitstatus; /* exit status of backquoted command */
5290 #define EV_EXIT 01 /* exit after evaluating tree */
5291 static void evaltree(union node *, int);
5294 evalbackcmd(union node *n, struct backcmd *result)
5306 saveherefd = herefd;
5314 ash_msg_and_raise_error("Pipe call failed");
5316 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5325 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5329 result->fd = pip[0];
5332 herefd = saveherefd;
5334 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5335 result->fd, result->buf, result->nleft, result->jp));
5339 * Expand stuff in backwards quotes.
5342 expbackq(union node *cmd, int quoted, int quotes)
5350 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5351 struct stackmark smark;
5354 setstackmark(&smark);
5356 startloc = dest - (char *)stackblock();
5358 evalbackcmd(cmd, &in);
5359 popstackmark(&smark);
5366 memtodest(p, i, syntax, quotes);
5370 i = safe_read(in.fd, buf, sizeof(buf));
5371 TRACE(("expbackq: read returns %d\n", i));
5381 back_exitstatus = waitforjob(in.jp);
5385 /* Eat all trailing newlines */
5387 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5392 recordregion(startloc, dest - (char *)stackblock(), 0);
5393 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5394 (dest - (char *)stackblock()) - startloc,
5395 (dest - (char *)stackblock()) - startloc,
5396 stackblock() + startloc));
5399 #if ENABLE_ASH_MATH_SUPPORT
5401 * Expand arithmetic expression. Backup to start of expression,
5402 * evaluate, place result in (backed up) result, adjust string position.
5415 * This routine is slightly over-complicated for
5416 * efficiency. Next we scan backwards looking for the
5417 * start of arithmetic.
5419 start = stackblock();
5426 while (*p != CTLARI) {
5430 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5435 esc = esclen(start, p);
5445 removerecordregions(begoff);
5454 len = cvtnum(dash_arith(p + 2));
5457 recordregion(begoff, begoff + len, 0);
5461 /* argstr needs it */
5462 static char *evalvar(char *p, int flag);
5465 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5466 * characters to allow for further processing. Otherwise treat
5467 * $@ like $* since no splitting will be performed.
5470 argstr(char *p, int flag)
5472 static const char spclchars[] = {
5480 CTLBACKQ | CTLQUOTE,
5481 #if ENABLE_ASH_MATH_SUPPORT
5486 const char *reject = spclchars;
5488 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5489 int breakall = flag & EXP_WORD;
5494 if (!(flag & EXP_VARTILDE)) {
5496 } else if (flag & EXP_VARTILDE2) {
5501 if (flag & EXP_TILDE) {
5507 if (*q == CTLESC && (flag & EXP_QWORD))
5510 p = exptilde(p, q, flag);
5513 startloc = expdest - (char *)stackblock();
5515 length += strcspn(p + length, reject);
5517 if (c && (!(c & 0x80)
5518 #if ENABLE_ASH_MATH_SUPPORT
5522 /* c == '=' || c == ':' || c == CTLENDARI */
5527 expdest = stack_nputstr(p, length, expdest);
5528 newloc = expdest - (char *)stackblock();
5529 if (breakall && !inquotes && newloc > startloc) {
5530 recordregion(startloc, newloc, 0);
5541 if (flag & EXP_VARTILDE2) {
5545 flag |= EXP_VARTILDE2;
5550 * sort of a hack - expand tildes in variable
5551 * assignments (after the first '=' and after ':'s).
5560 case CTLENDVAR: /* ??? */
5563 /* "$@" syntax adherence hack */
5566 !memcmp(p, dolatstr, 4) &&
5567 (p[4] == CTLQUOTEMARK || (
5568 p[4] == CTLENDVAR &&
5569 p[5] == CTLQUOTEMARK
5572 p = evalvar(p + 1, flag) + 1;
5575 inquotes = !inquotes;
5588 p = evalvar(p, flag);
5592 case CTLBACKQ|CTLQUOTE:
5593 expbackq(argbackq->n, c, quotes);
5594 argbackq = argbackq->next;
5596 #if ENABLE_ASH_MATH_SUPPORT
5609 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5620 const char *s = loc2;
5626 match = pmatch(str, s);
5630 if (quotes && *loc == CTLESC)
5639 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5646 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5649 const char *s = loc2;
5654 match = pmatch(str, s);
5661 esc = esclen(startp, loc);
5672 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5674 varunset(const char *end, const char *var, const char *umsg, int varflags)
5680 msg = "parameter not set";
5682 if (*end == CTLENDVAR) {
5683 if (varflags & VSNUL)
5688 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5692 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5696 int saveherefd = herefd;
5697 struct nodelist *saveargbackq = argbackq;
5699 char *rmesc, *rmescend;
5701 char *(*scan)(char *, char *, char *, char *, int , int);
5704 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5705 STPUTC('\0', expdest);
5706 herefd = saveherefd;
5707 argbackq = saveargbackq;
5708 startp = stackblock() + startloc;
5712 setvar(str, startp, 0);
5713 amount = startp - expdest;
5714 STADJUST(amount, expdest);
5718 varunset(p, str, startp, varflags);
5722 subtype -= VSTRIMRIGHT;
5724 if (subtype < 0 || subtype > 3)
5729 rmescend = stackblock() + strloc;
5731 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5732 if (rmesc != startp) {
5734 startp = stackblock() + startloc;
5738 str = stackblock() + strloc;
5739 preglob(str, varflags & VSQUOTE, 0);
5741 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5742 zero = subtype >> 1;
5743 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5744 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5746 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5749 memmove(startp, loc, str - loc);
5750 loc = startp + (str - loc) - 1;
5753 amount = loc - expdest;
5754 STADJUST(amount, expdest);
5760 * Add the value of a specialized variable to the stack string.
5763 varvalue(char *name, int varflags, int flags)
5773 int quoted = varflags & VSQUOTE;
5774 int subtype = varflags & VSTYPE;
5775 int quotes = flags & (EXP_FULL | EXP_CASE);
5777 if (quoted && (flags & EXP_FULL))
5778 sep = 1 << CHAR_BIT;
5780 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5789 num = shellparam.nparam;
5799 p = makestrspace(NOPTS, expdest);
5800 for (i = NOPTS - 1; i >= 0; i--) {
5802 USTPUTC(optletters(i), p);
5813 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5814 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5820 while ((p = *ap++)) {
5823 partlen = strlen(p);
5826 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5827 memtodest(p, partlen, syntax, quotes);
5833 if (subtype == VSPLUS || subtype == VSLENGTH) {
5855 if (num < 0 || num > shellparam.nparam)
5857 p = num ? shellparam.p[num - 1] : arg0;
5860 p = lookupvar(name);
5866 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5867 memtodest(p, len, syntax, quotes);
5871 if (subtype == VSPLUS || subtype == VSLENGTH)
5872 STADJUST(-len, expdest);
5877 * Expand a variable, and return a pointer to the next character in the
5881 evalvar(char *p, int flag)
5894 quotes = flag & (EXP_FULL | EXP_CASE);
5896 subtype = varflags & VSTYPE;
5897 quoted = varflags & VSQUOTE;
5899 easy = (!quoted || (*var == '@' && shellparam.nparam));
5900 startloc = expdest - (char *)stackblock();
5901 p = strchr(p, '=') + 1;
5904 varlen = varvalue(var, varflags, flag);
5905 if (varflags & VSNUL)
5908 if (subtype == VSPLUS) {
5909 varlen = -1 - varlen;
5913 if (subtype == VSMINUS) {
5917 p, flag | EXP_TILDE |
5918 (quoted ? EXP_QWORD : EXP_WORD)
5927 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5929 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5932 * Remove any recorded regions beyond
5935 removerecordregions(startloc);
5945 if (varlen < 0 && uflag)
5946 varunset(p, var, 0, 0);
5948 if (subtype == VSLENGTH) {
5949 cvtnum(varlen > 0 ? varlen : 0);
5953 if (subtype == VSNORMAL) {
5957 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5966 case VSTRIMRIGHTMAX:
5975 * Terminate the string and start recording the pattern
5978 STPUTC('\0', expdest);
5979 patloc = expdest - (char *)stackblock();
5980 if (subevalvar(p, NULL, patloc, subtype,
5981 startloc, varflags, quotes) == 0) {
5982 int amount = expdest - (
5983 (char *)stackblock() + patloc - 1
5985 STADJUST(-amount, expdest);
5987 /* Remove any recorded regions beyond start of variable */
5988 removerecordregions(startloc);
5993 if (subtype != VSNORMAL) { /* skip to end of alternative */
5999 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6001 argbackq = argbackq->next;
6002 } else if (c == CTLVAR) {
6003 if ((*p++ & VSTYPE) != VSNORMAL)
6005 } else if (c == CTLENDVAR) {
6015 * Break the argument string into pieces based upon IFS and add the
6016 * strings to the argument list. The regions of the string to be
6017 * searched for IFS characters have been stored by recordregion.
6020 ifsbreakup(char *string, struct arglist *arglist)
6022 struct ifsregion *ifsp;
6027 const char *ifs, *realifs;
6032 if (ifslastp != NULL) {
6035 realifs = ifsset() ? ifsval() : defifs;
6038 p = string + ifsp->begoff;
6039 nulonly = ifsp->nulonly;
6040 ifs = nulonly ? nullstr : realifs;
6042 while (p < string + ifsp->endoff) {
6046 if (!strchr(ifs, *p)) {
6051 ifsspc = (strchr(defifs, *p) != NULL);
6052 /* Ignore IFS whitespace at start */
6053 if (q == start && ifsspc) {
6059 sp = stalloc(sizeof(*sp));
6061 *arglist->lastp = sp;
6062 arglist->lastp = &sp->next;
6066 if (p >= string + ifsp->endoff) {
6072 if (strchr(ifs, *p) == NULL ) {
6075 } else if (strchr(defifs, *p) == NULL) {
6090 } while (ifsp != NULL);
6099 sp = stalloc(sizeof(*sp));
6101 *arglist->lastp = sp;
6102 arglist->lastp = &sp->next;
6108 struct ifsregion *p;
6113 struct ifsregion *ifsp;
6119 ifsfirst.next = NULL;
6124 * Add a file name to the list.
6127 addfname(const char *name)
6131 sp = stalloc(sizeof(*sp));
6132 sp->text = ststrdup(name);
6134 exparg.lastp = &sp->next;
6137 static char *expdir;
6140 * Do metacharacter (i.e. *, ?, [...]) expansion.
6143 expmeta(char *enddir, char *name)
6158 for (p = name; *p; p++) {
6159 if (*p == '*' || *p == '?')
6161 else if (*p == '[') {
6168 if (*q == '/' || *q == '\0')
6175 } else if (*p == '\\')
6177 else if (*p == '/') {
6184 if (metaflag == 0) { /* we've reached the end of the file name */
6185 if (enddir != expdir)
6193 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6204 } while (p < start);
6206 if (enddir == expdir) {
6208 } else if (enddir == expdir + 1 && *expdir == '/') {
6217 if (enddir != expdir)
6219 if (*endname == 0) {
6231 while (! intpending && (dp = readdir(dirp)) != NULL) {
6232 if (dp->d_name[0] == '.' && ! matchdot)
6234 if (pmatch(start, dp->d_name)) {
6236 strcpy(enddir, dp->d_name);
6239 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6242 expmeta(p, endname);
6251 static struct strlist *
6252 msort(struct strlist *list, int len)
6254 struct strlist *p, *q = NULL;
6255 struct strlist **lpp;
6263 for (n = half; --n >= 0; ) {
6267 q->next = NULL; /* terminate first half of list */
6268 q = msort(list, half); /* sort first half of list */
6269 p = msort(p, len - half); /* sort second half */
6272 #if ENABLE_LOCALE_SUPPORT
6273 if (strcoll(p->text, q->text) < 0)
6275 if (strcmp(p->text, q->text) < 0)
6299 * Sort the results of file name expansion. It calculates the number of
6300 * strings to sort and then calls msort (short for merge sort) to do the
6303 static struct strlist *
6304 expsort(struct strlist *str)
6310 for (sp = str; sp; sp = sp->next)
6312 return msort(str, len);
6316 expandmeta(struct strlist *str, int flag)
6318 static const char metachars[] = {
6321 /* TODO - EXP_REDIR */
6324 struct strlist **savelastp;
6330 if (!strpbrk(str->text, metachars))
6332 savelastp = exparg.lastp;
6335 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6337 int i = strlen(str->text);
6338 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6346 if (exparg.lastp == savelastp) {
6351 *exparg.lastp = str;
6352 rmescapes(str->text);
6353 exparg.lastp = &str->next;
6355 *exparg.lastp = NULL;
6356 *savelastp = sp = expsort(*savelastp);
6357 while (sp->next != NULL)
6359 exparg.lastp = &sp->next;
6366 * Perform variable substitution and command substitution on an argument,
6367 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6368 * perform splitting and file name expansion. When arglist is NULL, perform
6369 * here document expansion.
6372 expandarg(union node *arg, struct arglist *arglist, int flag)
6377 argbackq = arg->narg.backquote;
6378 STARTSTACKSTR(expdest);
6379 ifsfirst.next = NULL;
6381 argstr(arg->narg.text, flag);
6382 p = _STPUTC('\0', expdest);
6384 if (arglist == NULL) {
6385 return; /* here document expanded */
6387 p = grabstackstr(p);
6388 exparg.lastp = &exparg.list;
6392 if (flag & EXP_FULL) {
6393 ifsbreakup(p, &exparg);
6394 *exparg.lastp = NULL;
6395 exparg.lastp = &exparg.list;
6396 expandmeta(exparg.list, flag);
6398 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6400 sp = stalloc(sizeof(*sp));
6403 exparg.lastp = &sp->next;
6407 *exparg.lastp = NULL;
6409 *arglist->lastp = exparg.list;
6410 arglist->lastp = exparg.lastp;
6415 * Expand shell variables and backquotes inside a here document.
6418 expandhere(union node *arg, int fd)
6421 expandarg(arg, (struct arglist *)NULL, 0);
6422 full_write(fd, stackblock(), expdest - (char *)stackblock());
6426 * Returns true if the pattern matches the string.
6429 patmatch(char *pattern, const char *string)
6431 return pmatch(preglob(pattern, 0, 0), string);
6435 * See if a pattern matches in a case statement.
6438 casematch(union node *pattern, char *val)
6440 struct stackmark smark;
6443 setstackmark(&smark);
6444 argbackq = pattern->narg.backquote;
6445 STARTSTACKSTR(expdest);
6447 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6448 STACKSTRNUL(expdest);
6449 result = patmatch(stackblock(), val);
6450 popstackmark(&smark);
6455 /* ============ find_command */
6457 static int is_safe_applet(char *name)
6459 /* It isn't a bug to have non-existent applet here... */
6460 /* ...just a waste of space... */
6461 static const char safe_applets[][8] = {
6465 USE_CHMOD (, "chmod" )
6466 USE_CHOWN (, "chown" )
6470 USE_ECHO (, "echo" )
6471 USE_FIND (, "find" )
6472 USE_HEXDUMP(, "hexdump")
6475 USE_MKDIR (, "mkdir" )
6477 USE_SORT (, "sort" )
6478 USE_TEST (, "test" )
6479 USE_TOUCH (, "touch" )
6480 USE_XARGS (, "xargs" )
6482 int n = sizeof(safe_applets) / sizeof(safe_applets[0]);
6484 for (i = 0; i < n; i++)
6485 if (strcmp(safe_applets[i], name) == 0)
6493 int (*builtin)(int, char **);
6494 /* unsigned flags; */
6496 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6497 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6498 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6504 const struct builtincmd *cmd;
6505 struct funcnode *func;
6508 /* values of cmdtype */
6509 #define CMDUNKNOWN -1 /* no entry in table for command */
6510 #define CMDNORMAL 0 /* command is an executable program */
6511 #define CMDFUNCTION 1 /* command is a shell function */
6512 #define CMDBUILTIN 2 /* command is a shell builtin */
6514 /* action to find_command() */
6515 #define DO_ERR 0x01 /* prints errors */
6516 #define DO_ABS 0x02 /* checks absolute paths */
6517 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6518 #define DO_ALTPATH 0x08 /* using alternate path */
6519 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6521 static void find_command(char *, struct cmdentry *, int, const char *);
6524 /* ============ Hashing commands */
6527 * When commands are first encountered, they are entered in a hash table.
6528 * This ensures that a full path search will not have to be done for them
6529 * on each invocation.
6531 * We should investigate converting to a linear search, even though that
6532 * would make the command name "hash" a misnomer.
6535 #define CMDTABLESIZE 31 /* should be prime */
6536 #define ARB 1 /* actual size determined at run time */
6539 struct tblentry *next; /* next entry in hash chain */
6540 union param param; /* definition of builtin function */
6541 short cmdtype; /* index identifying command */
6542 char rehash; /* if set, cd done since entry created */
6543 char cmdname[ARB]; /* name of command */
6546 static struct tblentry *cmdtable[CMDTABLESIZE];
6547 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6550 tryexec(char *cmd, char **argv, char **envp)
6553 struct BB_applet *a;
6557 if (strchr(cmd, '/') == NULL
6558 && (a = find_applet_by_name(cmd)) != NULL
6559 && is_safe_applet(cmd)
6562 while (*c != NULL) {
6566 exit(a->main(argc, argv));
6568 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
6569 if (find_applet_by_name(cmd) != NULL) {
6570 /* re-exec ourselves with the new arguments */
6571 execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
6572 /* If they called chroot or otherwise made the binary no longer
6573 * executable, fall through */
6580 execve(cmd, argv, envp);
6581 } while (errno == EINTR);
6583 execve(cmd, argv, envp);
6587 } else if (errno == ENOEXEC) {
6591 for (ap = argv; *ap; ap++)
6593 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6595 *ap = cmd = (char *)DEFAULT_SHELL;
6598 while ((*ap++ = *argv++))
6606 * Exec a program. Never returns. If you change this routine, you may
6607 * have to change the find_command routine as well.
6609 #define environment() listvars(VEXPORT, VUNSET, 0)
6610 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6612 shellexec(char **argv, const char *path, int idx)
6620 envp = environment();
6621 if (strchr(argv[0], '/') || is_safe_applet(argv[0])
6622 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
6623 || find_applet_by_name(argv[0])
6626 tryexec(argv[0], argv, envp);
6630 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6631 if (--idx < 0 && pathopt == NULL) {
6632 tryexec(cmdname, argv, envp);
6633 if (errno != ENOENT && errno != ENOTDIR)
6640 /* Map to POSIX errors */
6652 exitstatus = exerrno;
6653 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6654 argv[0], e, suppressint ));
6655 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6660 printentry(struct tblentry *cmdp)
6666 idx = cmdp->param.index;
6669 name = padvance(&path, cmdp->cmdname);
6671 } while (--idx >= 0);
6672 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6676 * Clear out command entries. The argument specifies the first entry in
6677 * PATH which has changed.
6680 clearcmdentry(int firstchange)
6682 struct tblentry **tblp;
6683 struct tblentry **pp;
6684 struct tblentry *cmdp;
6687 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6689 while ((cmdp = *pp) != NULL) {
6690 if ((cmdp->cmdtype == CMDNORMAL &&
6691 cmdp->param.index >= firstchange)
6692 || (cmdp->cmdtype == CMDBUILTIN &&
6693 builtinloc >= firstchange)
6706 * Locate a command in the command hash table. If "add" is nonzero,
6707 * add the command to the table if it is not already present. The
6708 * variable "lastcmdentry" is set to point to the address of the link
6709 * pointing to the entry, so that delete_cmd_entry can delete the
6712 * Interrupts must be off if called with add != 0.
6714 static struct tblentry **lastcmdentry;
6716 static struct tblentry *
6717 cmdlookup(const char *name, int add)
6719 unsigned int hashval;
6721 struct tblentry *cmdp;
6722 struct tblentry **pp;
6725 hashval = (unsigned char)*p << 4;
6727 hashval += (unsigned char)*p++;
6729 pp = &cmdtable[hashval % CMDTABLESIZE];
6730 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6731 if (strcmp(cmdp->cmdname, name) == 0)
6735 if (add && cmdp == NULL) {
6736 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6737 + strlen(name) + 1);
6739 cmdp->cmdtype = CMDUNKNOWN;
6740 strcpy(cmdp->cmdname, name);
6747 * Delete the command entry returned on the last lookup.
6750 delete_cmd_entry(void)
6752 struct tblentry *cmdp;
6755 cmdp = *lastcmdentry;
6756 *lastcmdentry = cmdp->next;
6757 if (cmdp->cmdtype == CMDFUNCTION)
6758 freefunc(cmdp->param.func);
6764 * Add a new command entry, replacing any existing command entry for
6765 * the same name - except special builtins.
6768 addcmdentry(char *name, struct cmdentry *entry)
6770 struct tblentry *cmdp;
6772 cmdp = cmdlookup(name, 1);
6773 if (cmdp->cmdtype == CMDFUNCTION) {
6774 freefunc(cmdp->param.func);
6776 cmdp->cmdtype = entry->cmdtype;
6777 cmdp->param = entry->u;
6782 hashcmd(int argc, char **argv)
6784 struct tblentry **pp;
6785 struct tblentry *cmdp;
6787 struct cmdentry entry;
6790 while ((c = nextopt("r")) != '\0') {
6794 if (*argptr == NULL) {
6795 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6796 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6797 if (cmdp->cmdtype == CMDNORMAL)
6804 while ((name = *argptr) != NULL) {
6805 cmdp = cmdlookup(name, 0);
6807 && (cmdp->cmdtype == CMDNORMAL
6808 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6810 find_command(name, &entry, DO_ERR, pathval());
6811 if (entry.cmdtype == CMDUNKNOWN)
6819 * Called when a cd is done. Marks all commands so the next time they
6820 * are executed they will be rehashed.
6825 struct tblentry **pp;
6826 struct tblentry *cmdp;
6828 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6829 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6830 if (cmdp->cmdtype == CMDNORMAL || (
6831 cmdp->cmdtype == CMDBUILTIN &&
6832 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6841 * Fix command hash table when PATH changed.
6842 * Called before PATH is changed. The argument is the new value of PATH;
6843 * pathval() still returns the old value at this point.
6844 * Called with interrupts off.
6847 changepath(const char *newval)
6849 const char *old, *new;
6856 firstchange = 9999; /* assume no change */
6862 if ((*old == '\0' && *new == ':')
6863 || (*old == ':' && *new == '\0'))
6865 old = new; /* ignore subsequent differences */
6869 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6876 if (builtinloc < 0 && idx_bltin >= 0)
6877 builtinloc = idx_bltin; /* zap builtins */
6878 if (builtinloc >= 0 && idx_bltin < 0)
6880 clearcmdentry(firstchange);
6881 builtinloc = idx_bltin;
6896 #define TENDBQUOTE 12
6914 /* first char is indicating which tokens mark the end of a list */
6915 static const char *const tokname_array[] = {
6929 #define KWDOFFSET 13
6930 /* the following are keywords */
6952 static char buf[16];
6956 sprintf(buf + (tok >= TSEMI), "%s%c",
6957 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6961 /* Wrapper around strcmp for qsort/bsearch/... */
6963 pstrcmp(const void *a, const void *b)
6965 return strcmp((const char *) a, (*(const char *const *) b) + 1);
6968 static const char *const *
6969 findkwd(const char *s)
6971 return bsearch(s, tokname_array + KWDOFFSET,
6972 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
6973 sizeof(const char *), pstrcmp);
6977 * Locate and print what a word is...
6979 #if ENABLE_ASH_CMDCMD
6981 describe_command(char *command, int describe_command_verbose)
6983 #define describe_command_verbose 1
6985 describe_command(char *command)
6988 struct cmdentry entry;
6989 struct tblentry *cmdp;
6990 #if ENABLE_ASH_ALIAS
6991 const struct alias *ap;
6993 const char *path = pathval();
6995 if (describe_command_verbose) {
6999 /* First look at the keywords */
7000 if (findkwd(command)) {
7001 out1str(describe_command_verbose ? " is a shell keyword" : command);
7005 #if ENABLE_ASH_ALIAS
7006 /* Then look at the aliases */
7007 ap = lookupalias(command, 0);
7009 if (describe_command_verbose) {
7010 out1fmt(" is an alias for %s", ap->val);
7019 /* Then check if it is a tracked alias */
7020 cmdp = cmdlookup(command, 0);
7022 entry.cmdtype = cmdp->cmdtype;
7023 entry.u = cmdp->param;
7025 /* Finally use brute force */
7026 find_command(command, &entry, DO_ABS, path);
7029 switch (entry.cmdtype) {
7031 int j = entry.u.index;
7037 p = padvance(&path, command);
7041 if (describe_command_verbose) {
7043 (cmdp ? " a tracked alias for" : nullstr), p
7052 if (describe_command_verbose) {
7053 out1str(" is a shell function");
7060 if (describe_command_verbose) {
7061 out1fmt(" is a %sshell builtin",
7062 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7063 "special " : nullstr
7071 if (describe_command_verbose) {
7072 out1str(": not found\n");
7077 outstr("\n", stdout);
7082 typecmd(int argc, char **argv)
7087 for (i = 1; i < argc; i++) {
7088 #if ENABLE_ASH_CMDCMD
7089 err |= describe_command(argv[i], 1);
7091 err |= describe_command(argv[i]);
7097 #if ENABLE_ASH_CMDCMD
7099 commandcmd(int argc, char **argv)
7107 while ((c = nextopt("pvV")) != '\0')
7109 verify |= VERIFY_VERBOSE;
7111 verify |= VERIFY_BRIEF;
7117 return describe_command(*argptr, verify - VERIFY_BRIEF);
7124 /* ============ eval.c */
7126 static int funcblocksize; /* size of structures in function */
7127 static int funcstringsize; /* size of strings in node */
7128 static void *funcblock; /* block to allocate function from */
7129 static char *funcstring; /* block to allocate strings from */
7131 /* flags in argument to evaltree */
7132 #define EV_EXIT 01 /* exit after evaluating tree */
7133 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7134 #define EV_BACKCMD 04 /* command executing within back quotes */
7136 static const short nodesize[26] = {
7137 SHELL_ALIGN(sizeof(struct ncmd)),
7138 SHELL_ALIGN(sizeof(struct npipe)),
7139 SHELL_ALIGN(sizeof(struct nredir)),
7140 SHELL_ALIGN(sizeof(struct nredir)),
7141 SHELL_ALIGN(sizeof(struct nredir)),
7142 SHELL_ALIGN(sizeof(struct nbinary)),
7143 SHELL_ALIGN(sizeof(struct nbinary)),
7144 SHELL_ALIGN(sizeof(struct nbinary)),
7145 SHELL_ALIGN(sizeof(struct nif)),
7146 SHELL_ALIGN(sizeof(struct nbinary)),
7147 SHELL_ALIGN(sizeof(struct nbinary)),
7148 SHELL_ALIGN(sizeof(struct nfor)),
7149 SHELL_ALIGN(sizeof(struct ncase)),
7150 SHELL_ALIGN(sizeof(struct nclist)),
7151 SHELL_ALIGN(sizeof(struct narg)),
7152 SHELL_ALIGN(sizeof(struct narg)),
7153 SHELL_ALIGN(sizeof(struct nfile)),
7154 SHELL_ALIGN(sizeof(struct nfile)),
7155 SHELL_ALIGN(sizeof(struct nfile)),
7156 SHELL_ALIGN(sizeof(struct nfile)),
7157 SHELL_ALIGN(sizeof(struct nfile)),
7158 SHELL_ALIGN(sizeof(struct ndup)),
7159 SHELL_ALIGN(sizeof(struct ndup)),
7160 SHELL_ALIGN(sizeof(struct nhere)),
7161 SHELL_ALIGN(sizeof(struct nhere)),
7162 SHELL_ALIGN(sizeof(struct nnot)),
7165 static void calcsize(union node *n);
7168 sizenodelist(struct nodelist *lp)
7171 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7178 calcsize(union node *n)
7182 funcblocksize += nodesize[n->type];
7185 calcsize(n->ncmd.redirect);
7186 calcsize(n->ncmd.args);
7187 calcsize(n->ncmd.assign);
7190 sizenodelist(n->npipe.cmdlist);
7195 calcsize(n->nredir.redirect);
7196 calcsize(n->nredir.n);
7203 calcsize(n->nbinary.ch2);
7204 calcsize(n->nbinary.ch1);
7207 calcsize(n->nif.elsepart);
7208 calcsize(n->nif.ifpart);
7209 calcsize(n->nif.test);
7212 funcstringsize += strlen(n->nfor.var) + 1;
7213 calcsize(n->nfor.body);
7214 calcsize(n->nfor.args);
7217 calcsize(n->ncase.cases);
7218 calcsize(n->ncase.expr);
7221 calcsize(n->nclist.body);
7222 calcsize(n->nclist.pattern);
7223 calcsize(n->nclist.next);
7227 sizenodelist(n->narg.backquote);
7228 funcstringsize += strlen(n->narg.text) + 1;
7229 calcsize(n->narg.next);
7236 calcsize(n->nfile.fname);
7237 calcsize(n->nfile.next);
7241 calcsize(n->ndup.vname);
7242 calcsize(n->ndup.next);
7246 calcsize(n->nhere.doc);
7247 calcsize(n->nhere.next);
7250 calcsize(n->nnot.com);
7256 nodeckstrdup(char *s)
7258 char *rtn = funcstring;
7260 strcpy(funcstring, s);
7261 funcstring += strlen(s) + 1;
7265 static union node *copynode(union node *);
7267 static struct nodelist *
7268 copynodelist(struct nodelist *lp)
7270 struct nodelist *start;
7271 struct nodelist **lpp;
7276 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7277 (*lpp)->n = copynode(lp->n);
7279 lpp = &(*lpp)->next;
7286 copynode(union node *n)
7293 funcblock = (char *) funcblock + nodesize[n->type];
7297 new->ncmd.redirect = copynode(n->ncmd.redirect);
7298 new->ncmd.args = copynode(n->ncmd.args);
7299 new->ncmd.assign = copynode(n->ncmd.assign);
7302 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7303 new->npipe.backgnd = n->npipe.backgnd;
7308 new->nredir.redirect = copynode(n->nredir.redirect);
7309 new->nredir.n = copynode(n->nredir.n);
7316 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7317 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7320 new->nif.elsepart = copynode(n->nif.elsepart);
7321 new->nif.ifpart = copynode(n->nif.ifpart);
7322 new->nif.test = copynode(n->nif.test);
7325 new->nfor.var = nodeckstrdup(n->nfor.var);
7326 new->nfor.body = copynode(n->nfor.body);
7327 new->nfor.args = copynode(n->nfor.args);
7330 new->ncase.cases = copynode(n->ncase.cases);
7331 new->ncase.expr = copynode(n->ncase.expr);
7334 new->nclist.body = copynode(n->nclist.body);
7335 new->nclist.pattern = copynode(n->nclist.pattern);
7336 new->nclist.next = copynode(n->nclist.next);
7340 new->narg.backquote = copynodelist(n->narg.backquote);
7341 new->narg.text = nodeckstrdup(n->narg.text);
7342 new->narg.next = copynode(n->narg.next);
7349 new->nfile.fname = copynode(n->nfile.fname);
7350 new->nfile.fd = n->nfile.fd;
7351 new->nfile.next = copynode(n->nfile.next);
7355 new->ndup.vname = copynode(n->ndup.vname);
7356 new->ndup.dupfd = n->ndup.dupfd;
7357 new->ndup.fd = n->ndup.fd;
7358 new->ndup.next = copynode(n->ndup.next);
7362 new->nhere.doc = copynode(n->nhere.doc);
7363 new->nhere.fd = n->nhere.fd;
7364 new->nhere.next = copynode(n->nhere.next);
7367 new->nnot.com = copynode(n->nnot.com);
7370 new->type = n->type;
7375 * Make a copy of a parse tree.
7377 static struct funcnode *
7378 copyfunc(union node *n)
7383 funcblocksize = offsetof(struct funcnode, n);
7386 blocksize = funcblocksize;
7387 f = ckmalloc(blocksize + funcstringsize);
7388 funcblock = (char *) f + offsetof(struct funcnode, n);
7389 funcstring = (char *) f + blocksize;
7396 * Define a shell function.
7399 defun(char *name, union node *func)
7401 struct cmdentry entry;
7404 entry.cmdtype = CMDFUNCTION;
7405 entry.u.func = copyfunc(func);
7406 addcmdentry(name, &entry);
7410 static int evalskip; /* set if we are skipping commands */
7411 /* reasons for skipping commands (see comment on breakcmd routine) */
7412 #define SKIPBREAK (1 << 0)
7413 #define SKIPCONT (1 << 1)
7414 #define SKIPFUNC (1 << 2)
7415 #define SKIPFILE (1 << 3)
7416 #define SKIPEVAL (1 << 4)
7417 static int skipcount; /* number of levels to skip */
7418 static int funcnest; /* depth of function calls */
7420 /* forward decl way out to parsing code - dotrap needs it */
7421 static int evalstring(char *s, int mask);
7424 * Called to execute a trap. Perhaps we should avoid entering new trap
7425 * handlers while we are executing a trap handler.
7436 savestatus = exitstatus;
7440 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7448 skip = evalstring(p, SKIPEVAL);
7449 exitstatus = savestatus;
7457 /* forward declarations - evaluation is fairly recursive business... */
7458 static void evalloop(union node *, int);
7459 static void evalfor(union node *, int);
7460 static void evalcase(union node *, int);
7461 static void evalsubshell(union node *, int);
7462 static void expredir(union node *);
7463 static void evalpipe(union node *, int);
7464 static void evalcommand(union node *, int);
7465 static int evalbltin(const struct builtincmd *, int, char **);
7466 static void prehash(union node *);
7469 * Evaluate a parse tree. The value is left in the global variable
7473 evaltree(union node *n, int flags)
7476 void (*evalfn)(union node *, int);
7480 TRACE(("evaltree(NULL) called\n"));
7483 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7484 getpid(), n, n->type, flags));
7488 out1fmt("Node type = %d\n", n->type);
7493 evaltree(n->nnot.com, EV_TESTED);
7494 status = !exitstatus;
7497 expredir(n->nredir.redirect);
7498 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7500 evaltree(n->nredir.n, flags & EV_TESTED);
7501 status = exitstatus;
7506 evalfn = evalcommand;
7508 if (eflag && !(flags & EV_TESTED))
7520 evalfn = evalsubshell;
7532 #error NAND + 1 != NOR
7534 #if NOR + 1 != NSEMI
7535 #error NOR + 1 != NSEMI
7537 isor = n->type - NAND;
7540 (flags | ((isor >> 1) - 1)) & EV_TESTED
7542 if (!exitstatus == isor)
7554 evaltree(n->nif.test, EV_TESTED);
7557 if (exitstatus == 0) {
7560 } else if (n->nif.elsepart) {
7561 n = n->nif.elsepart;
7566 defun(n->narg.text, n->narg.next);
7570 exitstatus = status;
7574 if ((checkexit & exitstatus))
7575 evalskip |= SKIPEVAL;
7576 else if (pendingsigs && dotrap())
7579 if (flags & EV_EXIT) {
7581 raise_exception(EXEXIT);
7585 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7588 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7590 static int loopnest; /* current loop nesting level */
7593 evalloop(union node *n, int flags)
7603 evaltree(n->nbinary.ch1, EV_TESTED);
7606 if (evalskip == SKIPCONT && --skipcount <= 0) {
7610 if (evalskip == SKIPBREAK && --skipcount <= 0)
7615 if (n->type != NWHILE)
7619 evaltree(n->nbinary.ch2, flags);
7620 status = exitstatus;
7625 exitstatus = status;
7629 evalfor(union node *n, int flags)
7631 struct arglist arglist;
7634 struct stackmark smark;
7636 setstackmark(&smark);
7637 arglist.lastp = &arglist.list;
7638 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7639 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7644 *arglist.lastp = NULL;
7649 for (sp = arglist.list; sp; sp = sp->next) {
7650 setvar(n->nfor.var, sp->text, 0);
7651 evaltree(n->nfor.body, flags);
7653 if (evalskip == SKIPCONT && --skipcount <= 0) {
7657 if (evalskip == SKIPBREAK && --skipcount <= 0)
7664 popstackmark(&smark);
7668 evalcase(union node *n, int flags)
7672 struct arglist arglist;
7673 struct stackmark smark;
7675 setstackmark(&smark);
7676 arglist.lastp = &arglist.list;
7677 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7679 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7680 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7681 if (casematch(patp, arglist.list->text)) {
7682 if (evalskip == 0) {
7683 evaltree(cp->nclist.body, flags);
7690 popstackmark(&smark);
7694 * Kick off a subshell to evaluate a tree.
7697 evalsubshell(union node *n, int flags)
7700 int backgnd = (n->type == NBACKGND);
7703 expredir(n->nredir.redirect);
7704 if (!backgnd && flags & EV_EXIT && !trap[0])
7708 if (forkshell(jp, n, backgnd) == 0) {
7712 flags &=~ EV_TESTED;
7714 redirect(n->nredir.redirect, 0);
7715 evaltreenr(n->nredir.n, flags);
7720 status = waitforjob(jp);
7721 exitstatus = status;
7726 * Compute the names of the files in a redirection list.
7728 static void fixredir(union node *, const char *, int);
7730 expredir(union node *n)
7734 for (redir = n; redir; redir = redir->nfile.next) {
7737 memset(&fn, 0, sizeof(fn));
7738 fn.lastp = &fn.list;
7739 switch (redir->type) {
7745 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7746 redir->nfile.expfname = fn.list->text;
7750 if (redir->ndup.vname) {
7751 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7752 if (fn.list == NULL)
7753 ash_msg_and_raise_error("redir error");
7754 fixredir(redir, fn.list->text, 1);
7762 * Evaluate a pipeline. All the processes in the pipeline are children
7763 * of the process creating the pipeline. (This differs from some versions
7764 * of the shell, which make the last process in a pipeline the parent
7768 evalpipe(union node *n, int flags)
7771 struct nodelist *lp;
7776 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7778 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7782 jp = makejob(n, pipelen);
7784 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7788 if (pipe(pip) < 0) {
7790 ash_msg_and_raise_error("Pipe call failed");
7793 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7806 evaltreenr(lp->n, flags);
7814 if (n->npipe.backgnd == 0) {
7815 exitstatus = waitforjob(jp);
7816 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7822 * Controls whether the shell is interactive or not.
7825 setinteractive(int on)
7827 static int is_interactive;
7829 if (++on == is_interactive)
7831 is_interactive = on;
7835 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7836 if (is_interactive > 1) {
7837 /* Looks like they want an interactive shell */
7838 static smallint do_banner;
7843 "%s Built-in shell (ash)\n"
7844 "Enter 'help' for a list of built-in commands."
7853 #if ENABLE_FEATURE_EDITING_VI
7854 #define setvimode(on) do { \
7855 if (on) line_input_state->flags |= VI_MODE; \
7856 else line_input_state->flags &= ~VI_MODE; \
7859 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7868 setinteractive(iflag);
7873 static struct localvar *localvars;
7876 * Called after a function returns.
7877 * Interrupts must be off.
7882 struct localvar *lvp;
7885 while ((lvp = localvars) != NULL) {
7886 localvars = lvp->next;
7888 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7889 if (vp == NULL) { /* $- saved */
7890 memcpy(optlist, lvp->text, sizeof(optlist));
7891 free((char*)lvp->text);
7893 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7897 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7898 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7899 free((char*)vp->text);
7900 vp->flags = lvp->flags;
7901 vp->text = lvp->text;
7908 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7910 volatile struct shparam saveparam;
7911 struct localvar *volatile savelocalvars;
7912 struct jmploc *volatile savehandler;
7913 struct jmploc jmploc;
7916 saveparam = shellparam;
7917 savelocalvars = localvars;
7918 e = setjmp(jmploc.loc);
7923 savehandler = exception_handler;
7924 exception_handler = &jmploc;
7926 shellparam.malloc = 0;
7930 shellparam.nparam = argc - 1;
7931 shellparam.p = argv + 1;
7932 #if ENABLE_ASH_GETOPTS
7933 shellparam.optind = 1;
7934 shellparam.optoff = -1;
7936 evaltree(&func->n, flags & EV_TESTED);
7942 localvars = savelocalvars;
7943 freeparam(&shellparam);
7944 shellparam = saveparam;
7945 exception_handler = savehandler;
7947 evalskip &= ~SKIPFUNC;
7951 #if ENABLE_ASH_CMDCMD
7953 parse_command_args(char **argv, const char **path)
7966 if (c == '-' && !*cp) {
7976 /* run 'typecmd' for other options */
7987 * Make a variable a local variable. When a variable is made local, it's
7988 * value and flags are saved in a localvar structure. The saved values
7989 * will be restored when the shell function returns. We handle the name
7990 * "-" as a special case.
7995 struct localvar *lvp;
8000 lvp = ckmalloc(sizeof(struct localvar));
8001 if (LONE_DASH(name)) {
8003 p = ckmalloc(sizeof(optlist));
8004 lvp->text = memcpy(p, optlist, sizeof(optlist));
8009 vpp = hashvar(name);
8010 vp = *findvar(vpp, name);
8011 eq = strchr(name, '=');
8014 setvareq(name, VSTRFIXED);
8016 setvar(name, NULL, VSTRFIXED);
8017 vp = *vpp; /* the new variable */
8018 lvp->flags = VUNSET;
8020 lvp->text = vp->text;
8021 lvp->flags = vp->flags;
8022 vp->flags |= VSTRFIXED|VTEXTFIXED;
8028 lvp->next = localvars;
8034 * The "local" command.
8037 localcmd(int argc, char **argv)
8042 while ((name = *argv++) != NULL) {
8048 /* Forward declarations for builtintab[] */
8050 static int fg_bgcmd(int, char **);
8052 static int breakcmd(int, char **);
8053 #if ENABLE_ASH_CMDCMD
8054 static int commandcmd(int, char **);
8056 static int dotcmd(int, char **);
8057 static int evalcmd(int, char **);
8058 #if ENABLE_ASH_BUILTIN_ECHO
8059 static int echocmd(int, char **);
8061 #if ENABLE_ASH_BUILTIN_TEST
8062 static int testcmd(int, char **);
8064 static int execcmd(int, char **);
8065 static int exitcmd(int, char **);
8066 static int exportcmd(int, char **);
8067 static int falsecmd(int, char **);
8068 #if ENABLE_ASH_GETOPTS
8069 static int getoptscmd(int, char **);
8071 static int hashcmd(int, char **);
8072 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8073 static int helpcmd(int argc, char **argv);
8076 static int jobscmd(int, char **);
8078 #if ENABLE_ASH_MATH_SUPPORT
8079 static int letcmd(int, char **);
8081 static int pwdcmd(int, char **);
8082 static int readcmd(int, char **);
8083 static int returncmd(int, char **);
8084 static int setcmd(int, char **);
8085 static int shiftcmd(int, char **);
8086 static int timescmd(int, char **);
8087 static int trapcmd(int, char **);
8088 static int truecmd(int, char **);
8089 static int typecmd(int, char **);
8090 static int umaskcmd(int, char **);
8091 static int unsetcmd(int, char **);
8092 static int waitcmd(int, char **);
8093 static int ulimitcmd(int, char **);
8095 static int killcmd(int, char **);
8098 #define BUILTIN_NOSPEC "0"
8099 #define BUILTIN_SPECIAL "1"
8100 #define BUILTIN_REGULAR "2"
8101 #define BUILTIN_SPEC_REG "3"
8102 #define BUILTIN_ASSIGN "4"
8103 #define BUILTIN_SPEC_ASSG "5"
8104 #define BUILTIN_REG_ASSG "6"
8105 #define BUILTIN_SPEC_REG_ASSG "7"
8107 /* make sure to keep these in proper order since it is searched via bsearch() */
8108 static const struct builtincmd builtintab[] = {
8109 { BUILTIN_SPEC_REG ".", dotcmd },
8110 { BUILTIN_SPEC_REG ":", truecmd },
8111 #if ENABLE_ASH_BUILTIN_TEST
8112 { BUILTIN_REGULAR "[", testcmd },
8113 { BUILTIN_REGULAR "[[", testcmd },
8115 #if ENABLE_ASH_ALIAS
8116 { BUILTIN_REG_ASSG "alias", aliascmd },
8119 { BUILTIN_REGULAR "bg", fg_bgcmd },
8121 { BUILTIN_SPEC_REG "break", breakcmd },
8122 { BUILTIN_REGULAR "cd", cdcmd },
8123 { BUILTIN_NOSPEC "chdir", cdcmd },
8124 #if ENABLE_ASH_CMDCMD
8125 { BUILTIN_REGULAR "command", commandcmd },
8127 { BUILTIN_SPEC_REG "continue", breakcmd },
8128 #if ENABLE_ASH_BUILTIN_ECHO
8129 { BUILTIN_REGULAR "echo", echocmd },
8131 { BUILTIN_SPEC_REG "eval", evalcmd },
8132 { BUILTIN_SPEC_REG "exec", execcmd },
8133 { BUILTIN_SPEC_REG "exit", exitcmd },
8134 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8135 { BUILTIN_REGULAR "false", falsecmd },
8137 { BUILTIN_REGULAR "fg", fg_bgcmd },
8139 #if ENABLE_ASH_GETOPTS
8140 { BUILTIN_REGULAR "getopts", getoptscmd },
8142 { BUILTIN_NOSPEC "hash", hashcmd },
8143 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8144 { BUILTIN_NOSPEC "help", helpcmd },
8147 { BUILTIN_REGULAR "jobs", jobscmd },
8148 { BUILTIN_REGULAR "kill", killcmd },
8150 #if ENABLE_ASH_MATH_SUPPORT
8151 { BUILTIN_NOSPEC "let", letcmd },
8153 { BUILTIN_ASSIGN "local", localcmd },
8154 { BUILTIN_NOSPEC "pwd", pwdcmd },
8155 { BUILTIN_REGULAR "read", readcmd },
8156 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8157 { BUILTIN_SPEC_REG "return", returncmd },
8158 { BUILTIN_SPEC_REG "set", setcmd },
8159 { BUILTIN_SPEC_REG "shift", shiftcmd },
8160 { BUILTIN_SPEC_REG "source", dotcmd },
8161 #if ENABLE_ASH_BUILTIN_TEST
8162 { BUILTIN_REGULAR "test", testcmd },
8164 { BUILTIN_SPEC_REG "times", timescmd },
8165 { BUILTIN_SPEC_REG "trap", trapcmd },
8166 { BUILTIN_REGULAR "true", truecmd },
8167 { BUILTIN_NOSPEC "type", typecmd },
8168 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8169 { BUILTIN_REGULAR "umask", umaskcmd },
8170 #if ENABLE_ASH_ALIAS
8171 { BUILTIN_REGULAR "unalias", unaliascmd },
8173 { BUILTIN_SPEC_REG "unset", unsetcmd },
8174 { BUILTIN_REGULAR "wait", waitcmd },
8177 #define NUMBUILTINS (sizeof(builtintab) / sizeof(builtintab[0]))
8179 #define COMMANDCMD (builtintab + 5 + \
8180 2 * ENABLE_ASH_BUILTIN_TEST + \
8181 ENABLE_ASH_ALIAS + \
8182 ENABLE_ASH_JOB_CONTROL)
8183 #define EXECCMD (builtintab + 7 + \
8184 2 * ENABLE_ASH_BUILTIN_TEST + \
8185 ENABLE_ASH_ALIAS + \
8186 ENABLE_ASH_JOB_CONTROL + \
8187 ENABLE_ASH_CMDCMD + \
8188 ENABLE_ASH_BUILTIN_ECHO)
8191 * Search the table of builtin commands.
8193 static struct builtincmd *
8194 find_builtin(const char *name)
8196 struct builtincmd *bp;
8199 name, builtintab, NUMBUILTINS, sizeof(builtintab[0]),
8206 * Execute a simple command.
8208 static int back_exitstatus; /* exit status of backquoted command */
8210 isassignment(const char *p)
8212 const char *q = endofname(p);
8218 bltincmd(int argc, char **argv)
8220 /* Preserve exitstatus of a previous possible redirection
8221 * as POSIX mandates */
8222 return back_exitstatus;
8225 evalcommand(union node *cmd, int flags)
8227 static const struct builtincmd bltin = {
8230 struct stackmark smark;
8232 struct arglist arglist;
8233 struct arglist varlist;
8236 const struct strlist *sp;
8237 struct cmdentry cmdentry;
8245 struct builtincmd *bcmd;
8246 int pseudovarflag = 0;
8248 /* First expand the arguments. */
8249 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8250 setstackmark(&smark);
8251 back_exitstatus = 0;
8253 cmdentry.cmdtype = CMDBUILTIN;
8254 cmdentry.u.cmd = &bltin;
8255 varlist.lastp = &varlist.list;
8256 *varlist.lastp = NULL;
8257 arglist.lastp = &arglist.list;
8258 *arglist.lastp = NULL;
8261 if (cmd->ncmd.args) {
8262 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8263 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8266 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8267 struct strlist **spp;
8269 spp = arglist.lastp;
8270 if (pseudovarflag && isassignment(argp->narg.text))
8271 expandarg(argp, &arglist, EXP_VARTILDE);
8273 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8275 for (sp = *spp; sp; sp = sp->next)
8279 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8280 for (sp = arglist.list; sp; sp = sp->next) {
8281 TRACE(("evalcommand arg: %s\n", sp->text));
8282 *nargv++ = sp->text;
8287 if (iflag && funcnest == 0 && argc > 0)
8288 lastarg = nargv[-1];
8291 expredir(cmd->ncmd.redirect);
8292 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8295 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8296 struct strlist **spp;
8299 spp = varlist.lastp;
8300 expandarg(argp, &varlist, EXP_VARTILDE);
8303 * Modify the command lookup path, if a PATH= assignment
8307 if (varequal(p, path))
8311 /* Print the command if xflag is set. */
8314 const char *p = " %s";
8317 dprintf(preverrout_fd, p, expandstr(ps4val()));
8320 for (n = 0; n < 2; n++) {
8322 dprintf(preverrout_fd, p, sp->text);
8330 full_write(preverrout_fd, "\n", 1);
8336 /* Now locate the command. */
8338 const char *oldpath;
8339 int cmd_flag = DO_ERR;
8344 find_command(argv[0], &cmdentry, cmd_flag, path);
8345 if (cmdentry.cmdtype == CMDUNKNOWN) {
8351 /* implement bltin and command here */
8352 if (cmdentry.cmdtype != CMDBUILTIN)
8355 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8356 if (cmdentry.u.cmd == EXECCMD)
8358 #if ENABLE_ASH_CMDCMD
8359 if (cmdentry.u.cmd == COMMANDCMD) {
8361 nargv = parse_command_args(argv, &path);
8364 argc -= nargv - argv;
8366 cmd_flag |= DO_NOFUNC;
8374 /* We have a redirection error. */
8376 raise_exception(EXERROR);
8378 exitstatus = status;
8382 /* Execute the command. */
8383 switch (cmdentry.cmdtype) {
8385 /* Fork off a child process if necessary. */
8386 if (!(flags & EV_EXIT) || trap[0]) {
8388 jp = makejob(cmd, 1);
8389 if (forkshell(jp, cmd, FORK_FG) != 0) {
8390 exitstatus = waitforjob(jp);
8396 listsetvar(varlist.list, VEXPORT|VSTACK);
8397 shellexec(argv, path, cmdentry.u.index);
8401 cmdenviron = varlist.list;
8403 struct strlist *list = cmdenviron;
8405 if (spclbltin > 0 || argc == 0) {
8407 if (cmd_is_exec && argc > 1)
8410 listsetvar(list, i);
8412 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8427 exit_status = j + 128;
8428 exitstatus = exit_status;
8430 if (i == EXINT || spclbltin > 0) {
8432 longjmp(exception_handler->loc, 1);
8439 listsetvar(varlist.list, 0);
8440 if (evalfun(cmdentry.u.func, argc, argv, flags))
8446 popredir(cmd_is_exec);
8448 /* dsl: I think this is intended to be used to support
8449 * '_' in 'vi' command mode during line editing...
8450 * However I implemented that within libedit itself.
8452 setvar("_", lastarg, 0);
8453 popstackmark(&smark);
8457 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8459 char *volatile savecmdname;
8460 struct jmploc *volatile savehandler;
8461 struct jmploc jmploc;
8464 savecmdname = commandname;
8465 i = setjmp(jmploc.loc);
8468 savehandler = exception_handler;
8469 exception_handler = &jmploc;
8470 commandname = argv[0];
8472 optptr = NULL; /* initialize nextopt */
8473 exitstatus = (*cmd->builtin)(argc, argv);
8474 flush_stdout_stderr();
8476 exitstatus |= ferror(stdout);
8478 commandname = savecmdname;
8480 exception_handler = savehandler;
8486 goodname(const char *p)
8488 return !*endofname(p);
8493 * Search for a command. This is called before we fork so that the
8494 * location of the command will be available in the parent as well as
8495 * the child. The check for "goodname" is an overly conservative
8496 * check that the name will not be subject to expansion.
8499 prehash(union node *n)
8501 struct cmdentry entry;
8503 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8504 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8509 * Builtin commands. Builtin commands whose functions are closely
8510 * tied to evaluation are implemented here.
8514 * Handle break and continue commands. Break, continue, and return are
8515 * all handled by setting the evalskip flag. The evaluation routines
8516 * above all check this flag, and if it is set they start skipping
8517 * commands rather than executing them. The variable skipcount is
8518 * the number of loops to break/continue, or the number of function
8519 * levels to return. (The latter is always 1.) It should probably
8520 * be an error to break out of more loops than exist, but it isn't
8521 * in the standard shell so we don't make it one here.
8525 breakcmd(int argc, char **argv)
8527 int n = argc > 1 ? number(argv[1]) : 1;
8530 ash_msg_and_raise_error(illnum, argv[1]);
8534 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
8541 * The return command.
8544 returncmd(int argc, char **argv)
8547 * If called outside a function, do what ksh does;
8548 * skip the rest of the file.
8550 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8551 return argv[1] ? number(argv[1]) : exitstatus;
8555 falsecmd(int argc, char **argv)
8561 truecmd(int argc, char **argv)
8567 execcmd(int argc, char **argv)
8570 iflag = 0; /* exit on error */
8573 shellexec(argv + 1, pathval(), 0);
8579 /* ============ input.c
8581 * This implements the input routines used by the parser.
8584 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8587 INPUT_PUSH_FILE = 1,
8588 INPUT_NOFILE_OK = 2,
8592 * NEOF is returned by parsecmd when it encounters an end of file. It
8593 * must be distinct from NULL, so we use the address of a variable that
8594 * happens to be handy.
8596 static int plinno = 1; /* input line number */
8597 /* number of characters left in input buffer */
8598 static int parsenleft; /* copy of parsefile->nleft */
8599 static int parselleft; /* copy of parsefile->lleft */
8600 /* next character in input buffer */
8601 static char *parsenextc; /* copy of parsefile->nextc */
8603 static int checkkwd;
8604 /* values of checkkwd variable */
8605 #define CHKALIAS 0x1
8612 struct strpush *sp = parsefile->strpush;
8615 #if ENABLE_ASH_ALIAS
8617 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8618 checkkwd |= CHKALIAS;
8620 if (sp->string != sp->ap->val) {
8623 sp->ap->flag &= ~ALIASINUSE;
8624 if (sp->ap->flag & ALIASDEAD) {
8625 unalias(sp->ap->name);
8629 parsenextc = sp->prevstring;
8630 parsenleft = sp->prevnleft;
8631 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8632 parsefile->strpush = sp->prev;
8633 if (sp != &(parsefile->basestrpush))
8642 char *buf = parsefile->buf;
8646 #if ENABLE_FEATURE_EDITING
8647 if (!iflag || parsefile->fd)
8648 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8650 #if ENABLE_FEATURE_TAB_COMPLETION
8651 line_input_state->path_lookup = pathval();
8653 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8655 /* Ctrl+C pressed */
8664 if (nr < 0 && errno == 0) {
8665 /* Ctrl+D presend */
8670 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8674 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8675 int flags = fcntl(0, F_GETFL, 0);
8676 if (flags >= 0 && flags & O_NONBLOCK) {
8677 flags &=~ O_NONBLOCK;
8678 if (fcntl(0, F_SETFL, flags) >= 0) {
8679 out2str("sh: turning off NDELAY mode\n");
8689 * Refill the input buffer and return the next input character:
8691 * 1) If a string was pushed back on the input, pop it;
8692 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8693 * from a string so we can't refill the buffer, return EOF.
8694 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8695 * 4) Process input up to the next newline, deleting nul characters.
8704 while (parsefile->strpush) {
8705 #if ENABLE_ASH_ALIAS
8706 if (parsenleft == -1 && parsefile->strpush->ap &&
8707 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8712 if (--parsenleft >= 0)
8713 return signed_char2int(*parsenextc++);
8715 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8717 flush_stdout_stderr();
8724 parselleft = parsenleft = EOF_NLEFT;
8731 /* delete nul characters */
8739 memmove(q, q + 1, more);
8743 parsenleft = q - parsenextc - 1;
8749 parsenleft = q - parsenextc - 1;
8761 out2str(parsenextc);
8766 return signed_char2int(*parsenextc++);
8769 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8773 return pgetc_as_macro();
8776 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8777 #define pgetc_macro() pgetc()
8779 #define pgetc_macro() pgetc_as_macro()
8783 * Same as pgetc(), but ignores PEOA.
8785 #if ENABLE_ASH_ALIAS
8793 } while (c == PEOA);
8800 return pgetc_macro();
8805 * Read a line from the script.
8808 pfgets(char *line, int len)
8814 while (--nleft > 0) {
8830 * Undo the last call to pgetc. Only one character may be pushed back.
8831 * PEOF may be pushed back.
8841 * Push a string back onto the input at this current parsefile level.
8842 * We handle aliases this way.
8845 pushstring(char *s, void *ap)
8852 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8853 if (parsefile->strpush) {
8854 sp = ckmalloc(sizeof(struct strpush));
8855 sp->prev = parsefile->strpush;
8856 parsefile->strpush = sp;
8858 sp = parsefile->strpush = &(parsefile->basestrpush);
8859 sp->prevstring = parsenextc;
8860 sp->prevnleft = parsenleft;
8861 #if ENABLE_ASH_ALIAS
8862 sp->ap = (struct alias *)ap;
8864 ((struct alias *)ap)->flag |= ALIASINUSE;
8874 * To handle the "." command, a stack of input files is used. Pushfile
8875 * adds a new entry to the stack and popfile restores the previous level.
8880 struct parsefile *pf;
8882 parsefile->nleft = parsenleft;
8883 parsefile->lleft = parselleft;
8884 parsefile->nextc = parsenextc;
8885 parsefile->linno = plinno;
8886 pf = ckmalloc(sizeof(*pf));
8887 pf->prev = parsefile;
8890 pf->basestrpush.prev = NULL;
8897 struct parsefile *pf = parsefile;
8906 parsefile = pf->prev;
8908 parsenleft = parsefile->nleft;
8909 parselleft = parsefile->lleft;
8910 parsenextc = parsefile->nextc;
8911 plinno = parsefile->linno;
8916 * Return to top level.
8921 while (parsefile != &basepf)
8926 * Close the file(s) that the shell is reading commands from. Called
8927 * after a fork is done.
8933 if (parsefile->fd > 0) {
8934 close(parsefile->fd);
8940 * Like setinputfile, but takes an open file descriptor. Call this with
8944 setinputfd(int fd, int push)
8946 fcntl(fd, F_SETFD, FD_CLOEXEC);
8952 if (parsefile->buf == NULL)
8953 parsefile->buf = ckmalloc(IBUFSIZ);
8954 parselleft = parsenleft = 0;
8959 * Set the input to take input from a file. If push is set, push the
8960 * old input onto the stack first.
8963 setinputfile(const char *fname, int flags)
8969 fd = open(fname, O_RDONLY);
8971 if (flags & INPUT_NOFILE_OK)
8973 ash_msg_and_raise_error("Can't open %s", fname);
8976 fd2 = copyfd(fd, 10);
8979 ash_msg_and_raise_error("Out of file descriptors");
8982 setinputfd(fd, flags & INPUT_PUSH_FILE);
8989 * Like setinputfile, but takes input from a string.
8992 setinputstring(char *string)
8996 parsenextc = string;
8997 parsenleft = strlen(string);
8998 parsefile->buf = NULL;
9004 /* ============ mail.c
9006 * Routines to check for mail.
9011 #define MAXMBOXES 10
9013 /* times of mailboxes */
9014 static time_t mailtime[MAXMBOXES];
9015 /* Set if MAIL or MAILPATH is changed. */
9016 static int mail_var_path_changed;
9019 * Print appropriate message(s) if mail has arrived.
9020 * If mail_var_path_changed is set,
9021 * then the value of MAIL has mail_var_path_changed,
9022 * so we just update the values.
9031 struct stackmark smark;
9034 setstackmark(&smark);
9035 mpath = mpathset() ? mpathval() : mailval();
9036 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9037 p = padvance(&mpath, nullstr);
9042 for (q = p; *q; q++);
9047 q[-1] = '\0'; /* delete trailing '/' */
9048 if (stat(p, &statb) < 0) {
9052 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9055 pathopt ? pathopt : "you have mail"
9058 *mtp = statb.st_mtime;
9060 mail_var_path_changed = 0;
9061 popstackmark(&smark);
9065 changemail(const char *val)
9067 mail_var_path_changed++;
9070 #endif /* ASH_MAIL */
9073 /* ============ ??? */
9076 * Set the shell parameters.
9079 setparam(char **argv)
9085 for (nparam = 0; argv[nparam]; nparam++);
9086 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9088 *ap++ = ckstrdup(*argv++);
9091 freeparam(&shellparam);
9092 shellparam.malloc = 1;
9093 shellparam.nparam = nparam;
9094 shellparam.p = newparam;
9095 #if ENABLE_ASH_GETOPTS
9096 shellparam.optind = 1;
9097 shellparam.optoff = -1;
9102 * Process shell options. The global variable argptr contains a pointer
9103 * to the argument list; we advance it past the options.
9106 minus_o(char *name, int val)
9111 for (i = 0; i < NOPTS; i++) {
9112 if (strcmp(name, optnames(i)) == 0) {
9117 ash_msg_and_raise_error("Illegal option -o %s", name);
9119 out1str("Current option settings\n");
9120 for (i = 0; i < NOPTS; i++)
9121 out1fmt("%-16s%s\n", optnames(i),
9122 optlist[i] ? "on" : "off");
9125 setoption(int flag, int val)
9129 for (i = 0; i < NOPTS; i++) {
9130 if (optletters(i) == flag) {
9135 ash_msg_and_raise_error("Illegal option -%c", flag);
9139 options(int cmdline)
9147 while ((p = *argptr) != NULL) {
9152 if (p[0] == '\0' || LONE_DASH(p)) {
9154 /* "-" means turn off -x and -v */
9157 /* "--" means reset params */
9158 else if (*argptr == NULL)
9161 break; /* "-" or "--" terminates options */
9163 } else if (c == '+') {
9169 while ((c = *p++) != '\0') {
9170 if (c == 'c' && cmdline) {
9171 minusc = p; /* command is after shell args*/
9172 } else if (c == 'o') {
9173 minus_o(*argptr, val);
9176 } else if (cmdline && (c == '-')) { // long options
9177 if (strcmp(p, "login") == 0)
9188 * The shift builtin command.
9191 shiftcmd(int argc, char **argv)
9198 n = number(argv[1]);
9199 if (n > shellparam.nparam)
9200 ash_msg_and_raise_error("can't shift that many");
9202 shellparam.nparam -= n;
9203 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9204 if (shellparam.malloc)
9208 while ((*ap2++ = *ap1++) != NULL);
9209 #if ENABLE_ASH_GETOPTS
9210 shellparam.optind = 1;
9211 shellparam.optoff = -1;
9218 * POSIX requires that 'set' (but not export or readonly) output the
9219 * variables in lexicographic order - by the locale's collating order (sigh).
9220 * Maybe we could keep them in an ordered balanced binary tree
9221 * instead of hashed lists.
9222 * For now just roll 'em through qsort for printing...
9225 showvars(const char *sep_prefix, int on, int off)
9230 ep = listvars(on, off, &epend);
9231 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9233 sep = *sep_prefix ? " " : sep_prefix;
9235 for (; ep < epend; ep++) {
9239 p = strchrnul(*ep, '=');
9242 q = single_quote(++p);
9243 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9249 * The set command builtin.
9252 setcmd(int argc, char **argv)
9255 return showvars(nullstr, 0, VUNSET);
9259 if (*argptr != NULL) {
9266 #if ENABLE_ASH_RANDOM_SUPPORT
9267 /* Roughly copied from bash.. */
9269 change_random(const char *value)
9271 if (value == NULL) {
9272 /* "get", generate */
9275 rseed = rseed * 1103515245 + 12345;
9276 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9277 /* set without recursion */
9278 setvar(vrandom.text, buf, VNOFUNC);
9279 vrandom.flags &= ~VNOFUNC;
9282 rseed = strtoul(value, (char **)NULL, 10);
9287 #if ENABLE_ASH_GETOPTS
9289 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9298 if (*param_optind < 1)
9300 optnext = optfirst + *param_optind - 1;
9302 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9305 p = optnext[-1] + *optoff;
9306 if (p == NULL || *p == '\0') {
9307 /* Current word is done, advance */
9309 if (p == NULL || *p != '-' || *++p == '\0') {
9316 if (LONE_DASH(p)) /* check for "--" */
9321 for (q = optstr; *q != c; ) {
9323 if (optstr[0] == ':') {
9326 err |= setvarsafe("OPTARG", s, 0);
9328 fprintf(stderr, "Illegal option -%c\n", c);
9339 if (*p == '\0' && (p = *optnext) == NULL) {
9340 if (optstr[0] == ':') {
9343 err |= setvarsafe("OPTARG", s, 0);
9346 fprintf(stderr, "No arg for -%c option\n", c);
9355 err |= setvarsafe("OPTARG", p, 0);
9358 err |= setvarsafe("OPTARG", nullstr, 0);
9360 *optoff = p ? p - *(optnext - 1) : -1;
9361 *param_optind = optnext - optfirst + 1;
9362 fmtstr(s, sizeof(s), "%d", *param_optind);
9363 err |= setvarsafe("OPTIND", s, VNOFUNC);
9366 err |= setvarsafe(optvar, s, 0);
9370 flush_stdout_stderr();
9371 raise_exception(EXERROR);
9377 * The getopts builtin. Shellparam.optnext points to the next argument
9378 * to be processed. Shellparam.optptr points to the next character to
9379 * be processed in the current argument. If shellparam.optnext is NULL,
9380 * then it's the first time getopts has been called.
9383 getoptscmd(int argc, char **argv)
9388 ash_msg_and_raise_error("Usage: getopts optstring var [arg]");
9390 optbase = shellparam.p;
9391 if (shellparam.optind > shellparam.nparam + 1) {
9392 shellparam.optind = 1;
9393 shellparam.optoff = -1;
9397 if (shellparam.optind > argc - 2) {
9398 shellparam.optind = 1;
9399 shellparam.optoff = -1;
9403 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9404 &shellparam.optoff);
9406 #endif /* ASH_GETOPTS */
9409 /* ============ Shell parser */
9411 static int tokpushback; /* last token pushed back */
9412 #define NEOF ((union node *)&tokpushback)
9413 static int parsebackquote; /* nonzero if we are inside backquotes */
9414 static int lasttoken; /* last token read */
9415 static char *wordtext; /* text of last word returned by readtoken */
9416 static struct nodelist *backquotelist;
9417 static union node *redirnode;
9418 static struct heredoc *heredoc;
9419 static int quoteflag; /* set if (part of) last token was quoted */
9421 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9423 raise_error_syntax(const char *msg)
9425 ash_msg_and_raise_error("Syntax error: %s", msg);
9430 * Called when an unexpected token is read during the parse. The argument
9431 * is the token that is expected, or -1 if more than one type of token can
9432 * occur at this point.
9434 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9436 raise_error_unexpected_syntax(int token)
9441 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9443 sprintf(msg + l, " (expecting %s)", tokname(token));
9444 raise_error_syntax(msg);
9448 #define EOFMARKLEN 79
9451 struct heredoc *next; /* next here document in list */
9452 union node *here; /* redirection node */
9453 char *eofmark; /* string indicating end of input */
9454 int striptabs; /* if set, strip leading tabs */
9457 static struct heredoc *heredoclist; /* list of here documents to read */
9459 /* parsing is heavily cross-recursive, need these forward decls */
9460 static union node *andor(void);
9461 static union node *pipeline(void);
9462 static union node *parse_command(void);
9463 static void parseheredoc(void);
9464 static char peektoken(void);
9465 static int readtoken(void);
9470 union node *n1, *n2, *n3;
9473 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9474 if (nlflag == 2 && peektoken())
9480 if (tok == TBACKGND) {
9481 if (n2->type == NPIPE) {
9482 n2->npipe.backgnd = 1;
9484 if (n2->type != NREDIR) {
9485 n3 = stalloc(sizeof(struct nredir));
9487 n3->nredir.redirect = NULL;
9490 n2->type = NBACKGND;
9496 n3 = stalloc(sizeof(struct nbinary));
9498 n3->nbinary.ch1 = n1;
9499 n3->nbinary.ch2 = n2;
9515 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9523 pungetc(); /* push back EOF on input */
9527 raise_error_unexpected_syntax(-1);
9537 union node *n1, *n2, *n3;
9545 } else if (t == TOR) {
9551 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9553 n3 = stalloc(sizeof(struct nbinary));
9555 n3->nbinary.ch1 = n1;
9556 n3->nbinary.ch2 = n2;
9564 union node *n1, *n2, *pipenode;
9565 struct nodelist *lp, *prev;
9569 TRACE(("pipeline: entered\n"));
9570 if (readtoken() == TNOT) {
9572 checkkwd = CHKKWD | CHKALIAS;
9575 n1 = parse_command();
9576 if (readtoken() == TPIPE) {
9577 pipenode = stalloc(sizeof(struct npipe));
9578 pipenode->type = NPIPE;
9579 pipenode->npipe.backgnd = 0;
9580 lp = stalloc(sizeof(struct nodelist));
9581 pipenode->npipe.cmdlist = lp;
9585 lp = stalloc(sizeof(struct nodelist));
9586 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9587 lp->n = parse_command();
9589 } while (readtoken() == TPIPE);
9595 n2 = stalloc(sizeof(struct nnot));
9608 n = stalloc(sizeof(struct narg));
9610 n->narg.next = NULL;
9611 n->narg.text = wordtext;
9612 n->narg.backquote = backquotelist;
9617 fixredir(union node *n, const char *text, int err)
9619 TRACE(("Fix redir %s %d\n", text, err));
9621 n->ndup.vname = NULL;
9623 if (isdigit(text[0]) && text[1] == '\0')
9624 n->ndup.dupfd = text[0] - '0';
9625 else if (LONE_DASH(text))
9629 raise_error_syntax("Bad fd number");
9630 n->ndup.vname = makename();
9635 * Returns true if the text contains nothing to expand (no dollar signs
9639 noexpand(char *text)
9645 while ((c = *p++) != '\0') {
9646 if (c == CTLQUOTEMARK)
9650 else if (SIT(c, BASESYNTAX) == CCTL)
9659 union node *n = redirnode;
9661 if (readtoken() != TWORD)
9662 raise_error_unexpected_syntax(-1);
9663 if (n->type == NHERE) {
9664 struct heredoc *here = heredoc;
9670 TRACE(("Here document %d\n", n->type));
9671 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9672 raise_error_syntax("Illegal eof marker for << redirection");
9673 rmescapes(wordtext);
9674 here->eofmark = wordtext;
9676 if (heredoclist == NULL)
9679 for (p = heredoclist; p->next; p = p->next);
9682 } else if (n->type == NTOFD || n->type == NFROMFD) {
9683 fixredir(n, wordtext, 0);
9685 n->nfile.fname = makename();
9692 union node *args, **app;
9693 union node *n = NULL;
9694 union node *vars, **vpp;
9695 union node **rpp, *redir;
9705 savecheckkwd = CHKALIAS;
9707 checkkwd = savecheckkwd;
9708 switch (readtoken()) {
9710 n = stalloc(sizeof(struct narg));
9712 n->narg.text = wordtext;
9713 n->narg.backquote = backquotelist;
9714 if (savecheckkwd && isassignment(wordtext)) {
9716 vpp = &n->narg.next;
9719 app = &n->narg.next;
9724 *rpp = n = redirnode;
9725 rpp = &n->nfile.next;
9726 parsefname(); /* read name of redirection file */
9729 if (args && app == &args->narg.next
9732 struct builtincmd *bcmd;
9735 /* We have a function */
9736 if (readtoken() != TRP)
9737 raise_error_unexpected_syntax(TRP);
9738 name = n->narg.text;
9740 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9742 raise_error_syntax("Bad function name");
9745 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9746 n->narg.next = parse_command();
9759 n = stalloc(sizeof(struct ncmd));
9761 n->ncmd.args = args;
9762 n->ncmd.assign = vars;
9763 n->ncmd.redirect = redir;
9770 union node *n1, *n2;
9771 union node *ap, **app;
9772 union node *cp, **cpp;
9773 union node *redir, **rpp;
9780 switch (readtoken()) {
9782 raise_error_unexpected_syntax(-1);
9785 n1 = stalloc(sizeof(struct nif));
9787 n1->nif.test = list(0);
9788 if (readtoken() != TTHEN)
9789 raise_error_unexpected_syntax(TTHEN);
9790 n1->nif.ifpart = list(0);
9792 while (readtoken() == TELIF) {
9793 n2->nif.elsepart = stalloc(sizeof(struct nif));
9794 n2 = n2->nif.elsepart;
9796 n2->nif.test = list(0);
9797 if (readtoken() != TTHEN)
9798 raise_error_unexpected_syntax(TTHEN);
9799 n2->nif.ifpart = list(0);
9801 if (lasttoken == TELSE)
9802 n2->nif.elsepart = list(0);
9804 n2->nif.elsepart = NULL;
9812 n1 = stalloc(sizeof(struct nbinary));
9813 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9814 n1->nbinary.ch1 = list(0);
9817 TRACE(("expecting DO got %s %s\n", tokname(got),
9818 got == TWORD ? wordtext : ""));
9819 raise_error_unexpected_syntax(TDO);
9821 n1->nbinary.ch2 = list(0);
9826 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9827 raise_error_syntax("Bad for loop variable");
9828 n1 = stalloc(sizeof(struct nfor));
9830 n1->nfor.var = wordtext;
9831 checkkwd = CHKKWD | CHKALIAS;
9832 if (readtoken() == TIN) {
9834 while (readtoken() == TWORD) {
9835 n2 = stalloc(sizeof(struct narg));
9837 n2->narg.text = wordtext;
9838 n2->narg.backquote = backquotelist;
9840 app = &n2->narg.next;
9844 if (lasttoken != TNL && lasttoken != TSEMI)
9845 raise_error_unexpected_syntax(-1);
9847 n2 = stalloc(sizeof(struct narg));
9849 n2->narg.text = (char *)dolatstr;
9850 n2->narg.backquote = NULL;
9851 n2->narg.next = NULL;
9854 * Newline or semicolon here is optional (but note
9855 * that the original Bourne shell only allowed NL).
9857 if (lasttoken != TNL && lasttoken != TSEMI)
9860 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9861 if (readtoken() != TDO)
9862 raise_error_unexpected_syntax(TDO);
9863 n1->nfor.body = list(0);
9867 n1 = stalloc(sizeof(struct ncase));
9869 if (readtoken() != TWORD)
9870 raise_error_unexpected_syntax(TWORD);
9871 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9873 n2->narg.text = wordtext;
9874 n2->narg.backquote = backquotelist;
9875 n2->narg.next = NULL;
9877 checkkwd = CHKKWD | CHKALIAS;
9878 } while (readtoken() == TNL);
9879 if (lasttoken != TIN)
9880 raise_error_unexpected_syntax(TIN);
9881 cpp = &n1->ncase.cases;
9883 checkkwd = CHKNL | CHKKWD;
9885 while (t != TESAC) {
9886 if (lasttoken == TLP)
9888 *cpp = cp = stalloc(sizeof(struct nclist));
9890 app = &cp->nclist.pattern;
9892 *app = ap = stalloc(sizeof(struct narg));
9894 ap->narg.text = wordtext;
9895 ap->narg.backquote = backquotelist;
9896 if (readtoken() != TPIPE)
9898 app = &ap->narg.next;
9901 ap->narg.next = NULL;
9902 if (lasttoken != TRP)
9903 raise_error_unexpected_syntax(TRP);
9904 cp->nclist.body = list(2);
9906 cpp = &cp->nclist.next;
9908 checkkwd = CHKNL | CHKKWD;
9912 raise_error_unexpected_syntax(TENDCASE);
9919 n1 = stalloc(sizeof(struct nredir));
9920 n1->type = NSUBSHELL;
9921 n1->nredir.n = list(0);
9922 n1->nredir.redirect = NULL;
9935 if (readtoken() != t)
9936 raise_error_unexpected_syntax(t);
9939 /* Now check for redirection which may follow command */
9940 checkkwd = CHKKWD | CHKALIAS;
9942 while (readtoken() == TREDIR) {
9943 *rpp = n2 = redirnode;
9944 rpp = &n2->nfile.next;
9950 if (n1->type != NSUBSHELL) {
9951 n2 = stalloc(sizeof(struct nredir));
9956 n1->nredir.redirect = redir;
9962 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9963 * is not NULL, read a here document. In the latter case, eofmark is the
9964 * word which marks the end of the document and striptabs is true if
9965 * leading tabs should be stripped from the document. The argument firstc
9966 * is the first character of the input token or document.
9968 * Because C does not have internal subroutines, I have simulated them
9969 * using goto's to implement the subroutine linkage. The following macros
9970 * will run code that appears at the end of readtoken1.
9973 static int parsebackquote; /* nonzero if we are inside backquotes */
9975 #define CHECKEND() {goto checkend; checkend_return:;}
9976 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9977 #define PARSESUB() {goto parsesub; parsesub_return:;}
9978 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9979 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9980 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9983 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9988 char line[EOFMARKLEN + 1];
9989 struct nodelist *bqlist = 0;
9992 int varnest = 0; /* levels of variables expansion */
9993 int arinest = 0; /* levels of arithmetic expansion */
9994 int parenlevel = 0; /* levels of parens in arithmetic */
9995 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9997 int prevsyntax = 0; /* syntax before arithmetic */
9999 /* Avoid longjmp clobbering */
10005 (void) &parenlevel;
10008 (void) &prevsyntax;
10012 startlinno = plinno;
10014 if (syntax == DQSYNTAX)
10023 STARTSTACKSTR(out);
10024 loop: { /* for each line, until end of word */
10025 CHECKEND(); /* set c to PEOF if at end of here document */
10026 for (;;) { /* until end of line or end of word */
10027 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10028 switch (SIT(c, syntax)) {
10029 case CNL: /* '\n' */
10030 if (syntax == BASESYNTAX)
10031 goto endword; /* exit outer loop */
10037 goto loop; /* continue outer loop */
10042 if (eofmark == NULL || dblquote)
10043 USTPUTC(CTLESC, out);
10046 case CBACK: /* backslash */
10049 USTPUTC(CTLESC, out);
10050 USTPUTC('\\', out);
10052 } else if (c == '\n') {
10057 c != '\\' && c != '`' &&
10062 USTPUTC(CTLESC, out);
10063 USTPUTC('\\', out);
10065 if (SIT(c, SQSYNTAX) == CCTL)
10066 USTPUTC(CTLESC, out);
10074 if (eofmark == NULL) {
10075 USTPUTC(CTLQUOTEMARK, out);
10083 if (eofmark != NULL && arinest == 0
10088 if (dqvarnest == 0) {
10089 syntax = BASESYNTAX;
10096 case CVAR: /* '$' */
10097 PARSESUB(); /* parse substitution */
10099 case CENDVAR: /* '}' */
10102 if (dqvarnest > 0) {
10105 USTPUTC(CTLENDVAR, out);
10110 #if ENABLE_ASH_MATH_SUPPORT
10111 case CLP: /* '(' in arithmetic */
10115 case CRP: /* ')' in arithmetic */
10116 if (parenlevel > 0) {
10120 if (pgetc() == ')') {
10121 if (--arinest == 0) {
10122 USTPUTC(CTLENDARI, out);
10123 syntax = prevsyntax;
10124 if (syntax == DQSYNTAX)
10132 * unbalanced parens
10133 * (don't 2nd guess - no error)
10141 case CBQUOTE: /* '`' */
10145 goto endword; /* exit outer loop */
10150 goto endword; /* exit outer loop */
10151 #if ENABLE_ASH_ALIAS
10161 #if ENABLE_ASH_MATH_SUPPORT
10162 if (syntax == ARISYNTAX)
10163 raise_error_syntax("Missing '))'");
10165 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10166 raise_error_syntax("Unterminated quoted string");
10167 if (varnest != 0) {
10168 startlinno = plinno;
10170 raise_error_syntax("Missing '}'");
10172 USTPUTC('\0', out);
10173 len = out - (char *)stackblock();
10174 out = stackblock();
10175 if (eofmark == NULL) {
10176 if ((c == '>' || c == '<')
10179 && (*out == '\0' || isdigit(*out))) {
10181 return lasttoken = TREDIR;
10186 quoteflag = quotef;
10187 backquotelist = bqlist;
10188 grabstackblock(len);
10192 /* end of readtoken routine */
10195 * Check to see whether we are at the end of the here document. When this
10196 * is called, c is set to the first character of the next input line. If
10197 * we are at the end of the here document, this routine sets the c to PEOF.
10201 #if ENABLE_ASH_ALIAS
10207 while (c == '\t') {
10211 if (c == *eofmark) {
10212 if (pfgets(line, sizeof(line)) != NULL) {
10216 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10217 if (*p == '\n' && *q == '\0') {
10220 needprompt = doprompt;
10222 pushstring(line, NULL);
10227 goto checkend_return;
10231 * Parse a redirection operator. The variable "out" points to a string
10232 * specifying the fd to be redirected. The variable "c" contains the
10233 * first character of the redirection operator.
10239 np = stalloc(sizeof(struct nfile));
10244 np->type = NAPPEND;
10246 np->type = NCLOBBER;
10253 } else { /* c == '<' */
10258 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10259 np = stalloc(sizeof(struct nhere));
10263 heredoc = stalloc(sizeof(struct heredoc));
10264 heredoc->here = np;
10267 heredoc->striptabs = 1;
10269 heredoc->striptabs = 0;
10275 np->type = NFROMFD;
10279 np->type = NFROMTO;
10289 np->nfile.fd = fd - '0';
10291 goto parseredir_return;
10295 * Parse a substitution. At this point, we have read the dollar sign
10296 * and nothing else.
10299 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10300 * (assuming ascii char codes, as the original implementation did) */
10301 #define is_special(c) \
10302 ((((unsigned int)c) - 33 < 32) \
10303 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10309 static const char types[] = "}-+?=";
10313 c <= PEOA_OR_PEOF ||
10314 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10318 } else if (c == '(') { /* $(command) or $((arith)) */
10319 if (pgetc() == '(') {
10320 #if ENABLE_ASH_MATH_SUPPORT
10323 raise_error_syntax("We unsupport $((arith))");
10330 USTPUTC(CTLVAR, out);
10331 typeloc = out - (char *)stackblock();
10332 USTPUTC(VSNORMAL, out);
10333 subtype = VSNORMAL;
10341 subtype = VSLENGTH;
10345 if (c > PEOA_OR_PEOF && is_name(c)) {
10349 } while (c > PEOA_OR_PEOF && is_in_name(c));
10350 } else if (isdigit(c)) {
10354 } while (isdigit(c));
10355 } else if (is_special(c)) {
10359 badsub: raise_error_syntax("Bad substitution");
10363 if (subtype == 0) {
10370 p = strchr(types, c);
10373 subtype = p - types + VSNORMAL;
10379 subtype = c == '#' ? VSTRIMLEFT :
10392 if (dblquote || arinest)
10394 *((char *)stackblock() + typeloc) = subtype | flags;
10395 if (subtype != VSNORMAL) {
10397 if (dblquote || arinest) {
10402 goto parsesub_return;
10406 * Called to parse command substitutions. Newstyle is set if the command
10407 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10408 * list of commands (passed by reference), and savelen is the number of
10409 * characters on the top of the stack which must be preserved.
10412 struct nodelist **nlpp;
10415 char *volatile str;
10416 struct jmploc jmploc;
10417 struct jmploc *volatile savehandler;
10419 int saveprompt = 0;
10421 (void) &saveprompt;
10424 savepbq = parsebackquote;
10425 if (setjmp(jmploc.loc)) {
10428 parsebackquote = 0;
10429 exception_handler = savehandler;
10430 longjmp(exception_handler->loc, 1);
10434 savelen = out - (char *)stackblock();
10436 str = ckmalloc(savelen);
10437 memcpy(str, stackblock(), savelen);
10439 savehandler = exception_handler;
10440 exception_handler = &jmploc;
10443 /* We must read until the closing backquote, giving special
10444 treatment to some slashes, and then push the string and
10445 reread it as input, interpreting it normally. */
10452 STARTSTACKSTR(pout);
10469 * If eating a newline, avoid putting
10470 * the newline into the new character
10471 * stream (via the STPUTC after the
10476 if (pc != '\\' && pc != '`' && pc != '$'
10477 && (!dblquote || pc != '"'))
10478 STPUTC('\\', pout);
10479 if (pc > PEOA_OR_PEOF) {
10485 #if ENABLE_ASH_ALIAS
10488 startlinno = plinno;
10489 raise_error_syntax("EOF in backquote substitution");
10493 needprompt = doprompt;
10502 STPUTC('\0', pout);
10503 psavelen = pout - (char *)stackblock();
10504 if (psavelen > 0) {
10505 pstr = grabstackstr(pout);
10506 setinputstring(pstr);
10511 nlpp = &(*nlpp)->next;
10512 *nlpp = stalloc(sizeof(**nlpp));
10513 (*nlpp)->next = NULL;
10514 parsebackquote = oldstyle;
10517 saveprompt = doprompt;
10524 doprompt = saveprompt;
10525 else if (readtoken() != TRP)
10526 raise_error_unexpected_syntax(TRP);
10531 * Start reading from old file again, ignoring any pushed back
10532 * tokens left from the backquote parsing
10537 while (stackblocksize() <= savelen)
10539 STARTSTACKSTR(out);
10541 memcpy(out, str, savelen);
10542 STADJUST(savelen, out);
10548 parsebackquote = savepbq;
10549 exception_handler = savehandler;
10550 if (arinest || dblquote)
10551 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10553 USTPUTC(CTLBACKQ, out);
10555 goto parsebackq_oldreturn;
10556 goto parsebackq_newreturn;
10559 #if ENABLE_ASH_MATH_SUPPORT
10561 * Parse an arithmetic expansion (indicate start of one and set state)
10564 if (++arinest == 1) {
10565 prevsyntax = syntax;
10566 syntax = ARISYNTAX;
10567 USTPUTC(CTLARI, out);
10574 * we collapse embedded arithmetic expansion to
10575 * parenthesis, which should be equivalent
10579 goto parsearith_return;
10583 } /* end of readtoken */
10586 * Read the next input token.
10587 * If the token is a word, we set backquotelist to the list of cmds in
10588 * backquotes. We set quoteflag to true if any part of the word was
10590 * If the token is TREDIR, then we set redirnode to a structure containing
10592 * In all cases, the variable startlinno is set to the number of the line
10593 * on which the token starts.
10595 * [Change comment: here documents and internal procedures]
10596 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10597 * word parsing code into a separate routine. In this case, readtoken
10598 * doesn't need to have any internal procedures, but parseword does.
10599 * We could also make parseoperator in essence the main routine, and
10600 * have parseword (readtoken1?) handle both words and redirection.]
10602 #define NEW_xxreadtoken
10603 #ifdef NEW_xxreadtoken
10604 /* singles must be first! */
10605 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10607 static const char xxreadtoken_tokens[] = {
10608 TNL, TLP, TRP, /* only single occurrence allowed */
10609 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10610 TEOF, /* corresponds to trailing nul */
10611 TAND, TOR, TENDCASE, /* if double occurrence */
10614 #define xxreadtoken_doubles \
10615 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10616 #define xxreadtoken_singles \
10617 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10631 startlinno = plinno;
10632 for (;;) { /* until token or start of word found */
10635 if ((c != ' ') && (c != '\t')
10636 #if ENABLE_ASH_ALIAS
10641 while ((c = pgetc()) != '\n' && c != PEOF);
10643 } else if (c == '\\') {
10644 if (pgetc() != '\n') {
10648 startlinno = ++plinno;
10653 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10658 needprompt = doprompt;
10661 p = strchr(xxreadtoken_chars, c);
10664 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10667 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10668 if (pgetc() == *p) { /* double occurrence? */
10669 p += xxreadtoken_doubles + 1;
10675 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10681 #define RETURN(token) return lasttoken = token
10694 startlinno = plinno;
10695 for (;;) { /* until token or start of word found */
10698 case ' ': case '\t':
10699 #if ENABLE_ASH_ALIAS
10704 while ((c = pgetc()) != '\n' && c != PEOF);
10708 if (pgetc() == '\n') {
10709 startlinno = ++plinno;
10718 needprompt = doprompt;
10723 if (pgetc() == '&')
10728 if (pgetc() == '|')
10733 if (pgetc() == ';')
10746 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10749 #endif /* NEW_xxreadtoken */
10756 int alreadyseen = tokpushback;
10759 #if ENABLE_ASH_ALIAS
10768 if (checkkwd & CHKNL) {
10775 if (t != TWORD || quoteflag) {
10780 * check for keywords
10782 if (checkkwd & CHKKWD) {
10783 const char *const *pp;
10785 pp = findkwd(wordtext);
10787 lasttoken = t = pp - tokname_array;
10788 TRACE(("keyword %s recognized\n", tokname(t)));
10793 if (checkkwd & CHKALIAS) {
10794 #if ENABLE_ASH_ALIAS
10796 ap = lookupalias(wordtext, 1);
10799 pushstring(ap->val, ap);
10809 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10811 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10823 return tokname_array[t][0];
10827 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10828 * valid parse tree indicating a blank line.)
10830 static union node *
10831 parsecmd(int interact)
10836 doprompt = interact;
10838 setprompt(doprompt);
10850 * Input any here documents.
10855 struct heredoc *here;
10858 here = heredoclist;
10865 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10866 here->eofmark, here->striptabs);
10867 n = stalloc(sizeof(struct narg));
10868 n->narg.type = NARG;
10869 n->narg.next = NULL;
10870 n->narg.text = wordtext;
10871 n->narg.backquote = backquotelist;
10872 here->here->nhere.doc = n;
10879 * called by editline -- any expansions to the prompt
10880 * should be added here.
10882 #if ENABLE_ASH_EXPAND_PRMT
10883 static const char *
10884 expandstr(const char *ps)
10888 /* XXX Fix (char *) cast. */
10889 setinputstring((char *)ps);
10890 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10893 n.narg.type = NARG;
10894 n.narg.next = NULL;
10895 n.narg.text = wordtext;
10896 n.narg.backquote = backquotelist;
10898 expandarg(&n, NULL, 0);
10899 return stackblock();
10905 * Execute a command or commands contained in a string.
10908 evalstring(char *s, int mask)
10911 struct stackmark smark;
10915 setstackmark(&smark);
10918 while ((n = parsecmd(0)) != NEOF) {
10920 popstackmark(&smark);
10933 * The eval command.
10936 evalcmd(int argc, char **argv)
10945 STARTSTACKSTR(concat);
10948 concat = stack_putstr(p, concat);
10952 STPUTC(' ', concat);
10954 STPUTC('\0', concat);
10955 p = grabstackstr(concat);
10957 evalstring(p, ~SKIPEVAL);
10964 * Read and execute commands. "Top" is nonzero for the top level command
10965 * loop; it turns on prompting if the shell is interactive.
10971 struct stackmark smark;
10975 TRACE(("cmdloop(%d) called\n", top));
10979 setstackmark(&smark);
10982 showjobs(stderr, SHOW_CHANGED);
10985 if (iflag && top) {
10987 #if ENABLE_ASH_MAIL
10991 n = parsecmd(inter);
10992 /* showtree(n); DEBUG */
10994 if (!top || numeof >= 50)
10996 if (!stoppedjobs()) {
10999 out2str("\nUse \"exit\" to leave shell.\n");
11002 } else if (nflag == 0) {
11003 job_warning = (job_warning == 2) ? 1 : 0;
11007 popstackmark(&smark);
11012 return skip & SKIPEVAL;
11019 * Take commands from a file. To be compatible we should do a path
11020 * search for the file, which is necessary to find sub-commands.
11023 find_dot_file(char *name)
11026 const char *path = pathval();
11029 /* don't try this for absolute or relative paths */
11030 if (strchr(name, '/'))
11033 while ((fullname = padvance(&path, name)) != NULL) {
11034 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11036 * Don't bother freeing here, since it will
11037 * be freed by the caller.
11041 stunalloc(fullname);
11044 /* not found in the PATH */
11045 ash_msg_and_raise_error("%s: not found", name);
11050 dotcmd(int argc, char **argv)
11052 struct strlist *sp;
11053 volatile struct shparam saveparam;
11056 for (sp = cmdenviron; sp; sp = sp->next)
11057 setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11059 if (argc >= 2) { /* That's what SVR2 does */
11062 fullname = find_dot_file(argv[1]);
11065 saveparam = shellparam;
11066 shellparam.malloc = 0;
11067 shellparam.nparam = argc - 2;
11068 shellparam.p = argv + 2;
11071 setinputfile(fullname, INPUT_PUSH_FILE);
11072 commandname = fullname;
11077 freeparam(&shellparam);
11078 shellparam = saveparam;
11080 status = exitstatus;
11086 exitcmd(int argc, char **argv)
11091 exitstatus = number(argv[1]);
11092 raise_exception(EXEXIT);
11096 #if ENABLE_ASH_BUILTIN_ECHO
11098 echocmd(int argc, char **argv)
11100 return bb_echo(argv);
11104 #if ENABLE_ASH_BUILTIN_TEST
11106 testcmd(int argc, char **argv)
11108 return bb_test(argc, argv);
11113 * Read a file containing shell functions.
11116 readcmdfile(char *name)
11118 setinputfile(name, INPUT_PUSH_FILE);
11124 /* ============ find_command inplementation */
11127 * Resolve a command name. If you change this routine, you may have to
11128 * change the shellexec routine as well.
11131 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11133 struct tblentry *cmdp;
11140 struct builtincmd *bcmd;
11142 /* If name contains a slash, don't use PATH or hash table */
11143 if (strchr(name, '/') != NULL) {
11144 entry->u.index = -1;
11145 if (act & DO_ABS) {
11146 while (stat(name, &statb) < 0) {
11148 if (errno == EINTR)
11151 entry->cmdtype = CMDUNKNOWN;
11155 entry->cmdtype = CMDNORMAL;
11159 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
11160 if (find_applet_by_name(name)) {
11161 entry->cmdtype = CMDNORMAL;
11162 entry->u.index = -1;
11167 if (is_safe_applet(name)) {
11168 entry->cmdtype = CMDNORMAL;
11169 entry->u.index = -1;
11173 updatetbl = (path == pathval());
11176 if (strstr(path, "%builtin") != NULL)
11177 act |= DO_ALTBLTIN;
11180 /* If name is in the table, check answer will be ok */
11181 cmdp = cmdlookup(name, 0);
11182 if (cmdp != NULL) {
11185 switch (cmdp->cmdtype) {
11203 } else if (cmdp->rehash == 0)
11204 /* if not invalidated by cd, we're done */
11208 /* If %builtin not in path, check for builtin next */
11209 bcmd = find_builtin(name);
11210 if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
11211 act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
11213 goto builtin_success;
11215 /* We have to search path. */
11216 prev = -1; /* where to start */
11217 if (cmdp && cmdp->rehash) { /* doing a rehash */
11218 if (cmdp->cmdtype == CMDBUILTIN)
11221 prev = cmdp->param.index;
11227 while ((fullname = padvance(&path, name)) != NULL) {
11228 stunalloc(fullname);
11231 if (prefix(pathopt, "builtin")) {
11233 goto builtin_success;
11235 } else if (!(act & DO_NOFUNC) &&
11236 prefix(pathopt, "func")) {
11237 /* handled below */
11239 /* ignore unimplemented options */
11243 /* if rehash, don't redo absolute path names */
11244 if (fullname[0] == '/' && idx <= prev) {
11247 TRACE(("searchexec \"%s\": no change\n", name));
11250 while (stat(fullname, &statb) < 0) {
11252 if (errno == EINTR)
11255 if (errno != ENOENT && errno != ENOTDIR)
11259 e = EACCES; /* if we fail, this will be the error */
11260 if (!S_ISREG(statb.st_mode))
11262 if (pathopt) { /* this is a %func directory */
11263 stalloc(strlen(fullname) + 1);
11264 readcmdfile(fullname);
11265 cmdp = cmdlookup(name, 0);
11266 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11267 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11268 stunalloc(fullname);
11271 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11273 entry->cmdtype = CMDNORMAL;
11274 entry->u.index = idx;
11278 cmdp = cmdlookup(name, 1);
11279 cmdp->cmdtype = CMDNORMAL;
11280 cmdp->param.index = idx;
11285 /* We failed. If there was an entry for this command, delete it */
11286 if (cmdp && updatetbl)
11287 delete_cmd_entry();
11289 ash_msg("%s: %s", name, errmsg(e, "not found"));
11290 entry->cmdtype = CMDUNKNOWN;
11295 entry->cmdtype = CMDBUILTIN;
11296 entry->u.cmd = bcmd;
11300 cmdp = cmdlookup(name, 1);
11301 cmdp->cmdtype = CMDBUILTIN;
11302 cmdp->param.cmd = bcmd;
11306 entry->cmdtype = cmdp->cmdtype;
11307 entry->u = cmdp->param;
11311 /* ============ trap.c */
11314 * The trap builtin.
11317 trapcmd(int argc, char **argv)
11326 for (signo = 0; signo < NSIG; signo++) {
11327 if (trap[signo] != NULL) {
11330 sn = get_signame(signo);
11331 out1fmt("trap -- %s %s\n",
11332 single_quote(trap[signo]), sn);
11342 signo = get_signum(*ap);
11344 ash_msg_and_raise_error("%s: bad trap", *ap);
11347 if (LONE_DASH(action))
11350 action = ckstrdup(action);
11354 trap[signo] = action;
11364 /* ============ Builtins */
11366 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11368 * Lists available builtins
11371 helpcmd(int argc, char **argv)
11375 out1fmt("\nBuilt-in commands:\n-------------------\n");
11376 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11377 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11378 builtincmd[i].name + 1);
11384 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
11385 for (i = 0; i < NUM_APPLETS; i++) {
11386 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11394 return EXIT_SUCCESS;
11396 #endif /* FEATURE_SH_EXTRA_QUIET */
11399 * The export and readonly commands.
11402 exportcmd(int argc, char **argv)
11408 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11410 if (nextopt("p") != 'p') {
11415 p = strchr(name, '=');
11419 vp = *findvar(hashvar(name), name);
11425 setvar(name, p, flag);
11426 } while ((name = *++aptr) != NULL);
11430 showvars(argv[0], flag, 0);
11435 * Delete a function if it exists.
11438 unsetfunc(const char *name)
11440 struct tblentry *cmdp;
11442 cmdp = cmdlookup(name, 0);
11443 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11444 delete_cmd_entry();
11448 * The unset builtin command. We unset the function before we unset the
11449 * variable to allow a function to be unset when there is a readonly variable
11450 * with the same name.
11453 unsetcmd(int argc, char **argv)
11460 while ((i = nextopt("vf")) != '\0') {
11464 for (ap = argptr; *ap; ap++) {
11480 #include <sys/times.h>
11482 static const unsigned char timescmd_str[] = {
11483 ' ', offsetof(struct tms, tms_utime),
11484 '\n', offsetof(struct tms, tms_stime),
11485 ' ', offsetof(struct tms, tms_cutime),
11486 '\n', offsetof(struct tms, tms_cstime),
11491 timescmd(int ac, char **av)
11493 long clk_tck, s, t;
11494 const unsigned char *p;
11497 clk_tck = sysconf(_SC_CLK_TCK);
11502 t = *(clock_t *)(((char *) &buf) + p[1]);
11504 out1fmt("%ldm%ld.%.3lds%c",
11506 ((t - s * clk_tck) * 1000) / clk_tck,
11508 } while (*(p += 2));
11513 #if ENABLE_ASH_MATH_SUPPORT
11515 dash_arith(const char *s)
11521 result = arith(s, &errcode);
11524 ash_msg_and_raise_error("exponent less than 0");
11526 ash_msg_and_raise_error("divide by zero");
11528 ash_msg_and_raise_error("expression recursion loop detected");
11529 raise_error_syntax(s);
11537 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11538 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11540 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11543 letcmd(int argc, char **argv)
11550 ash_msg_and_raise_error("expression expected");
11551 for (ap = argv + 1; *ap; ap++) {
11552 i = dash_arith(*ap);
11557 #endif /* ASH_MATH_SUPPORT */
11560 /* ============ miscbltin.c
11562 * Miscellaneous builtins.
11567 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11568 typedef enum __rlimit_resource rlim_t;
11572 * The read builtin. The -e option causes backslashes to escape the
11573 * following character.
11575 * This uses unbuffered input, which may be avoidable in some cases.
11578 readcmd(int argc, char **argv)
11590 #if ENABLE_ASH_READ_NCHARS
11594 struct termios tty, old_tty;
11596 #if ENABLE_ASH_READ_TIMEOUT
11600 ts.tv_sec = ts.tv_usec = 0;
11605 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11606 while ((i = nextopt("p:rt:n:s")) != '\0')
11607 #elif ENABLE_ASH_READ_NCHARS
11608 while ((i = nextopt("p:rn:s")) != '\0')
11609 #elif ENABLE_ASH_READ_TIMEOUT
11610 while ((i = nextopt("p:rt:")) != '\0')
11612 while ((i = nextopt("p:r")) != '\0')
11617 prompt = optionarg;
11619 #if ENABLE_ASH_READ_NCHARS
11621 nchars = strtol(optionarg, &p, 10);
11623 ash_msg_and_raise_error("invalid count");
11624 nch_flag = (nchars > 0);
11630 #if ENABLE_ASH_READ_TIMEOUT
11632 ts.tv_sec = strtol(optionarg, &p, 10);
11638 ts.tv_usec = strtol(p, &p2, 10);
11640 ash_msg_and_raise_error("invalid timeout");
11642 /* normalize to usec */
11644 ash_msg_and_raise_error("invalid timeout");
11645 while (scale++ < 6)
11649 ash_msg_and_raise_error("invalid timeout");
11651 if ( ! ts.tv_sec && ! ts.tv_usec)
11652 ash_msg_and_raise_error("invalid timeout");
11662 if (prompt && isatty(0)) {
11667 ash_msg_and_raise_error("arg count");
11668 ifs = bltinlookup("IFS");
11671 #if ENABLE_ASH_READ_NCHARS
11672 if (nch_flag || silent) {
11673 tcgetattr(0, &tty);
11676 tty.c_lflag &= ~ICANON;
11677 tty.c_cc[VMIN] = nchars;
11680 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11683 tcsetattr(0, TCSANOW, &tty);
11686 #if ENABLE_ASH_READ_TIMEOUT
11687 if (ts.tv_sec || ts.tv_usec) {
11691 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11693 #if ENABLE_ASH_READ_NCHARS
11695 tcsetattr(0, TCSANOW, &old_tty);
11705 #if ENABLE_ASH_READ_NCHARS
11706 while (!nch_flag || nchars--)
11711 if (read(0, &c, 1) != 1) {
11723 if (!rflag && c == '\\') {
11729 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11733 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11735 setvar(*ap, stackblock(), 0);
11744 #if ENABLE_ASH_READ_NCHARS
11745 if (nch_flag || silent)
11746 tcsetattr(0, TCSANOW, &old_tty);
11750 /* Remove trailing blanks */
11751 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11753 setvar(*ap, stackblock(), 0);
11754 while (*++ap != NULL)
11755 setvar(*ap, nullstr, 0);
11760 umaskcmd(int argc, char **argv)
11762 static const char permuser[3] = "ugo";
11763 static const char permmode[3] = "rwx";
11764 static const short int permmask[] = {
11765 S_IRUSR, S_IWUSR, S_IXUSR,
11766 S_IRGRP, S_IWGRP, S_IXGRP,
11767 S_IROTH, S_IWOTH, S_IXOTH
11773 int symbolic_mode = 0;
11775 while (nextopt("S") != '\0') {
11786 if (symbolic_mode) {
11790 for (i = 0; i < 3; i++) {
11793 *p++ = permuser[i];
11795 for (j = 0; j < 3; j++) {
11796 if ((mask & permmask[3 * i + j]) == 0) {
11797 *p++ = permmode[j];
11805 out1fmt("%.4o\n", mask);
11808 if (isdigit((unsigned char) *ap)) {
11811 if (*ap >= '8' || *ap < '0')
11812 ash_msg_and_raise_error(illnum, argv[1]);
11813 mask = (mask << 3) + (*ap - '0');
11814 } while (*++ap != '\0');
11817 mask = ~mask & 0777;
11818 if (!bb_parse_mode(ap, &mask)) {
11819 ash_msg_and_raise_error("Illegal mode: %s", ap);
11821 umask(~mask & 0777);
11830 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11831 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11832 * ash by J.T. Conklin.
11840 int factor; /* multiply by to get rlim_{cur,max} values */
11844 static const struct limits limits[] = {
11846 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11848 #ifdef RLIMIT_FSIZE
11849 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11852 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11854 #ifdef RLIMIT_STACK
11855 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11858 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11861 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11863 #ifdef RLIMIT_MEMLOCK
11864 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11866 #ifdef RLIMIT_NPROC
11867 { "process", RLIMIT_NPROC, 1, 'p' },
11869 #ifdef RLIMIT_NOFILE
11870 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11873 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11875 #ifdef RLIMIT_LOCKS
11876 { "locks", RLIMIT_LOCKS, 1, 'w' },
11878 { NULL, 0, 0, '\0' }
11881 enum limtype { SOFT = 0x1, HARD = 0x2 };
11884 printlim(enum limtype how, const struct rlimit *limit,
11885 const struct limits *l)
11889 val = limit->rlim_max;
11891 val = limit->rlim_cur;
11893 if (val == RLIM_INFINITY)
11894 out1fmt("unlimited\n");
11897 out1fmt("%lld\n", (long long) val);
11902 ulimitcmd(int argc, char **argv)
11906 enum limtype how = SOFT | HARD;
11907 const struct limits *l;
11910 struct rlimit limit;
11913 while ((optc = nextopt("HSa"
11917 #ifdef RLIMIT_FSIZE
11923 #ifdef RLIMIT_STACK
11932 #ifdef RLIMIT_MEMLOCK
11935 #ifdef RLIMIT_NPROC
11938 #ifdef RLIMIT_NOFILE
11944 #ifdef RLIMIT_LOCKS
11962 for (l = limits; l->option != what; l++)
11965 set = *argptr ? 1 : 0;
11969 if (all || argptr[1])
11970 ash_msg_and_raise_error("too many arguments");
11971 if (strncmp(p, "unlimited\n", 9) == 0)
11972 val = RLIM_INFINITY;
11976 while ((c = *p++) >= '0' && c <= '9') {
11977 val = (val * 10) + (long)(c - '0');
11978 if (val < (rlim_t) 0)
11982 ash_msg_and_raise_error("bad number");
11987 for (l = limits; l->name; l++) {
11988 getrlimit(l->cmd, &limit);
11989 out1fmt("%-20s ", l->name);
11990 printlim(how, &limit, l);
11995 getrlimit(l->cmd, &limit);
11998 limit.rlim_max = val;
12000 limit.rlim_cur = val;
12001 if (setrlimit(l->cmd, &limit) < 0)
12002 ash_msg_and_raise_error("error setting limit (%m)");
12004 printlim(how, &limit, l);
12010 /* ============ Math support */
12012 #if ENABLE_ASH_MATH_SUPPORT
12014 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12016 Permission is hereby granted, free of charge, to any person obtaining
12017 a copy of this software and associated documentation files (the
12018 "Software"), to deal in the Software without restriction, including
12019 without limitation the rights to use, copy, modify, merge, publish,
12020 distribute, sublicense, and/or sell copies of the Software, and to
12021 permit persons to whom the Software is furnished to do so, subject to
12022 the following conditions:
12024 The above copyright notice and this permission notice shall be
12025 included in all copies or substantial portions of the Software.
12027 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12028 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12029 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12030 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12031 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12032 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12033 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12036 /* This is my infix parser/evaluator. It is optimized for size, intended
12037 * as a replacement for yacc-based parsers. However, it may well be faster
12038 * than a comparable parser written in yacc. The supported operators are
12039 * listed in #defines below. Parens, order of operations, and error handling
12040 * are supported. This code is thread safe. The exact expression format should
12041 * be that which POSIX specifies for shells. */
12043 /* The code uses a simple two-stack algorithm. See
12044 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12045 * for a detailed explanation of the infix-to-postfix algorithm on which
12046 * this is based (this code differs in that it applies operators immediately
12047 * to the stack instead of adding them to a queue to end up with an
12050 /* To use the routine, call it with an expression string and error return
12054 * Aug 24, 2001 Manuel Novoa III
12056 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12058 * 1) In arith_apply():
12059 * a) Cached values of *numptr and &(numptr[-1]).
12060 * b) Removed redundant test for zero denominator.
12063 * a) Eliminated redundant code for processing operator tokens by moving
12064 * to a table-based implementation. Also folded handling of parens
12066 * b) Combined all 3 loops which called arith_apply to reduce generated
12067 * code size at the cost of speed.
12069 * 3) The following expressions were treated as valid by the original code:
12070 * 1() , 0! , 1 ( *3 ) .
12071 * These bugs have been fixed by internally enclosing the expression in
12072 * parens and then checking that all binary ops and right parens are
12073 * preceded by a valid expression (NUM_TOKEN).
12075 * Note: It may be desirable to replace Aaron's test for whitespace with
12076 * ctype's isspace() if it is used by another busybox applet or if additional
12077 * whitespace chars should be considered. Look below the "#include"s for a
12078 * precompiler test.
12082 * Aug 26, 2001 Manuel Novoa III
12084 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12086 * Merge in Aaron's comments previously posted to the busybox list,
12087 * modified slightly to take account of my changes to the code.
12092 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12094 * - allow access to variable,
12095 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12096 * - realize assign syntax (VAR=expr, +=, *= etc)
12097 * - realize exponentiation (** operator)
12098 * - realize comma separated - expr, expr
12099 * - realise ++expr --expr expr++ expr--
12100 * - realise expr ? expr : expr (but, second expr calculate always)
12101 * - allow hexadecimal and octal numbers
12102 * - was restored loses XOR operator
12103 * - remove one goto label, added three ;-)
12104 * - protect $((num num)) as true zero expr (Manuel`s error)
12105 * - always use special isspace(), see comment from bash ;-)
12108 #define arith_isspace(arithval) \
12109 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12111 typedef unsigned char operator;
12113 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12114 * precedence, and 3 high bits are an ID unique across operators of that
12115 * precedence. The ID portion is so that multiple operators can have the
12116 * same precedence, ensuring that the leftmost one is evaluated first.
12117 * Consider * and /. */
12119 #define tok_decl(prec,id) (((id)<<5)|(prec))
12120 #define PREC(op) ((op) & 0x1F)
12122 #define TOK_LPAREN tok_decl(0,0)
12124 #define TOK_COMMA tok_decl(1,0)
12126 #define TOK_ASSIGN tok_decl(2,0)
12127 #define TOK_AND_ASSIGN tok_decl(2,1)
12128 #define TOK_OR_ASSIGN tok_decl(2,2)
12129 #define TOK_XOR_ASSIGN tok_decl(2,3)
12130 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12131 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12132 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12133 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12135 #define TOK_MUL_ASSIGN tok_decl(3,0)
12136 #define TOK_DIV_ASSIGN tok_decl(3,1)
12137 #define TOK_REM_ASSIGN tok_decl(3,2)
12139 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12140 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12142 /* conditional is right associativity too */
12143 #define TOK_CONDITIONAL tok_decl(4,0)
12144 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12146 #define TOK_OR tok_decl(5,0)
12148 #define TOK_AND tok_decl(6,0)
12150 #define TOK_BOR tok_decl(7,0)
12152 #define TOK_BXOR tok_decl(8,0)
12154 #define TOK_BAND tok_decl(9,0)
12156 #define TOK_EQ tok_decl(10,0)
12157 #define TOK_NE tok_decl(10,1)
12159 #define TOK_LT tok_decl(11,0)
12160 #define TOK_GT tok_decl(11,1)
12161 #define TOK_GE tok_decl(11,2)
12162 #define TOK_LE tok_decl(11,3)
12164 #define TOK_LSHIFT tok_decl(12,0)
12165 #define TOK_RSHIFT tok_decl(12,1)
12167 #define TOK_ADD tok_decl(13,0)
12168 #define TOK_SUB tok_decl(13,1)
12170 #define TOK_MUL tok_decl(14,0)
12171 #define TOK_DIV tok_decl(14,1)
12172 #define TOK_REM tok_decl(14,2)
12174 /* exponent is right associativity */
12175 #define TOK_EXPONENT tok_decl(15,1)
12177 /* For now unary operators. */
12178 #define UNARYPREC 16
12179 #define TOK_BNOT tok_decl(UNARYPREC,0)
12180 #define TOK_NOT tok_decl(UNARYPREC,1)
12182 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12183 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12185 #define PREC_PRE (UNARYPREC+2)
12187 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12188 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12190 #define PREC_POST (UNARYPREC+3)
12192 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12193 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12195 #define SPEC_PREC (UNARYPREC+4)
12197 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12198 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12200 #define NUMPTR (*numstackptr)
12203 tok_have_assign(operator op)
12205 operator prec = PREC(op);
12207 convert_prec_is_assing(prec);
12208 return (prec == PREC(TOK_ASSIGN) ||
12209 prec == PREC_PRE || prec == PREC_POST);
12213 is_right_associativity(operator prec)
12215 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12216 || prec == PREC(TOK_CONDITIONAL));
12219 typedef struct ARITCH_VAR_NUM {
12221 arith_t contidional_second_val;
12222 char contidional_second_val_initialized;
12223 char *var; /* if NULL then is regular number,
12224 else is variable name */
12227 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12229 struct CHK_VAR_RECURSIVE_LOOPED *next;
12230 } chk_var_recursive_looped_t;
12232 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12235 arith_lookup_val(v_n_t *t)
12238 const char * p = lookupvar(t->var);
12243 /* recursive try as expression */
12244 chk_var_recursive_looped_t *cur;
12245 chk_var_recursive_looped_t cur_save;
12247 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12248 if (strcmp(cur->var, t->var) == 0) {
12249 /* expression recursion loop detected */
12253 /* save current lookuped var name */
12254 cur = prev_chk_var_recursive;
12255 cur_save.var = t->var;
12256 cur_save.next = cur;
12257 prev_chk_var_recursive = &cur_save;
12259 t->val = arith (p, &errcode);
12260 /* restore previous ptr after recursiving */
12261 prev_chk_var_recursive = cur;
12264 /* allow undefined var as 0 */
12270 /* "applying" a token means performing it on the top elements on the integer
12271 * stack. For a unary operator it will only change the top element, but a
12272 * binary operator will pop two arguments and push a result */
12274 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12277 arith_t numptr_val, rez;
12278 int ret_arith_lookup_val;
12280 /* There is no operator that can work without arguments */
12281 if (NUMPTR == numstack) goto err;
12282 numptr_m1 = NUMPTR - 1;
12284 /* check operand is var with noninteger value */
12285 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12286 if (ret_arith_lookup_val)
12287 return ret_arith_lookup_val;
12289 rez = numptr_m1->val;
12290 if (op == TOK_UMINUS)
12292 else if (op == TOK_NOT)
12294 else if (op == TOK_BNOT)
12296 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12298 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12300 else if (op != TOK_UPLUS) {
12301 /* Binary operators */
12303 /* check and binary operators need two arguments */
12304 if (numptr_m1 == numstack) goto err;
12306 /* ... and they pop one */
12309 if (op == TOK_CONDITIONAL) {
12310 if (! numptr_m1->contidional_second_val_initialized) {
12311 /* protect $((expr1 ? expr2)) without ": expr" */
12314 rez = numptr_m1->contidional_second_val;
12315 } else if (numptr_m1->contidional_second_val_initialized) {
12316 /* protect $((expr1 : expr2)) without "expr ? " */
12319 numptr_m1 = NUMPTR - 1;
12320 if (op != TOK_ASSIGN) {
12321 /* check operand is var with noninteger value for not '=' */
12322 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12323 if (ret_arith_lookup_val)
12324 return ret_arith_lookup_val;
12326 if (op == TOK_CONDITIONAL) {
12327 numptr_m1->contidional_second_val = rez;
12329 rez = numptr_m1->val;
12330 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12332 else if (op == TOK_OR)
12333 rez = numptr_val || rez;
12334 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12336 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12338 else if (op == TOK_AND)
12339 rez = rez && numptr_val;
12340 else if (op == TOK_EQ)
12341 rez = (rez == numptr_val);
12342 else if (op == TOK_NE)
12343 rez = (rez != numptr_val);
12344 else if (op == TOK_GE)
12345 rez = (rez >= numptr_val);
12346 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12347 rez >>= numptr_val;
12348 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12349 rez <<= numptr_val;
12350 else if (op == TOK_GT)
12351 rez = (rez > numptr_val);
12352 else if (op == TOK_LT)
12353 rez = (rez < numptr_val);
12354 else if (op == TOK_LE)
12355 rez = (rez <= numptr_val);
12356 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12358 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12360 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12362 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12364 else if (op == TOK_CONDITIONAL_SEP) {
12365 if (numptr_m1 == numstack) {
12366 /* protect $((expr : expr)) without "expr ? " */
12369 numptr_m1->contidional_second_val_initialized = op;
12370 numptr_m1->contidional_second_val = numptr_val;
12371 } else if (op == TOK_CONDITIONAL) {
12373 numptr_val : numptr_m1->contidional_second_val;
12374 } else if (op == TOK_EXPONENT) {
12375 if (numptr_val < 0)
12376 return -3; /* exponent less than 0 */
12381 while (numptr_val--)
12385 } else if (numptr_val==0) /* zero divisor check */
12387 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12389 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12392 if (tok_have_assign(op)) {
12393 char buf[sizeof(arith_t_type)*3 + 2];
12395 if (numptr_m1->var == NULL) {
12399 /* save to shell variable */
12400 #if ENABLE_ASH_MATH_SUPPORT_64
12401 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12403 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12405 setvar(numptr_m1->var, buf, 0);
12406 /* after saving, make previous value for v++ or v-- */
12407 if (op == TOK_POST_INC)
12409 else if (op == TOK_POST_DEC)
12412 numptr_m1->val = rez;
12413 /* protect geting var value, is number now */
12414 numptr_m1->var = NULL;
12420 /* longest must be first */
12421 static const char op_tokens[] = {
12422 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12423 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12424 '<','<', 0, TOK_LSHIFT,
12425 '>','>', 0, TOK_RSHIFT,
12426 '|','|', 0, TOK_OR,
12427 '&','&', 0, TOK_AND,
12428 '!','=', 0, TOK_NE,
12429 '<','=', 0, TOK_LE,
12430 '>','=', 0, TOK_GE,
12431 '=','=', 0, TOK_EQ,
12432 '|','=', 0, TOK_OR_ASSIGN,
12433 '&','=', 0, TOK_AND_ASSIGN,
12434 '*','=', 0, TOK_MUL_ASSIGN,
12435 '/','=', 0, TOK_DIV_ASSIGN,
12436 '%','=', 0, TOK_REM_ASSIGN,
12437 '+','=', 0, TOK_PLUS_ASSIGN,
12438 '-','=', 0, TOK_MINUS_ASSIGN,
12439 '-','-', 0, TOK_POST_DEC,
12440 '^','=', 0, TOK_XOR_ASSIGN,
12441 '+','+', 0, TOK_POST_INC,
12442 '*','*', 0, TOK_EXPONENT,
12446 '=', 0, TOK_ASSIGN,
12458 '?', 0, TOK_CONDITIONAL,
12459 ':', 0, TOK_CONDITIONAL_SEP,
12460 ')', 0, TOK_RPAREN,
12461 '(', 0, TOK_LPAREN,
12465 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12468 arith(const char *expr, int *perrcode)
12470 char arithval; /* Current character under analysis */
12471 operator lasttok, op;
12474 const char *p = endexpression;
12477 size_t datasizes = strlen(expr) + 2;
12479 /* Stack of integers */
12480 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12481 * in any given correct or incorrect expression is left as an exercise to
12483 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12484 *numstackptr = numstack;
12485 /* Stack of operator tokens */
12486 operator *stack = alloca((datasizes) * sizeof(operator)),
12489 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12490 *perrcode = errcode = 0;
12494 if (arithval == 0) {
12495 if (p == endexpression) {
12496 /* Null expression. */
12500 /* This is only reached after all tokens have been extracted from the
12501 * input stream. If there are still tokens on the operator stack, they
12502 * are to be applied in order. At the end, there should be a final
12503 * result on the integer stack */
12505 if (expr != endexpression + 1) {
12506 /* If we haven't done so already, */
12507 /* append a closing right paren */
12508 expr = endexpression;
12509 /* and let the loop process it. */
12512 /* At this point, we're done with the expression. */
12513 if (numstackptr != numstack+1) {
12514 /* ... but if there isn't, it's bad */
12516 return (*perrcode = -1);
12518 if (numstack->var) {
12519 /* expression is $((var)) only, lookup now */
12520 errcode = arith_lookup_val(numstack);
12523 *perrcode = errcode;
12524 return numstack->val;
12527 /* Continue processing the expression. */
12528 if (arith_isspace(arithval)) {
12529 /* Skip whitespace */
12532 p = endofname(expr);
12534 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12536 numstackptr->var = alloca(var_name_size);
12537 safe_strncpy(numstackptr->var, expr, var_name_size);
12540 numstackptr->contidional_second_val_initialized = 0;
12545 if (isdigit(arithval)) {
12546 numstackptr->var = NULL;
12547 #if ENABLE_ASH_MATH_SUPPORT_64
12548 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12550 numstackptr->val = strtol(expr, (char **) &expr, 0);
12554 for (p = op_tokens; ; p++) {
12558 /* strange operator not found */
12561 for (o = expr; *p && *o == *p; p++)
12568 /* skip tail uncompared token */
12571 /* skip zero delim */
12576 /* post grammar: a++ reduce to num */
12577 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12580 /* Plus and minus are binary (not unary) _only_ if the last
12581 * token was as number, or a right paren (which pretends to be
12582 * a number, since it evaluates to one). Think about it.
12583 * It makes sense. */
12584 if (lasttok != TOK_NUM) {
12600 /* We don't want a unary operator to cause recursive descent on the
12601 * stack, because there can be many in a row and it could cause an
12602 * operator to be evaluated before its argument is pushed onto the
12603 * integer stack. */
12604 /* But for binary operators, "apply" everything on the operator
12605 * stack until we find an operator with a lesser priority than the
12606 * one we have just extracted. */
12607 /* Left paren is given the lowest priority so it will never be
12608 * "applied" in this way.
12609 * if associativity is right and priority eq, applied also skip
12612 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12613 /* not left paren or unary */
12614 if (lasttok != TOK_NUM) {
12615 /* binary op must be preceded by a num */
12618 while (stackptr != stack) {
12619 if (op == TOK_RPAREN) {
12620 /* The algorithm employed here is simple: while we don't
12621 * hit an open paren nor the bottom of the stack, pop
12622 * tokens and apply them */
12623 if (stackptr[-1] == TOK_LPAREN) {
12625 /* Any operator directly after a */
12627 /* close paren should consider itself binary */
12631 operator prev_prec = PREC(stackptr[-1]);
12633 convert_prec_is_assing(prec);
12634 convert_prec_is_assing(prev_prec);
12635 if (prev_prec < prec)
12637 /* check right assoc */
12638 if (prev_prec == prec && is_right_associativity(prec))
12641 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12642 if (errcode) goto ret;
12644 if (op == TOK_RPAREN) {
12649 /* Push this operator to the stack and remember it. */
12650 *stackptr++ = lasttok = op;
12655 #endif /* ASH_MATH_SUPPORT */
12658 /* ============ main() and helpers */
12661 * Called to exit the shell.
12663 static void exitshell(void) ATTRIBUTE_NORETURN;
12671 status = exitstatus;
12672 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12673 if (setjmp(loc.loc)) {
12674 if (exception == EXEXIT)
12675 /* dash bug: it just does _exit(exitstatus) here
12676 * but we have to do setjobctl(0) first!
12677 * (bug is still not fixed in dash-0.5.3 - if you run dash
12678 * under Midnight Commander, on exit from dash MC is backgrounded) */
12679 status = exitstatus;
12682 exception_handler = &loc;
12688 flush_stdout_stderr();
12698 /* from input.c: */
12699 basepf.nextc = basepf.buf = basebuf;
12702 signal(SIGCHLD, SIG_DFL);
12707 char ppid[sizeof(int)*3 + 1];
12709 struct stat st1, st2;
12712 for (envp = environ; envp && *envp; envp++) {
12713 if (strchr(*envp, '=')) {
12714 setvareq(*envp, VEXPORT|VTEXTFIXED);
12718 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12719 setvar("PPID", ppid, 0);
12721 p = lookupvar("PWD");
12723 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12724 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12731 * Process the shell command line arguments.
12734 procargs(int argc, char **argv)
12737 const char *xminusc;
12744 for (i = 0; i < NOPTS; i++)
12750 if (*xargv == NULL) {
12752 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12755 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12759 for (i = 0; i < NOPTS; i++)
12760 if (optlist[i] == 2)
12765 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12770 } else if (!sflag) {
12771 setinputfile(*xargv, 0);
12774 commandname = arg0;
12777 shellparam.p = xargv;
12778 #if ENABLE_ASH_GETOPTS
12779 shellparam.optind = 1;
12780 shellparam.optoff = -1;
12782 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12784 shellparam.nparam++;
12791 * Read /etc/profile or .profile.
12794 read_profile(const char *name)
12798 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12807 * This routine is called when an error or an interrupt occurs in an
12808 * interactive shell and control is returned to the main command loop.
12816 /* from input.c: */
12817 parselleft = parsenleft = 0; /* clear input buffer */
12819 /* from parser.c: */
12822 /* from redir.c: */
12827 static short profile_buf[16384];
12828 extern int etext();
12832 * Main routine. We initialize things, parse the arguments, execute
12833 * profiles if we're a login shell, and then call cmdloop to execute
12834 * commands. The setjmp call sets up the location to jump to when an
12835 * exception occurs. When an exception occurs the variable "state"
12836 * is used to figure out how far we had gotten.
12838 int ash_main(int argc, char **argv);
12839 int ash_main(int argc, char **argv)
12842 volatile int state;
12843 struct jmploc jmploc;
12844 struct stackmark smark;
12847 dash_errno = __errno_location();
12851 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12854 #if ENABLE_FEATURE_EDITING
12855 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12858 if (setjmp(jmploc.loc)) {
12868 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12872 outcslow('\n', stderr);
12874 popstackmark(&smark);
12875 FORCE_INT_ON; /* enable interrupts */
12884 exception_handler = &jmploc;
12887 trace_puts("Shell args: ");
12888 trace_puts_args(argv);
12890 rootpid = getpid();
12892 #if ENABLE_ASH_RANDOM_SUPPORT
12893 rseed = rootpid + time(NULL);
12896 setstackmark(&smark);
12897 procargs(argc, argv);
12898 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12900 const char *hp = lookupvar("HISTFILE");
12903 hp = lookupvar("HOME");
12905 char *defhp = concat_path_file(hp, ".ash_history");
12906 setvar("HISTFILE", defhp, 0);
12912 if (argv[0] && argv[0][0] == '-')
12916 read_profile("/etc/profile");
12919 read_profile(".profile");
12925 getuid() == geteuid() && getgid() == getegid() &&
12929 shinit = lookupvar("ENV");
12930 if (shinit != NULL && *shinit != '\0') {
12931 read_profile(shinit);
12937 evalstring(minusc, 0);
12939 if (sflag || minusc == NULL) {
12940 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12942 const char *hp = lookupvar("HISTFILE");
12945 line_input_state->hist_file = hp;
12948 state4: /* XXX ??? - why isn't this before the "if" statement */
12956 extern void _mcleanup(void);
12965 const char *applet_name = "debug stuff usage";
12966 int main(int argc, char **argv)
12968 return ash_main(argc, argv);
12974 * Copyright (c) 1989, 1991, 1993, 1994
12975 * The Regents of the University of California. All rights reserved.
12977 * This code is derived from software contributed to Berkeley by
12978 * Kenneth Almquist.
12980 * Redistribution and use in source and binary forms, with or without
12981 * modification, are permitted provided that the following conditions
12983 * 1. Redistributions of source code must retain the above copyright
12984 * notice, this list of conditions and the following disclaimer.
12985 * 2. Redistributions in binary form must reproduce the above copyright
12986 * notice, this list of conditions and the following disclaimer in the
12987 * documentation and/or other materials provided with the distribution.
12988 * 3. Neither the name of the University nor the names of its contributors
12989 * may be used to endorse or promote products derived from this software
12990 * without specific prior written permission.
12992 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12993 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12994 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12995 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12996 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12997 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12998 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12999 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13000 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13001 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF