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 */
161 * We enclose jmp_buf in a structure so that we can declare pointers to
162 * jump locations. The global variable handler contains the location to
163 * jump to when an exception occurs, and the global variable exception
164 * contains a code identifying the exception. To implement nested
165 * exception handlers, the user should save the value of handler on entry
166 * to an inner scope, set handler to point to a jmploc structure for the
167 * inner scope, and restore handler on exit from the scope.
172 static struct jmploc *exception_handler;
173 static int exception;
175 #define EXINT 0 /* SIGINT received */
176 #define EXERROR 1 /* a generic error */
177 #define EXSHELLPROC 2 /* execute a shell procedure */
178 #define EXEXEC 3 /* command execution failed */
179 #define EXEXIT 4 /* exit the shell */
180 #define EXSIG 5 /* trapped signal in wait(1) */
181 static volatile int suppressint;
182 static volatile sig_atomic_t intpending;
183 /* do we generate EXSIG events */
185 /* last pending signal */
186 static volatile sig_atomic_t pendingsig;
189 * Sigmode records the current value of the signal handlers for the various
190 * modes. A value of zero means that the current handler is not known.
191 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
194 #define S_DFL 1 /* default signal handling (SIG_DFL) */
195 #define S_CATCH 2 /* signal is caught */
196 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
197 #define S_HARD_IGN 4 /* signal is ignored permenantly */
198 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
201 * These macros allow the user to suspend the handling of interrupt signals
202 * over a period of time. This is similar to SIGHOLD to or sigblock, but
203 * much more efficient and portable. (But hacking the kernel is so much
204 * more fun than worrying about efficiency and portability. :-))
213 * Called to raise an exception. Since C doesn't include exceptions, we
214 * just do a longjmp to the exception handler. The type of exception is
215 * stored in the global variable "exception".
217 static void raise_exception(int) ATTRIBUTE_NORETURN;
219 raise_exception(int e)
222 if (exception_handler == NULL)
227 longjmp(exception_handler->loc, 1);
231 * Called from trap.c when a SIGINT is received. (If the user specifies
232 * that SIGINT is to be trapped or ignored using the trap builtin, then
233 * this routine is not called.) Suppressint is nonzero when interrupts
234 * are held using the INT_OFF macro. (The test for iflag is just
235 * defensive programming.)
237 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
239 raise_interrupt(void)
245 /* Signal is not automatically re-enabled after it is raised,
248 sigprocmask(SIG_SETMASK, &mask, 0);
249 /* pendingsig = 0; - now done in onsig() */
252 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
253 if (!(rootshell && iflag)) {
254 signal(SIGINT, SIG_DFL);
263 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
267 if (--suppressint == 0 && intpending) {
271 #define INT_ON int_on()
279 #define FORCE_INT_ON force_int_on()
284 if (--suppressint == 0 && intpending) \
287 #define FORCE_INT_ON \
294 #endif /* ASH_OPTIMIZE_FOR_SIZE */
296 #define SAVE_INT(v) ((v) = suppressint)
298 #define RESTORE_INT(v) \
302 if (suppressint == 0 && intpending) \
311 raise_exception(EXSIG); \
313 /* EXSIG is turned off by evalbltin(). */
316 * Ignore a signal. Only one usage site - in forkchild()
321 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
322 signal(signo, SIG_IGN);
324 sigmode[signo - 1] = S_HARD_IGN;
328 * Signal handler. Only one usage site - in setsignal()
333 gotsig[signo - 1] = 1;
336 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
346 /* ============ Stdout/stderr output */
349 outstr(const char *p, FILE *file)
357 flush_stdout_stderr(void)
374 outcslow(int c, FILE *dest)
382 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
384 out1fmt(const char *fmt, ...)
391 r = vprintf(fmt, ap);
397 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
399 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
406 ret = vsnprintf(outbuf, length, fmt, ap);
413 out1str(const char *p)
419 out2str(const char *p)
426 /* ============ Parser structures */
428 /* control characters in argument strings */
429 #define CTLESC '\201' /* escape next character */
430 #define CTLVAR '\202' /* variable defn */
431 #define CTLENDVAR '\203'
432 #define CTLBACKQ '\204'
433 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
434 /* CTLBACKQ | CTLQUOTE == '\205' */
435 #define CTLARI '\206' /* arithmetic expression */
436 #define CTLENDARI '\207'
437 #define CTLQUOTEMARK '\210'
439 /* variable substitution byte (follows CTLVAR) */
440 #define VSTYPE 0x0f /* type of variable substitution */
441 #define VSNUL 0x10 /* colon--treat the empty string as unset */
442 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
444 /* values of VSTYPE field */
445 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
446 #define VSMINUS 0x2 /* ${var-text} */
447 #define VSPLUS 0x3 /* ${var+text} */
448 #define VSQUESTION 0x4 /* ${var?message} */
449 #define VSASSIGN 0x5 /* ${var=text} */
450 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
451 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
452 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
453 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
454 #define VSLENGTH 0xa /* ${#var} */
456 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
491 union node *redirect;
497 struct nodelist *cmdlist;
503 union node *redirect;
516 union node *elsepart;
543 struct nodelist *backquote;
578 struct nredir nredir;
579 struct nbinary nbinary;
583 struct nclist nclist;
592 struct nodelist *next;
605 freefunc(struct funcnode *f)
607 if (f && --f->count < 0)
612 /* ============ Debugging output */
616 static FILE *tracefile;
619 trace_printf(const char *fmt, ...)
626 vfprintf(tracefile, fmt, va);
631 trace_vprintf(const char *fmt, va_list va)
635 vfprintf(tracefile, fmt, va);
639 trace_puts(const char *s)
647 trace_puts_quoted(char *s)
654 putc('"', tracefile);
655 for (p = s; *p; p++) {
657 case '\n': c = 'n'; goto backslash;
658 case '\t': c = 't'; goto backslash;
659 case '\r': c = 'r'; goto backslash;
660 case '"': c = '"'; goto backslash;
661 case '\\': c = '\\'; goto backslash;
662 case CTLESC: c = 'e'; goto backslash;
663 case CTLVAR: c = 'v'; goto backslash;
664 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
665 case CTLBACKQ: c = 'q'; goto backslash;
666 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
668 putc('\\', tracefile);
672 if (*p >= ' ' && *p <= '~')
675 putc('\\', tracefile);
676 putc(*p >> 6 & 03, tracefile);
677 putc(*p >> 3 & 07, tracefile);
678 putc(*p & 07, tracefile);
683 putc('"', tracefile);
687 trace_puts_args(char **ap)
694 trace_puts_quoted(*ap);
696 putc('\n', tracefile);
699 putc(' ', tracefile);
714 /* leave open because libedit might be using it */
717 strcpy(s, "./trace");
719 if (!freopen(s, "a", tracefile)) {
720 fprintf(stderr, "Can't re-open %s\n", s);
725 tracefile = fopen(s, "a");
726 if (tracefile == NULL) {
727 fprintf(stderr, "Can't open %s\n", s);
733 flags = fcntl(fileno(tracefile), F_GETFL, 0);
735 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
737 setlinebuf(tracefile);
738 fputs("\nTracing started.\n", tracefile);
742 indent(int amount, char *pfx, FILE *fp)
746 for (i = 0; i < amount; i++) {
747 if (pfx && i == amount - 1)
753 /* little circular references here... */
754 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
757 sharg(union node *arg, FILE *fp)
760 struct nodelist *bqlist;
763 if (arg->type != NARG) {
764 out1fmt("<node type %d>\n", arg->type);
767 bqlist = arg->narg.backquote;
768 for (p = arg->narg.text; *p; p++) {
777 if (subtype == VSLENGTH)
786 switch (subtype & VSTYPE) {
819 out1fmt("<subtype %d>", subtype);
826 case CTLBACKQ|CTLQUOTE:
829 shtree(bqlist->n, -1, NULL, fp);
840 shcmd(union node *cmd, FILE *fp)
848 for (np = cmd->ncmd.args; np; np = np->narg.next) {
854 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
857 switch (np->nfile.type) {
858 case NTO: s = ">"; dftfd = 1; break;
859 case NCLOBBER: s = ">|"; dftfd = 1; break;
860 case NAPPEND: s = ">>"; dftfd = 1; break;
861 case NTOFD: s = ">&"; dftfd = 1; break;
862 case NFROM: s = "<"; dftfd = 0; break;
863 case NFROMFD: s = "<&"; dftfd = 0; break;
864 case NFROMTO: s = "<>"; dftfd = 0; break;
865 default: s = "*error*"; dftfd = 0; break;
867 if (np->nfile.fd != dftfd)
868 fprintf(fp, "%d", np->nfile.fd);
870 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
871 fprintf(fp, "%d", np->ndup.dupfd);
873 sharg(np->nfile.fname, fp);
880 shtree(union node *n, int ind, char *pfx, FILE *fp)
888 indent(ind, pfx, fp);
899 shtree(n->nbinary.ch1, ind, NULL, fp);
902 shtree(n->nbinary.ch2, ind, NULL, fp);
910 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
915 if (n->npipe.backgnd)
921 fprintf(fp, "<node type %d>", n->type);
929 showtree(union node *n)
931 trace_puts("showtree called\n");
932 shtree(n, 1, NULL, stdout);
935 #define TRACE(param) trace_printf param
936 #define TRACEV(param) trace_vprintf param
941 #define TRACEV(param)
946 /* ============ Parser data */
949 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
952 struct strlist *next;
961 struct strpush *prev; /* preceding string on stack */
965 struct alias *ap; /* if push was associated with an alias */
967 char *string; /* remember the string since it may change */
971 struct parsefile *prev; /* preceding file on stack */
972 int linno; /* current line */
973 int fd; /* file descriptor (or -1 if string) */
974 int nleft; /* number of chars left in this line */
975 int lleft; /* number of chars left in this buffer */
976 char *nextc; /* next char in buffer */
977 char *buf; /* input buffer */
978 struct strpush *strpush; /* for pushing strings at this level */
979 struct strpush basestrpush; /* so pushing one is fast */
982 static struct parsefile basepf; /* top level input file */
983 static struct parsefile *parsefile = &basepf; /* current input file */
984 static int startlinno; /* line # where last token started */
985 static char *commandname; /* currently executing command */
986 static struct strlist *cmdenviron; /* environment for builtin command */
987 static int exitstatus; /* exit status of last command */
990 /* ============ Message printing */
993 ash_vmsg(const char *msg, va_list ap)
995 fprintf(stderr, "%s: ", arg0);
997 if (strcmp(arg0, commandname))
998 fprintf(stderr, "%s: ", commandname);
999 if (!iflag || parsefile->fd)
1000 fprintf(stderr, "line %d: ", startlinno);
1002 vfprintf(stderr, msg, ap);
1003 outcslow('\n', stderr);
1007 * Exverror is called to raise the error exception. If the second argument
1008 * is not NULL then error prints an error message using printf style
1009 * formatting. It then raises the error exception.
1011 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1013 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1017 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1019 TRACE(("\") pid=%d\n", getpid()));
1021 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1026 flush_stdout_stderr();
1027 raise_exception(cond);
1031 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1033 ash_msg_and_raise_error(const char *msg, ...)
1038 ash_vmsg_and_raise(EXERROR, msg, ap);
1043 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1045 ash_msg_and_raise(int cond, const char *msg, ...)
1050 ash_vmsg_and_raise(cond, msg, ap);
1056 * error/warning routines for external builtins
1059 ash_msg(const char *fmt, ...)
1069 * Return a string describing an error. The returned string may be a
1070 * pointer to a static buffer that will be overwritten on the next call.
1071 * Action describes the operation that got the error.
1074 errmsg(int e, const char *em)
1076 if (e == ENOENT || e == ENOTDIR) {
1083 /* ============ Memory allocation */
1086 * It appears that grabstackstr() will barf with such alignments
1087 * because stalloc() will return a string allocated in a new stackblock.
1089 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1091 /* Most machines require the value returned from malloc to be aligned
1092 * in some way. The following macro will get this right
1093 * on many machines. */
1094 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1095 /* Minimum size of a block */
1096 MINSIZE = SHELL_ALIGN(504),
1099 struct stack_block {
1100 struct stack_block *prev;
1101 char space[MINSIZE];
1105 struct stack_block *stackp;
1108 struct stackmark *marknext;
1111 static struct stack_block stackbase;
1112 static struct stack_block *stackp = &stackbase;
1113 static struct stackmark *markp;
1114 static char *stacknxt = stackbase.space;
1115 static size_t stacknleft = MINSIZE;
1116 static char *sstrend = stackbase.space + MINSIZE;
1117 static int herefd = -1;
1119 #define stackblock() ((void *)stacknxt)
1120 #define stackblocksize() stacknleft
1123 ckrealloc(void * p, size_t nbytes)
1125 p = realloc(p, nbytes);
1127 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1132 ckmalloc(size_t nbytes)
1134 return ckrealloc(NULL, nbytes);
1138 * Make a copy of a string in safe storage.
1141 ckstrdup(const char *s)
1143 char *p = strdup(s);
1145 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1150 * Parse trees for commands are allocated in lifo order, so we use a stack
1151 * to make this more efficient, and also to avoid all sorts of exception
1152 * handling code to handle interrupts in the middle of a parse.
1154 * The size 504 was chosen because the Ultrix malloc handles that size
1158 stalloc(size_t nbytes)
1163 aligned = SHELL_ALIGN(nbytes);
1164 if (aligned > stacknleft) {
1167 struct stack_block *sp;
1169 blocksize = aligned;
1170 if (blocksize < MINSIZE)
1171 blocksize = MINSIZE;
1172 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1173 if (len < blocksize)
1174 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1178 stacknxt = sp->space;
1179 stacknleft = blocksize;
1180 sstrend = stacknxt + blocksize;
1185 stacknxt += aligned;
1186 stacknleft -= aligned;
1194 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1195 write(2, "stunalloc\n", 10);
1199 stacknleft += stacknxt - (char *)p;
1204 * Like strdup but works with the ash stack.
1207 ststrdup(const char *p)
1209 size_t len = strlen(p) + 1;
1210 return memcpy(stalloc(len), p, len);
1214 setstackmark(struct stackmark *mark)
1216 mark->stackp = stackp;
1217 mark->stacknxt = stacknxt;
1218 mark->stacknleft = stacknleft;
1219 mark->marknext = markp;
1224 popstackmark(struct stackmark *mark)
1226 struct stack_block *sp;
1232 markp = mark->marknext;
1233 while (stackp != mark->stackp) {
1238 stacknxt = mark->stacknxt;
1239 stacknleft = mark->stacknleft;
1240 sstrend = mark->stacknxt + mark->stacknleft;
1245 * When the parser reads in a string, it wants to stick the string on the
1246 * stack and only adjust the stack pointer when it knows how big the
1247 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1248 * of space on top of the stack and stackblocklen returns the length of
1249 * this block. Growstackblock will grow this space by at least one byte,
1250 * possibly moving it (like realloc). Grabstackblock actually allocates the
1251 * part of the block that has been used.
1254 growstackblock(void)
1258 newlen = stacknleft * 2;
1259 if (newlen < stacknleft)
1260 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1264 if (stacknxt == stackp->space && stackp != &stackbase) {
1265 struct stack_block *oldstackp;
1266 struct stackmark *xmark;
1267 struct stack_block *sp;
1268 struct stack_block *prevstackp;
1274 prevstackp = sp->prev;
1275 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1276 sp = ckrealloc(sp, grosslen);
1277 sp->prev = prevstackp;
1279 stacknxt = sp->space;
1280 stacknleft = newlen;
1281 sstrend = sp->space + newlen;
1284 * Stack marks pointing to the start of the old block
1285 * must be relocated to point to the new block
1288 while (xmark != NULL && xmark->stackp == oldstackp) {
1289 xmark->stackp = stackp;
1290 xmark->stacknxt = stacknxt;
1291 xmark->stacknleft = stacknleft;
1292 xmark = xmark->marknext;
1296 char *oldspace = stacknxt;
1297 int oldlen = stacknleft;
1298 char *p = stalloc(newlen);
1300 /* free the space we just allocated */
1301 stacknxt = memcpy(p, oldspace, oldlen);
1302 stacknleft += newlen;
1307 grabstackblock(size_t len)
1309 len = SHELL_ALIGN(len);
1315 * The following routines are somewhat easier to use than the above.
1316 * The user declares a variable of type STACKSTR, which may be declared
1317 * to be a register. The macro STARTSTACKSTR initializes things. Then
1318 * the user uses the macro STPUTC to add characters to the string. In
1319 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1320 * grown as necessary. When the user is done, she can just leave the
1321 * string there and refer to it using stackblock(). Or she can allocate
1322 * the space for it using grabstackstr(). If it is necessary to allow
1323 * someone else to use the stack temporarily and then continue to grow
1324 * the string, the user should use grabstack to allocate the space, and
1325 * then call ungrabstr(p) to return to the previous mode of operation.
1327 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1328 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1329 * is space for at least one character.
1334 size_t len = stackblocksize();
1335 if (herefd >= 0 && len >= 1024) {
1336 full_write(herefd, stackblock(), len);
1337 return stackblock();
1340 return stackblock() + len;
1344 * Called from CHECKSTRSPACE.
1347 makestrspace(size_t newlen, char *p)
1349 size_t len = p - stacknxt;
1350 size_t size = stackblocksize();
1355 size = stackblocksize();
1357 if (nleft >= newlen)
1361 return stackblock() + len;
1365 stack_nputstr(const char *s, size_t n, char *p)
1367 p = makestrspace(n, p);
1368 p = memcpy(p, s, n) + n;
1373 stack_putstr(const char *s, char *p)
1375 return stack_nputstr(s, strlen(s), p);
1379 _STPUTC(int c, char *p)
1387 #define STARTSTACKSTR(p) ((p) = stackblock())
1388 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1389 #define CHECKSTRSPACE(n, p) \
1393 size_t m = sstrend - q; \
1395 (p) = makestrspace(l, q); \
1397 #define USTPUTC(c, p) (*p++ = (c))
1398 #define STACKSTRNUL(p) \
1400 if ((p) == sstrend) \
1401 p = growstackstr(); \
1404 #define STUNPUTC(p) (--p)
1405 #define STTOPC(p) (p[-1])
1406 #define STADJUST(amount, p) (p += (amount))
1408 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1409 #define ungrabstackstr(s, p) stunalloc((s))
1410 #define stackstrend() ((void *)sstrend)
1413 /* ============ String helpers */
1416 * prefix -- see if pfx is a prefix of string.
1419 prefix(const char *string, const char *pfx)
1422 if (*pfx++ != *string++)
1425 return (char *) string;
1429 * Check for a valid number. This should be elsewhere.
1432 is_number(const char *p)
1437 } while (*++p != '\0');
1442 * Convert a string of digits to an integer, printing an error message on
1446 number(const char *s)
1449 ash_msg_and_raise_error(illnum, s);
1454 * Produce a possibly single quoted string suitable as input to the shell.
1455 * The return string is allocated on the stack.
1458 single_quote(const char *s)
1468 len = strchrnul(s, '\'') - s;
1470 q = p = makestrspace(len + 3, p);
1473 q = memcpy(q, s, len) + len;
1479 len = strspn(s, "'");
1483 q = p = makestrspace(len + 3, p);
1486 q = memcpy(q, s, len) + len;
1495 return stackblock();
1499 /* ============ nextopt */
1501 static char **argptr; /* argument list for builtin commands */
1502 static char *optionarg; /* set by nextopt (like getopt) */
1503 static char *optptr; /* used by nextopt */
1506 * XXX - should get rid of. have all builtins use getopt(3). the
1507 * library getopt must have the BSD extension static variable "optreset"
1508 * otherwise it can't be used within the shell safely.
1510 * Standard option processing (a la getopt) for builtin routines. The
1511 * only argument that is passed to nextopt is the option string; the
1512 * other arguments are unnecessary. It return the character, or '\0' on
1516 nextopt(const char *optstring)
1523 if (p == NULL || *p == '\0') {
1525 if (p == NULL || *p != '-' || *++p == '\0')
1528 if (LONE_DASH(p)) /* check for "--" */
1532 for (q = optstring; *q != c; ) {
1534 ash_msg_and_raise_error("illegal option -%c", c);
1539 if (*p == '\0' && (p = *argptr++) == NULL)
1540 ash_msg_and_raise_error("no arg for -%c option", c);
1549 /* ============ Math support definitions */
1551 #if ENABLE_ASH_MATH_SUPPORT_64
1552 typedef int64_t arith_t;
1553 #define arith_t_type long long
1555 typedef long arith_t;
1556 #define arith_t_type long
1559 #if ENABLE_ASH_MATH_SUPPORT
1560 static arith_t dash_arith(const char *);
1561 static arith_t arith(const char *expr, int *perrcode);
1564 #if ENABLE_ASH_RANDOM_SUPPORT
1565 static unsigned long rseed;
1572 /* ============ Shell variables */
1575 #define VEXPORT 0x01 /* variable is exported */
1576 #define VREADONLY 0x02 /* variable cannot be modified */
1577 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1578 #define VTEXTFIXED 0x08 /* text is statically allocated */
1579 #define VSTACK 0x10 /* text is allocated on the stack */
1580 #define VUNSET 0x20 /* the variable is not set */
1581 #define VNOFUNC 0x40 /* don't call the callback function */
1582 #define VNOSET 0x80 /* do not set variable - just readonly test */
1583 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1585 # define VDYNAMIC 0x200 /* dynamic variable */
1590 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
1592 static const char defifsvar[] = "IFS= \t\n";
1593 #define defifs (defifsvar + 4)
1595 static const char defifs[] = " \t\n";
1599 int nparam; /* # of positional parameters (without $0) */
1600 unsigned char malloc; /* if parameter list dynamically allocated */
1601 char **p; /* parameter list */
1602 #if ENABLE_ASH_GETOPTS
1603 int optind; /* next parameter to be processed by getopts */
1604 int optoff; /* used by getopts */
1608 static struct shparam shellparam; /* $@ current positional parameters */
1611 * Free the list of positional parameters.
1614 freeparam(volatile struct shparam *param)
1618 if (param->malloc) {
1619 for (ap = param->p; *ap; ap++)
1625 #if ENABLE_ASH_GETOPTS
1627 getoptsreset(const char *value)
1629 shellparam.optind = number(value);
1630 shellparam.optoff = -1;
1635 struct var *next; /* next entry in hash list */
1636 int flags; /* flags are defined above */
1637 const char *text; /* name=value */
1638 void (*func)(const char *); /* function to be called when */
1639 /* the variable gets set/unset */
1643 struct localvar *next; /* next local variable in list */
1644 struct var *vp; /* the variable that was made local */
1645 int flags; /* saved flags */
1646 const char *text; /* saved text */
1649 /* Forward decls for varinit[] */
1650 #if ENABLE_LOCALE_SUPPORT
1652 change_lc_all(const char *value)
1654 if (value && *value != '\0')
1655 setlocale(LC_ALL, value);
1658 change_lc_ctype(const char *value)
1660 if (value && *value != '\0')
1661 setlocale(LC_CTYPE, value);
1665 static void chkmail(void);
1666 static void changemail(const char *);
1668 static void changepath(const char *);
1669 #if ENABLE_ASH_RANDOM_SUPPORT
1670 static void change_random(const char *);
1673 static struct var varinit[] = {
1675 { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
1677 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
1680 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1681 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1683 { NULL, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
1684 { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
1685 { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
1686 { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
1687 #if ENABLE_ASH_GETOPTS
1688 { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1690 #if ENABLE_ASH_RANDOM_SUPPORT
1691 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1693 #if ENABLE_LOCALE_SUPPORT
1694 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1695 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1697 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1698 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1702 #define vifs varinit[0]
1704 #define vmail (&vifs)[1]
1705 #define vmpath (&vmail)[1]
1709 #define vpath (&vmpath)[1]
1710 #define vps1 (&vpath)[1]
1711 #define vps2 (&vps1)[1]
1712 #define vps4 (&vps2)[1]
1713 #define voptind (&vps4)[1]
1714 #if ENABLE_ASH_GETOPTS
1715 #define vrandom (&voptind)[1]
1717 #define vrandom (&vps4)[1]
1719 #define defpath (defpathvar + 5)
1722 * The following macros access the values of the above variables.
1723 * They have to skip over the name. They return the null string
1724 * for unset variables.
1726 #define ifsval() (vifs.text + 4)
1727 #define ifsset() ((vifs.flags & VUNSET) == 0)
1728 #define mailval() (vmail.text + 5)
1729 #define mpathval() (vmpath.text + 9)
1730 #define pathval() (vpath.text + 5)
1731 #define ps1val() (vps1.text + 4)
1732 #define ps2val() (vps2.text + 4)
1733 #define ps4val() (vps4.text + 4)
1734 #define optindval() (voptind.text + 7)
1736 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1739 * The parsefile structure pointed to by the global variable parsefile
1740 * contains information about the current file being read.
1743 struct redirtab *next;
1748 static struct redirtab *redirlist;
1749 static int nullredirs;
1750 extern char **environ;
1751 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1755 static struct var *vartab[VTABSIZE];
1757 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1758 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1761 * Return of a legal variable name (a letter or underscore followed by zero or
1762 * more letters, underscores, and digits).
1765 endofname(const char *name)
1773 if (!is_in_name(*p))
1780 * Compares two strings up to the first = or '\0'. The first
1781 * string must be terminated by '='; the second may be terminated by
1782 * either '=' or '\0'.
1785 varcmp(const char *p, const char *q)
1789 while ((c = *p) == (d = *q)) {
1804 varequal(const char *a, const char *b)
1806 return !varcmp(a, b);
1810 * Find the appropriate entry in the hash table from the name.
1812 static struct var **
1813 hashvar(const char *p)
1817 hashval = ((unsigned char) *p) << 4;
1818 while (*p && *p != '=')
1819 hashval += (unsigned char) *p++;
1820 return &vartab[hashval % VTABSIZE];
1824 vpcmp(const void *a, const void *b)
1826 return varcmp(*(const char **)a, *(const char **)b);
1830 * This routine initializes the builtin variables.
1840 * PS1 depends on uid
1842 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1843 vps1.text = "PS1=\\w \\$ ";
1846 vps1.text = "PS1=# ";
1849 end = vp + sizeof(varinit) / sizeof(varinit[0]);
1851 vpp = hashvar(vp->text);
1854 } while (++vp < end);
1857 static struct var **
1858 findvar(struct var **vpp, const char *name)
1860 for (; *vpp; vpp = &(*vpp)->next) {
1861 if (varequal((*vpp)->text, name)) {
1869 * Find the value of a variable. Returns NULL if not set.
1872 lookupvar(const char *name)
1876 v = *findvar(hashvar(name), name);
1880 * Dynamic variables are implemented roughly the same way they are
1881 * in bash. Namely, they're "special" so long as they aren't unset.
1882 * As soon as they're unset, they're no longer dynamic, and dynamic
1883 * lookup will no longer happen at that point. -- PFM.
1885 if ((v->flags & VDYNAMIC))
1888 if (!(v->flags & VUNSET))
1889 return strchrnul(v->text, '=') + 1;
1895 * Search the environment of a builtin command.
1898 bltinlookup(const char *name)
1902 for (sp = cmdenviron; sp; sp = sp->next) {
1903 if (varequal(sp->text, name))
1904 return strchrnul(sp->text, '=') + 1;
1906 return lookupvar(name);
1910 * Same as setvar except that the variable and value are passed in
1911 * the first argument as name=value. Since the first argument will
1912 * be actually stored in the table, it should not be a string that
1914 * Called with interrupts off.
1917 setvareq(char *s, int flags)
1919 struct var *vp, **vpp;
1922 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1923 vp = *findvar(vpp, s);
1925 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1928 if (flags & VNOSAVE)
1931 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1937 if (vp->func && (flags & VNOFUNC) == 0)
1938 (*vp->func)(strchrnul(s, '=') + 1);
1940 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1941 free((char*)vp->text);
1943 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1948 vp = ckmalloc(sizeof(*vp));
1953 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1960 * Set the value of a variable. The flags argument is ored with the
1961 * flags of the variable. If val is NULL, the variable is unset.
1964 setvar(const char *name, const char *val, int flags)
1971 q = endofname(name);
1972 p = strchrnul(q, '=');
1974 if (!namelen || p != q)
1975 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1980 vallen = strlen(val);
1983 nameeq = ckmalloc(namelen + vallen + 2);
1984 p = memcpy(nameeq, name, namelen) + namelen;
1987 p = memcpy(p, val, vallen) + vallen;
1990 setvareq(nameeq, flags | VNOSAVE);
1994 #if ENABLE_ASH_GETOPTS
1996 * Safe version of setvar, returns 1 on success 0 on failure.
1999 setvarsafe(const char *name, const char *val, int flags)
2002 volatile int saveint;
2003 struct jmploc *volatile savehandler = exception_handler;
2004 struct jmploc jmploc;
2007 if (setjmp(jmploc.loc))
2010 exception_handler = &jmploc;
2011 setvar(name, val, flags);
2014 exception_handler = savehandler;
2015 RESTORE_INT(saveint);
2021 * Unset the specified variable.
2024 unsetvar(const char *s)
2030 vpp = findvar(hashvar(s), s);
2034 int flags = vp->flags;
2037 if (flags & VREADONLY)
2040 vp->flags &= ~VDYNAMIC;
2044 if ((flags & VSTRFIXED) == 0) {
2046 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2047 free((char*)vp->text);
2053 vp->flags &= ~VEXPORT;
2063 * Process a linked list of variable assignments.
2066 listsetvar(struct strlist *list_set_var, int flags)
2068 struct strlist *lp = list_set_var;
2074 setvareq(lp->text, flags);
2081 * Generate a list of variables satisfying the given conditions.
2084 listvars(int on, int off, char ***end)
2095 for (vp = *vpp; vp; vp = vp->next) {
2096 if ((vp->flags & mask) == on) {
2097 if (ep == stackstrend())
2098 ep = growstackstr();
2099 *ep++ = (char *) vp->text;
2102 } while (++vpp < vartab + VTABSIZE);
2103 if (ep == stackstrend())
2104 ep = growstackstr();
2108 return grabstackstr(ep);
2112 /* ============ Path search helper
2114 * The variable path (passed by reference) should be set to the start
2115 * of the path before the first call; padvance will update
2116 * this value as it proceeds. Successive calls to padvance will return
2117 * the possible path expansions in sequence. If an option (indicated by
2118 * a percent sign) appears in the path entry then the global variable
2119 * pathopt will be set to point to it; otherwise pathopt will be set to
2122 static const char *pathopt; /* set by padvance */
2125 padvance(const char **path, const char *name)
2135 for (p = start; *p && *p != ':' && *p != '%'; p++);
2136 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2137 while (stackblocksize() < len)
2141 memcpy(q, start, p - start);
2149 while (*p && *p != ':') p++;
2155 return stalloc(len);
2159 /* ============ Prompt */
2161 static int doprompt; /* if set, prompt the user */
2162 static int needprompt; /* true if interactive and at start of line */
2164 #if ENABLE_FEATURE_EDITING
2165 static line_input_t *line_input_state;
2166 static const char *cmdedit_prompt;
2168 putprompt(const char *s)
2170 if (ENABLE_ASH_EXPAND_PRMT) {
2171 free((char*)cmdedit_prompt);
2172 cmdedit_prompt = ckstrdup(s);
2179 putprompt(const char *s)
2185 #if ENABLE_ASH_EXPAND_PRMT
2186 /* expandstr() needs parsing machinery, so it is far away ahead... */
2187 static const char *expandstr(const char *ps);
2189 #define expandstr(s) s
2193 setprompt(int whichprompt)
2196 #if ENABLE_ASH_EXPAND_PRMT
2197 struct stackmark smark;
2202 switch (whichprompt) {
2212 #if ENABLE_ASH_EXPAND_PRMT
2213 setstackmark(&smark);
2214 stalloc(stackblocksize());
2216 putprompt(expandstr(prompt));
2217 #if ENABLE_ASH_EXPAND_PRMT
2218 popstackmark(&smark);
2223 /* ============ The cd and pwd commands */
2225 #define CD_PHYSICAL 1
2228 static int docd(const char *, int);
2230 static char *curdir = nullstr; /* current working directory */
2231 static char *physdir = nullstr; /* physical working directory */
2240 while ((i = nextopt("LP"))) {
2242 flags ^= CD_PHYSICAL;
2251 * Update curdir (the name of the current directory) in response to a
2255 updatepwd(const char *dir)
2262 cdcomppath = ststrdup(dir);
2265 if (curdir == nullstr)
2267 new = stack_putstr(curdir, new);
2269 new = makestrspace(strlen(dir) + 2, new);
2270 lim = stackblock() + 1;
2274 if (new > lim && *lim == '/')
2279 if (dir[1] == '/' && dir[2] != '/') {
2285 p = strtok(cdcomppath, "/");
2289 if (p[1] == '.' && p[2] == '\0') {
2301 new = stack_putstr(p, new);
2309 return stackblock();
2313 * Find out what the current directory is. If we already know the current
2314 * directory, this routine returns immediately.
2319 char *dir = getcwd(0, 0);
2320 return dir ? dir : nullstr;
2324 setpwd(const char *val, int setold)
2328 oldcur = dir = curdir;
2331 setvar("OLDPWD", oldcur, VEXPORT);
2334 if (physdir != nullstr) {
2335 if (physdir != oldcur)
2339 if (oldcur == val || !val) {
2345 dir = ckstrdup(val);
2346 if (oldcur != dir && oldcur != nullstr) {
2351 setvar("PWD", dir, VEXPORT);
2354 static void hashcd(void);
2357 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2358 * know that the current directory has changed.
2361 docd(const char *dest, int flags)
2363 const char *dir = 0;
2366 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2369 if (!(flags & CD_PHYSICAL)) {
2370 dir = updatepwd(dest);
2385 cdcmd(int argc, char **argv)
2397 dest = bltinlookup(homestr);
2398 else if (LONE_DASH(dest)) {
2399 dest = bltinlookup("OLDPWD");
2421 path = bltinlookup("CDPATH");
2430 p = padvance(&path, dest);
2431 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2435 if (!docd(p, flags))
2440 ash_msg_and_raise_error("can't cd to %s", dest);
2443 if (flags & CD_PRINT)
2444 out1fmt(snlfmt, curdir);
2449 pwdcmd(int argc, char **argv)
2452 const char *dir = curdir;
2456 if (physdir == nullstr)
2460 out1fmt(snlfmt, dir);
2465 /* ============ ... */
2467 #define IBUFSIZ (BUFSIZ + 1)
2468 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2470 /* Syntax classes */
2471 #define CWORD 0 /* character is nothing special */
2472 #define CNL 1 /* newline character */
2473 #define CBACK 2 /* a backslash character */
2474 #define CSQUOTE 3 /* single quote */
2475 #define CDQUOTE 4 /* double quote */
2476 #define CENDQUOTE 5 /* a terminating quote */
2477 #define CBQUOTE 6 /* backwards single quote */
2478 #define CVAR 7 /* a dollar sign */
2479 #define CENDVAR 8 /* a '}' character */
2480 #define CLP 9 /* a left paren in arithmetic */
2481 #define CRP 10 /* a right paren in arithmetic */
2482 #define CENDFILE 11 /* end of file */
2483 #define CCTL 12 /* like CWORD, except it must be escaped */
2484 #define CSPCL 13 /* these terminate a word */
2485 #define CIGN 14 /* character should be ignored */
2487 #if ENABLE_ASH_ALIAS
2491 #define PEOA_OR_PEOF PEOA
2495 #define PEOA_OR_PEOF PEOF
2498 /* number syntax index */
2499 #define BASESYNTAX 0 /* not in quotes */
2500 #define DQSYNTAX 1 /* in double quotes */
2501 #define SQSYNTAX 2 /* in single quotes */
2502 #define ARISYNTAX 3 /* in arithmetic */
2504 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2505 #define USE_SIT_FUNCTION
2508 #if ENABLE_ASH_MATH_SUPPORT
2509 static const char S_I_T[][4] = {
2510 #if ENABLE_ASH_ALIAS
2511 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2513 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2514 { CNL, CNL, CNL, CNL }, /* 2, \n */
2515 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2516 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2517 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2518 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2519 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2520 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2521 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2522 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2523 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2524 #ifndef USE_SIT_FUNCTION
2525 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2526 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2527 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2531 static const char S_I_T[][3] = {
2532 #if ENABLE_ASH_ALIAS
2533 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2535 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2536 { CNL, CNL, CNL }, /* 2, \n */
2537 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2538 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2539 { CVAR, CVAR, CWORD }, /* 5, $ */
2540 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2541 { CSPCL, CWORD, CWORD }, /* 7, ( */
2542 { CSPCL, CWORD, CWORD }, /* 8, ) */
2543 { CBACK, CBACK, CCTL }, /* 9, \ */
2544 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2545 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2546 #ifndef USE_SIT_FUNCTION
2547 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2548 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2549 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2552 #endif /* ASH_MATH_SUPPORT */
2554 #ifdef USE_SIT_FUNCTION
2557 SIT(int c, int syntax)
2559 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2560 #if ENABLE_ASH_ALIAS
2561 static const char syntax_index_table[] = {
2562 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2563 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2564 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2568 static const char syntax_index_table[] = {
2569 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2570 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2571 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2578 if (c == PEOF) /* 2^8+2 */
2580 #if ENABLE_ASH_ALIAS
2581 if (c == PEOA) /* 2^8+1 */
2585 #define U_C(c) ((unsigned char)(c))
2587 if ((unsigned char)c >= (unsigned char)(CTLESC)
2588 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2592 s = strchr(spec_symbls, c);
2593 if (s == NULL || *s == '\0')
2595 indx = syntax_index_table[(s - spec_symbls)];
2597 return S_I_T[indx][syntax];
2600 #else /* !USE_SIT_FUNCTION */
2602 #if ENABLE_ASH_ALIAS
2603 #define CSPCL_CIGN_CIGN_CIGN 0
2604 #define CSPCL_CWORD_CWORD_CWORD 1
2605 #define CNL_CNL_CNL_CNL 2
2606 #define CWORD_CCTL_CCTL_CWORD 3
2607 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2608 #define CVAR_CVAR_CWORD_CVAR 5
2609 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2610 #define CSPCL_CWORD_CWORD_CLP 7
2611 #define CSPCL_CWORD_CWORD_CRP 8
2612 #define CBACK_CBACK_CCTL_CBACK 9
2613 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2614 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2615 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2616 #define CWORD_CWORD_CWORD_CWORD 13
2617 #define CCTL_CCTL_CCTL_CCTL 14
2619 #define CSPCL_CWORD_CWORD_CWORD 0
2620 #define CNL_CNL_CNL_CNL 1
2621 #define CWORD_CCTL_CCTL_CWORD 2
2622 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2623 #define CVAR_CVAR_CWORD_CVAR 4
2624 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2625 #define CSPCL_CWORD_CWORD_CLP 6
2626 #define CSPCL_CWORD_CWORD_CRP 7
2627 #define CBACK_CBACK_CCTL_CBACK 8
2628 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2629 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2630 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2631 #define CWORD_CWORD_CWORD_CWORD 12
2632 #define CCTL_CCTL_CCTL_CCTL 13
2635 static const char syntax_index_table[258] = {
2636 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2637 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2638 #if ENABLE_ASH_ALIAS
2639 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2641 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2642 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2643 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2644 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2645 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2646 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2647 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2648 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2649 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2650 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2779 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2780 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2802 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2803 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2804 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2806 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2808 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2809 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2810 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2811 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2812 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2814 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2815 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2816 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2817 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2828 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2829 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2830 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2831 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2832 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2833 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2857 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2861 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2862 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2863 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2866 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2894 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2895 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2896 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2899 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2901 #endif /* USE_SIT_FUNCTION */
2904 /* ============ Alias handling */
2906 #if ENABLE_ASH_ALIAS
2908 #define ALIASINUSE 1
2920 static struct alias *atab[ATABSIZE];
2922 static struct alias **
2923 __lookupalias(const char *name) {
2924 unsigned int hashval;
2931 ch = (unsigned char)*p;
2935 ch = (unsigned char)*++p;
2937 app = &atab[hashval % ATABSIZE];
2939 for (; *app; app = &(*app)->next) {
2940 if (strcmp(name, (*app)->name) == 0) {
2948 static struct alias *
2949 lookupalias(const char *name, int check)
2951 struct alias *ap = *__lookupalias(name);
2953 if (check && ap && (ap->flag & ALIASINUSE))
2958 static struct alias *
2959 freealias(struct alias *ap)
2963 if (ap->flag & ALIASINUSE) {
2964 ap->flag |= ALIASDEAD;
2976 setalias(const char *name, const char *val)
2978 struct alias *ap, **app;
2980 app = __lookupalias(name);
2984 if (!(ap->flag & ALIASINUSE)) {
2987 ap->val = ckstrdup(val);
2988 ap->flag &= ~ALIASDEAD;
2991 ap = ckmalloc(sizeof(struct alias));
2992 ap->name = ckstrdup(name);
2993 ap->val = ckstrdup(val);
3002 unalias(const char *name)
3006 app = __lookupalias(name);
3010 *app = freealias(*app);
3021 struct alias *ap, **app;
3025 for (i = 0; i < ATABSIZE; i++) {
3027 for (ap = *app; ap; ap = *app) {
3028 *app = freealias(*app);
3038 printalias(const struct alias *ap)
3040 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3044 * TODO - sort output
3047 aliascmd(int argc, char **argv)
3056 for (i = 0; i < ATABSIZE; i++)
3057 for (ap = atab[i]; ap; ap = ap->next) {
3062 while ((n = *++argv) != NULL) {
3063 v = strchr(n+1, '=');
3064 if (v == NULL) { /* n+1: funny ksh stuff */
3065 ap = *__lookupalias(n);
3067 fprintf(stderr, "%s: %s not found\n", "alias", n);
3081 unaliascmd(int argc, char **argv)
3085 while ((i = nextopt("a")) != '\0') {
3091 for (i = 0; *argptr; argptr++) {
3092 if (unalias(*argptr)) {
3093 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3101 #endif /* ASH_ALIAS */
3104 /* ============ jobs.c */
3106 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3109 #define FORK_NOJOB 2
3111 /* mode flags for showjob(s) */
3112 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3113 #define SHOW_PID 0x04 /* include process pid */
3114 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3117 * A job structure contains information about a job. A job is either a
3118 * single process or a set of processes contained in a pipeline. In the
3119 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3124 pid_t pid; /* process id */
3125 int status; /* last process status from wait() */
3126 char *cmd; /* text of command being run */
3130 struct procstat ps0; /* status of process */
3131 struct procstat *ps; /* status or processes when more than one */
3133 int stopstatus; /* status of a stopped job */
3136 nprocs: 16, /* number of processes */
3138 #define JOBRUNNING 0 /* at least one proc running */
3139 #define JOBSTOPPED 1 /* all procs are stopped */
3140 #define JOBDONE 2 /* all procs are completed */
3142 sigint: 1, /* job was killed by SIGINT */
3143 jobctl: 1, /* job running under job control */
3145 waited: 1, /* true if this entry has been waited for */
3146 used: 1, /* true if this entry is in used */
3147 changed: 1; /* true if status has changed */
3148 struct job *prev_job; /* previous job */
3151 static pid_t backgndpid; /* pid of last background process */
3152 static int job_warning; /* user was warned about stopped jobs */
3154 static int jobctl; /* true if doing job control */
3157 static struct job *makejob(union node *, int);
3158 static int forkshell(struct job *, union node *, int);
3159 static int waitforjob(struct job *);
3162 #define setjobctl(on) /* do nothing */
3164 static void setjobctl(int);
3165 static void showjobs(FILE *, int);
3169 * Set the signal handler for the specified signal. The routine figures
3170 * out what it should be set to.
3173 setsignal(int signo)
3177 struct sigaction act;
3182 else if (*t != '\0')
3186 if (rootshell && action == S_DFL) {
3189 if (iflag || minusc || sflag == 0)
3212 t = &sigmode[signo - 1];
3216 * current setting unknown
3218 if (sigaction(signo, 0, &act) == -1) {
3220 * Pretend it worked; maybe we should give a warning
3221 * here, but other shells don't. We don't alter
3222 * sigmode, so that we retry every time.
3226 if (act.sa_handler == SIG_IGN) {
3228 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3230 tsig = S_IGN; /* don't hard ignore these */
3234 tsig = S_RESET; /* force to be set */
3237 if (tsig == S_HARD_IGN || tsig == action)
3241 act.sa_handler = onsig;
3244 act.sa_handler = SIG_IGN;
3247 act.sa_handler = SIG_DFL;
3251 sigfillset(&act.sa_mask);
3252 sigaction(signo, &act, 0);
3255 /* mode flags for set_curjob */
3256 #define CUR_DELETE 2
3257 #define CUR_RUNNING 1
3258 #define CUR_STOPPED 0
3260 /* mode flags for dowait */
3261 #define DOWAIT_NORMAL 0
3262 #define DOWAIT_BLOCK 1
3265 /* pgrp of shell on invocation */
3266 static int initialpgrp;
3267 static int ttyfd = -1;
3270 static struct job *jobtab;
3272 static unsigned njobs;
3274 static struct job *curjob;
3275 /* number of presumed living untracked jobs */
3279 set_curjob(struct job *jp, unsigned mode)
3282 struct job **jpp, **curp;
3284 /* first remove from list */
3285 jpp = curp = &curjob;
3290 jpp = &jp1->prev_job;
3292 *jpp = jp1->prev_job;
3294 /* Then re-insert in correct position */
3302 /* job being deleted */
3305 /* newly created job or backgrounded job,
3306 put after all stopped jobs. */
3310 if (!jp1 || jp1->state != JOBSTOPPED)
3313 jpp = &jp1->prev_job;
3319 /* newly stopped job - becomes curjob */
3320 jp->prev_job = *jpp;
3328 jobno(const struct job *jp)
3330 return jp - jobtab + 1;
3335 * Convert a job name to a job structure.
3338 getjob(const char *name, int getctl)
3342 const char *err_msg = "No such job: %s";
3346 char *(*match)(const char *, const char *);
3361 if (c == '+' || c == '%') {
3363 err_msg = "No current job";
3369 err_msg = "No previous job";
3380 jp = jobtab + num - 1;
3397 if (match(jp->ps[0].cmd, p)) {
3401 err_msg = "%s: ambiguous";
3408 err_msg = "job %s not created under job control";
3409 if (getctl && jp->jobctl == 0)
3414 ash_msg_and_raise_error(err_msg, name);
3418 * Mark a job structure as unused.
3421 freejob(struct job *jp)
3423 struct procstat *ps;
3427 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3428 if (ps->cmd != nullstr)
3431 if (jp->ps != &jp->ps0)
3434 set_curjob(jp, CUR_DELETE);
3440 xtcsetpgrp(int fd, pid_t pgrp)
3442 if (tcsetpgrp(fd, pgrp))
3443 ash_msg_and_raise_error("cannot set tty process group (%m)");
3447 * Turn job control on and off.
3449 * Note: This code assumes that the third arg to ioctl is a character
3450 * pointer, which is true on Berkeley systems but not System V. Since
3451 * System V doesn't have job control yet, this isn't a problem now.
3453 * Called with interrupts off.
3461 if (on == jobctl || rootshell == 0)
3465 ofd = fd = open(_PATH_TTY, O_RDWR);
3467 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3468 * That sometimes helps to acquire controlling tty.
3469 * Obviously, a workaround for bugs when someone
3470 * failed to provide a controlling tty to bash! :) */
3472 while (!isatty(fd) && --fd >= 0)
3475 fd = fcntl(fd, F_DUPFD, 10);
3479 fcntl(fd, F_SETFD, FD_CLOEXEC);
3480 do { /* while we are in the background */
3481 pgrp = tcgetpgrp(fd);
3484 ash_msg("can't access tty; job control turned off");
3488 if (pgrp == getpgrp())
3499 xtcsetpgrp(fd, pgrp);
3501 /* turning job control off */
3504 xtcsetpgrp(fd, pgrp);
3518 killcmd(int argc, char **argv)
3528 ash_msg_and_raise_error(
3529 "usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
3530 "kill -l [exitstatus]"
3534 if (**++argv == '-') {
3535 signo = get_signum(*argv + 1);
3539 while ((c = nextopt("ls:")) != '\0') {
3549 signo = get_signum(optionarg);
3551 ash_msg_and_raise_error(
3552 "invalid signal number or name: %s",
3564 if (!list && signo < 0)
3567 if ((signo < 0 || !*argv) ^ list) {
3575 for (i = 1; i < NSIG; i++) {
3576 name = get_signame(i);
3577 if (!isdigit(*name))
3578 out1fmt(snlfmt, name);
3582 name = get_signame(signo);
3583 if (!isdigit(*name))
3584 ash_msg_and_raise_error("invalid signal number or exit status: %s", *argptr);
3585 out1fmt(snlfmt, name);
3591 if (**argv == '%') {
3592 jp = getjob(*argv, 0);
3593 pid = -jp->ps[0].pid;
3595 pid = **argv == '-' ?
3596 -number(*argv + 1) : number(*argv);
3598 if (kill(pid, signo) != 0) {
3599 ash_msg("(%d) - %m", pid);
3608 showpipe(struct job *jp, FILE *out)
3610 struct procstat *sp;
3611 struct procstat *spend;
3613 spend = jp->ps + jp->nprocs;
3614 for (sp = jp->ps + 1; sp < spend; sp++)
3615 fprintf(out, " | %s", sp->cmd);
3616 outcslow('\n', out);
3617 flush_stdout_stderr();
3622 restartjob(struct job *jp, int mode)
3624 struct procstat *ps;
3630 if (jp->state == JOBDONE)
3632 jp->state = JOBRUNNING;
3634 if (mode == FORK_FG)
3635 xtcsetpgrp(ttyfd, pgid);
3636 killpg(pgid, SIGCONT);
3640 if (WIFSTOPPED(ps->status)) {
3643 } while (ps++, --i);
3645 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3651 fg_bgcmd(int argc, char **argv)
3658 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3663 jp = getjob(*argv, 1);
3664 if (mode == FORK_BG) {
3665 set_curjob(jp, CUR_RUNNING);
3666 fprintf(out, "[%d] ", jobno(jp));
3668 outstr(jp->ps->cmd, out);
3670 retval = restartjob(jp, mode);
3671 } while (*argv && *++argv);
3677 sprint_status(char *s, int status, int sigonly)
3683 if (!WIFEXITED(status)) {
3685 if (WIFSTOPPED(status))
3686 st = WSTOPSIG(status);
3689 st = WTERMSIG(status);
3691 if (st == SIGINT || st == SIGPIPE)
3694 if (WIFSTOPPED(status))
3699 col = fmtstr(s, 32, strsignal(st));
3700 if (WCOREDUMP(status)) {
3701 col += fmtstr(s + col, 16, " (core dumped)");
3703 } else if (!sigonly) {
3704 st = WEXITSTATUS(status);
3706 col = fmtstr(s, 16, "Done(%d)", st);
3708 col = fmtstr(s, 16, "Done");
3715 * Do a wait system call. If job control is compiled in, we accept
3716 * stopped processes. If block is zero, we return a value of zero
3717 * rather than blocking.
3719 * System V doesn't have a non-blocking wait system call. It does
3720 * have a SIGCLD signal that is sent to a process when one of it's
3721 * children dies. The obvious way to use SIGCLD would be to install
3722 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3723 * was received, and have waitproc bump another counter when it got
3724 * the status of a process. Waitproc would then know that a wait
3725 * system call would not block if the two counters were different.
3726 * This approach doesn't work because if a process has children that
3727 * have not been waited for, System V will send it a SIGCLD when it
3728 * installs a signal handler for SIGCLD. What this means is that when
3729 * a child exits, the shell will be sent SIGCLD signals continuously
3730 * until is runs out of stack space, unless it does a wait call before
3731 * restoring the signal handler. The code below takes advantage of
3732 * this (mis)feature by installing a signal handler for SIGCLD and
3733 * then checking to see whether it was called. If there are any
3734 * children to be waited for, it will be.
3736 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3737 * waits at all. In this case, the user will not be informed when
3738 * a background process until the next time she runs a real program
3739 * (as opposed to running a builtin command or just typing return),
3740 * and the jobs command may give out of date information.
3743 waitproc(int block, int *status)
3753 return wait3(status, flags, (struct rusage *)NULL);
3757 * Wait for a process to terminate.
3760 dowait(int block, struct job *job)
3765 struct job *thisjob;
3768 TRACE(("dowait(%d) called\n", block));
3769 pid = waitproc(block, &status);
3770 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3775 for (jp = curjob; jp; jp = jp->prev_job) {
3776 struct procstat *sp;
3777 struct procstat *spend;
3778 if (jp->state == JOBDONE)
3781 spend = jp->ps + jp->nprocs;
3784 if (sp->pid == pid) {
3785 TRACE(("Job %d: changing status of proc %d "
3786 "from 0x%x to 0x%x\n",
3787 jobno(jp), pid, sp->status, status));
3788 sp->status = status;
3791 if (sp->status == -1)
3794 if (state == JOBRUNNING)
3796 if (WIFSTOPPED(sp->status)) {
3797 jp->stopstatus = sp->status;
3801 } while (++sp < spend);
3806 if (!WIFSTOPPED(status))
3813 if (state != JOBRUNNING) {
3814 thisjob->changed = 1;
3816 if (thisjob->state != state) {
3817 TRACE(("Job %d: changing state from %d to %d\n",
3818 jobno(thisjob), thisjob->state, state));
3819 thisjob->state = state;
3821 if (state == JOBSTOPPED) {
3822 set_curjob(thisjob, CUR_STOPPED);
3831 if (thisjob && thisjob == job) {
3835 len = sprint_status(s, status, 1);
3847 showjob(FILE *out, struct job *jp, int mode)
3849 struct procstat *ps;
3850 struct procstat *psend;
3857 if (mode & SHOW_PGID) {
3858 /* just output process (group) id of pipeline */
3859 fprintf(out, "%d\n", ps->pid);
3863 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3868 else if (curjob && jp == curjob->prev_job)
3871 if (mode & SHOW_PID)
3872 col += fmtstr(s + col, 16, "%d ", ps->pid);
3874 psend = ps + jp->nprocs;
3876 if (jp->state == JOBRUNNING) {
3877 strcpy(s + col, "Running");
3878 col += sizeof("Running") - 1;
3880 int status = psend[-1].status;
3881 if (jp->state == JOBSTOPPED)
3882 status = jp->stopstatus;
3883 col += sprint_status(s + col, status, 0);
3889 /* for each process */
3890 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
3892 fprintf(out, "%s%*c%s",
3893 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3895 if (!(mode & SHOW_PID)) {
3899 if (++ps == psend) {
3900 outcslow('\n', out);
3907 if (jp->state == JOBDONE) {
3908 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3914 jobscmd(int argc, char **argv)
3920 while ((m = nextopt("lp"))) {
3931 showjob(out, getjob(*argv,0), mode);
3934 showjobs(out, mode);
3940 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3941 * statuses have changed since the last call to showjobs.
3944 showjobs(FILE *out, int mode)
3948 TRACE(("showjobs(%x) called\n", mode));
3950 /* If not even one one job changed, there is nothing to do */
3951 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3954 for (jp = curjob; jp; jp = jp->prev_job) {
3955 if (!(mode & SHOW_CHANGED) || jp->changed)
3956 showjob(out, jp, mode);
3962 getstatus(struct job *job)
3967 status = job->ps[job->nprocs - 1].status;
3968 retval = WEXITSTATUS(status);
3969 if (!WIFEXITED(status)) {
3971 retval = WSTOPSIG(status);
3972 if (!WIFSTOPPED(status))
3975 /* XXX: limits number of signals */
3976 retval = WTERMSIG(status);
3978 if (retval == SIGINT)
3984 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3985 jobno(job), job->nprocs, status, retval));
3990 waitcmd(int argc, char **argv)
4003 /* wait for all jobs */
4008 /* no running procs */
4011 if (jp->state == JOBRUNNING)
4016 dowait(DOWAIT_BLOCK, 0);
4022 if (**argv != '%') {
4023 pid_t pid = number(*argv);
4027 if (job->ps[job->nprocs - 1].pid == pid)
4029 job = job->prev_job;
4035 job = getjob(*argv, 0);
4036 /* loop until process terminated or stopped */
4037 while (job->state == JOBRUNNING)
4038 dowait(DOWAIT_BLOCK, 0);
4040 retval = getstatus(job);
4054 struct job *jp, *jq;
4056 len = njobs * sizeof(*jp);
4058 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4060 offset = (char *)jp - (char *)jq;
4062 /* Relocate pointers */
4065 jq = (struct job *)((char *)jq + l);
4069 #define joff(p) ((struct job *)((char *)(p) + l))
4070 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4071 if (joff(jp)->ps == &jq->ps0)
4072 jmove(joff(jp)->ps);
4073 if (joff(jp)->prev_job)
4074 jmove(joff(jp)->prev_job);
4084 jp = (struct job *)((char *)jp + len);
4088 } while (--jq >= jp);
4093 * Return a new job structure.
4094 * Called with interrupts off.
4097 makejob(union node *node, int nprocs)
4102 for (i = njobs, jp = jobtab; ; jp++) {
4109 if (jp->state != JOBDONE || !jp->waited)
4118 memset(jp, 0, sizeof(*jp));
4123 jp->prev_job = curjob;
4128 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4130 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4137 * Return a string identifying a command (to be printed by the
4140 static char *cmdnextc;
4143 cmdputs(const char *s)
4145 const char *p, *str;
4146 char c, cc[2] = " ";
4150 static const char vstype[VSTYPE + 1][4] = {
4151 "", "}", "-", "+", "?", "=",
4152 "%", "%%", "#", "##"
4155 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4157 while ((c = *p++) != 0) {
4165 if ((subtype & VSTYPE) == VSLENGTH)
4169 if (!(subtype & VSQUOTE) == !(quoted & 1))
4175 str = "\"}" + !(quoted & 1);
4182 case CTLBACKQ+CTLQUOTE:
4185 #if ENABLE_ASH_MATH_SUPPORT
4200 if ((subtype & VSTYPE) != VSNORMAL)
4202 str = vstype[subtype & VSTYPE];
4203 if (subtype & VSNUL)
4212 /* These can only happen inside quotes */
4225 while ((c = *str++)) {
4230 USTPUTC('"', nextc);
4236 /* cmdtxt() and cmdlist() call each other */
4237 static void cmdtxt(union node *n);
4240 cmdlist(union node *np, int sep)
4242 for (; np; np = np->narg.next) {
4246 if (sep && np->narg.next)
4252 cmdtxt(union node *n)
4255 struct nodelist *lp;
4267 lp = n->npipe.cmdlist;
4285 cmdtxt(n->nbinary.ch1);
4301 cmdtxt(n->nif.test);
4304 if (n->nif.elsepart) {
4307 n = n->nif.elsepart;
4323 cmdtxt(n->nbinary.ch1);
4333 cmdputs(n->nfor.var);
4335 cmdlist(n->nfor.args, 1);
4340 cmdputs(n->narg.text);
4344 cmdlist(n->ncmd.args, 1);
4345 cmdlist(n->ncmd.redirect, 0);
4358 cmdputs(n->ncase.expr->narg.text);
4360 for (np = n->ncase.cases; np; np = np->nclist.next) {
4361 cmdtxt(np->nclist.pattern);
4363 cmdtxt(np->nclist.body);
4389 s[0] = n->nfile.fd + '0';
4393 if (n->type == NTOFD || n->type == NFROMFD) {
4394 s[0] = n->ndup.dupfd + '0';
4404 commandtext(union node *n)
4408 STARTSTACKSTR(cmdnextc);
4410 name = stackblock();
4411 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4412 name, cmdnextc, cmdnextc));
4413 return ckstrdup(name);
4418 * Fork off a subshell. If we are doing job control, give the subshell its
4419 * own process group. Jp is a job structure that the job is to be added to.
4420 * N is the command that will be evaluated by the child. Both jp and n may
4421 * be NULL. The mode parameter can be one of the following:
4422 * FORK_FG - Fork off a foreground process.
4423 * FORK_BG - Fork off a background process.
4424 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4425 * process group even if job control is on.
4427 * When job control is turned off, background processes have their standard
4428 * input redirected to /dev/null (except for the second and later processes
4431 * Called with interrupts off.
4434 * Clear traps on a fork.
4441 for (tp = trap; tp < &trap[NSIG]; tp++) {
4442 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4447 setsignal(tp - trap);
4452 /* lives far away from here, needed for forkchild */
4453 static void closescript(void);
4455 forkchild(struct job *jp, union node *n, int mode)
4459 TRACE(("Child shell %d\n", getpid()));
4466 /* do job control only in root shell */
4468 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4471 if (jp->nprocs == 0)
4474 pgrp = jp->ps[0].pid;
4475 /* This can fail because we are doing it in the parent also */
4476 (void)setpgid(0, pgrp);
4477 if (mode == FORK_FG)
4478 xtcsetpgrp(ttyfd, pgrp);
4483 if (mode == FORK_BG) {
4486 if (jp->nprocs == 0) {
4488 if (open(bb_dev_null, O_RDONLY) != 0)
4489 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4492 if (!oldlvl && iflag) {
4497 for (jp = curjob; jp; jp = jp->prev_job)
4503 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4505 TRACE(("In parent shell: child = %d\n", pid));
4507 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4512 if (mode != FORK_NOJOB && jp->jobctl) {
4515 if (jp->nprocs == 0)
4518 pgrp = jp->ps[0].pid;
4519 /* This can fail because we are doing it in the child also */
4523 if (mode == FORK_BG) {
4524 backgndpid = pid; /* set $! */
4525 set_curjob(jp, CUR_RUNNING);
4528 struct procstat *ps = &jp->ps[jp->nprocs++];
4534 ps->cmd = commandtext(n);
4540 forkshell(struct job *jp, union node *n, int mode)
4544 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4547 TRACE(("Fork failed, errno=%d", errno));
4550 ash_msg_and_raise_error("cannot fork");
4553 forkchild(jp, n, mode);
4555 forkparent(jp, n, mode, pid);
4560 * Wait for job to finish.
4562 * Under job control we have the problem that while a child process is
4563 * running interrupts generated by the user are sent to the child but not
4564 * to the shell. This means that an infinite loop started by an inter-
4565 * active user may be hard to kill. With job control turned off, an
4566 * interactive user may place an interactive program inside a loop. If
4567 * the interactive program catches interrupts, the user doesn't want
4568 * these interrupts to also abort the loop. The approach we take here
4569 * is to have the shell ignore interrupt signals while waiting for a
4570 * foreground process to terminate, and then send itself an interrupt
4571 * signal if the child process was terminated by an interrupt signal.
4572 * Unfortunately, some programs want to do a bit of cleanup and then
4573 * exit on interrupt; unless these processes terminate themselves by
4574 * sending a signal to themselves (instead of calling exit) they will
4575 * confuse this approach.
4577 * Called with interrupts off.
4580 waitforjob(struct job *jp)
4584 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4585 while (jp->state == JOBRUNNING) {
4586 dowait(DOWAIT_BLOCK, jp);
4591 xtcsetpgrp(ttyfd, rootpid);
4593 * This is truly gross.
4594 * If we're doing job control, then we did a TIOCSPGRP which
4595 * caused us (the shell) to no longer be in the controlling
4596 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4597 * intuit from the subprocess exit status whether a SIGINT
4598 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4603 if (jp->state == JOBDONE)
4610 * return 1 if there are stopped jobs, otherwise 0
4622 if (jp && jp->state == JOBSTOPPED) {
4623 out2str("You have stopped jobs.\n");
4632 /* ============ redir.c
4634 * Code for dealing with input/output redirection.
4637 #define EMPTY -2 /* marks an unused slot in redirtab */
4639 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4641 # define PIPESIZE PIPE_BUF
4645 * Open a file in noclobber mode.
4646 * The code was copied from bash.
4649 noclobberopen(const char *fname)
4652 struct stat finfo, finfo2;
4655 * If the file exists and is a regular file, return an error
4658 r = stat(fname, &finfo);
4659 if (r == 0 && S_ISREG(finfo.st_mode)) {
4665 * If the file was not present (r != 0), make sure we open it
4666 * exclusively so that if it is created before we open it, our open
4667 * will fail. Make sure that we do not truncate an existing file.
4668 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4669 * file was not a regular file, we leave O_EXCL off.
4672 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4673 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4675 /* If the open failed, return the file descriptor right away. */
4680 * OK, the open succeeded, but the file may have been changed from a
4681 * non-regular file to a regular file between the stat and the open.
4682 * We are assuming that the O_EXCL open handles the case where FILENAME
4683 * did not exist and is symlinked to an existing file between the stat
4688 * If we can open it and fstat the file descriptor, and neither check
4689 * revealed that it was a regular file, and the file has not been
4690 * replaced, return the file descriptor.
4692 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4693 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4696 /* The file has been replaced. badness. */
4703 * Handle here documents. Normally we fork off a process to write the
4704 * data to a pipe. If the document is short, we can stuff the data in
4705 * the pipe without forking.
4707 /* openhere needs this forward reference */
4708 static void expandhere(union node *arg, int fd);
4710 openhere(union node *redir)
4716 ash_msg_and_raise_error("pipe call failed");
4717 if (redir->type == NHERE) {
4718 len = strlen(redir->nhere.doc->narg.text);
4719 if (len <= PIPESIZE) {
4720 full_write(pip[1], redir->nhere.doc->narg.text, len);
4724 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4726 signal(SIGINT, SIG_IGN);
4727 signal(SIGQUIT, SIG_IGN);
4728 signal(SIGHUP, SIG_IGN);
4730 signal(SIGTSTP, SIG_IGN);
4732 signal(SIGPIPE, SIG_DFL);
4733 if (redir->type == NHERE)
4734 full_write(pip[1], redir->nhere.doc->narg.text, len);
4736 expandhere(redir->nhere.doc, pip[1]);
4745 openredirect(union node *redir)
4750 switch (redir->nfile.type) {
4752 fname = redir->nfile.expfname;
4753 f = open(fname, O_RDONLY);
4758 fname = redir->nfile.expfname;
4759 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4764 /* Take care of noclobber mode. */
4766 fname = redir->nfile.expfname;
4767 f = noclobberopen(fname);
4774 fname = redir->nfile.expfname;
4775 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4780 fname = redir->nfile.expfname;
4781 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4789 /* Fall through to eliminate warning. */
4796 f = openhere(redir);
4802 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4804 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4808 * Copy a file descriptor to be >= to. Returns -1
4809 * if the source file descriptor is closed, EMPTY if there are no unused
4810 * file descriptors left.
4813 copyfd(int from, int to)
4817 newfd = fcntl(from, F_DUPFD, to);
4819 if (errno == EMFILE)
4821 ash_msg_and_raise_error("%d: %m", from);
4827 dupredirect(union node *redir, int f)
4829 int fd = redir->nfile.fd;
4831 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4832 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4833 copyfd(redir->ndup.dupfd, fd);
4845 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4846 * old file descriptors are stashed away so that the redirection can be
4847 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4848 * standard output, and the standard error if it becomes a duplicate of
4849 * stdout, is saved in memory.
4851 /* flags passed to redirect */
4852 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4853 #define REDIR_SAVEFD2 03 /* set preverrout */
4855 redirect(union node *redir, int flags)
4858 struct redirtab *sv;
4869 if (flags & REDIR_PUSH) {
4871 q = ckmalloc(sizeof(struct redirtab));
4872 q->next = redirlist;
4874 q->nullredirs = nullredirs - 1;
4875 for (i = 0; i < 10; i++)
4876 q->renamed[i] = EMPTY;
4883 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4884 && n->ndup.dupfd == fd)
4885 continue; /* redirect from/to same file descriptor */
4887 newfd = openredirect(n);
4890 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4891 i = fcntl(fd, F_DUPFD, 10);
4898 ash_msg_and_raise_error("%d: %m", fd);
4908 dupredirect(n, newfd);
4909 } while ((n = n->nfile.next));
4911 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4912 preverrout_fd = sv->renamed[2];
4916 * Undo the effects of the last redirection.
4921 struct redirtab *rp;
4924 if (--nullredirs >= 0)
4928 for (i = 0; i < 10; i++) {
4929 if (rp->renamed[i] != EMPTY) {
4932 copyfd(rp->renamed[i], i);
4934 close(rp->renamed[i]);
4937 redirlist = rp->next;
4938 nullredirs = rp->nullredirs;
4944 * Undo all redirections. Called on error or interrupt.
4948 * Discard all saved file descriptors.
4951 clearredir(int drop)
4962 redirectsafe(union node *redir, int flags)
4965 volatile int saveint;
4966 struct jmploc *volatile savehandler = exception_handler;
4967 struct jmploc jmploc;
4970 err = setjmp(jmploc.loc) * 2;
4972 exception_handler = &jmploc;
4973 redirect(redir, flags);
4975 exception_handler = savehandler;
4976 if (err && exception != EXERROR)
4977 longjmp(exception_handler->loc, 1);
4978 RESTORE_INT(saveint);
4983 /* ============ Routines to expand arguments to commands
4985 * We have to deal with backquotes, shell variables, and file metacharacters.
4991 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4992 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4993 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4994 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4995 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4996 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4997 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4998 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4999 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5003 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5004 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5005 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5006 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5007 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5010 * Structure specifying which parts of the string should be searched
5011 * for IFS characters.
5014 struct ifsregion *next; /* next region in list */
5015 int begoff; /* offset of start of region */
5016 int endoff; /* offset of end of region */
5017 int nulonly; /* search for nul bytes only */
5021 struct strlist *list;
5022 struct strlist **lastp;
5025 /* output of current string */
5026 static char *expdest;
5027 /* list of back quote expressions */
5028 static struct nodelist *argbackq;
5029 /* first struct in list of ifs regions */
5030 static struct ifsregion ifsfirst;
5031 /* last struct in list */
5032 static struct ifsregion *ifslastp;
5033 /* holds expanded arg list */
5034 static struct arglist exparg;
5044 expdest = makestrspace(32, expdest);
5045 #if ENABLE_ASH_MATH_SUPPORT_64
5046 len = fmtstr(expdest, 32, "%lld", (long long) num);
5048 len = fmtstr(expdest, 32, "%ld", num);
5050 STADJUST(len, expdest);
5055 esclen(const char *start, const char *p)
5059 while (p > start && *--p == CTLESC) {
5066 * Remove any CTLESC characters from a string.
5069 _rmescapes(char *str, int flag)
5072 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5077 p = strpbrk(str, qchars);
5083 if (flag & RMESCAPE_ALLOC) {
5084 size_t len = p - str;
5085 size_t fulllen = len + strlen(p) + 1;
5087 if (flag & RMESCAPE_GROW) {
5088 r = makestrspace(fulllen, expdest);
5089 } else if (flag & RMESCAPE_HEAP) {
5090 r = ckmalloc(fulllen);
5092 r = stalloc(fulllen);
5096 q = memcpy(q, str, len) + len;
5099 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5100 globbing = flag & RMESCAPE_GLOB;
5101 notescaped = globbing;
5103 if (*p == CTLQUOTEMARK) {
5104 inquotes = ~inquotes;
5106 notescaped = globbing;
5110 /* naked back slash */
5116 if (notescaped && inquotes && *p != '/') {
5120 notescaped = globbing;
5125 if (flag & RMESCAPE_GROW) {
5127 STADJUST(q - r + 1, expdest);
5131 #define rmescapes(p) _rmescapes((p), 0)
5133 #define pmatch(a, b) !fnmatch((a), (b), 0)
5136 * Prepare a pattern for a expmeta (internal glob(3)) call.
5138 * Returns an stalloced string.
5141 preglob(const char *pattern, int quoted, int flag)
5143 flag |= RMESCAPE_GLOB;
5145 flag |= RMESCAPE_QUOTED;
5147 return _rmescapes((char *)pattern, flag);
5151 * Put a string on the stack.
5154 memtodest(const char *p, size_t len, int syntax, int quotes)
5158 q = makestrspace(len * 2, q);
5161 int c = signed_char2int(*p++);
5164 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5173 strtodest(const char *p, int syntax, int quotes)
5175 memtodest(p, strlen(p), syntax, quotes);
5179 * Record the fact that we have to scan this region of the
5180 * string for IFS characters.
5183 recordregion(int start, int end, int nulonly)
5185 struct ifsregion *ifsp;
5187 if (ifslastp == NULL) {
5191 ifsp = ckmalloc(sizeof(*ifsp));
5193 ifslastp->next = ifsp;
5197 ifslastp->begoff = start;
5198 ifslastp->endoff = end;
5199 ifslastp->nulonly = nulonly;
5203 removerecordregions(int endoff)
5205 if (ifslastp == NULL)
5208 if (ifsfirst.endoff > endoff) {
5209 while (ifsfirst.next != NULL) {
5210 struct ifsregion *ifsp;
5212 ifsp = ifsfirst.next->next;
5213 free(ifsfirst.next);
5214 ifsfirst.next = ifsp;
5217 if (ifsfirst.begoff > endoff)
5220 ifslastp = &ifsfirst;
5221 ifsfirst.endoff = endoff;
5226 ifslastp = &ifsfirst;
5227 while (ifslastp->next && ifslastp->next->begoff < endoff)
5228 ifslastp=ifslastp->next;
5229 while (ifslastp->next != NULL) {
5230 struct ifsregion *ifsp;
5232 ifsp = ifslastp->next->next;
5233 free(ifslastp->next);
5234 ifslastp->next = ifsp;
5237 if (ifslastp->endoff > endoff)
5238 ifslastp->endoff = endoff;
5242 exptilde(char *startp, char *p, int flag)
5248 int quotes = flag & (EXP_FULL | EXP_CASE);
5253 while ((c = *++p) != '\0') {
5260 if (flag & EXP_VARTILDE)
5270 if (*name == '\0') {
5271 home = lookupvar(homestr);
5273 pw = getpwnam(name);
5278 if (!home || !*home)
5281 startloc = expdest - (char *)stackblock();
5282 strtodest(home, SQSYNTAX, quotes);
5283 recordregion(startloc, expdest - (char *)stackblock(), 0);
5291 * Execute a command inside back quotes. If it's a builtin command, we
5292 * want to save its output in a block obtained from malloc. Otherwise
5293 * we fork off a subprocess and get the output of the command via a pipe.
5294 * Should be called with interrupts off.
5296 struct backcmd { /* result of evalbackcmd */
5297 int fd; /* file descriptor to read from */
5298 char *buf; /* buffer */
5299 int nleft; /* number of chars in buffer */
5300 struct job *jp; /* job structure for command */
5303 /* These forward decls are needed to use "eval" code for backticks handling: */
5304 static int back_exitstatus; /* exit status of backquoted command */
5305 #define EV_EXIT 01 /* exit after evaluating tree */
5306 static void evaltree(union node *, int);
5309 evalbackcmd(union node *n, struct backcmd *result)
5321 saveherefd = herefd;
5329 ash_msg_and_raise_error("pipe call failed");
5331 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5340 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5344 result->fd = pip[0];
5347 herefd = saveherefd;
5349 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5350 result->fd, result->buf, result->nleft, result->jp));
5354 * Expand stuff in backwards quotes.
5357 expbackq(union node *cmd, int quoted, int quotes)
5365 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5366 struct stackmark smark;
5369 setstackmark(&smark);
5371 startloc = dest - (char *)stackblock();
5373 evalbackcmd(cmd, &in);
5374 popstackmark(&smark);
5381 memtodest(p, i, syntax, quotes);
5385 i = safe_read(in.fd, buf, sizeof(buf));
5386 TRACE(("expbackq: read returns %d\n", i));
5396 back_exitstatus = waitforjob(in.jp);
5400 /* Eat all trailing newlines */
5402 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5407 recordregion(startloc, dest - (char *)stackblock(), 0);
5408 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5409 (dest - (char *)stackblock()) - startloc,
5410 (dest - (char *)stackblock()) - startloc,
5411 stackblock() + startloc));
5414 #if ENABLE_ASH_MATH_SUPPORT
5416 * Expand arithmetic expression. Backup to start of expression,
5417 * evaluate, place result in (backed up) result, adjust string position.
5430 * This routine is slightly over-complicated for
5431 * efficiency. Next we scan backwards looking for the
5432 * start of arithmetic.
5434 start = stackblock();
5441 while (*p != CTLARI) {
5445 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5450 esc = esclen(start, p);
5460 removerecordregions(begoff);
5469 len = cvtnum(dash_arith(p + 2));
5472 recordregion(begoff, begoff + len, 0);
5476 /* argstr needs it */
5477 static char *evalvar(char *p, int flag);
5480 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5481 * characters to allow for further processing. Otherwise treat
5482 * $@ like $* since no splitting will be performed.
5485 argstr(char *p, int flag)
5487 static const char spclchars[] = {
5495 CTLBACKQ | CTLQUOTE,
5496 #if ENABLE_ASH_MATH_SUPPORT
5501 const char *reject = spclchars;
5503 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5504 int breakall = flag & EXP_WORD;
5509 if (!(flag & EXP_VARTILDE)) {
5511 } else if (flag & EXP_VARTILDE2) {
5516 if (flag & EXP_TILDE) {
5522 if (*q == CTLESC && (flag & EXP_QWORD))
5525 p = exptilde(p, q, flag);
5528 startloc = expdest - (char *)stackblock();
5530 length += strcspn(p + length, reject);
5532 if (c && (!(c & 0x80)
5533 #if ENABLE_ASH_MATH_SUPPORT
5537 /* c == '=' || c == ':' || c == CTLENDARI */
5542 expdest = stack_nputstr(p, length, expdest);
5543 newloc = expdest - (char *)stackblock();
5544 if (breakall && !inquotes && newloc > startloc) {
5545 recordregion(startloc, newloc, 0);
5556 if (flag & EXP_VARTILDE2) {
5560 flag |= EXP_VARTILDE2;
5565 * sort of a hack - expand tildes in variable
5566 * assignments (after the first '=' and after ':'s).
5575 case CTLENDVAR: /* ??? */
5578 /* "$@" syntax adherence hack */
5581 !memcmp(p, dolatstr, 4) &&
5582 (p[4] == CTLQUOTEMARK || (
5583 p[4] == CTLENDVAR &&
5584 p[5] == CTLQUOTEMARK
5587 p = evalvar(p + 1, flag) + 1;
5590 inquotes = !inquotes;
5603 p = evalvar(p, flag);
5607 case CTLBACKQ|CTLQUOTE:
5608 expbackq(argbackq->n, c, quotes);
5609 argbackq = argbackq->next;
5611 #if ENABLE_ASH_MATH_SUPPORT
5624 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5635 const char *s = loc2;
5641 match = pmatch(str, s);
5645 if (quotes && *loc == CTLESC)
5654 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5661 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5664 const char *s = loc2;
5669 match = pmatch(str, s);
5676 esc = esclen(startp, loc);
5687 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5689 varunset(const char *end, const char *var, const char *umsg, int varflags)
5695 msg = "parameter not set";
5697 if (*end == CTLENDVAR) {
5698 if (varflags & VSNUL)
5703 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5707 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5711 int saveherefd = herefd;
5712 struct nodelist *saveargbackq = argbackq;
5714 char *rmesc, *rmescend;
5716 char *(*scan)(char *, char *, char *, char *, int , int);
5719 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5720 STPUTC('\0', expdest);
5721 herefd = saveherefd;
5722 argbackq = saveargbackq;
5723 startp = stackblock() + startloc;
5727 setvar(str, startp, 0);
5728 amount = startp - expdest;
5729 STADJUST(amount, expdest);
5733 varunset(p, str, startp, varflags);
5737 subtype -= VSTRIMRIGHT;
5739 if (subtype < 0 || subtype > 3)
5744 rmescend = stackblock() + strloc;
5746 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5747 if (rmesc != startp) {
5749 startp = stackblock() + startloc;
5753 str = stackblock() + strloc;
5754 preglob(str, varflags & VSQUOTE, 0);
5756 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5757 zero = subtype >> 1;
5758 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5759 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5761 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5764 memmove(startp, loc, str - loc);
5765 loc = startp + (str - loc) - 1;
5768 amount = loc - expdest;
5769 STADJUST(amount, expdest);
5775 * Add the value of a specialized variable to the stack string.
5778 varvalue(char *name, int varflags, int flags)
5788 int quoted = varflags & VSQUOTE;
5789 int subtype = varflags & VSTYPE;
5790 int quotes = flags & (EXP_FULL | EXP_CASE);
5792 if (quoted && (flags & EXP_FULL))
5793 sep = 1 << CHAR_BIT;
5795 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5804 num = shellparam.nparam;
5814 p = makestrspace(NOPTS, expdest);
5815 for (i = NOPTS - 1; i >= 0; i--) {
5817 USTPUTC(optletters(i), p);
5828 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5829 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5835 while ((p = *ap++)) {
5838 partlen = strlen(p);
5841 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5842 memtodest(p, partlen, syntax, quotes);
5848 if (subtype == VSPLUS || subtype == VSLENGTH) {
5870 if (num < 0 || num > shellparam.nparam)
5872 p = num ? shellparam.p[num - 1] : arg0;
5875 p = lookupvar(name);
5881 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5882 memtodest(p, len, syntax, quotes);
5886 if (subtype == VSPLUS || subtype == VSLENGTH)
5887 STADJUST(-len, expdest);
5892 * Expand a variable, and return a pointer to the next character in the
5896 evalvar(char *p, int flag)
5909 quotes = flag & (EXP_FULL | EXP_CASE);
5911 subtype = varflags & VSTYPE;
5912 quoted = varflags & VSQUOTE;
5914 easy = (!quoted || (*var == '@' && shellparam.nparam));
5915 startloc = expdest - (char *)stackblock();
5916 p = strchr(p, '=') + 1;
5919 varlen = varvalue(var, varflags, flag);
5920 if (varflags & VSNUL)
5923 if (subtype == VSPLUS) {
5924 varlen = -1 - varlen;
5928 if (subtype == VSMINUS) {
5932 p, flag | EXP_TILDE |
5933 (quoted ? EXP_QWORD : EXP_WORD)
5942 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5944 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5947 * Remove any recorded regions beyond
5950 removerecordregions(startloc);
5960 if (varlen < 0 && uflag)
5961 varunset(p, var, 0, 0);
5963 if (subtype == VSLENGTH) {
5964 cvtnum(varlen > 0 ? varlen : 0);
5968 if (subtype == VSNORMAL) {
5972 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5981 case VSTRIMRIGHTMAX:
5990 * Terminate the string and start recording the pattern
5993 STPUTC('\0', expdest);
5994 patloc = expdest - (char *)stackblock();
5995 if (subevalvar(p, NULL, patloc, subtype,
5996 startloc, varflags, quotes) == 0) {
5997 int amount = expdest - (
5998 (char *)stackblock() + patloc - 1
6000 STADJUST(-amount, expdest);
6002 /* Remove any recorded regions beyond start of variable */
6003 removerecordregions(startloc);
6008 if (subtype != VSNORMAL) { /* skip to end of alternative */
6014 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6016 argbackq = argbackq->next;
6017 } else if (c == CTLVAR) {
6018 if ((*p++ & VSTYPE) != VSNORMAL)
6020 } else if (c == CTLENDVAR) {
6030 * Break the argument string into pieces based upon IFS and add the
6031 * strings to the argument list. The regions of the string to be
6032 * searched for IFS characters have been stored by recordregion.
6035 ifsbreakup(char *string, struct arglist *arglist)
6037 struct ifsregion *ifsp;
6042 const char *ifs, *realifs;
6047 if (ifslastp != NULL) {
6050 realifs = ifsset() ? ifsval() : defifs;
6053 p = string + ifsp->begoff;
6054 nulonly = ifsp->nulonly;
6055 ifs = nulonly ? nullstr : realifs;
6057 while (p < string + ifsp->endoff) {
6061 if (!strchr(ifs, *p)) {
6066 ifsspc = (strchr(defifs, *p) != NULL);
6067 /* Ignore IFS whitespace at start */
6068 if (q == start && ifsspc) {
6074 sp = stalloc(sizeof(*sp));
6076 *arglist->lastp = sp;
6077 arglist->lastp = &sp->next;
6081 if (p >= string + ifsp->endoff) {
6087 if (strchr(ifs, *p) == NULL ) {
6090 } else if (strchr(defifs, *p) == NULL) {
6105 } while (ifsp != NULL);
6114 sp = stalloc(sizeof(*sp));
6116 *arglist->lastp = sp;
6117 arglist->lastp = &sp->next;
6123 struct ifsregion *p;
6128 struct ifsregion *ifsp;
6134 ifsfirst.next = NULL;
6139 * Add a file name to the list.
6142 addfname(const char *name)
6146 sp = stalloc(sizeof(*sp));
6147 sp->text = ststrdup(name);
6149 exparg.lastp = &sp->next;
6152 static char *expdir;
6155 * Do metacharacter (i.e. *, ?, [...]) expansion.
6158 expmeta(char *enddir, char *name)
6173 for (p = name; *p; p++) {
6174 if (*p == '*' || *p == '?')
6176 else if (*p == '[') {
6183 if (*q == '/' || *q == '\0')
6190 } else if (*p == '\\')
6192 else if (*p == '/') {
6199 if (metaflag == 0) { /* we've reached the end of the file name */
6200 if (enddir != expdir)
6208 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6219 } while (p < start);
6221 if (enddir == expdir) {
6223 } else if (enddir == expdir + 1 && *expdir == '/') {
6232 if (enddir != expdir)
6234 if (*endname == 0) {
6246 while (! intpending && (dp = readdir(dirp)) != NULL) {
6247 if (dp->d_name[0] == '.' && ! matchdot)
6249 if (pmatch(start, dp->d_name)) {
6251 strcpy(enddir, dp->d_name);
6254 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6257 expmeta(p, endname);
6266 static struct strlist *
6267 msort(struct strlist *list, int len)
6269 struct strlist *p, *q = NULL;
6270 struct strlist **lpp;
6278 for (n = half; --n >= 0; ) {
6282 q->next = NULL; /* terminate first half of list */
6283 q = msort(list, half); /* sort first half of list */
6284 p = msort(p, len - half); /* sort second half */
6287 #if ENABLE_LOCALE_SUPPORT
6288 if (strcoll(p->text, q->text) < 0)
6290 if (strcmp(p->text, q->text) < 0)
6314 * Sort the results of file name expansion. It calculates the number of
6315 * strings to sort and then calls msort (short for merge sort) to do the
6318 static struct strlist *
6319 expsort(struct strlist *str)
6325 for (sp = str; sp; sp = sp->next)
6327 return msort(str, len);
6331 expandmeta(struct strlist *str, int flag)
6333 static const char metachars[] = {
6336 /* TODO - EXP_REDIR */
6339 struct strlist **savelastp;
6345 if (!strpbrk(str->text, metachars))
6347 savelastp = exparg.lastp;
6350 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6352 int i = strlen(str->text);
6353 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6361 if (exparg.lastp == savelastp) {
6366 *exparg.lastp = str;
6367 rmescapes(str->text);
6368 exparg.lastp = &str->next;
6370 *exparg.lastp = NULL;
6371 *savelastp = sp = expsort(*savelastp);
6372 while (sp->next != NULL)
6374 exparg.lastp = &sp->next;
6381 * Perform variable substitution and command substitution on an argument,
6382 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6383 * perform splitting and file name expansion. When arglist is NULL, perform
6384 * here document expansion.
6387 expandarg(union node *arg, struct arglist *arglist, int flag)
6392 argbackq = arg->narg.backquote;
6393 STARTSTACKSTR(expdest);
6394 ifsfirst.next = NULL;
6396 argstr(arg->narg.text, flag);
6397 p = _STPUTC('\0', expdest);
6399 if (arglist == NULL) {
6400 return; /* here document expanded */
6402 p = grabstackstr(p);
6403 exparg.lastp = &exparg.list;
6407 if (flag & EXP_FULL) {
6408 ifsbreakup(p, &exparg);
6409 *exparg.lastp = NULL;
6410 exparg.lastp = &exparg.list;
6411 expandmeta(exparg.list, flag);
6413 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6415 sp = stalloc(sizeof(*sp));
6418 exparg.lastp = &sp->next;
6422 *exparg.lastp = NULL;
6424 *arglist->lastp = exparg.list;
6425 arglist->lastp = exparg.lastp;
6430 * Expand shell variables and backquotes inside a here document.
6433 expandhere(union node *arg, int fd)
6436 expandarg(arg, (struct arglist *)NULL, 0);
6437 full_write(fd, stackblock(), expdest - (char *)stackblock());
6441 * Returns true if the pattern matches the string.
6444 patmatch(char *pattern, const char *string)
6446 return pmatch(preglob(pattern, 0, 0), string);
6450 * See if a pattern matches in a case statement.
6453 casematch(union node *pattern, char *val)
6455 struct stackmark smark;
6458 setstackmark(&smark);
6459 argbackq = pattern->narg.backquote;
6460 STARTSTACKSTR(expdest);
6462 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6463 STACKSTRNUL(expdest);
6464 result = patmatch(stackblock(), val);
6465 popstackmark(&smark);
6470 /* ============ find_command */
6474 int (*builtin)(int, char **);
6475 /* unsigned flags; */
6477 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6478 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6479 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6485 const struct builtincmd *cmd;
6486 struct funcnode *func;
6489 /* values of cmdtype */
6490 #define CMDUNKNOWN -1 /* no entry in table for command */
6491 #define CMDNORMAL 0 /* command is an executable program */
6492 #define CMDFUNCTION 1 /* command is a shell function */
6493 #define CMDBUILTIN 2 /* command is a shell builtin */
6495 /* action to find_command() */
6496 #define DO_ERR 0x01 /* prints errors */
6497 #define DO_ABS 0x02 /* checks absolute paths */
6498 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6499 #define DO_ALTPATH 0x08 /* using alternate path */
6500 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6502 static void find_command(char *, struct cmdentry *, int, const char *);
6505 /* ============ Hashing commands */
6508 * When commands are first encountered, they are entered in a hash table.
6509 * This ensures that a full path search will not have to be done for them
6510 * on each invocation.
6512 * We should investigate converting to a linear search, even though that
6513 * would make the command name "hash" a misnomer.
6516 #define CMDTABLESIZE 31 /* should be prime */
6517 #define ARB 1 /* actual size determined at run time */
6520 struct tblentry *next; /* next entry in hash chain */
6521 union param param; /* definition of builtin function */
6522 short cmdtype; /* index identifying command */
6523 char rehash; /* if set, cd done since entry created */
6524 char cmdname[ARB]; /* name of command */
6527 static struct tblentry *cmdtable[CMDTABLESIZE];
6528 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6531 tryexec(char *cmd, char **argv, char **envp)
6535 #if ENABLE_FEATURE_SH_STANDALONE
6536 if (strchr(cmd, '/') == NULL) {
6537 const struct bb_applet *a;
6539 a = find_applet_by_name(cmd);
6543 run_current_applet_and_exit(argv);
6545 /* re-exec ourselves with the new arguments */
6546 execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
6547 /* If they called chroot or otherwise made the binary no longer
6548 * executable, fall through */
6556 execve(cmd, argv, envp);
6557 } while (errno == EINTR);
6559 execve(cmd, argv, envp);
6563 } else if (errno == ENOEXEC) {
6567 for (ap = argv; *ap; ap++)
6569 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6571 ap[0] = cmd = (char *)DEFAULT_SHELL;
6574 while ((*ap++ = *argv++))
6582 * Exec a program. Never returns. If you change this routine, you may
6583 * have to change the find_command routine as well.
6585 #define environment() listvars(VEXPORT, VUNSET, 0)
6586 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6588 shellexec(char **argv, const char *path, int idx)
6596 envp = environment();
6597 if (strchr(argv[0], '/')
6598 #if ENABLE_FEATURE_SH_STANDALONE
6599 || find_applet_by_name(argv[0])
6602 tryexec(argv[0], argv, envp);
6606 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6607 if (--idx < 0 && pathopt == NULL) {
6608 tryexec(cmdname, argv, envp);
6609 if (errno != ENOENT && errno != ENOTDIR)
6616 /* Map to POSIX errors */
6628 exitstatus = exerrno;
6629 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6630 argv[0], e, suppressint ));
6631 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6636 printentry(struct tblentry *cmdp)
6642 idx = cmdp->param.index;
6645 name = padvance(&path, cmdp->cmdname);
6647 } while (--idx >= 0);
6648 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6652 * Clear out command entries. The argument specifies the first entry in
6653 * PATH which has changed.
6656 clearcmdentry(int firstchange)
6658 struct tblentry **tblp;
6659 struct tblentry **pp;
6660 struct tblentry *cmdp;
6663 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6665 while ((cmdp = *pp) != NULL) {
6666 if ((cmdp->cmdtype == CMDNORMAL &&
6667 cmdp->param.index >= firstchange)
6668 || (cmdp->cmdtype == CMDBUILTIN &&
6669 builtinloc >= firstchange)
6682 * Locate a command in the command hash table. If "add" is nonzero,
6683 * add the command to the table if it is not already present. The
6684 * variable "lastcmdentry" is set to point to the address of the link
6685 * pointing to the entry, so that delete_cmd_entry can delete the
6688 * Interrupts must be off if called with add != 0.
6690 static struct tblentry **lastcmdentry;
6692 static struct tblentry *
6693 cmdlookup(const char *name, int add)
6695 unsigned int hashval;
6697 struct tblentry *cmdp;
6698 struct tblentry **pp;
6701 hashval = (unsigned char)*p << 4;
6703 hashval += (unsigned char)*p++;
6705 pp = &cmdtable[hashval % CMDTABLESIZE];
6706 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6707 if (strcmp(cmdp->cmdname, name) == 0)
6711 if (add && cmdp == NULL) {
6712 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6713 + strlen(name) + 1);
6715 cmdp->cmdtype = CMDUNKNOWN;
6716 strcpy(cmdp->cmdname, name);
6723 * Delete the command entry returned on the last lookup.
6726 delete_cmd_entry(void)
6728 struct tblentry *cmdp;
6731 cmdp = *lastcmdentry;
6732 *lastcmdentry = cmdp->next;
6733 if (cmdp->cmdtype == CMDFUNCTION)
6734 freefunc(cmdp->param.func);
6740 * Add a new command entry, replacing any existing command entry for
6741 * the same name - except special builtins.
6744 addcmdentry(char *name, struct cmdentry *entry)
6746 struct tblentry *cmdp;
6748 cmdp = cmdlookup(name, 1);
6749 if (cmdp->cmdtype == CMDFUNCTION) {
6750 freefunc(cmdp->param.func);
6752 cmdp->cmdtype = entry->cmdtype;
6753 cmdp->param = entry->u;
6758 hashcmd(int argc, char **argv)
6760 struct tblentry **pp;
6761 struct tblentry *cmdp;
6763 struct cmdentry entry;
6766 while ((c = nextopt("r")) != '\0') {
6770 if (*argptr == NULL) {
6771 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6772 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6773 if (cmdp->cmdtype == CMDNORMAL)
6780 while ((name = *argptr) != NULL) {
6781 cmdp = cmdlookup(name, 0);
6783 && (cmdp->cmdtype == CMDNORMAL
6784 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6786 find_command(name, &entry, DO_ERR, pathval());
6787 if (entry.cmdtype == CMDUNKNOWN)
6795 * Called when a cd is done. Marks all commands so the next time they
6796 * are executed they will be rehashed.
6801 struct tblentry **pp;
6802 struct tblentry *cmdp;
6804 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6805 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6806 if (cmdp->cmdtype == CMDNORMAL || (
6807 cmdp->cmdtype == CMDBUILTIN &&
6808 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6817 * Fix command hash table when PATH changed.
6818 * Called before PATH is changed. The argument is the new value of PATH;
6819 * pathval() still returns the old value at this point.
6820 * Called with interrupts off.
6823 changepath(const char *newval)
6825 const char *old, *new;
6832 firstchange = 9999; /* assume no change */
6838 if ((*old == '\0' && *new == ':')
6839 || (*old == ':' && *new == '\0'))
6841 old = new; /* ignore subsequent differences */
6845 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6852 if (builtinloc < 0 && idx_bltin >= 0)
6853 builtinloc = idx_bltin; /* zap builtins */
6854 if (builtinloc >= 0 && idx_bltin < 0)
6856 clearcmdentry(firstchange);
6857 builtinloc = idx_bltin;
6872 #define TENDBQUOTE 12
6890 /* first char is indicating which tokens mark the end of a list */
6891 static const char *const tokname_array[] = {
6905 #define KWDOFFSET 13
6906 /* the following are keywords */
6928 static char buf[16];
6931 //if (tok < TSEMI) return tokname_array[tok] + 1;
6932 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6937 sprintf(buf + (tok >= TSEMI), "%s%c",
6938 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6942 /* Wrapper around strcmp for qsort/bsearch/... */
6944 pstrcmp(const void *a, const void *b)
6946 return strcmp((char*) a, (*(char**) b) + 1);
6949 static const char *const *
6950 findkwd(const char *s)
6952 return bsearch(s, tokname_array + KWDOFFSET,
6953 (sizeof(tokname_array) / sizeof(char *)) - KWDOFFSET,
6954 sizeof(char *), pstrcmp);
6958 * Locate and print what a word is...
6960 #if ENABLE_ASH_CMDCMD
6962 describe_command(char *command, int describe_command_verbose)
6964 #define describe_command_verbose 1
6966 describe_command(char *command)
6969 struct cmdentry entry;
6970 struct tblentry *cmdp;
6971 #if ENABLE_ASH_ALIAS
6972 const struct alias *ap;
6974 const char *path = pathval();
6976 if (describe_command_verbose) {
6980 /* First look at the keywords */
6981 if (findkwd(command)) {
6982 out1str(describe_command_verbose ? " is a shell keyword" : command);
6986 #if ENABLE_ASH_ALIAS
6987 /* Then look at the aliases */
6988 ap = lookupalias(command, 0);
6990 if (describe_command_verbose) {
6991 out1fmt(" is an alias for %s", ap->val);
7000 /* Then check if it is a tracked alias */
7001 cmdp = cmdlookup(command, 0);
7003 entry.cmdtype = cmdp->cmdtype;
7004 entry.u = cmdp->param;
7006 /* Finally use brute force */
7007 find_command(command, &entry, DO_ABS, path);
7010 switch (entry.cmdtype) {
7012 int j = entry.u.index;
7018 p = padvance(&path, command);
7022 if (describe_command_verbose) {
7024 (cmdp ? " a tracked alias for" : nullstr), p
7033 if (describe_command_verbose) {
7034 out1str(" is a shell function");
7041 if (describe_command_verbose) {
7042 out1fmt(" is a %sshell builtin",
7043 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7044 "special " : nullstr
7052 if (describe_command_verbose) {
7053 out1str(": not found\n");
7058 outstr("\n", stdout);
7063 typecmd(int argc, char **argv)
7068 for (i = 1; i < argc; i++) {
7069 #if ENABLE_ASH_CMDCMD
7070 err |= describe_command(argv[i], 1);
7072 err |= describe_command(argv[i]);
7078 #if ENABLE_ASH_CMDCMD
7080 commandcmd(int argc, char **argv)
7088 while ((c = nextopt("pvV")) != '\0')
7090 verify |= VERIFY_VERBOSE;
7092 verify |= VERIFY_BRIEF;
7098 return describe_command(*argptr, verify - VERIFY_BRIEF);
7105 /* ============ eval.c */
7107 static int funcblocksize; /* size of structures in function */
7108 static int funcstringsize; /* size of strings in node */
7109 static void *funcblock; /* block to allocate function from */
7110 static char *funcstring; /* block to allocate strings from */
7112 /* flags in argument to evaltree */
7113 #define EV_EXIT 01 /* exit after evaluating tree */
7114 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7115 #define EV_BACKCMD 04 /* command executing within back quotes */
7117 static const short nodesize[26] = {
7118 SHELL_ALIGN(sizeof(struct ncmd)),
7119 SHELL_ALIGN(sizeof(struct npipe)),
7120 SHELL_ALIGN(sizeof(struct nredir)),
7121 SHELL_ALIGN(sizeof(struct nredir)),
7122 SHELL_ALIGN(sizeof(struct nredir)),
7123 SHELL_ALIGN(sizeof(struct nbinary)),
7124 SHELL_ALIGN(sizeof(struct nbinary)),
7125 SHELL_ALIGN(sizeof(struct nbinary)),
7126 SHELL_ALIGN(sizeof(struct nif)),
7127 SHELL_ALIGN(sizeof(struct nbinary)),
7128 SHELL_ALIGN(sizeof(struct nbinary)),
7129 SHELL_ALIGN(sizeof(struct nfor)),
7130 SHELL_ALIGN(sizeof(struct ncase)),
7131 SHELL_ALIGN(sizeof(struct nclist)),
7132 SHELL_ALIGN(sizeof(struct narg)),
7133 SHELL_ALIGN(sizeof(struct narg)),
7134 SHELL_ALIGN(sizeof(struct nfile)),
7135 SHELL_ALIGN(sizeof(struct nfile)),
7136 SHELL_ALIGN(sizeof(struct nfile)),
7137 SHELL_ALIGN(sizeof(struct nfile)),
7138 SHELL_ALIGN(sizeof(struct nfile)),
7139 SHELL_ALIGN(sizeof(struct ndup)),
7140 SHELL_ALIGN(sizeof(struct ndup)),
7141 SHELL_ALIGN(sizeof(struct nhere)),
7142 SHELL_ALIGN(sizeof(struct nhere)),
7143 SHELL_ALIGN(sizeof(struct nnot)),
7146 static void calcsize(union node *n);
7149 sizenodelist(struct nodelist *lp)
7152 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7159 calcsize(union node *n)
7163 funcblocksize += nodesize[n->type];
7166 calcsize(n->ncmd.redirect);
7167 calcsize(n->ncmd.args);
7168 calcsize(n->ncmd.assign);
7171 sizenodelist(n->npipe.cmdlist);
7176 calcsize(n->nredir.redirect);
7177 calcsize(n->nredir.n);
7184 calcsize(n->nbinary.ch2);
7185 calcsize(n->nbinary.ch1);
7188 calcsize(n->nif.elsepart);
7189 calcsize(n->nif.ifpart);
7190 calcsize(n->nif.test);
7193 funcstringsize += strlen(n->nfor.var) + 1;
7194 calcsize(n->nfor.body);
7195 calcsize(n->nfor.args);
7198 calcsize(n->ncase.cases);
7199 calcsize(n->ncase.expr);
7202 calcsize(n->nclist.body);
7203 calcsize(n->nclist.pattern);
7204 calcsize(n->nclist.next);
7208 sizenodelist(n->narg.backquote);
7209 funcstringsize += strlen(n->narg.text) + 1;
7210 calcsize(n->narg.next);
7217 calcsize(n->nfile.fname);
7218 calcsize(n->nfile.next);
7222 calcsize(n->ndup.vname);
7223 calcsize(n->ndup.next);
7227 calcsize(n->nhere.doc);
7228 calcsize(n->nhere.next);
7231 calcsize(n->nnot.com);
7237 nodeckstrdup(char *s)
7239 char *rtn = funcstring;
7241 strcpy(funcstring, s);
7242 funcstring += strlen(s) + 1;
7246 static union node *copynode(union node *);
7248 static struct nodelist *
7249 copynodelist(struct nodelist *lp)
7251 struct nodelist *start;
7252 struct nodelist **lpp;
7257 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7258 (*lpp)->n = copynode(lp->n);
7260 lpp = &(*lpp)->next;
7267 copynode(union node *n)
7274 funcblock = (char *) funcblock + nodesize[n->type];
7278 new->ncmd.redirect = copynode(n->ncmd.redirect);
7279 new->ncmd.args = copynode(n->ncmd.args);
7280 new->ncmd.assign = copynode(n->ncmd.assign);
7283 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7284 new->npipe.backgnd = n->npipe.backgnd;
7289 new->nredir.redirect = copynode(n->nredir.redirect);
7290 new->nredir.n = copynode(n->nredir.n);
7297 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7298 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7301 new->nif.elsepart = copynode(n->nif.elsepart);
7302 new->nif.ifpart = copynode(n->nif.ifpart);
7303 new->nif.test = copynode(n->nif.test);
7306 new->nfor.var = nodeckstrdup(n->nfor.var);
7307 new->nfor.body = copynode(n->nfor.body);
7308 new->nfor.args = copynode(n->nfor.args);
7311 new->ncase.cases = copynode(n->ncase.cases);
7312 new->ncase.expr = copynode(n->ncase.expr);
7315 new->nclist.body = copynode(n->nclist.body);
7316 new->nclist.pattern = copynode(n->nclist.pattern);
7317 new->nclist.next = copynode(n->nclist.next);
7321 new->narg.backquote = copynodelist(n->narg.backquote);
7322 new->narg.text = nodeckstrdup(n->narg.text);
7323 new->narg.next = copynode(n->narg.next);
7330 new->nfile.fname = copynode(n->nfile.fname);
7331 new->nfile.fd = n->nfile.fd;
7332 new->nfile.next = copynode(n->nfile.next);
7336 new->ndup.vname = copynode(n->ndup.vname);
7337 new->ndup.dupfd = n->ndup.dupfd;
7338 new->ndup.fd = n->ndup.fd;
7339 new->ndup.next = copynode(n->ndup.next);
7343 new->nhere.doc = copynode(n->nhere.doc);
7344 new->nhere.fd = n->nhere.fd;
7345 new->nhere.next = copynode(n->nhere.next);
7348 new->nnot.com = copynode(n->nnot.com);
7351 new->type = n->type;
7356 * Make a copy of a parse tree.
7358 static struct funcnode *
7359 copyfunc(union node *n)
7364 funcblocksize = offsetof(struct funcnode, n);
7367 blocksize = funcblocksize;
7368 f = ckmalloc(blocksize + funcstringsize);
7369 funcblock = (char *) f + offsetof(struct funcnode, n);
7370 funcstring = (char *) f + blocksize;
7377 * Define a shell function.
7380 defun(char *name, union node *func)
7382 struct cmdentry entry;
7385 entry.cmdtype = CMDFUNCTION;
7386 entry.u.func = copyfunc(func);
7387 addcmdentry(name, &entry);
7391 static int evalskip; /* set if we are skipping commands */
7392 /* reasons for skipping commands (see comment on breakcmd routine) */
7393 #define SKIPBREAK (1 << 0)
7394 #define SKIPCONT (1 << 1)
7395 #define SKIPFUNC (1 << 2)
7396 #define SKIPFILE (1 << 3)
7397 #define SKIPEVAL (1 << 4)
7398 static int skipcount; /* number of levels to skip */
7399 static int funcnest; /* depth of function calls */
7401 /* forward decl way out to parsing code - dotrap needs it */
7402 static int evalstring(char *s, int mask);
7405 * Called to execute a trap. Perhaps we should avoid entering new trap
7406 * handlers while we are executing a trap handler.
7417 savestatus = exitstatus;
7421 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7429 skip = evalstring(p, SKIPEVAL);
7430 exitstatus = savestatus;
7438 /* forward declarations - evaluation is fairly recursive business... */
7439 static void evalloop(union node *, int);
7440 static void evalfor(union node *, int);
7441 static void evalcase(union node *, int);
7442 static void evalsubshell(union node *, int);
7443 static void expredir(union node *);
7444 static void evalpipe(union node *, int);
7445 static void evalcommand(union node *, int);
7446 static int evalbltin(const struct builtincmd *, int, char **);
7447 static void prehash(union node *);
7450 * Evaluate a parse tree. The value is left in the global variable
7454 evaltree(union node *n, int flags)
7457 void (*evalfn)(union node *, int);
7461 TRACE(("evaltree(NULL) called\n"));
7464 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7465 getpid(), n, n->type, flags));
7469 out1fmt("Node type = %d\n", n->type);
7474 evaltree(n->nnot.com, EV_TESTED);
7475 status = !exitstatus;
7478 expredir(n->nredir.redirect);
7479 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7481 evaltree(n->nredir.n, flags & EV_TESTED);
7482 status = exitstatus;
7487 evalfn = evalcommand;
7489 if (eflag && !(flags & EV_TESTED))
7501 evalfn = evalsubshell;
7513 #error NAND + 1 != NOR
7515 #if NOR + 1 != NSEMI
7516 #error NOR + 1 != NSEMI
7518 isor = n->type - NAND;
7521 (flags | ((isor >> 1) - 1)) & EV_TESTED
7523 if (!exitstatus == isor)
7535 evaltree(n->nif.test, EV_TESTED);
7538 if (exitstatus == 0) {
7541 } else if (n->nif.elsepart) {
7542 n = n->nif.elsepart;
7547 defun(n->narg.text, n->narg.next);
7551 exitstatus = status;
7555 if ((checkexit & exitstatus))
7556 evalskip |= SKIPEVAL;
7557 else if (pendingsig && dotrap())
7560 if (flags & EV_EXIT) {
7562 raise_exception(EXEXIT);
7566 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7569 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7571 static int loopnest; /* current loop nesting level */
7574 evalloop(union node *n, int flags)
7584 evaltree(n->nbinary.ch1, EV_TESTED);
7587 if (evalskip == SKIPCONT && --skipcount <= 0) {
7591 if (evalskip == SKIPBREAK && --skipcount <= 0)
7596 if (n->type != NWHILE)
7600 evaltree(n->nbinary.ch2, flags);
7601 status = exitstatus;
7606 exitstatus = status;
7610 evalfor(union node *n, int flags)
7612 struct arglist arglist;
7615 struct stackmark smark;
7617 setstackmark(&smark);
7618 arglist.lastp = &arglist.list;
7619 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7620 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7625 *arglist.lastp = NULL;
7630 for (sp = arglist.list; sp; sp = sp->next) {
7631 setvar(n->nfor.var, sp->text, 0);
7632 evaltree(n->nfor.body, flags);
7634 if (evalskip == SKIPCONT && --skipcount <= 0) {
7638 if (evalskip == SKIPBREAK && --skipcount <= 0)
7645 popstackmark(&smark);
7649 evalcase(union node *n, int flags)
7653 struct arglist arglist;
7654 struct stackmark smark;
7656 setstackmark(&smark);
7657 arglist.lastp = &arglist.list;
7658 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7660 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7661 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7662 if (casematch(patp, arglist.list->text)) {
7663 if (evalskip == 0) {
7664 evaltree(cp->nclist.body, flags);
7671 popstackmark(&smark);
7675 * Kick off a subshell to evaluate a tree.
7678 evalsubshell(union node *n, int flags)
7681 int backgnd = (n->type == NBACKGND);
7684 expredir(n->nredir.redirect);
7685 if (!backgnd && flags & EV_EXIT && !trap[0])
7689 if (forkshell(jp, n, backgnd) == 0) {
7693 flags &=~ EV_TESTED;
7695 redirect(n->nredir.redirect, 0);
7696 evaltreenr(n->nredir.n, flags);
7701 status = waitforjob(jp);
7702 exitstatus = status;
7707 * Compute the names of the files in a redirection list.
7709 static void fixredir(union node *, const char *, int);
7711 expredir(union node *n)
7715 for (redir = n; redir; redir = redir->nfile.next) {
7718 memset(&fn, 0, sizeof(fn));
7719 fn.lastp = &fn.list;
7720 switch (redir->type) {
7726 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7727 redir->nfile.expfname = fn.list->text;
7731 if (redir->ndup.vname) {
7732 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7733 if (fn.list == NULL)
7734 ash_msg_and_raise_error("redir error");
7735 fixredir(redir, fn.list->text, 1);
7743 * Evaluate a pipeline. All the processes in the pipeline are children
7744 * of the process creating the pipeline. (This differs from some versions
7745 * of the shell, which make the last process in a pipeline the parent
7749 evalpipe(union node *n, int flags)
7752 struct nodelist *lp;
7757 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7759 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7763 jp = makejob(n, pipelen);
7765 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7769 if (pipe(pip) < 0) {
7771 ash_msg_and_raise_error("pipe call failed");
7774 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7787 evaltreenr(lp->n, flags);
7795 if (n->npipe.backgnd == 0) {
7796 exitstatus = waitforjob(jp);
7797 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7803 * Controls whether the shell is interactive or not.
7806 setinteractive(int on)
7808 static int is_interactive;
7810 if (++on == is_interactive)
7812 is_interactive = on;
7816 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7817 if (is_interactive > 1) {
7818 /* Looks like they want an interactive shell */
7819 static smallint do_banner;
7824 "%s Built-in shell (ash)\n"
7825 "Enter 'help' for a list of built-in commands."
7834 #if ENABLE_FEATURE_EDITING_VI
7835 #define setvimode(on) do { \
7836 if (on) line_input_state->flags |= VI_MODE; \
7837 else line_input_state->flags &= ~VI_MODE; \
7840 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7849 setinteractive(iflag);
7854 static struct localvar *localvars;
7857 * Called after a function returns.
7858 * Interrupts must be off.
7863 struct localvar *lvp;
7866 while ((lvp = localvars) != NULL) {
7867 localvars = lvp->next;
7869 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7870 if (vp == NULL) { /* $- saved */
7871 memcpy(optlist, lvp->text, sizeof(optlist));
7872 free((char*)lvp->text);
7874 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7878 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7879 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7880 free((char*)vp->text);
7881 vp->flags = lvp->flags;
7882 vp->text = lvp->text;
7889 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7891 volatile struct shparam saveparam;
7892 struct localvar *volatile savelocalvars;
7893 struct jmploc *volatile savehandler;
7894 struct jmploc jmploc;
7897 saveparam = shellparam;
7898 savelocalvars = localvars;
7899 e = setjmp(jmploc.loc);
7904 savehandler = exception_handler;
7905 exception_handler = &jmploc;
7907 shellparam.malloc = 0;
7911 shellparam.nparam = argc - 1;
7912 shellparam.p = argv + 1;
7913 #if ENABLE_ASH_GETOPTS
7914 shellparam.optind = 1;
7915 shellparam.optoff = -1;
7917 evaltree(&func->n, flags & EV_TESTED);
7923 localvars = savelocalvars;
7924 freeparam(&shellparam);
7925 shellparam = saveparam;
7926 exception_handler = savehandler;
7928 evalskip &= ~SKIPFUNC;
7932 #if ENABLE_ASH_CMDCMD
7934 parse_command_args(char **argv, const char **path)
7947 if (c == '-' && !*cp) {
7957 /* run 'typecmd' for other options */
7968 * Make a variable a local variable. When a variable is made local, it's
7969 * value and flags are saved in a localvar structure. The saved values
7970 * will be restored when the shell function returns. We handle the name
7971 * "-" as a special case.
7976 struct localvar *lvp;
7981 lvp = ckmalloc(sizeof(struct localvar));
7982 if (LONE_DASH(name)) {
7984 p = ckmalloc(sizeof(optlist));
7985 lvp->text = memcpy(p, optlist, sizeof(optlist));
7990 vpp = hashvar(name);
7991 vp = *findvar(vpp, name);
7992 eq = strchr(name, '=');
7995 setvareq(name, VSTRFIXED);
7997 setvar(name, NULL, VSTRFIXED);
7998 vp = *vpp; /* the new variable */
7999 lvp->flags = VUNSET;
8001 lvp->text = vp->text;
8002 lvp->flags = vp->flags;
8003 vp->flags |= VSTRFIXED|VTEXTFIXED;
8009 lvp->next = localvars;
8015 * The "local" command.
8018 localcmd(int argc, char **argv)
8023 while ((name = *argv++) != NULL) {
8030 falsecmd(int argc, char **argv)
8036 truecmd(int argc, char **argv)
8042 execcmd(int argc, char **argv)
8045 iflag = 0; /* exit on error */
8048 shellexec(argv + 1, pathval(), 0);
8054 * The return command.
8057 returncmd(int argc, char **argv)
8060 * If called outside a function, do what ksh does;
8061 * skip the rest of the file.
8063 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8064 return argv[1] ? number(argv[1]) : exitstatus;
8067 /* Forward declarations for builtintab[] */
8068 static int breakcmd(int, char **);
8069 static int dotcmd(int, char **);
8070 static int evalcmd(int, char **);
8071 #if ENABLE_ASH_BUILTIN_ECHO
8072 static int echocmd(int, char **);
8074 #if ENABLE_ASH_BUILTIN_TEST
8075 static int testcmd(int, char **);
8077 static int exitcmd(int, char **);
8078 static int exportcmd(int, char **);
8079 #if ENABLE_ASH_GETOPTS
8080 static int getoptscmd(int, char **);
8082 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8083 static int helpcmd(int argc, char **argv);
8085 #if ENABLE_ASH_MATH_SUPPORT
8086 static int letcmd(int, char **);
8088 static int readcmd(int, char **);
8089 static int setcmd(int, char **);
8090 static int shiftcmd(int, char **);
8091 static int timescmd(int, char **);
8092 static int trapcmd(int, char **);
8093 static int umaskcmd(int, char **);
8094 static int unsetcmd(int, char **);
8095 static int ulimitcmd(int, char **);
8097 #define BUILTIN_NOSPEC "0"
8098 #define BUILTIN_SPECIAL "1"
8099 #define BUILTIN_REGULAR "2"
8100 #define BUILTIN_SPEC_REG "3"
8101 #define BUILTIN_ASSIGN "4"
8102 #define BUILTIN_SPEC_ASSG "5"
8103 #define BUILTIN_REG_ASSG "6"
8104 #define BUILTIN_SPEC_REG_ASSG "7"
8106 /* make sure to keep these in proper order since it is searched via bsearch() */
8107 static const struct builtincmd builtintab[] = {
8108 { BUILTIN_SPEC_REG ".", dotcmd },
8109 { BUILTIN_SPEC_REG ":", truecmd },
8110 #if ENABLE_ASH_BUILTIN_TEST
8111 { BUILTIN_REGULAR "[", testcmd },
8112 { BUILTIN_REGULAR "[[", testcmd },
8114 #if ENABLE_ASH_ALIAS
8115 { BUILTIN_REG_ASSG "alias", aliascmd },
8118 { BUILTIN_REGULAR "bg", fg_bgcmd },
8120 { BUILTIN_SPEC_REG "break", breakcmd },
8121 { BUILTIN_REGULAR "cd", cdcmd },
8122 { BUILTIN_NOSPEC "chdir", cdcmd },
8123 #if ENABLE_ASH_CMDCMD
8124 { BUILTIN_REGULAR "command", commandcmd },
8126 { BUILTIN_SPEC_REG "continue", breakcmd },
8127 #if ENABLE_ASH_BUILTIN_ECHO
8128 { BUILTIN_REGULAR "echo", echocmd },
8130 { BUILTIN_SPEC_REG "eval", evalcmd },
8131 { BUILTIN_SPEC_REG "exec", execcmd },
8132 { BUILTIN_SPEC_REG "exit", exitcmd },
8133 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8134 { BUILTIN_REGULAR "false", falsecmd },
8136 { BUILTIN_REGULAR "fg", fg_bgcmd },
8138 #if ENABLE_ASH_GETOPTS
8139 { BUILTIN_REGULAR "getopts", getoptscmd },
8141 { BUILTIN_NOSPEC "hash", hashcmd },
8142 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8143 { BUILTIN_NOSPEC "help", helpcmd },
8146 { BUILTIN_REGULAR "jobs", jobscmd },
8147 { BUILTIN_REGULAR "kill", killcmd },
8149 #if ENABLE_ASH_MATH_SUPPORT
8150 { BUILTIN_NOSPEC "let", letcmd },
8152 { BUILTIN_ASSIGN "local", localcmd },
8153 { BUILTIN_NOSPEC "pwd", pwdcmd },
8154 { BUILTIN_REGULAR "read", readcmd },
8155 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8156 { BUILTIN_SPEC_REG "return", returncmd },
8157 { BUILTIN_SPEC_REG "set", setcmd },
8158 { BUILTIN_SPEC_REG "shift", shiftcmd },
8159 { BUILTIN_SPEC_REG "source", dotcmd },
8160 #if ENABLE_ASH_BUILTIN_TEST
8161 { BUILTIN_REGULAR "test", testcmd },
8163 { BUILTIN_SPEC_REG "times", timescmd },
8164 { BUILTIN_SPEC_REG "trap", trapcmd },
8165 { BUILTIN_REGULAR "true", truecmd },
8166 { BUILTIN_NOSPEC "type", typecmd },
8167 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8168 { BUILTIN_REGULAR "umask", umaskcmd },
8169 #if ENABLE_ASH_ALIAS
8170 { BUILTIN_REGULAR "unalias", unaliascmd },
8172 { BUILTIN_SPEC_REG "unset", unsetcmd },
8173 { BUILTIN_REGULAR "wait", waitcmd },
8176 #define NUMBUILTINS (sizeof(builtintab) / sizeof(builtintab[0]))
8178 #define COMMANDCMD (builtintab + 5 + \
8179 2 * ENABLE_ASH_BUILTIN_TEST + \
8180 ENABLE_ASH_ALIAS + \
8181 ENABLE_ASH_JOB_CONTROL)
8182 #define EXECCMD (builtintab + 7 + \
8183 2 * ENABLE_ASH_BUILTIN_TEST + \
8184 ENABLE_ASH_ALIAS + \
8185 ENABLE_ASH_JOB_CONTROL + \
8186 ENABLE_ASH_CMDCMD + \
8187 ENABLE_ASH_BUILTIN_ECHO)
8190 * Search the table of builtin commands.
8192 static struct builtincmd *
8193 find_builtin(const char *name)
8195 struct builtincmd *bp;
8198 name, builtintab, NUMBUILTINS, sizeof(builtintab[0]),
8205 * Execute a simple command.
8207 static int back_exitstatus; /* exit status of backquoted command */
8209 isassignment(const char *p)
8211 const char *q = endofname(p);
8217 bltincmd(int argc, char **argv)
8219 /* Preserve exitstatus of a previous possible redirection
8220 * as POSIX mandates */
8221 return back_exitstatus;
8224 evalcommand(union node *cmd, int flags)
8226 static const struct builtincmd bltin = {
8229 struct stackmark smark;
8231 struct arglist arglist;
8232 struct arglist varlist;
8235 const struct strlist *sp;
8236 struct cmdentry cmdentry;
8244 struct builtincmd *bcmd;
8245 int pseudovarflag = 0;
8247 /* First expand the arguments. */
8248 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8249 setstackmark(&smark);
8250 back_exitstatus = 0;
8252 cmdentry.cmdtype = CMDBUILTIN;
8253 cmdentry.u.cmd = &bltin;
8254 varlist.lastp = &varlist.list;
8255 *varlist.lastp = NULL;
8256 arglist.lastp = &arglist.list;
8257 *arglist.lastp = NULL;
8260 if (cmd->ncmd.args) {
8261 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8262 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8265 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8266 struct strlist **spp;
8268 spp = arglist.lastp;
8269 if (pseudovarflag && isassignment(argp->narg.text))
8270 expandarg(argp, &arglist, EXP_VARTILDE);
8272 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8274 for (sp = *spp; sp; sp = sp->next)
8278 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8279 for (sp = arglist.list; sp; sp = sp->next) {
8280 TRACE(("evalcommand arg: %s\n", sp->text));
8281 *nargv++ = sp->text;
8286 if (iflag && funcnest == 0 && argc > 0)
8287 lastarg = nargv[-1];
8290 expredir(cmd->ncmd.redirect);
8291 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8294 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8295 struct strlist **spp;
8298 spp = varlist.lastp;
8299 expandarg(argp, &varlist, EXP_VARTILDE);
8302 * Modify the command lookup path, if a PATH= assignment
8306 if (varequal(p, path))
8310 /* Print the command if xflag is set. */
8313 const char *p = " %s";
8316 dprintf(preverrout_fd, p, expandstr(ps4val()));
8319 for (n = 0; n < 2; n++) {
8321 dprintf(preverrout_fd, p, sp->text);
8329 full_write(preverrout_fd, "\n", 1);
8335 /* Now locate the command. */
8337 const char *oldpath;
8338 int cmd_flag = DO_ERR;
8343 find_command(argv[0], &cmdentry, cmd_flag, path);
8344 if (cmdentry.cmdtype == CMDUNKNOWN) {
8350 /* implement bltin and command here */
8351 if (cmdentry.cmdtype != CMDBUILTIN)
8354 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8355 if (cmdentry.u.cmd == EXECCMD)
8357 #if ENABLE_ASH_CMDCMD
8358 if (cmdentry.u.cmd == COMMANDCMD) {
8360 nargv = parse_command_args(argv, &path);
8363 argc -= nargv - argv;
8365 cmd_flag |= DO_NOFUNC;
8373 /* We have a redirection error. */
8375 raise_exception(EXERROR);
8377 exitstatus = status;
8381 /* Execute the command. */
8382 switch (cmdentry.cmdtype) {
8384 /* Fork off a child process if necessary. */
8385 if (!(flags & EV_EXIT) || trap[0]) {
8387 jp = makejob(cmd, 1);
8388 if (forkshell(jp, cmd, FORK_FG) != 0) {
8389 exitstatus = waitforjob(jp);
8395 listsetvar(varlist.list, VEXPORT|VSTACK);
8396 shellexec(argv, path, cmdentry.u.index);
8400 cmdenviron = varlist.list;
8402 struct strlist *list = cmdenviron;
8404 if (spclbltin > 0 || argc == 0) {
8406 if (cmd_is_exec && argc > 1)
8409 listsetvar(list, i);
8411 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8426 exit_status = j + 128;
8427 exitstatus = exit_status;
8429 if (i == EXINT || spclbltin > 0) {
8431 longjmp(exception_handler->loc, 1);
8438 listsetvar(varlist.list, 0);
8439 if (evalfun(cmdentry.u.func, argc, argv, flags))
8445 popredir(cmd_is_exec);
8447 /* dsl: I think this is intended to be used to support
8448 * '_' in 'vi' command mode during line editing...
8449 * However I implemented that within libedit itself.
8451 setvar("_", lastarg, 0);
8452 popstackmark(&smark);
8456 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8458 char *volatile savecmdname;
8459 struct jmploc *volatile savehandler;
8460 struct jmploc jmploc;
8463 savecmdname = commandname;
8464 i = setjmp(jmploc.loc);
8467 savehandler = exception_handler;
8468 exception_handler = &jmploc;
8469 commandname = argv[0];
8471 optptr = NULL; /* initialize nextopt */
8472 exitstatus = (*cmd->builtin)(argc, argv);
8473 flush_stdout_stderr();
8475 exitstatus |= ferror(stdout);
8477 commandname = savecmdname;
8479 exception_handler = savehandler;
8485 goodname(const char *p)
8487 return !*endofname(p);
8492 * Search for a command. This is called before we fork so that the
8493 * location of the command will be available in the parent as well as
8494 * the child. The check for "goodname" is an overly conservative
8495 * check that the name will not be subject to expansion.
8498 prehash(union node *n)
8500 struct cmdentry entry;
8502 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8503 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8507 /* ============ Builtin commands
8509 * Builtin commands whose functions are closely tied to evaluation
8510 * 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.
8524 breakcmd(int argc, char **argv)
8526 int n = argc > 1 ? number(argv[1]) : 1;
8529 ash_msg_and_raise_error(illnum, argv[1]);
8533 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8540 /* ============ input.c
8542 * This implements the input routines used by the parser.
8545 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8548 INPUT_PUSH_FILE = 1,
8549 INPUT_NOFILE_OK = 2,
8553 * NEOF is returned by parsecmd when it encounters an end of file. It
8554 * must be distinct from NULL, so we use the address of a variable that
8555 * happens to be handy.
8557 static int plinno = 1; /* input line number */
8558 /* number of characters left in input buffer */
8559 static int parsenleft; /* copy of parsefile->nleft */
8560 static int parselleft; /* copy of parsefile->lleft */
8561 /* next character in input buffer */
8562 static char *parsenextc; /* copy of parsefile->nextc */
8564 static int checkkwd;
8565 /* values of checkkwd variable */
8566 #define CHKALIAS 0x1
8573 struct strpush *sp = parsefile->strpush;
8576 #if ENABLE_ASH_ALIAS
8578 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8579 checkkwd |= CHKALIAS;
8581 if (sp->string != sp->ap->val) {
8584 sp->ap->flag &= ~ALIASINUSE;
8585 if (sp->ap->flag & ALIASDEAD) {
8586 unalias(sp->ap->name);
8590 parsenextc = sp->prevstring;
8591 parsenleft = sp->prevnleft;
8592 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8593 parsefile->strpush = sp->prev;
8594 if (sp != &(parsefile->basestrpush))
8603 char *buf = parsefile->buf;
8607 #if ENABLE_FEATURE_EDITING
8608 if (!iflag || parsefile->fd)
8609 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8611 #if ENABLE_FEATURE_TAB_COMPLETION
8612 line_input_state->path_lookup = pathval();
8614 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8616 /* Ctrl+C pressed */
8625 if (nr < 0 && errno == 0) {
8626 /* Ctrl+D presend */
8631 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8635 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8636 int flags = fcntl(0, F_GETFL, 0);
8637 if (flags >= 0 && flags & O_NONBLOCK) {
8638 flags &=~ O_NONBLOCK;
8639 if (fcntl(0, F_SETFL, flags) >= 0) {
8640 out2str("sh: turning off NDELAY mode\n");
8650 * Refill the input buffer and return the next input character:
8652 * 1) If a string was pushed back on the input, pop it;
8653 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8654 * from a string so we can't refill the buffer, return EOF.
8655 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8656 * 4) Process input up to the next newline, deleting nul characters.
8665 while (parsefile->strpush) {
8666 #if ENABLE_ASH_ALIAS
8667 if (parsenleft == -1 && parsefile->strpush->ap &&
8668 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8673 if (--parsenleft >= 0)
8674 return signed_char2int(*parsenextc++);
8676 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8678 flush_stdout_stderr();
8685 parselleft = parsenleft = EOF_NLEFT;
8692 /* delete nul characters */
8700 memmove(q, q + 1, more);
8704 parsenleft = q - parsenextc - 1;
8710 parsenleft = q - parsenextc - 1;
8722 out2str(parsenextc);
8727 return signed_char2int(*parsenextc++);
8730 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8734 return pgetc_as_macro();
8737 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8738 #define pgetc_macro() pgetc()
8740 #define pgetc_macro() pgetc_as_macro()
8744 * Same as pgetc(), but ignores PEOA.
8746 #if ENABLE_ASH_ALIAS
8754 } while (c == PEOA);
8761 return pgetc_macro();
8766 * Read a line from the script.
8769 pfgets(char *line, int len)
8775 while (--nleft > 0) {
8791 * Undo the last call to pgetc. Only one character may be pushed back.
8792 * PEOF may be pushed back.
8802 * Push a string back onto the input at this current parsefile level.
8803 * We handle aliases this way.
8806 pushstring(char *s, void *ap)
8813 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8814 if (parsefile->strpush) {
8815 sp = ckmalloc(sizeof(struct strpush));
8816 sp->prev = parsefile->strpush;
8817 parsefile->strpush = sp;
8819 sp = parsefile->strpush = &(parsefile->basestrpush);
8820 sp->prevstring = parsenextc;
8821 sp->prevnleft = parsenleft;
8822 #if ENABLE_ASH_ALIAS
8823 sp->ap = (struct alias *)ap;
8825 ((struct alias *)ap)->flag |= ALIASINUSE;
8835 * To handle the "." command, a stack of input files is used. Pushfile
8836 * adds a new entry to the stack and popfile restores the previous level.
8841 struct parsefile *pf;
8843 parsefile->nleft = parsenleft;
8844 parsefile->lleft = parselleft;
8845 parsefile->nextc = parsenextc;
8846 parsefile->linno = plinno;
8847 pf = ckmalloc(sizeof(*pf));
8848 pf->prev = parsefile;
8851 pf->basestrpush.prev = NULL;
8858 struct parsefile *pf = parsefile;
8867 parsefile = pf->prev;
8869 parsenleft = parsefile->nleft;
8870 parselleft = parsefile->lleft;
8871 parsenextc = parsefile->nextc;
8872 plinno = parsefile->linno;
8877 * Return to top level.
8882 while (parsefile != &basepf)
8887 * Close the file(s) that the shell is reading commands from. Called
8888 * after a fork is done.
8894 if (parsefile->fd > 0) {
8895 close(parsefile->fd);
8901 * Like setinputfile, but takes an open file descriptor. Call this with
8905 setinputfd(int fd, int push)
8907 fcntl(fd, F_SETFD, FD_CLOEXEC);
8913 if (parsefile->buf == NULL)
8914 parsefile->buf = ckmalloc(IBUFSIZ);
8915 parselleft = parsenleft = 0;
8920 * Set the input to take input from a file. If push is set, push the
8921 * old input onto the stack first.
8924 setinputfile(const char *fname, int flags)
8930 fd = open(fname, O_RDONLY);
8932 if (flags & INPUT_NOFILE_OK)
8934 ash_msg_and_raise_error("can't open %s", fname);
8937 fd2 = copyfd(fd, 10);
8940 ash_msg_and_raise_error("out of file descriptors");
8943 setinputfd(fd, flags & INPUT_PUSH_FILE);
8950 * Like setinputfile, but takes input from a string.
8953 setinputstring(char *string)
8957 parsenextc = string;
8958 parsenleft = strlen(string);
8959 parsefile->buf = NULL;
8965 /* ============ mail.c
8967 * Routines to check for mail.
8972 #define MAXMBOXES 10
8974 /* times of mailboxes */
8975 static time_t mailtime[MAXMBOXES];
8976 /* Set if MAIL or MAILPATH is changed. */
8977 static int mail_var_path_changed;
8980 * Print appropriate message(s) if mail has arrived.
8981 * If mail_var_path_changed is set,
8982 * then the value of MAIL has mail_var_path_changed,
8983 * so we just update the values.
8992 struct stackmark smark;
8995 setstackmark(&smark);
8996 mpath = mpathset() ? mpathval() : mailval();
8997 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8998 p = padvance(&mpath, nullstr);
9003 for (q = p; *q; q++);
9008 q[-1] = '\0'; /* delete trailing '/' */
9009 if (stat(p, &statb) < 0) {
9013 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9016 pathopt ? pathopt : "you have mail"
9019 *mtp = statb.st_mtime;
9021 mail_var_path_changed = 0;
9022 popstackmark(&smark);
9026 changemail(const char *val)
9028 mail_var_path_changed++;
9031 #endif /* ASH_MAIL */
9034 /* ============ ??? */
9037 * Set the shell parameters.
9040 setparam(char **argv)
9046 for (nparam = 0; argv[nparam]; nparam++);
9047 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9049 *ap++ = ckstrdup(*argv++);
9052 freeparam(&shellparam);
9053 shellparam.malloc = 1;
9054 shellparam.nparam = nparam;
9055 shellparam.p = newparam;
9056 #if ENABLE_ASH_GETOPTS
9057 shellparam.optind = 1;
9058 shellparam.optoff = -1;
9063 * Process shell options. The global variable argptr contains a pointer
9064 * to the argument list; we advance it past the options.
9067 minus_o(char *name, int val)
9072 for (i = 0; i < NOPTS; i++) {
9073 if (strcmp(name, optnames(i)) == 0) {
9078 ash_msg_and_raise_error("illegal option -o %s", name);
9080 out1str("Current option settings\n");
9081 for (i = 0; i < NOPTS; i++)
9082 out1fmt("%-16s%s\n", optnames(i),
9083 optlist[i] ? "on" : "off");
9086 setoption(int flag, int val)
9090 for (i = 0; i < NOPTS; i++) {
9091 if (optletters(i) == flag) {
9096 ash_msg_and_raise_error("illegal option -%c", flag);
9100 options(int cmdline)
9108 while ((p = *argptr) != NULL) {
9113 if (p[0] == '\0' || LONE_DASH(p)) {
9115 /* "-" means turn off -x and -v */
9118 /* "--" means reset params */
9119 else if (*argptr == NULL)
9122 break; /* "-" or "--" terminates options */
9124 } else if (c == '+') {
9130 while ((c = *p++) != '\0') {
9131 if (c == 'c' && cmdline) {
9132 minusc = p; /* command is after shell args*/
9133 } else if (c == 'o') {
9134 minus_o(*argptr, val);
9137 } else if (cmdline && (c == '-')) { // long options
9138 if (strcmp(p, "login") == 0)
9149 * The shift builtin command.
9152 shiftcmd(int argc, char **argv)
9159 n = number(argv[1]);
9160 if (n > shellparam.nparam)
9161 ash_msg_and_raise_error("can't shift that many");
9163 shellparam.nparam -= n;
9164 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9165 if (shellparam.malloc)
9169 while ((*ap2++ = *ap1++) != NULL);
9170 #if ENABLE_ASH_GETOPTS
9171 shellparam.optind = 1;
9172 shellparam.optoff = -1;
9179 * POSIX requires that 'set' (but not export or readonly) output the
9180 * variables in lexicographic order - by the locale's collating order (sigh).
9181 * Maybe we could keep them in an ordered balanced binary tree
9182 * instead of hashed lists.
9183 * For now just roll 'em through qsort for printing...
9186 showvars(const char *sep_prefix, int on, int off)
9191 ep = listvars(on, off, &epend);
9192 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9194 sep = *sep_prefix ? " " : sep_prefix;
9196 for (; ep < epend; ep++) {
9200 p = strchrnul(*ep, '=');
9203 q = single_quote(++p);
9204 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9210 * The set command builtin.
9213 setcmd(int argc, char **argv)
9216 return showvars(nullstr, 0, VUNSET);
9220 if (*argptr != NULL) {
9227 #if ENABLE_ASH_RANDOM_SUPPORT
9228 /* Roughly copied from bash.. */
9230 change_random(const char *value)
9232 if (value == NULL) {
9233 /* "get", generate */
9236 rseed = rseed * 1103515245 + 12345;
9237 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9238 /* set without recursion */
9239 setvar(vrandom.text, buf, VNOFUNC);
9240 vrandom.flags &= ~VNOFUNC;
9243 rseed = strtoul(value, (char **)NULL, 10);
9248 #if ENABLE_ASH_GETOPTS
9250 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9259 if (*param_optind < 1)
9261 optnext = optfirst + *param_optind - 1;
9263 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9266 p = optnext[-1] + *optoff;
9267 if (p == NULL || *p == '\0') {
9268 /* Current word is done, advance */
9270 if (p == NULL || *p != '-' || *++p == '\0') {
9277 if (LONE_DASH(p)) /* check for "--" */
9282 for (q = optstr; *q != c; ) {
9284 if (optstr[0] == ':') {
9287 err |= setvarsafe("OPTARG", s, 0);
9289 fprintf(stderr, "Illegal option -%c\n", c);
9300 if (*p == '\0' && (p = *optnext) == NULL) {
9301 if (optstr[0] == ':') {
9304 err |= setvarsafe("OPTARG", s, 0);
9307 fprintf(stderr, "No arg for -%c option\n", c);
9316 err |= setvarsafe("OPTARG", p, 0);
9319 err |= setvarsafe("OPTARG", nullstr, 0);
9321 *optoff = p ? p - *(optnext - 1) : -1;
9322 *param_optind = optnext - optfirst + 1;
9323 fmtstr(s, sizeof(s), "%d", *param_optind);
9324 err |= setvarsafe("OPTIND", s, VNOFUNC);
9327 err |= setvarsafe(optvar, s, 0);
9331 flush_stdout_stderr();
9332 raise_exception(EXERROR);
9338 * The getopts builtin. Shellparam.optnext points to the next argument
9339 * to be processed. Shellparam.optptr points to the next character to
9340 * be processed in the current argument. If shellparam.optnext is NULL,
9341 * then it's the first time getopts has been called.
9344 getoptscmd(int argc, char **argv)
9349 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9351 optbase = shellparam.p;
9352 if (shellparam.optind > shellparam.nparam + 1) {
9353 shellparam.optind = 1;
9354 shellparam.optoff = -1;
9358 if (shellparam.optind > argc - 2) {
9359 shellparam.optind = 1;
9360 shellparam.optoff = -1;
9364 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9365 &shellparam.optoff);
9367 #endif /* ASH_GETOPTS */
9370 /* ============ Shell parser */
9372 static int tokpushback; /* last token pushed back */
9373 #define NEOF ((union node *)&tokpushback)
9374 static int parsebackquote; /* nonzero if we are inside backquotes */
9375 static int lasttoken; /* last token read */
9376 static char *wordtext; /* text of last word returned by readtoken */
9377 static struct nodelist *backquotelist;
9378 static union node *redirnode;
9379 static struct heredoc *heredoc;
9380 static int quoteflag; /* set if (part of) last token was quoted */
9382 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9384 raise_error_syntax(const char *msg)
9386 ash_msg_and_raise_error("syntax error: %s", msg);
9391 * Called when an unexpected token is read during the parse. The argument
9392 * is the token that is expected, or -1 if more than one type of token can
9393 * occur at this point.
9395 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9397 raise_error_unexpected_syntax(int token)
9402 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9404 sprintf(msg + l, " (expecting %s)", tokname(token));
9405 raise_error_syntax(msg);
9409 #define EOFMARKLEN 79
9412 struct heredoc *next; /* next here document in list */
9413 union node *here; /* redirection node */
9414 char *eofmark; /* string indicating end of input */
9415 int striptabs; /* if set, strip leading tabs */
9418 static struct heredoc *heredoclist; /* list of here documents to read */
9420 /* parsing is heavily cross-recursive, need these forward decls */
9421 static union node *andor(void);
9422 static union node *pipeline(void);
9423 static union node *parse_command(void);
9424 static void parseheredoc(void);
9425 static char peektoken(void);
9426 static int readtoken(void);
9431 union node *n1, *n2, *n3;
9434 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9435 if (nlflag == 2 && peektoken())
9441 if (tok == TBACKGND) {
9442 if (n2->type == NPIPE) {
9443 n2->npipe.backgnd = 1;
9445 if (n2->type != NREDIR) {
9446 n3 = stalloc(sizeof(struct nredir));
9448 n3->nredir.redirect = NULL;
9451 n2->type = NBACKGND;
9457 n3 = stalloc(sizeof(struct nbinary));
9459 n3->nbinary.ch1 = n1;
9460 n3->nbinary.ch2 = n2;
9476 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9484 pungetc(); /* push back EOF on input */
9488 raise_error_unexpected_syntax(-1);
9498 union node *n1, *n2, *n3;
9506 } else if (t == TOR) {
9512 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9514 n3 = stalloc(sizeof(struct nbinary));
9516 n3->nbinary.ch1 = n1;
9517 n3->nbinary.ch2 = n2;
9525 union node *n1, *n2, *pipenode;
9526 struct nodelist *lp, *prev;
9530 TRACE(("pipeline: entered\n"));
9531 if (readtoken() == TNOT) {
9533 checkkwd = CHKKWD | CHKALIAS;
9536 n1 = parse_command();
9537 if (readtoken() == TPIPE) {
9538 pipenode = stalloc(sizeof(struct npipe));
9539 pipenode->type = NPIPE;
9540 pipenode->npipe.backgnd = 0;
9541 lp = stalloc(sizeof(struct nodelist));
9542 pipenode->npipe.cmdlist = lp;
9546 lp = stalloc(sizeof(struct nodelist));
9547 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9548 lp->n = parse_command();
9550 } while (readtoken() == TPIPE);
9556 n2 = stalloc(sizeof(struct nnot));
9569 n = stalloc(sizeof(struct narg));
9571 n->narg.next = NULL;
9572 n->narg.text = wordtext;
9573 n->narg.backquote = backquotelist;
9578 fixredir(union node *n, const char *text, int err)
9580 TRACE(("Fix redir %s %d\n", text, err));
9582 n->ndup.vname = NULL;
9584 if (isdigit(text[0]) && text[1] == '\0')
9585 n->ndup.dupfd = text[0] - '0';
9586 else if (LONE_DASH(text))
9590 raise_error_syntax("Bad fd number");
9591 n->ndup.vname = makename();
9596 * Returns true if the text contains nothing to expand (no dollar signs
9600 noexpand(char *text)
9606 while ((c = *p++) != '\0') {
9607 if (c == CTLQUOTEMARK)
9611 else if (SIT(c, BASESYNTAX) == CCTL)
9620 union node *n = redirnode;
9622 if (readtoken() != TWORD)
9623 raise_error_unexpected_syntax(-1);
9624 if (n->type == NHERE) {
9625 struct heredoc *here = heredoc;
9631 TRACE(("Here document %d\n", n->type));
9632 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9633 raise_error_syntax("Illegal eof marker for << redirection");
9634 rmescapes(wordtext);
9635 here->eofmark = wordtext;
9637 if (heredoclist == NULL)
9640 for (p = heredoclist; p->next; p = p->next);
9643 } else if (n->type == NTOFD || n->type == NFROMFD) {
9644 fixredir(n, wordtext, 0);
9646 n->nfile.fname = makename();
9653 union node *args, **app;
9654 union node *n = NULL;
9655 union node *vars, **vpp;
9656 union node **rpp, *redir;
9666 savecheckkwd = CHKALIAS;
9668 checkkwd = savecheckkwd;
9669 switch (readtoken()) {
9671 n = stalloc(sizeof(struct narg));
9673 n->narg.text = wordtext;
9674 n->narg.backquote = backquotelist;
9675 if (savecheckkwd && isassignment(wordtext)) {
9677 vpp = &n->narg.next;
9680 app = &n->narg.next;
9685 *rpp = n = redirnode;
9686 rpp = &n->nfile.next;
9687 parsefname(); /* read name of redirection file */
9690 if (args && app == &args->narg.next
9693 struct builtincmd *bcmd;
9696 /* We have a function */
9697 if (readtoken() != TRP)
9698 raise_error_unexpected_syntax(TRP);
9699 name = n->narg.text;
9701 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9703 raise_error_syntax("Bad function name");
9706 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9707 n->narg.next = parse_command();
9720 n = stalloc(sizeof(struct ncmd));
9722 n->ncmd.args = args;
9723 n->ncmd.assign = vars;
9724 n->ncmd.redirect = redir;
9731 union node *n1, *n2;
9732 union node *ap, **app;
9733 union node *cp, **cpp;
9734 union node *redir, **rpp;
9741 switch (readtoken()) {
9743 raise_error_unexpected_syntax(-1);
9746 n1 = stalloc(sizeof(struct nif));
9748 n1->nif.test = list(0);
9749 if (readtoken() != TTHEN)
9750 raise_error_unexpected_syntax(TTHEN);
9751 n1->nif.ifpart = list(0);
9753 while (readtoken() == TELIF) {
9754 n2->nif.elsepart = stalloc(sizeof(struct nif));
9755 n2 = n2->nif.elsepart;
9757 n2->nif.test = list(0);
9758 if (readtoken() != TTHEN)
9759 raise_error_unexpected_syntax(TTHEN);
9760 n2->nif.ifpart = list(0);
9762 if (lasttoken == TELSE)
9763 n2->nif.elsepart = list(0);
9765 n2->nif.elsepart = NULL;
9773 n1 = stalloc(sizeof(struct nbinary));
9774 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9775 n1->nbinary.ch1 = list(0);
9778 TRACE(("expecting DO got %s %s\n", tokname(got),
9779 got == TWORD ? wordtext : ""));
9780 raise_error_unexpected_syntax(TDO);
9782 n1->nbinary.ch2 = list(0);
9787 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9788 raise_error_syntax("Bad for loop variable");
9789 n1 = stalloc(sizeof(struct nfor));
9791 n1->nfor.var = wordtext;
9792 checkkwd = CHKKWD | CHKALIAS;
9793 if (readtoken() == TIN) {
9795 while (readtoken() == TWORD) {
9796 n2 = stalloc(sizeof(struct narg));
9798 n2->narg.text = wordtext;
9799 n2->narg.backquote = backquotelist;
9801 app = &n2->narg.next;
9805 if (lasttoken != TNL && lasttoken != TSEMI)
9806 raise_error_unexpected_syntax(-1);
9808 n2 = stalloc(sizeof(struct narg));
9810 n2->narg.text = (char *)dolatstr;
9811 n2->narg.backquote = NULL;
9812 n2->narg.next = NULL;
9815 * Newline or semicolon here is optional (but note
9816 * that the original Bourne shell only allowed NL).
9818 if (lasttoken != TNL && lasttoken != TSEMI)
9821 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9822 if (readtoken() != TDO)
9823 raise_error_unexpected_syntax(TDO);
9824 n1->nfor.body = list(0);
9828 n1 = stalloc(sizeof(struct ncase));
9830 if (readtoken() != TWORD)
9831 raise_error_unexpected_syntax(TWORD);
9832 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9834 n2->narg.text = wordtext;
9835 n2->narg.backquote = backquotelist;
9836 n2->narg.next = NULL;
9838 checkkwd = CHKKWD | CHKALIAS;
9839 } while (readtoken() == TNL);
9840 if (lasttoken != TIN)
9841 raise_error_unexpected_syntax(TIN);
9842 cpp = &n1->ncase.cases;
9844 checkkwd = CHKNL | CHKKWD;
9846 while (t != TESAC) {
9847 if (lasttoken == TLP)
9849 *cpp = cp = stalloc(sizeof(struct nclist));
9851 app = &cp->nclist.pattern;
9853 *app = ap = stalloc(sizeof(struct narg));
9855 ap->narg.text = wordtext;
9856 ap->narg.backquote = backquotelist;
9857 if (readtoken() != TPIPE)
9859 app = &ap->narg.next;
9862 ap->narg.next = NULL;
9863 if (lasttoken != TRP)
9864 raise_error_unexpected_syntax(TRP);
9865 cp->nclist.body = list(2);
9867 cpp = &cp->nclist.next;
9869 checkkwd = CHKNL | CHKKWD;
9873 raise_error_unexpected_syntax(TENDCASE);
9880 n1 = stalloc(sizeof(struct nredir));
9881 n1->type = NSUBSHELL;
9882 n1->nredir.n = list(0);
9883 n1->nredir.redirect = NULL;
9896 if (readtoken() != t)
9897 raise_error_unexpected_syntax(t);
9900 /* Now check for redirection which may follow command */
9901 checkkwd = CHKKWD | CHKALIAS;
9903 while (readtoken() == TREDIR) {
9904 *rpp = n2 = redirnode;
9905 rpp = &n2->nfile.next;
9911 if (n1->type != NSUBSHELL) {
9912 n2 = stalloc(sizeof(struct nredir));
9917 n1->nredir.redirect = redir;
9923 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9924 * is not NULL, read a here document. In the latter case, eofmark is the
9925 * word which marks the end of the document and striptabs is true if
9926 * leading tabs should be stripped from the document. The argument firstc
9927 * is the first character of the input token or document.
9929 * Because C does not have internal subroutines, I have simulated them
9930 * using goto's to implement the subroutine linkage. The following macros
9931 * will run code that appears at the end of readtoken1.
9934 static int parsebackquote; /* nonzero if we are inside backquotes */
9936 #define CHECKEND() {goto checkend; checkend_return:;}
9937 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9938 #define PARSESUB() {goto parsesub; parsesub_return:;}
9939 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9940 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9941 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9944 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9949 char line[EOFMARKLEN + 1];
9950 struct nodelist *bqlist = 0;
9953 int varnest = 0; /* levels of variables expansion */
9954 int arinest = 0; /* levels of arithmetic expansion */
9955 int parenlevel = 0; /* levels of parens in arithmetic */
9956 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9958 int prevsyntax = 0; /* syntax before arithmetic */
9960 /* Avoid longjmp clobbering */
9973 startlinno = plinno;
9975 if (syntax == DQSYNTAX)
9985 loop: { /* for each line, until end of word */
9986 CHECKEND(); /* set c to PEOF if at end of here document */
9987 for (;;) { /* until end of line or end of word */
9988 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9989 switch (SIT(c, syntax)) {
9990 case CNL: /* '\n' */
9991 if (syntax == BASESYNTAX)
9992 goto endword; /* exit outer loop */
9998 goto loop; /* continue outer loop */
10003 if (eofmark == NULL || dblquote)
10004 USTPUTC(CTLESC, out);
10007 case CBACK: /* backslash */
10010 USTPUTC(CTLESC, out);
10011 USTPUTC('\\', out);
10013 } else if (c == '\n') {
10018 c != '\\' && c != '`' &&
10023 USTPUTC(CTLESC, out);
10024 USTPUTC('\\', out);
10026 if (SIT(c, SQSYNTAX) == CCTL)
10027 USTPUTC(CTLESC, out);
10035 if (eofmark == NULL) {
10036 USTPUTC(CTLQUOTEMARK, out);
10044 if (eofmark != NULL && arinest == 0
10049 if (dqvarnest == 0) {
10050 syntax = BASESYNTAX;
10057 case CVAR: /* '$' */
10058 PARSESUB(); /* parse substitution */
10060 case CENDVAR: /* '}' */
10063 if (dqvarnest > 0) {
10066 USTPUTC(CTLENDVAR, out);
10071 #if ENABLE_ASH_MATH_SUPPORT
10072 case CLP: /* '(' in arithmetic */
10076 case CRP: /* ')' in arithmetic */
10077 if (parenlevel > 0) {
10081 if (pgetc() == ')') {
10082 if (--arinest == 0) {
10083 USTPUTC(CTLENDARI, out);
10084 syntax = prevsyntax;
10085 if (syntax == DQSYNTAX)
10093 * unbalanced parens
10094 * (don't 2nd guess - no error)
10102 case CBQUOTE: /* '`' */
10106 goto endword; /* exit outer loop */
10111 goto endword; /* exit outer loop */
10112 #if ENABLE_ASH_ALIAS
10122 #if ENABLE_ASH_MATH_SUPPORT
10123 if (syntax == ARISYNTAX)
10124 raise_error_syntax("Missing '))'");
10126 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10127 raise_error_syntax("Unterminated quoted string");
10128 if (varnest != 0) {
10129 startlinno = plinno;
10131 raise_error_syntax("Missing '}'");
10133 USTPUTC('\0', out);
10134 len = out - (char *)stackblock();
10135 out = stackblock();
10136 if (eofmark == NULL) {
10137 if ((c == '>' || c == '<')
10140 && (*out == '\0' || isdigit(*out))) {
10142 return lasttoken = TREDIR;
10147 quoteflag = quotef;
10148 backquotelist = bqlist;
10149 grabstackblock(len);
10153 /* end of readtoken routine */
10156 * Check to see whether we are at the end of the here document. When this
10157 * is called, c is set to the first character of the next input line. If
10158 * we are at the end of the here document, this routine sets the c to PEOF.
10162 #if ENABLE_ASH_ALIAS
10168 while (c == '\t') {
10172 if (c == *eofmark) {
10173 if (pfgets(line, sizeof(line)) != NULL) {
10177 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10178 if (*p == '\n' && *q == '\0') {
10181 needprompt = doprompt;
10183 pushstring(line, NULL);
10188 goto checkend_return;
10192 * Parse a redirection operator. The variable "out" points to a string
10193 * specifying the fd to be redirected. The variable "c" contains the
10194 * first character of the redirection operator.
10200 np = stalloc(sizeof(struct nfile));
10205 np->type = NAPPEND;
10207 np->type = NCLOBBER;
10214 } else { /* c == '<' */
10219 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10220 np = stalloc(sizeof(struct nhere));
10224 heredoc = stalloc(sizeof(struct heredoc));
10225 heredoc->here = np;
10228 heredoc->striptabs = 1;
10230 heredoc->striptabs = 0;
10236 np->type = NFROMFD;
10240 np->type = NFROMTO;
10250 np->nfile.fd = fd - '0';
10252 goto parseredir_return;
10256 * Parse a substitution. At this point, we have read the dollar sign
10257 * and nothing else.
10260 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10261 * (assuming ascii char codes, as the original implementation did) */
10262 #define is_special(c) \
10263 ((((unsigned int)c) - 33 < 32) \
10264 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10270 static const char types[] = "}-+?=";
10274 c <= PEOA_OR_PEOF ||
10275 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10279 } else if (c == '(') { /* $(command) or $((arith)) */
10280 if (pgetc() == '(') {
10281 #if ENABLE_ASH_MATH_SUPPORT
10284 raise_error_syntax("We unsupport $((arith))");
10291 USTPUTC(CTLVAR, out);
10292 typeloc = out - (char *)stackblock();
10293 USTPUTC(VSNORMAL, out);
10294 subtype = VSNORMAL;
10302 subtype = VSLENGTH;
10306 if (c > PEOA_OR_PEOF && is_name(c)) {
10310 } while (c > PEOA_OR_PEOF && is_in_name(c));
10311 } else if (isdigit(c)) {
10315 } while (isdigit(c));
10316 } else if (is_special(c)) {
10320 badsub: raise_error_syntax("Bad substitution");
10324 if (subtype == 0) {
10331 p = strchr(types, c);
10334 subtype = p - types + VSNORMAL;
10340 subtype = c == '#' ? VSTRIMLEFT :
10353 if (dblquote || arinest)
10355 *((char *)stackblock() + typeloc) = subtype | flags;
10356 if (subtype != VSNORMAL) {
10358 if (dblquote || arinest) {
10363 goto parsesub_return;
10367 * Called to parse command substitutions. Newstyle is set if the command
10368 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10369 * list of commands (passed by reference), and savelen is the number of
10370 * characters on the top of the stack which must be preserved.
10373 struct nodelist **nlpp;
10376 char *volatile str;
10377 struct jmploc jmploc;
10378 struct jmploc *volatile savehandler;
10380 int saveprompt = 0;
10382 (void) &saveprompt;
10385 savepbq = parsebackquote;
10386 if (setjmp(jmploc.loc)) {
10389 parsebackquote = 0;
10390 exception_handler = savehandler;
10391 longjmp(exception_handler->loc, 1);
10395 savelen = out - (char *)stackblock();
10397 str = ckmalloc(savelen);
10398 memcpy(str, stackblock(), savelen);
10400 savehandler = exception_handler;
10401 exception_handler = &jmploc;
10404 /* We must read until the closing backquote, giving special
10405 treatment to some slashes, and then push the string and
10406 reread it as input, interpreting it normally. */
10413 STARTSTACKSTR(pout);
10430 * If eating a newline, avoid putting
10431 * the newline into the new character
10432 * stream (via the STPUTC after the
10437 if (pc != '\\' && pc != '`' && pc != '$'
10438 && (!dblquote || pc != '"'))
10439 STPUTC('\\', pout);
10440 if (pc > PEOA_OR_PEOF) {
10446 #if ENABLE_ASH_ALIAS
10449 startlinno = plinno;
10450 raise_error_syntax("EOF in backquote substitution");
10454 needprompt = doprompt;
10463 STPUTC('\0', pout);
10464 psavelen = pout - (char *)stackblock();
10465 if (psavelen > 0) {
10466 pstr = grabstackstr(pout);
10467 setinputstring(pstr);
10472 nlpp = &(*nlpp)->next;
10473 *nlpp = stalloc(sizeof(**nlpp));
10474 (*nlpp)->next = NULL;
10475 parsebackquote = oldstyle;
10478 saveprompt = doprompt;
10485 doprompt = saveprompt;
10486 else if (readtoken() != TRP)
10487 raise_error_unexpected_syntax(TRP);
10492 * Start reading from old file again, ignoring any pushed back
10493 * tokens left from the backquote parsing
10498 while (stackblocksize() <= savelen)
10500 STARTSTACKSTR(out);
10502 memcpy(out, str, savelen);
10503 STADJUST(savelen, out);
10509 parsebackquote = savepbq;
10510 exception_handler = savehandler;
10511 if (arinest || dblquote)
10512 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10514 USTPUTC(CTLBACKQ, out);
10516 goto parsebackq_oldreturn;
10517 goto parsebackq_newreturn;
10520 #if ENABLE_ASH_MATH_SUPPORT
10522 * Parse an arithmetic expansion (indicate start of one and set state)
10525 if (++arinest == 1) {
10526 prevsyntax = syntax;
10527 syntax = ARISYNTAX;
10528 USTPUTC(CTLARI, out);
10535 * we collapse embedded arithmetic expansion to
10536 * parenthesis, which should be equivalent
10540 goto parsearith_return;
10544 } /* end of readtoken */
10547 * Read the next input token.
10548 * If the token is a word, we set backquotelist to the list of cmds in
10549 * backquotes. We set quoteflag to true if any part of the word was
10551 * If the token is TREDIR, then we set redirnode to a structure containing
10553 * In all cases, the variable startlinno is set to the number of the line
10554 * on which the token starts.
10556 * [Change comment: here documents and internal procedures]
10557 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10558 * word parsing code into a separate routine. In this case, readtoken
10559 * doesn't need to have any internal procedures, but parseword does.
10560 * We could also make parseoperator in essence the main routine, and
10561 * have parseword (readtoken1?) handle both words and redirection.]
10563 #define NEW_xxreadtoken
10564 #ifdef NEW_xxreadtoken
10565 /* singles must be first! */
10566 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10568 static const char xxreadtoken_tokens[] = {
10569 TNL, TLP, TRP, /* only single occurrence allowed */
10570 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10571 TEOF, /* corresponds to trailing nul */
10572 TAND, TOR, TENDCASE, /* if double occurrence */
10575 #define xxreadtoken_doubles \
10576 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10577 #define xxreadtoken_singles \
10578 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10592 startlinno = plinno;
10593 for (;;) { /* until token or start of word found */
10596 if ((c != ' ') && (c != '\t')
10597 #if ENABLE_ASH_ALIAS
10602 while ((c = pgetc()) != '\n' && c != PEOF);
10604 } else if (c == '\\') {
10605 if (pgetc() != '\n') {
10609 startlinno = ++plinno;
10614 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10619 needprompt = doprompt;
10622 p = strchr(xxreadtoken_chars, c);
10625 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10628 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10629 if (pgetc() == *p) { /* double occurrence? */
10630 p += xxreadtoken_doubles + 1;
10636 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10642 #define RETURN(token) return lasttoken = token
10655 startlinno = plinno;
10656 for (;;) { /* until token or start of word found */
10659 case ' ': case '\t':
10660 #if ENABLE_ASH_ALIAS
10665 while ((c = pgetc()) != '\n' && c != PEOF);
10669 if (pgetc() == '\n') {
10670 startlinno = ++plinno;
10679 needprompt = doprompt;
10684 if (pgetc() == '&')
10689 if (pgetc() == '|')
10694 if (pgetc() == ';')
10707 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10710 #endif /* NEW_xxreadtoken */
10717 int alreadyseen = tokpushback;
10720 #if ENABLE_ASH_ALIAS
10729 if (checkkwd & CHKNL) {
10736 if (t != TWORD || quoteflag) {
10741 * check for keywords
10743 if (checkkwd & CHKKWD) {
10744 const char *const *pp;
10746 pp = findkwd(wordtext);
10748 lasttoken = t = pp - tokname_array;
10749 TRACE(("keyword %s recognized\n", tokname(t)));
10754 if (checkkwd & CHKALIAS) {
10755 #if ENABLE_ASH_ALIAS
10757 ap = lookupalias(wordtext, 1);
10760 pushstring(ap->val, ap);
10770 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10772 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10784 return tokname_array[t][0];
10788 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10789 * valid parse tree indicating a blank line.)
10791 static union node *
10792 parsecmd(int interact)
10797 doprompt = interact;
10799 setprompt(doprompt);
10811 * Input any here documents.
10816 struct heredoc *here;
10819 here = heredoclist;
10826 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10827 here->eofmark, here->striptabs);
10828 n = stalloc(sizeof(struct narg));
10829 n->narg.type = NARG;
10830 n->narg.next = NULL;
10831 n->narg.text = wordtext;
10832 n->narg.backquote = backquotelist;
10833 here->here->nhere.doc = n;
10840 * called by editline -- any expansions to the prompt should be added here.
10842 #if ENABLE_ASH_EXPAND_PRMT
10843 static const char *
10844 expandstr(const char *ps)
10848 /* XXX Fix (char *) cast. */
10849 setinputstring((char *)ps);
10850 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10853 n.narg.type = NARG;
10854 n.narg.next = NULL;
10855 n.narg.text = wordtext;
10856 n.narg.backquote = backquotelist;
10858 expandarg(&n, NULL, 0);
10859 return stackblock();
10864 * Execute a command or commands contained in a string.
10867 evalstring(char *s, int mask)
10870 struct stackmark smark;
10874 setstackmark(&smark);
10877 while ((n = parsecmd(0)) != NEOF) {
10879 popstackmark(&smark);
10892 * The eval command.
10895 evalcmd(int argc, char **argv)
10904 STARTSTACKSTR(concat);
10907 concat = stack_putstr(p, concat);
10911 STPUTC(' ', concat);
10913 STPUTC('\0', concat);
10914 p = grabstackstr(concat);
10916 evalstring(p, ~SKIPEVAL);
10923 * Read and execute commands. "Top" is nonzero for the top level command
10924 * loop; it turns on prompting if the shell is interactive.
10930 struct stackmark smark;
10934 TRACE(("cmdloop(%d) called\n", top));
10938 setstackmark(&smark);
10941 showjobs(stderr, SHOW_CHANGED);
10944 if (iflag && top) {
10946 #if ENABLE_ASH_MAIL
10950 n = parsecmd(inter);
10951 /* showtree(n); DEBUG */
10953 if (!top || numeof >= 50)
10955 if (!stoppedjobs()) {
10958 out2str("\nUse \"exit\" to leave shell.\n");
10961 } else if (nflag == 0) {
10962 job_warning = (job_warning == 2) ? 1 : 0;
10966 popstackmark(&smark);
10971 return skip & SKIPEVAL;
10978 * Take commands from a file. To be compatible we should do a path
10979 * search for the file, which is necessary to find sub-commands.
10982 find_dot_file(char *name)
10985 const char *path = pathval();
10988 /* don't try this for absolute or relative paths */
10989 if (strchr(name, '/'))
10992 while ((fullname = padvance(&path, name)) != NULL) {
10993 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
10995 * Don't bother freeing here, since it will
10996 * be freed by the caller.
11000 stunalloc(fullname);
11003 /* not found in the PATH */
11004 ash_msg_and_raise_error("%s: not found", name);
11009 dotcmd(int argc, char **argv)
11011 struct strlist *sp;
11012 volatile struct shparam saveparam;
11015 for (sp = cmdenviron; sp; sp = sp->next)
11016 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11018 if (argc >= 2) { /* That's what SVR2 does */
11021 fullname = find_dot_file(argv[1]);
11024 saveparam = shellparam;
11025 shellparam.malloc = 0;
11026 shellparam.nparam = argc - 2;
11027 shellparam.p = argv + 2;
11030 setinputfile(fullname, INPUT_PUSH_FILE);
11031 commandname = fullname;
11036 freeparam(&shellparam);
11037 shellparam = saveparam;
11039 status = exitstatus;
11045 exitcmd(int argc, char **argv)
11050 exitstatus = number(argv[1]);
11051 raise_exception(EXEXIT);
11055 #if ENABLE_ASH_BUILTIN_ECHO
11057 echocmd(int argc, char **argv)
11059 return bb_echo(argv);
11063 #if ENABLE_ASH_BUILTIN_TEST
11065 testcmd(int argc, char **argv)
11067 return bb_test(argc, argv);
11072 * Read a file containing shell functions.
11075 readcmdfile(char *name)
11077 setinputfile(name, INPUT_PUSH_FILE);
11083 /* ============ find_command inplementation */
11086 * Resolve a command name. If you change this routine, you may have to
11087 * change the shellexec routine as well.
11090 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11092 struct tblentry *cmdp;
11099 struct builtincmd *bcmd;
11101 /* If name contains a slash, don't use PATH or hash table */
11102 if (strchr(name, '/') != NULL) {
11103 entry->u.index = -1;
11104 if (act & DO_ABS) {
11105 while (stat(name, &statb) < 0) {
11107 if (errno == EINTR)
11110 entry->cmdtype = CMDUNKNOWN;
11114 entry->cmdtype = CMDNORMAL;
11118 #if ENABLE_FEATURE_SH_STANDALONE
11119 if (find_applet_by_name(name)) {
11120 entry->cmdtype = CMDNORMAL;
11121 entry->u.index = -1;
11126 updatetbl = (path == pathval());
11129 if (strstr(path, "%builtin") != NULL)
11130 act |= DO_ALTBLTIN;
11133 /* If name is in the table, check answer will be ok */
11134 cmdp = cmdlookup(name, 0);
11135 if (cmdp != NULL) {
11138 switch (cmdp->cmdtype) {
11156 } else if (cmdp->rehash == 0)
11157 /* if not invalidated by cd, we're done */
11161 /* If %builtin not in path, check for builtin next */
11162 bcmd = find_builtin(name);
11164 if (IS_BUILTIN_REGULAR(bcmd))
11165 goto builtin_success;
11166 if (act & DO_ALTPATH) {
11167 if (!(act & DO_ALTBLTIN))
11168 goto builtin_success;
11169 } else if (builtinloc <= 0) {
11170 goto builtin_success;
11174 /* We have to search path. */
11175 prev = -1; /* where to start */
11176 if (cmdp && cmdp->rehash) { /* doing a rehash */
11177 if (cmdp->cmdtype == CMDBUILTIN)
11180 prev = cmdp->param.index;
11186 while ((fullname = padvance(&path, name)) != NULL) {
11187 stunalloc(fullname);
11190 if (prefix(pathopt, "builtin")) {
11192 goto builtin_success;
11194 } else if (!(act & DO_NOFUNC) &&
11195 prefix(pathopt, "func")) {
11196 /* handled below */
11198 /* ignore unimplemented options */
11202 /* if rehash, don't redo absolute path names */
11203 if (fullname[0] == '/' && idx <= prev) {
11206 TRACE(("searchexec \"%s\": no change\n", name));
11209 while (stat(fullname, &statb) < 0) {
11211 if (errno == EINTR)
11214 if (errno != ENOENT && errno != ENOTDIR)
11218 e = EACCES; /* if we fail, this will be the error */
11219 if (!S_ISREG(statb.st_mode))
11221 if (pathopt) { /* this is a %func directory */
11222 stalloc(strlen(fullname) + 1);
11223 readcmdfile(fullname);
11224 cmdp = cmdlookup(name, 0);
11225 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11226 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11227 stunalloc(fullname);
11230 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11232 entry->cmdtype = CMDNORMAL;
11233 entry->u.index = idx;
11237 cmdp = cmdlookup(name, 1);
11238 cmdp->cmdtype = CMDNORMAL;
11239 cmdp->param.index = idx;
11244 /* We failed. If there was an entry for this command, delete it */
11245 if (cmdp && updatetbl)
11246 delete_cmd_entry();
11248 ash_msg("%s: %s", name, errmsg(e, "not found"));
11249 entry->cmdtype = CMDUNKNOWN;
11254 entry->cmdtype = CMDBUILTIN;
11255 entry->u.cmd = bcmd;
11259 cmdp = cmdlookup(name, 1);
11260 cmdp->cmdtype = CMDBUILTIN;
11261 cmdp->param.cmd = bcmd;
11265 entry->cmdtype = cmdp->cmdtype;
11266 entry->u = cmdp->param;
11270 /* ============ trap.c */
11273 * The trap builtin.
11276 trapcmd(int argc, char **argv)
11285 for (signo = 0; signo < NSIG; signo++) {
11286 if (trap[signo] != NULL) {
11289 sn = get_signame(signo);
11290 out1fmt("trap -- %s %s\n",
11291 single_quote(trap[signo]), sn);
11301 signo = get_signum(*ap);
11303 ash_msg_and_raise_error("%s: bad trap", *ap);
11306 if (LONE_DASH(action))
11309 action = ckstrdup(action);
11313 trap[signo] = action;
11323 /* ============ Builtins */
11325 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11327 * Lists available builtins
11330 helpcmd(int argc, char **argv)
11334 out1fmt("\nBuilt-in commands:\n-------------------\n");
11335 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11336 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11337 builtintab[i].name + 1);
11343 #if ENABLE_FEATURE_SH_STANDALONE
11344 for (i = 0; i < NUM_APPLETS; i++) {
11345 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11353 return EXIT_SUCCESS;
11355 #endif /* FEATURE_SH_EXTRA_QUIET */
11358 * The export and readonly commands.
11361 exportcmd(int argc, char **argv)
11367 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11369 if (nextopt("p") != 'p') {
11374 p = strchr(name, '=');
11378 vp = *findvar(hashvar(name), name);
11384 setvar(name, p, flag);
11385 } while ((name = *++aptr) != NULL);
11389 showvars(argv[0], flag, 0);
11394 * Delete a function if it exists.
11397 unsetfunc(const char *name)
11399 struct tblentry *cmdp;
11401 cmdp = cmdlookup(name, 0);
11402 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11403 delete_cmd_entry();
11407 * The unset builtin command. We unset the function before we unset the
11408 * variable to allow a function to be unset when there is a readonly variable
11409 * with the same name.
11412 unsetcmd(int argc, char **argv)
11419 while ((i = nextopt("vf")) != '\0') {
11423 for (ap = argptr; *ap; ap++) {
11439 #include <sys/times.h>
11441 static const unsigned char timescmd_str[] = {
11442 ' ', offsetof(struct tms, tms_utime),
11443 '\n', offsetof(struct tms, tms_stime),
11444 ' ', offsetof(struct tms, tms_cutime),
11445 '\n', offsetof(struct tms, tms_cstime),
11450 timescmd(int ac, char **av)
11452 long clk_tck, s, t;
11453 const unsigned char *p;
11456 clk_tck = sysconf(_SC_CLK_TCK);
11461 t = *(clock_t *)(((char *) &buf) + p[1]);
11463 out1fmt("%ldm%ld.%.3lds%c",
11465 ((t - s * clk_tck) * 1000) / clk_tck,
11467 } while (*(p += 2));
11472 #if ENABLE_ASH_MATH_SUPPORT
11474 dash_arith(const char *s)
11480 result = arith(s, &errcode);
11483 ash_msg_and_raise_error("exponent less than 0");
11485 ash_msg_and_raise_error("divide by zero");
11487 ash_msg_and_raise_error("expression recursion loop detected");
11488 raise_error_syntax(s);
11496 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11497 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11499 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11502 letcmd(int argc, char **argv)
11509 ash_msg_and_raise_error("expression expected");
11510 for (ap = argv + 1; *ap; ap++) {
11511 i = dash_arith(*ap);
11516 #endif /* ASH_MATH_SUPPORT */
11519 /* ============ miscbltin.c
11521 * Miscellaneous builtins.
11526 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11527 typedef enum __rlimit_resource rlim_t;
11531 * The read builtin. The -e option causes backslashes to escape the
11532 * following character.
11534 * This uses unbuffered input, which may be avoidable in some cases.
11537 readcmd(int argc, char **argv)
11549 #if ENABLE_ASH_READ_NCHARS
11553 struct termios tty, old_tty;
11555 #if ENABLE_ASH_READ_TIMEOUT
11559 ts.tv_sec = ts.tv_usec = 0;
11564 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11565 while ((i = nextopt("p:rt:n:s")) != '\0')
11566 #elif ENABLE_ASH_READ_NCHARS
11567 while ((i = nextopt("p:rn:s")) != '\0')
11568 #elif ENABLE_ASH_READ_TIMEOUT
11569 while ((i = nextopt("p:rt:")) != '\0')
11571 while ((i = nextopt("p:r")) != '\0')
11576 prompt = optionarg;
11578 #if ENABLE_ASH_READ_NCHARS
11580 nchars = strtol(optionarg, &p, 10);
11582 ash_msg_and_raise_error("invalid count");
11583 nch_flag = (nchars > 0);
11589 #if ENABLE_ASH_READ_TIMEOUT
11591 ts.tv_sec = strtol(optionarg, &p, 10);
11597 ts.tv_usec = strtol(p, &p2, 10);
11599 ash_msg_and_raise_error("invalid timeout");
11601 /* normalize to usec */
11603 ash_msg_and_raise_error("invalid timeout");
11604 while (scale++ < 6)
11608 ash_msg_and_raise_error("invalid timeout");
11610 if ( ! ts.tv_sec && ! ts.tv_usec)
11611 ash_msg_and_raise_error("invalid timeout");
11621 if (prompt && isatty(0)) {
11626 ash_msg_and_raise_error("arg count");
11627 ifs = bltinlookup("IFS");
11630 #if ENABLE_ASH_READ_NCHARS
11631 if (nch_flag || silent) {
11632 tcgetattr(0, &tty);
11635 tty.c_lflag &= ~ICANON;
11636 tty.c_cc[VMIN] = nchars;
11639 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11642 tcsetattr(0, TCSANOW, &tty);
11645 #if ENABLE_ASH_READ_TIMEOUT
11646 if (ts.tv_sec || ts.tv_usec) {
11650 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11652 #if ENABLE_ASH_READ_NCHARS
11654 tcsetattr(0, TCSANOW, &old_tty);
11664 #if ENABLE_ASH_READ_NCHARS
11665 while (!nch_flag || nchars--)
11670 if (read(0, &c, 1) != 1) {
11682 if (!rflag && c == '\\') {
11688 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11692 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11694 setvar(*ap, stackblock(), 0);
11703 #if ENABLE_ASH_READ_NCHARS
11704 if (nch_flag || silent)
11705 tcsetattr(0, TCSANOW, &old_tty);
11709 /* Remove trailing blanks */
11710 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11712 setvar(*ap, stackblock(), 0);
11713 while (*++ap != NULL)
11714 setvar(*ap, nullstr, 0);
11719 umaskcmd(int argc, char **argv)
11721 static const char permuser[3] = "ugo";
11722 static const char permmode[3] = "rwx";
11723 static const short int permmask[] = {
11724 S_IRUSR, S_IWUSR, S_IXUSR,
11725 S_IRGRP, S_IWGRP, S_IXGRP,
11726 S_IROTH, S_IWOTH, S_IXOTH
11732 int symbolic_mode = 0;
11734 while (nextopt("S") != '\0') {
11745 if (symbolic_mode) {
11749 for (i = 0; i < 3; i++) {
11752 *p++ = permuser[i];
11754 for (j = 0; j < 3; j++) {
11755 if ((mask & permmask[3 * i + j]) == 0) {
11756 *p++ = permmode[j];
11764 out1fmt("%.4o\n", mask);
11767 if (isdigit((unsigned char) *ap)) {
11770 if (*ap >= '8' || *ap < '0')
11771 ash_msg_and_raise_error(illnum, argv[1]);
11772 mask = (mask << 3) + (*ap - '0');
11773 } while (*++ap != '\0');
11776 mask = ~mask & 0777;
11777 if (!bb_parse_mode(ap, &mask)) {
11778 ash_msg_and_raise_error("illegal mode: %s", ap);
11780 umask(~mask & 0777);
11789 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11790 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11791 * ash by J.T. Conklin.
11799 int factor; /* multiply by to get rlim_{cur,max} values */
11803 static const struct limits limits[] = {
11805 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11807 #ifdef RLIMIT_FSIZE
11808 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11811 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11813 #ifdef RLIMIT_STACK
11814 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11817 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11820 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11822 #ifdef RLIMIT_MEMLOCK
11823 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11825 #ifdef RLIMIT_NPROC
11826 { "process", RLIMIT_NPROC, 1, 'p' },
11828 #ifdef RLIMIT_NOFILE
11829 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11832 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11834 #ifdef RLIMIT_LOCKS
11835 { "locks", RLIMIT_LOCKS, 1, 'w' },
11837 { NULL, 0, 0, '\0' }
11840 enum limtype { SOFT = 0x1, HARD = 0x2 };
11843 printlim(enum limtype how, const struct rlimit *limit,
11844 const struct limits *l)
11848 val = limit->rlim_max;
11850 val = limit->rlim_cur;
11852 if (val == RLIM_INFINITY)
11853 out1fmt("unlimited\n");
11856 out1fmt("%lld\n", (long long) val);
11861 ulimitcmd(int argc, char **argv)
11865 enum limtype how = SOFT | HARD;
11866 const struct limits *l;
11869 struct rlimit limit;
11872 while ((optc = nextopt("HSa"
11876 #ifdef RLIMIT_FSIZE
11882 #ifdef RLIMIT_STACK
11891 #ifdef RLIMIT_MEMLOCK
11894 #ifdef RLIMIT_NPROC
11897 #ifdef RLIMIT_NOFILE
11903 #ifdef RLIMIT_LOCKS
11921 for (l = limits; l->option != what; l++)
11924 set = *argptr ? 1 : 0;
11928 if (all || argptr[1])
11929 ash_msg_and_raise_error("too many arguments");
11930 if (strncmp(p, "unlimited\n", 9) == 0)
11931 val = RLIM_INFINITY;
11935 while ((c = *p++) >= '0' && c <= '9') {
11936 val = (val * 10) + (long)(c - '0');
11937 if (val < (rlim_t) 0)
11941 ash_msg_and_raise_error("bad number");
11946 for (l = limits; l->name; l++) {
11947 getrlimit(l->cmd, &limit);
11948 out1fmt("%-20s ", l->name);
11949 printlim(how, &limit, l);
11954 getrlimit(l->cmd, &limit);
11957 limit.rlim_max = val;
11959 limit.rlim_cur = val;
11960 if (setrlimit(l->cmd, &limit) < 0)
11961 ash_msg_and_raise_error("error setting limit (%m)");
11963 printlim(how, &limit, l);
11969 /* ============ Math support */
11971 #if ENABLE_ASH_MATH_SUPPORT
11973 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11975 Permission is hereby granted, free of charge, to any person obtaining
11976 a copy of this software and associated documentation files (the
11977 "Software"), to deal in the Software without restriction, including
11978 without limitation the rights to use, copy, modify, merge, publish,
11979 distribute, sublicense, and/or sell copies of the Software, and to
11980 permit persons to whom the Software is furnished to do so, subject to
11981 the following conditions:
11983 The above copyright notice and this permission notice shall be
11984 included in all copies or substantial portions of the Software.
11986 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11987 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11988 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
11989 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
11990 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11991 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11992 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11995 /* This is my infix parser/evaluator. It is optimized for size, intended
11996 * as a replacement for yacc-based parsers. However, it may well be faster
11997 * than a comparable parser written in yacc. The supported operators are
11998 * listed in #defines below. Parens, order of operations, and error handling
11999 * are supported. This code is thread safe. The exact expression format should
12000 * be that which POSIX specifies for shells. */
12002 /* The code uses a simple two-stack algorithm. See
12003 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12004 * for a detailed explanation of the infix-to-postfix algorithm on which
12005 * this is based (this code differs in that it applies operators immediately
12006 * to the stack instead of adding them to a queue to end up with an
12009 /* To use the routine, call it with an expression string and error return
12013 * Aug 24, 2001 Manuel Novoa III
12015 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12017 * 1) In arith_apply():
12018 * a) Cached values of *numptr and &(numptr[-1]).
12019 * b) Removed redundant test for zero denominator.
12022 * a) Eliminated redundant code for processing operator tokens by moving
12023 * to a table-based implementation. Also folded handling of parens
12025 * b) Combined all 3 loops which called arith_apply to reduce generated
12026 * code size at the cost of speed.
12028 * 3) The following expressions were treated as valid by the original code:
12029 * 1() , 0! , 1 ( *3 ) .
12030 * These bugs have been fixed by internally enclosing the expression in
12031 * parens and then checking that all binary ops and right parens are
12032 * preceded by a valid expression (NUM_TOKEN).
12034 * Note: It may be desirable to replace Aaron's test for whitespace with
12035 * ctype's isspace() if it is used by another busybox applet or if additional
12036 * whitespace chars should be considered. Look below the "#include"s for a
12037 * precompiler test.
12041 * Aug 26, 2001 Manuel Novoa III
12043 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12045 * Merge in Aaron's comments previously posted to the busybox list,
12046 * modified slightly to take account of my changes to the code.
12051 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12053 * - allow access to variable,
12054 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12055 * - realize assign syntax (VAR=expr, +=, *= etc)
12056 * - realize exponentiation (** operator)
12057 * - realize comma separated - expr, expr
12058 * - realise ++expr --expr expr++ expr--
12059 * - realise expr ? expr : expr (but, second expr calculate always)
12060 * - allow hexadecimal and octal numbers
12061 * - was restored loses XOR operator
12062 * - remove one goto label, added three ;-)
12063 * - protect $((num num)) as true zero expr (Manuel`s error)
12064 * - always use special isspace(), see comment from bash ;-)
12067 #define arith_isspace(arithval) \
12068 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12070 typedef unsigned char operator;
12072 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12073 * precedence, and 3 high bits are an ID unique across operators of that
12074 * precedence. The ID portion is so that multiple operators can have the
12075 * same precedence, ensuring that the leftmost one is evaluated first.
12076 * Consider * and /. */
12078 #define tok_decl(prec,id) (((id)<<5)|(prec))
12079 #define PREC(op) ((op) & 0x1F)
12081 #define TOK_LPAREN tok_decl(0,0)
12083 #define TOK_COMMA tok_decl(1,0)
12085 #define TOK_ASSIGN tok_decl(2,0)
12086 #define TOK_AND_ASSIGN tok_decl(2,1)
12087 #define TOK_OR_ASSIGN tok_decl(2,2)
12088 #define TOK_XOR_ASSIGN tok_decl(2,3)
12089 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12090 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12091 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12092 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12094 #define TOK_MUL_ASSIGN tok_decl(3,0)
12095 #define TOK_DIV_ASSIGN tok_decl(3,1)
12096 #define TOK_REM_ASSIGN tok_decl(3,2)
12098 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12099 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12101 /* conditional is right associativity too */
12102 #define TOK_CONDITIONAL tok_decl(4,0)
12103 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12105 #define TOK_OR tok_decl(5,0)
12107 #define TOK_AND tok_decl(6,0)
12109 #define TOK_BOR tok_decl(7,0)
12111 #define TOK_BXOR tok_decl(8,0)
12113 #define TOK_BAND tok_decl(9,0)
12115 #define TOK_EQ tok_decl(10,0)
12116 #define TOK_NE tok_decl(10,1)
12118 #define TOK_LT tok_decl(11,0)
12119 #define TOK_GT tok_decl(11,1)
12120 #define TOK_GE tok_decl(11,2)
12121 #define TOK_LE tok_decl(11,3)
12123 #define TOK_LSHIFT tok_decl(12,0)
12124 #define TOK_RSHIFT tok_decl(12,1)
12126 #define TOK_ADD tok_decl(13,0)
12127 #define TOK_SUB tok_decl(13,1)
12129 #define TOK_MUL tok_decl(14,0)
12130 #define TOK_DIV tok_decl(14,1)
12131 #define TOK_REM tok_decl(14,2)
12133 /* exponent is right associativity */
12134 #define TOK_EXPONENT tok_decl(15,1)
12136 /* For now unary operators. */
12137 #define UNARYPREC 16
12138 #define TOK_BNOT tok_decl(UNARYPREC,0)
12139 #define TOK_NOT tok_decl(UNARYPREC,1)
12141 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12142 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12144 #define PREC_PRE (UNARYPREC+2)
12146 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12147 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12149 #define PREC_POST (UNARYPREC+3)
12151 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12152 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12154 #define SPEC_PREC (UNARYPREC+4)
12156 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12157 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12159 #define NUMPTR (*numstackptr)
12162 tok_have_assign(operator op)
12164 operator prec = PREC(op);
12166 convert_prec_is_assing(prec);
12167 return (prec == PREC(TOK_ASSIGN) ||
12168 prec == PREC_PRE || prec == PREC_POST);
12172 is_right_associativity(operator prec)
12174 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12175 || prec == PREC(TOK_CONDITIONAL));
12178 typedef struct ARITCH_VAR_NUM {
12180 arith_t contidional_second_val;
12181 char contidional_second_val_initialized;
12182 char *var; /* if NULL then is regular number,
12183 else is variable name */
12186 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12188 struct CHK_VAR_RECURSIVE_LOOPED *next;
12189 } chk_var_recursive_looped_t;
12191 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12194 arith_lookup_val(v_n_t *t)
12197 const char * p = lookupvar(t->var);
12202 /* recursive try as expression */
12203 chk_var_recursive_looped_t *cur;
12204 chk_var_recursive_looped_t cur_save;
12206 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12207 if (strcmp(cur->var, t->var) == 0) {
12208 /* expression recursion loop detected */
12212 /* save current lookuped var name */
12213 cur = prev_chk_var_recursive;
12214 cur_save.var = t->var;
12215 cur_save.next = cur;
12216 prev_chk_var_recursive = &cur_save;
12218 t->val = arith (p, &errcode);
12219 /* restore previous ptr after recursiving */
12220 prev_chk_var_recursive = cur;
12223 /* allow undefined var as 0 */
12229 /* "applying" a token means performing it on the top elements on the integer
12230 * stack. For a unary operator it will only change the top element, but a
12231 * binary operator will pop two arguments and push a result */
12233 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12236 arith_t numptr_val, rez;
12237 int ret_arith_lookup_val;
12239 /* There is no operator that can work without arguments */
12240 if (NUMPTR == numstack) goto err;
12241 numptr_m1 = NUMPTR - 1;
12243 /* check operand is var with noninteger value */
12244 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12245 if (ret_arith_lookup_val)
12246 return ret_arith_lookup_val;
12248 rez = numptr_m1->val;
12249 if (op == TOK_UMINUS)
12251 else if (op == TOK_NOT)
12253 else if (op == TOK_BNOT)
12255 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12257 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12259 else if (op != TOK_UPLUS) {
12260 /* Binary operators */
12262 /* check and binary operators need two arguments */
12263 if (numptr_m1 == numstack) goto err;
12265 /* ... and they pop one */
12268 if (op == TOK_CONDITIONAL) {
12269 if (! numptr_m1->contidional_second_val_initialized) {
12270 /* protect $((expr1 ? expr2)) without ": expr" */
12273 rez = numptr_m1->contidional_second_val;
12274 } else if (numptr_m1->contidional_second_val_initialized) {
12275 /* protect $((expr1 : expr2)) without "expr ? " */
12278 numptr_m1 = NUMPTR - 1;
12279 if (op != TOK_ASSIGN) {
12280 /* check operand is var with noninteger value for not '=' */
12281 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12282 if (ret_arith_lookup_val)
12283 return ret_arith_lookup_val;
12285 if (op == TOK_CONDITIONAL) {
12286 numptr_m1->contidional_second_val = rez;
12288 rez = numptr_m1->val;
12289 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12291 else if (op == TOK_OR)
12292 rez = numptr_val || rez;
12293 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12295 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12297 else if (op == TOK_AND)
12298 rez = rez && numptr_val;
12299 else if (op == TOK_EQ)
12300 rez = (rez == numptr_val);
12301 else if (op == TOK_NE)
12302 rez = (rez != numptr_val);
12303 else if (op == TOK_GE)
12304 rez = (rez >= numptr_val);
12305 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12306 rez >>= numptr_val;
12307 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12308 rez <<= numptr_val;
12309 else if (op == TOK_GT)
12310 rez = (rez > numptr_val);
12311 else if (op == TOK_LT)
12312 rez = (rez < numptr_val);
12313 else if (op == TOK_LE)
12314 rez = (rez <= numptr_val);
12315 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12317 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12319 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12321 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12323 else if (op == TOK_CONDITIONAL_SEP) {
12324 if (numptr_m1 == numstack) {
12325 /* protect $((expr : expr)) without "expr ? " */
12328 numptr_m1->contidional_second_val_initialized = op;
12329 numptr_m1->contidional_second_val = numptr_val;
12330 } else if (op == TOK_CONDITIONAL) {
12332 numptr_val : numptr_m1->contidional_second_val;
12333 } else if (op == TOK_EXPONENT) {
12334 if (numptr_val < 0)
12335 return -3; /* exponent less than 0 */
12340 while (numptr_val--)
12344 } else if (numptr_val==0) /* zero divisor check */
12346 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12348 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12351 if (tok_have_assign(op)) {
12352 char buf[sizeof(arith_t_type)*3 + 2];
12354 if (numptr_m1->var == NULL) {
12358 /* save to shell variable */
12359 #if ENABLE_ASH_MATH_SUPPORT_64
12360 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12362 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12364 setvar(numptr_m1->var, buf, 0);
12365 /* after saving, make previous value for v++ or v-- */
12366 if (op == TOK_POST_INC)
12368 else if (op == TOK_POST_DEC)
12371 numptr_m1->val = rez;
12372 /* protect geting var value, is number now */
12373 numptr_m1->var = NULL;
12379 /* longest must be first */
12380 static const char op_tokens[] = {
12381 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12382 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12383 '<','<', 0, TOK_LSHIFT,
12384 '>','>', 0, TOK_RSHIFT,
12385 '|','|', 0, TOK_OR,
12386 '&','&', 0, TOK_AND,
12387 '!','=', 0, TOK_NE,
12388 '<','=', 0, TOK_LE,
12389 '>','=', 0, TOK_GE,
12390 '=','=', 0, TOK_EQ,
12391 '|','=', 0, TOK_OR_ASSIGN,
12392 '&','=', 0, TOK_AND_ASSIGN,
12393 '*','=', 0, TOK_MUL_ASSIGN,
12394 '/','=', 0, TOK_DIV_ASSIGN,
12395 '%','=', 0, TOK_REM_ASSIGN,
12396 '+','=', 0, TOK_PLUS_ASSIGN,
12397 '-','=', 0, TOK_MINUS_ASSIGN,
12398 '-','-', 0, TOK_POST_DEC,
12399 '^','=', 0, TOK_XOR_ASSIGN,
12400 '+','+', 0, TOK_POST_INC,
12401 '*','*', 0, TOK_EXPONENT,
12405 '=', 0, TOK_ASSIGN,
12417 '?', 0, TOK_CONDITIONAL,
12418 ':', 0, TOK_CONDITIONAL_SEP,
12419 ')', 0, TOK_RPAREN,
12420 '(', 0, TOK_LPAREN,
12424 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12427 arith(const char *expr, int *perrcode)
12429 char arithval; /* Current character under analysis */
12430 operator lasttok, op;
12433 const char *p = endexpression;
12436 size_t datasizes = strlen(expr) + 2;
12438 /* Stack of integers */
12439 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12440 * in any given correct or incorrect expression is left as an exercise to
12442 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12443 *numstackptr = numstack;
12444 /* Stack of operator tokens */
12445 operator *stack = alloca((datasizes) * sizeof(operator)),
12448 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12449 *perrcode = errcode = 0;
12453 if (arithval == 0) {
12454 if (p == endexpression) {
12455 /* Null expression. */
12459 /* This is only reached after all tokens have been extracted from the
12460 * input stream. If there are still tokens on the operator stack, they
12461 * are to be applied in order. At the end, there should be a final
12462 * result on the integer stack */
12464 if (expr != endexpression + 1) {
12465 /* If we haven't done so already, */
12466 /* append a closing right paren */
12467 expr = endexpression;
12468 /* and let the loop process it. */
12471 /* At this point, we're done with the expression. */
12472 if (numstackptr != numstack+1) {
12473 /* ... but if there isn't, it's bad */
12475 return (*perrcode = -1);
12477 if (numstack->var) {
12478 /* expression is $((var)) only, lookup now */
12479 errcode = arith_lookup_val(numstack);
12482 *perrcode = errcode;
12483 return numstack->val;
12486 /* Continue processing the expression. */
12487 if (arith_isspace(arithval)) {
12488 /* Skip whitespace */
12491 p = endofname(expr);
12493 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12495 numstackptr->var = alloca(var_name_size);
12496 safe_strncpy(numstackptr->var, expr, var_name_size);
12499 numstackptr->contidional_second_val_initialized = 0;
12504 if (isdigit(arithval)) {
12505 numstackptr->var = NULL;
12506 #if ENABLE_ASH_MATH_SUPPORT_64
12507 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12509 numstackptr->val = strtol(expr, (char **) &expr, 0);
12513 for (p = op_tokens; ; p++) {
12517 /* strange operator not found */
12520 for (o = expr; *p && *o == *p; p++)
12527 /* skip tail uncompared token */
12530 /* skip zero delim */
12535 /* post grammar: a++ reduce to num */
12536 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12539 /* Plus and minus are binary (not unary) _only_ if the last
12540 * token was as number, or a right paren (which pretends to be
12541 * a number, since it evaluates to one). Think about it.
12542 * It makes sense. */
12543 if (lasttok != TOK_NUM) {
12559 /* We don't want a unary operator to cause recursive descent on the
12560 * stack, because there can be many in a row and it could cause an
12561 * operator to be evaluated before its argument is pushed onto the
12562 * integer stack. */
12563 /* But for binary operators, "apply" everything on the operator
12564 * stack until we find an operator with a lesser priority than the
12565 * one we have just extracted. */
12566 /* Left paren is given the lowest priority so it will never be
12567 * "applied" in this way.
12568 * if associativity is right and priority eq, applied also skip
12571 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12572 /* not left paren or unary */
12573 if (lasttok != TOK_NUM) {
12574 /* binary op must be preceded by a num */
12577 while (stackptr != stack) {
12578 if (op == TOK_RPAREN) {
12579 /* The algorithm employed here is simple: while we don't
12580 * hit an open paren nor the bottom of the stack, pop
12581 * tokens and apply them */
12582 if (stackptr[-1] == TOK_LPAREN) {
12584 /* Any operator directly after a */
12586 /* close paren should consider itself binary */
12590 operator prev_prec = PREC(stackptr[-1]);
12592 convert_prec_is_assing(prec);
12593 convert_prec_is_assing(prev_prec);
12594 if (prev_prec < prec)
12596 /* check right assoc */
12597 if (prev_prec == prec && is_right_associativity(prec))
12600 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12601 if (errcode) goto ret;
12603 if (op == TOK_RPAREN) {
12608 /* Push this operator to the stack and remember it. */
12609 *stackptr++ = lasttok = op;
12614 #endif /* ASH_MATH_SUPPORT */
12617 /* ============ main() and helpers */
12620 * Called to exit the shell.
12622 static void exitshell(void) ATTRIBUTE_NORETURN;
12630 status = exitstatus;
12631 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12632 if (setjmp(loc.loc)) {
12633 if (exception == EXEXIT)
12634 /* dash bug: it just does _exit(exitstatus) here
12635 * but we have to do setjobctl(0) first!
12636 * (bug is still not fixed in dash-0.5.3 - if you run dash
12637 * under Midnight Commander, on exit from dash MC is backgrounded) */
12638 status = exitstatus;
12641 exception_handler = &loc;
12647 flush_stdout_stderr();
12657 /* from input.c: */
12658 basepf.nextc = basepf.buf = basebuf;
12661 signal(SIGCHLD, SIG_DFL);
12666 char ppid[sizeof(int)*3 + 1];
12668 struct stat st1, st2;
12671 for (envp = environ; envp && *envp; envp++) {
12672 if (strchr(*envp, '=')) {
12673 setvareq(*envp, VEXPORT|VTEXTFIXED);
12677 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12678 setvar("PPID", ppid, 0);
12680 p = lookupvar("PWD");
12682 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12683 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12690 * Process the shell command line arguments.
12693 procargs(int argc, char **argv)
12696 const char *xminusc;
12703 for (i = 0; i < NOPTS; i++)
12709 if (*xargv == NULL) {
12711 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12714 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12718 for (i = 0; i < NOPTS; i++)
12719 if (optlist[i] == 2)
12724 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12729 } else if (!sflag) {
12730 setinputfile(*xargv, 0);
12733 commandname = arg0;
12736 shellparam.p = xargv;
12737 #if ENABLE_ASH_GETOPTS
12738 shellparam.optind = 1;
12739 shellparam.optoff = -1;
12741 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12743 shellparam.nparam++;
12750 * Read /etc/profile or .profile.
12753 read_profile(const char *name)
12757 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12766 * This routine is called when an error or an interrupt occurs in an
12767 * interactive shell and control is returned to the main command loop.
12775 /* from input.c: */
12776 parselleft = parsenleft = 0; /* clear input buffer */
12778 /* from parser.c: */
12781 /* from redir.c: */
12786 static short profile_buf[16384];
12787 extern int etext();
12791 * Main routine. We initialize things, parse the arguments, execute
12792 * profiles if we're a login shell, and then call cmdloop to execute
12793 * commands. The setjmp call sets up the location to jump to when an
12794 * exception occurs. When an exception occurs the variable "state"
12795 * is used to figure out how far we had gotten.
12797 int ash_main(int argc, char **argv);
12798 int ash_main(int argc, char **argv)
12801 volatile int state;
12802 struct jmploc jmploc;
12803 struct stackmark smark;
12806 dash_errno = __errno_location();
12810 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12813 #if ENABLE_FEATURE_EDITING
12814 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12817 if (setjmp(jmploc.loc)) {
12827 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12831 outcslow('\n', stderr);
12833 popstackmark(&smark);
12834 FORCE_INT_ON; /* enable interrupts */
12843 exception_handler = &jmploc;
12846 trace_puts("Shell args: ");
12847 trace_puts_args(argv);
12849 rootpid = getpid();
12851 #if ENABLE_ASH_RANDOM_SUPPORT
12852 rseed = rootpid + time(NULL);
12855 setstackmark(&smark);
12856 procargs(argc, argv);
12857 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12859 const char *hp = lookupvar("HISTFILE");
12862 hp = lookupvar("HOME");
12864 char *defhp = concat_path_file(hp, ".ash_history");
12865 setvar("HISTFILE", defhp, 0);
12871 if (argv[0] && argv[0][0] == '-')
12875 read_profile("/etc/profile");
12878 read_profile(".profile");
12884 getuid() == geteuid() && getgid() == getegid() &&
12888 shinit = lookupvar("ENV");
12889 if (shinit != NULL && *shinit != '\0') {
12890 read_profile(shinit);
12896 evalstring(minusc, 0);
12898 if (sflag || minusc == NULL) {
12899 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12901 const char *hp = lookupvar("HISTFILE");
12904 line_input_state->hist_file = hp;
12907 state4: /* XXX ??? - why isn't this before the "if" statement */
12915 extern void _mcleanup(void);
12924 const char *applet_name = "debug stuff usage";
12925 int main(int argc, char **argv)
12927 return ash_main(argc, argv);
12933 * Copyright (c) 1989, 1991, 1993, 1994
12934 * The Regents of the University of California. All rights reserved.
12936 * This code is derived from software contributed to Berkeley by
12937 * Kenneth Almquist.
12939 * Redistribution and use in source and binary forms, with or without
12940 * modification, are permitted provided that the following conditions
12942 * 1. Redistributions of source code must retain the above copyright
12943 * notice, this list of conditions and the following disclaimer.
12944 * 2. Redistributions in binary form must reproduce the above copyright
12945 * notice, this list of conditions and the following disclaimer in the
12946 * documentation and/or other materials provided with the distribution.
12947 * 3. Neither the name of the University nor the names of its contributors
12948 * may be used to endorse or promote products derived from this software
12949 * without specific prior written permission.
12951 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12952 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12953 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12954 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12955 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12956 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12957 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12958 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12959 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12960 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF