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') {
2296 } else if (p[1] == '\0')
2300 new = stack_putstr(p, new);
2308 return stackblock();
2312 * Find out what the current directory is. If we already know the current
2313 * directory, this routine returns immediately.
2318 char *dir = getcwd(0, 0);
2319 return dir ? dir : nullstr;
2323 setpwd(const char *val, int setold)
2327 oldcur = dir = curdir;
2330 setvar("OLDPWD", oldcur, VEXPORT);
2333 if (physdir != nullstr) {
2334 if (physdir != oldcur)
2338 if (oldcur == val || !val) {
2344 dir = ckstrdup(val);
2345 if (oldcur != dir && oldcur != nullstr) {
2350 setvar("PWD", dir, VEXPORT);
2353 static void hashcd(void);
2356 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2357 * know that the current directory has changed.
2360 docd(const char *dest, int flags)
2362 const char *dir = 0;
2365 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2368 if (!(flags & CD_PHYSICAL)) {
2369 dir = updatepwd(dest);
2384 cdcmd(int argc, char **argv)
2396 dest = bltinlookup(homestr);
2397 else if (LONE_DASH(dest)) {
2398 dest = bltinlookup("OLDPWD");
2420 path = bltinlookup("CDPATH");
2429 p = padvance(&path, dest);
2430 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2434 if (!docd(p, flags))
2439 ash_msg_and_raise_error("can't cd to %s", dest);
2442 if (flags & CD_PRINT)
2443 out1fmt(snlfmt, curdir);
2448 pwdcmd(int argc, char **argv)
2451 const char *dir = curdir;
2455 if (physdir == nullstr)
2459 out1fmt(snlfmt, dir);
2464 /* ============ ... */
2466 #define IBUFSIZ (BUFSIZ + 1)
2467 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2469 /* Syntax classes */
2470 #define CWORD 0 /* character is nothing special */
2471 #define CNL 1 /* newline character */
2472 #define CBACK 2 /* a backslash character */
2473 #define CSQUOTE 3 /* single quote */
2474 #define CDQUOTE 4 /* double quote */
2475 #define CENDQUOTE 5 /* a terminating quote */
2476 #define CBQUOTE 6 /* backwards single quote */
2477 #define CVAR 7 /* a dollar sign */
2478 #define CENDVAR 8 /* a '}' character */
2479 #define CLP 9 /* a left paren in arithmetic */
2480 #define CRP 10 /* a right paren in arithmetic */
2481 #define CENDFILE 11 /* end of file */
2482 #define CCTL 12 /* like CWORD, except it must be escaped */
2483 #define CSPCL 13 /* these terminate a word */
2484 #define CIGN 14 /* character should be ignored */
2486 #if ENABLE_ASH_ALIAS
2490 #define PEOA_OR_PEOF PEOA
2494 #define PEOA_OR_PEOF PEOF
2497 /* number syntax index */
2498 #define BASESYNTAX 0 /* not in quotes */
2499 #define DQSYNTAX 1 /* in double quotes */
2500 #define SQSYNTAX 2 /* in single quotes */
2501 #define ARISYNTAX 3 /* in arithmetic */
2503 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2504 #define USE_SIT_FUNCTION
2507 #if ENABLE_ASH_MATH_SUPPORT
2508 static const char S_I_T[][4] = {
2509 #if ENABLE_ASH_ALIAS
2510 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2512 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2513 { CNL, CNL, CNL, CNL }, /* 2, \n */
2514 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2515 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2516 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2517 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2518 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2519 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2520 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2521 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2522 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2523 #ifndef USE_SIT_FUNCTION
2524 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2525 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2526 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2530 static const char S_I_T[][3] = {
2531 #if ENABLE_ASH_ALIAS
2532 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2534 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2535 { CNL, CNL, CNL }, /* 2, \n */
2536 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2537 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2538 { CVAR, CVAR, CWORD }, /* 5, $ */
2539 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2540 { CSPCL, CWORD, CWORD }, /* 7, ( */
2541 { CSPCL, CWORD, CWORD }, /* 8, ) */
2542 { CBACK, CBACK, CCTL }, /* 9, \ */
2543 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2544 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2545 #ifndef USE_SIT_FUNCTION
2546 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2547 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2548 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2551 #endif /* ASH_MATH_SUPPORT */
2553 #ifdef USE_SIT_FUNCTION
2556 SIT(int c, int syntax)
2558 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2559 #if ENABLE_ASH_ALIAS
2560 static const char syntax_index_table[] = {
2561 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2562 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2563 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2567 static const char syntax_index_table[] = {
2568 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2569 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2570 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2577 if (c == PEOF) /* 2^8+2 */
2579 #if ENABLE_ASH_ALIAS
2580 if (c == PEOA) /* 2^8+1 */
2584 #define U_C(c) ((unsigned char)(c))
2586 if ((unsigned char)c >= (unsigned char)(CTLESC)
2587 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2591 s = strchr(spec_symbls, c);
2592 if (s == NULL || *s == '\0')
2594 indx = syntax_index_table[(s - spec_symbls)];
2596 return S_I_T[indx][syntax];
2599 #else /* !USE_SIT_FUNCTION */
2601 #if ENABLE_ASH_ALIAS
2602 #define CSPCL_CIGN_CIGN_CIGN 0
2603 #define CSPCL_CWORD_CWORD_CWORD 1
2604 #define CNL_CNL_CNL_CNL 2
2605 #define CWORD_CCTL_CCTL_CWORD 3
2606 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2607 #define CVAR_CVAR_CWORD_CVAR 5
2608 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2609 #define CSPCL_CWORD_CWORD_CLP 7
2610 #define CSPCL_CWORD_CWORD_CRP 8
2611 #define CBACK_CBACK_CCTL_CBACK 9
2612 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2613 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2614 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2615 #define CWORD_CWORD_CWORD_CWORD 13
2616 #define CCTL_CCTL_CCTL_CCTL 14
2618 #define CSPCL_CWORD_CWORD_CWORD 0
2619 #define CNL_CNL_CNL_CNL 1
2620 #define CWORD_CCTL_CCTL_CWORD 2
2621 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2622 #define CVAR_CVAR_CWORD_CVAR 4
2623 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2624 #define CSPCL_CWORD_CWORD_CLP 6
2625 #define CSPCL_CWORD_CWORD_CRP 7
2626 #define CBACK_CBACK_CCTL_CBACK 8
2627 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2628 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2629 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2630 #define CWORD_CWORD_CWORD_CWORD 12
2631 #define CCTL_CCTL_CCTL_CCTL 13
2634 static const char syntax_index_table[258] = {
2635 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2636 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2637 #if ENABLE_ASH_ALIAS
2638 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2640 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2641 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2642 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2643 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2644 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2645 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2646 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2647 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2648 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2649 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2778 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2779 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2801 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2802 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2803 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2805 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2807 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2808 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2809 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2810 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2811 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2813 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2814 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2815 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2816 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2827 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2828 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2829 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2830 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2831 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2832 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2857 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2860 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2861 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2862 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2865 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2893 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2894 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2895 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2898 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2900 #endif /* USE_SIT_FUNCTION */
2903 /* ============ Alias handling */
2905 #if ENABLE_ASH_ALIAS
2907 #define ALIASINUSE 1
2919 static struct alias *atab[ATABSIZE];
2921 static struct alias **
2922 __lookupalias(const char *name) {
2923 unsigned int hashval;
2930 ch = (unsigned char)*p;
2934 ch = (unsigned char)*++p;
2936 app = &atab[hashval % ATABSIZE];
2938 for (; *app; app = &(*app)->next) {
2939 if (strcmp(name, (*app)->name) == 0) {
2947 static struct alias *
2948 lookupalias(const char *name, int check)
2950 struct alias *ap = *__lookupalias(name);
2952 if (check && ap && (ap->flag & ALIASINUSE))
2957 static struct alias *
2958 freealias(struct alias *ap)
2962 if (ap->flag & ALIASINUSE) {
2963 ap->flag |= ALIASDEAD;
2975 setalias(const char *name, const char *val)
2977 struct alias *ap, **app;
2979 app = __lookupalias(name);
2983 if (!(ap->flag & ALIASINUSE)) {
2986 ap->val = ckstrdup(val);
2987 ap->flag &= ~ALIASDEAD;
2990 ap = ckmalloc(sizeof(struct alias));
2991 ap->name = ckstrdup(name);
2992 ap->val = ckstrdup(val);
3001 unalias(const char *name)
3005 app = __lookupalias(name);
3009 *app = freealias(*app);
3020 struct alias *ap, **app;
3024 for (i = 0; i < ATABSIZE; i++) {
3026 for (ap = *app; ap; ap = *app) {
3027 *app = freealias(*app);
3037 printalias(const struct alias *ap)
3039 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3043 * TODO - sort output
3046 aliascmd(int argc, char **argv)
3055 for (i = 0; i < ATABSIZE; i++)
3056 for (ap = atab[i]; ap; ap = ap->next) {
3061 while ((n = *++argv) != NULL) {
3062 v = strchr(n+1, '=');
3063 if (v == NULL) { /* n+1: funny ksh stuff */
3064 ap = *__lookupalias(n);
3066 fprintf(stderr, "%s: %s not found\n", "alias", n);
3080 unaliascmd(int argc, char **argv)
3084 while ((i = nextopt("a")) != '\0') {
3090 for (i = 0; *argptr; argptr++) {
3091 if (unalias(*argptr)) {
3092 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3100 #endif /* ASH_ALIAS */
3103 /* ============ jobs.c */
3105 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3108 #define FORK_NOJOB 2
3110 /* mode flags for showjob(s) */
3111 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3112 #define SHOW_PID 0x04 /* include process pid */
3113 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3116 * A job structure contains information about a job. A job is either a
3117 * single process or a set of processes contained in a pipeline. In the
3118 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3123 pid_t pid; /* process id */
3124 int status; /* last process status from wait() */
3125 char *cmd; /* text of command being run */
3129 struct procstat ps0; /* status of process */
3130 struct procstat *ps; /* status or processes when more than one */
3132 int stopstatus; /* status of a stopped job */
3135 nprocs: 16, /* number of processes */
3137 #define JOBRUNNING 0 /* at least one proc running */
3138 #define JOBSTOPPED 1 /* all procs are stopped */
3139 #define JOBDONE 2 /* all procs are completed */
3141 sigint: 1, /* job was killed by SIGINT */
3142 jobctl: 1, /* job running under job control */
3144 waited: 1, /* true if this entry has been waited for */
3145 used: 1, /* true if this entry is in used */
3146 changed: 1; /* true if status has changed */
3147 struct job *prev_job; /* previous job */
3150 static pid_t backgndpid; /* pid of last background process */
3151 static int job_warning; /* user was warned about stopped jobs */
3153 static int jobctl; /* true if doing job control */
3156 static struct job *makejob(union node *, int);
3157 static int forkshell(struct job *, union node *, int);
3158 static int waitforjob(struct job *);
3161 #define setjobctl(on) /* do nothing */
3163 static void setjobctl(int);
3164 static void showjobs(FILE *, int);
3168 * Set the signal handler for the specified signal. The routine figures
3169 * out what it should be set to.
3172 setsignal(int signo)
3176 struct sigaction act;
3181 else if (*t != '\0')
3185 if (rootshell && action == S_DFL) {
3188 if (iflag || minusc || sflag == 0)
3211 t = &sigmode[signo - 1];
3215 * current setting unknown
3217 if (sigaction(signo, 0, &act) == -1) {
3219 * Pretend it worked; maybe we should give a warning
3220 * here, but other shells don't. We don't alter
3221 * sigmode, so that we retry every time.
3225 if (act.sa_handler == SIG_IGN) {
3227 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3229 tsig = S_IGN; /* don't hard ignore these */
3233 tsig = S_RESET; /* force to be set */
3236 if (tsig == S_HARD_IGN || tsig == action)
3240 act.sa_handler = onsig;
3243 act.sa_handler = SIG_IGN;
3246 act.sa_handler = SIG_DFL;
3250 sigfillset(&act.sa_mask);
3251 sigaction(signo, &act, 0);
3254 /* mode flags for set_curjob */
3255 #define CUR_DELETE 2
3256 #define CUR_RUNNING 1
3257 #define CUR_STOPPED 0
3259 /* mode flags for dowait */
3260 #define DOWAIT_NORMAL 0
3261 #define DOWAIT_BLOCK 1
3264 /* pgrp of shell on invocation */
3265 static int initialpgrp;
3266 static int ttyfd = -1;
3269 static struct job *jobtab;
3271 static unsigned njobs;
3273 static struct job *curjob;
3274 /* number of presumed living untracked jobs */
3278 set_curjob(struct job *jp, unsigned mode)
3281 struct job **jpp, **curp;
3283 /* first remove from list */
3284 jpp = curp = &curjob;
3289 jpp = &jp1->prev_job;
3291 *jpp = jp1->prev_job;
3293 /* Then re-insert in correct position */
3301 /* job being deleted */
3304 /* newly created job or backgrounded job,
3305 put after all stopped jobs. */
3309 if (!jp1 || jp1->state != JOBSTOPPED)
3312 jpp = &jp1->prev_job;
3318 /* newly stopped job - becomes curjob */
3319 jp->prev_job = *jpp;
3327 jobno(const struct job *jp)
3329 return jp - jobtab + 1;
3334 * Convert a job name to a job structure.
3337 getjob(const char *name, int getctl)
3341 const char *err_msg = "No such job: %s";
3345 char *(*match)(const char *, const char *);
3360 if (c == '+' || c == '%') {
3362 err_msg = "No current job";
3368 err_msg = "No previous job";
3379 jp = jobtab + num - 1;
3396 if (match(jp->ps[0].cmd, p)) {
3400 err_msg = "%s: ambiguous";
3407 err_msg = "job %s not created under job control";
3408 if (getctl && jp->jobctl == 0)
3413 ash_msg_and_raise_error(err_msg, name);
3417 * Mark a job structure as unused.
3420 freejob(struct job *jp)
3422 struct procstat *ps;
3426 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3427 if (ps->cmd != nullstr)
3430 if (jp->ps != &jp->ps0)
3433 set_curjob(jp, CUR_DELETE);
3439 xtcsetpgrp(int fd, pid_t pgrp)
3441 if (tcsetpgrp(fd, pgrp))
3442 ash_msg_and_raise_error("cannot set tty process group (%m)");
3446 * Turn job control on and off.
3448 * Note: This code assumes that the third arg to ioctl is a character
3449 * pointer, which is true on Berkeley systems but not System V. Since
3450 * System V doesn't have job control yet, this isn't a problem now.
3452 * Called with interrupts off.
3460 if (on == jobctl || rootshell == 0)
3464 ofd = fd = open(_PATH_TTY, O_RDWR);
3466 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3467 * That sometimes helps to acquire controlling tty.
3468 * Obviously, a workaround for bugs when someone
3469 * failed to provide a controlling tty to bash! :) */
3471 while (!isatty(fd) && --fd >= 0)
3474 fd = fcntl(fd, F_DUPFD, 10);
3478 fcntl(fd, F_SETFD, FD_CLOEXEC);
3479 do { /* while we are in the background */
3480 pgrp = tcgetpgrp(fd);
3483 ash_msg("can't access tty; job control turned off");
3487 if (pgrp == getpgrp())
3498 xtcsetpgrp(fd, pgrp);
3500 /* turning job control off */
3503 xtcsetpgrp(fd, pgrp);
3517 killcmd(int argc, char **argv)
3527 ash_msg_and_raise_error(
3528 "usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
3529 "kill -l [exitstatus]"
3533 if (**++argv == '-') {
3534 signo = get_signum(*argv + 1);
3538 while ((c = nextopt("ls:")) != '\0') {
3548 signo = get_signum(optionarg);
3550 ash_msg_and_raise_error(
3551 "invalid signal number or name: %s",
3563 if (!list && signo < 0)
3566 if ((signo < 0 || !*argv) ^ list) {
3574 for (i = 1; i < NSIG; i++) {
3575 name = get_signame(i);
3577 out1fmt(snlfmt, name);
3581 name = get_signame(signo);
3582 if (!isdigit(*name))
3583 ash_msg_and_raise_error("invalid signal number or exit status: %s", *argptr);
3584 out1fmt(snlfmt, name);
3590 if (**argv == '%') {
3591 jp = getjob(*argv, 0);
3592 pid = -jp->ps[0].pid;
3594 pid = **argv == '-' ?
3595 -number(*argv + 1) : number(*argv);
3597 if (kill(pid, signo) != 0) {
3598 ash_msg("(%d) - %m", pid);
3607 showpipe(struct job *jp, FILE *out)
3609 struct procstat *sp;
3610 struct procstat *spend;
3612 spend = jp->ps + jp->nprocs;
3613 for (sp = jp->ps + 1; sp < spend; sp++)
3614 fprintf(out, " | %s", sp->cmd);
3615 outcslow('\n', out);
3616 flush_stdout_stderr();
3621 restartjob(struct job *jp, int mode)
3623 struct procstat *ps;
3629 if (jp->state == JOBDONE)
3631 jp->state = JOBRUNNING;
3633 if (mode == FORK_FG)
3634 xtcsetpgrp(ttyfd, pgid);
3635 killpg(pgid, SIGCONT);
3639 if (WIFSTOPPED(ps->status)) {
3642 } while (ps++, --i);
3644 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3650 fg_bgcmd(int argc, char **argv)
3657 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3662 jp = getjob(*argv, 1);
3663 if (mode == FORK_BG) {
3664 set_curjob(jp, CUR_RUNNING);
3665 fprintf(out, "[%d] ", jobno(jp));
3667 outstr(jp->ps->cmd, out);
3669 retval = restartjob(jp, mode);
3670 } while (*argv && *++argv);
3676 sprint_status(char *s, int status, int sigonly)
3682 if (!WIFEXITED(status)) {
3684 if (WIFSTOPPED(status))
3685 st = WSTOPSIG(status);
3688 st = WTERMSIG(status);
3690 if (st == SIGINT || st == SIGPIPE)
3693 if (WIFSTOPPED(status))
3698 col = fmtstr(s, 32, strsignal(st));
3699 if (WCOREDUMP(status)) {
3700 col += fmtstr(s + col, 16, " (core dumped)");
3702 } else if (!sigonly) {
3703 st = WEXITSTATUS(status);
3705 col = fmtstr(s, 16, "Done(%d)", st);
3707 col = fmtstr(s, 16, "Done");
3714 * Do a wait system call. If job control is compiled in, we accept
3715 * stopped processes. If block is zero, we return a value of zero
3716 * rather than blocking.
3718 * System V doesn't have a non-blocking wait system call. It does
3719 * have a SIGCLD signal that is sent to a process when one of it's
3720 * children dies. The obvious way to use SIGCLD would be to install
3721 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3722 * was received, and have waitproc bump another counter when it got
3723 * the status of a process. Waitproc would then know that a wait
3724 * system call would not block if the two counters were different.
3725 * This approach doesn't work because if a process has children that
3726 * have not been waited for, System V will send it a SIGCLD when it
3727 * installs a signal handler for SIGCLD. What this means is that when
3728 * a child exits, the shell will be sent SIGCLD signals continuously
3729 * until is runs out of stack space, unless it does a wait call before
3730 * restoring the signal handler. The code below takes advantage of
3731 * this (mis)feature by installing a signal handler for SIGCLD and
3732 * then checking to see whether it was called. If there are any
3733 * children to be waited for, it will be.
3735 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3736 * waits at all. In this case, the user will not be informed when
3737 * a background process until the next time she runs a real program
3738 * (as opposed to running a builtin command or just typing return),
3739 * and the jobs command may give out of date information.
3742 waitproc(int block, int *status)
3752 return wait3(status, flags, (struct rusage *)NULL);
3756 * Wait for a process to terminate.
3759 dowait(int block, struct job *job)
3764 struct job *thisjob;
3767 TRACE(("dowait(%d) called\n", block));
3768 pid = waitproc(block, &status);
3769 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3774 for (jp = curjob; jp; jp = jp->prev_job) {
3775 struct procstat *sp;
3776 struct procstat *spend;
3777 if (jp->state == JOBDONE)
3780 spend = jp->ps + jp->nprocs;
3783 if (sp->pid == pid) {
3784 TRACE(("Job %d: changing status of proc %d "
3785 "from 0x%x to 0x%x\n",
3786 jobno(jp), pid, sp->status, status));
3787 sp->status = status;
3790 if (sp->status == -1)
3793 if (state == JOBRUNNING)
3795 if (WIFSTOPPED(sp->status)) {
3796 jp->stopstatus = sp->status;
3800 } while (++sp < spend);
3805 if (!WIFSTOPPED(status))
3812 if (state != JOBRUNNING) {
3813 thisjob->changed = 1;
3815 if (thisjob->state != state) {
3816 TRACE(("Job %d: changing state from %d to %d\n",
3817 jobno(thisjob), thisjob->state, state));
3818 thisjob->state = state;
3820 if (state == JOBSTOPPED) {
3821 set_curjob(thisjob, CUR_STOPPED);
3830 if (thisjob && thisjob == job) {
3834 len = sprint_status(s, status, 1);
3846 showjob(FILE *out, struct job *jp, int mode)
3848 struct procstat *ps;
3849 struct procstat *psend;
3856 if (mode & SHOW_PGID) {
3857 /* just output process (group) id of pipeline */
3858 fprintf(out, "%d\n", ps->pid);
3862 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3867 else if (curjob && jp == curjob->prev_job)
3870 if (mode & SHOW_PID)
3871 col += fmtstr(s + col, 16, "%d ", ps->pid);
3873 psend = ps + jp->nprocs;
3875 if (jp->state == JOBRUNNING) {
3876 strcpy(s + col, "Running");
3877 col += sizeof("Running") - 1;
3879 int status = psend[-1].status;
3880 if (jp->state == JOBSTOPPED)
3881 status = jp->stopstatus;
3882 col += sprint_status(s + col, status, 0);
3888 /* for each process */
3889 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
3891 fprintf(out, "%s%*c%s",
3892 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3894 if (!(mode & SHOW_PID)) {
3898 if (++ps == psend) {
3899 outcslow('\n', out);
3906 if (jp->state == JOBDONE) {
3907 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3913 jobscmd(int argc, char **argv)
3919 while ((m = nextopt("lp"))) {
3930 showjob(out, getjob(*argv,0), mode);
3933 showjobs(out, mode);
3939 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3940 * statuses have changed since the last call to showjobs.
3943 showjobs(FILE *out, int mode)
3947 TRACE(("showjobs(%x) called\n", mode));
3949 /* If not even one one job changed, there is nothing to do */
3950 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3953 for (jp = curjob; jp; jp = jp->prev_job) {
3954 if (!(mode & SHOW_CHANGED) || jp->changed)
3955 showjob(out, jp, mode);
3961 getstatus(struct job *job)
3966 status = job->ps[job->nprocs - 1].status;
3967 retval = WEXITSTATUS(status);
3968 if (!WIFEXITED(status)) {
3970 retval = WSTOPSIG(status);
3971 if (!WIFSTOPPED(status))
3974 /* XXX: limits number of signals */
3975 retval = WTERMSIG(status);
3977 if (retval == SIGINT)
3983 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3984 jobno(job), job->nprocs, status, retval));
3989 waitcmd(int argc, char **argv)
4002 /* wait for all jobs */
4007 /* no running procs */
4010 if (jp->state == JOBRUNNING)
4015 dowait(DOWAIT_BLOCK, 0);
4021 if (**argv != '%') {
4022 pid_t pid = number(*argv);
4026 if (job->ps[job->nprocs - 1].pid == pid)
4028 job = job->prev_job;
4034 job = getjob(*argv, 0);
4035 /* loop until process terminated or stopped */
4036 while (job->state == JOBRUNNING)
4037 dowait(DOWAIT_BLOCK, 0);
4039 retval = getstatus(job);
4053 struct job *jp, *jq;
4055 len = njobs * sizeof(*jp);
4057 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4059 offset = (char *)jp - (char *)jq;
4061 /* Relocate pointers */
4064 jq = (struct job *)((char *)jq + l);
4068 #define joff(p) ((struct job *)((char *)(p) + l))
4069 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4070 if (joff(jp)->ps == &jq->ps0)
4071 jmove(joff(jp)->ps);
4072 if (joff(jp)->prev_job)
4073 jmove(joff(jp)->prev_job);
4083 jp = (struct job *)((char *)jp + len);
4087 } while (--jq >= jp);
4092 * Return a new job structure.
4093 * Called with interrupts off.
4096 makejob(union node *node, int nprocs)
4101 for (i = njobs, jp = jobtab; ; jp++) {
4108 if (jp->state != JOBDONE || !jp->waited)
4117 memset(jp, 0, sizeof(*jp));
4122 jp->prev_job = curjob;
4127 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4129 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4136 * Return a string identifying a command (to be printed by the
4139 static char *cmdnextc;
4142 cmdputs(const char *s)
4144 const char *p, *str;
4145 char c, cc[2] = " ";
4149 static const char vstype[VSTYPE + 1][4] = {
4150 "", "}", "-", "+", "?", "=",
4151 "%", "%%", "#", "##"
4154 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4156 while ((c = *p++) != 0) {
4164 if ((subtype & VSTYPE) == VSLENGTH)
4168 if (!(subtype & VSQUOTE) == !(quoted & 1))
4174 str = "\"}" + !(quoted & 1);
4181 case CTLBACKQ+CTLQUOTE:
4184 #if ENABLE_ASH_MATH_SUPPORT
4199 if ((subtype & VSTYPE) != VSNORMAL)
4201 str = vstype[subtype & VSTYPE];
4202 if (subtype & VSNUL)
4211 /* These can only happen inside quotes */
4224 while ((c = *str++)) {
4229 USTPUTC('"', nextc);
4235 /* cmdtxt() and cmdlist() call each other */
4236 static void cmdtxt(union node *n);
4239 cmdlist(union node *np, int sep)
4241 for (; np; np = np->narg.next) {
4245 if (sep && np->narg.next)
4251 cmdtxt(union node *n)
4254 struct nodelist *lp;
4266 lp = n->npipe.cmdlist;
4284 cmdtxt(n->nbinary.ch1);
4300 cmdtxt(n->nif.test);
4303 if (n->nif.elsepart) {
4306 n = n->nif.elsepart;
4322 cmdtxt(n->nbinary.ch1);
4332 cmdputs(n->nfor.var);
4334 cmdlist(n->nfor.args, 1);
4339 cmdputs(n->narg.text);
4343 cmdlist(n->ncmd.args, 1);
4344 cmdlist(n->ncmd.redirect, 0);
4357 cmdputs(n->ncase.expr->narg.text);
4359 for (np = n->ncase.cases; np; np = np->nclist.next) {
4360 cmdtxt(np->nclist.pattern);
4362 cmdtxt(np->nclist.body);
4388 s[0] = n->nfile.fd + '0';
4392 if (n->type == NTOFD || n->type == NFROMFD) {
4393 s[0] = n->ndup.dupfd + '0';
4403 commandtext(union node *n)
4407 STARTSTACKSTR(cmdnextc);
4409 name = stackblock();
4410 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4411 name, cmdnextc, cmdnextc));
4412 return ckstrdup(name);
4417 * Fork off a subshell. If we are doing job control, give the subshell its
4418 * own process group. Jp is a job structure that the job is to be added to.
4419 * N is the command that will be evaluated by the child. Both jp and n may
4420 * be NULL. The mode parameter can be one of the following:
4421 * FORK_FG - Fork off a foreground process.
4422 * FORK_BG - Fork off a background process.
4423 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4424 * process group even if job control is on.
4426 * When job control is turned off, background processes have their standard
4427 * input redirected to /dev/null (except for the second and later processes
4430 * Called with interrupts off.
4433 * Clear traps on a fork.
4440 for (tp = trap; tp < &trap[NSIG]; tp++) {
4441 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4446 setsignal(tp - trap);
4451 /* lives far away from here, needed for forkchild */
4452 static void closescript(void);
4454 forkchild(struct job *jp, union node *n, int mode)
4458 TRACE(("Child shell %d\n", getpid()));
4465 /* do job control only in root shell */
4467 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4470 if (jp->nprocs == 0)
4473 pgrp = jp->ps[0].pid;
4474 /* This can fail because we are doing it in the parent also */
4475 (void)setpgid(0, pgrp);
4476 if (mode == FORK_FG)
4477 xtcsetpgrp(ttyfd, pgrp);
4482 if (mode == FORK_BG) {
4485 if (jp->nprocs == 0) {
4487 if (open(bb_dev_null, O_RDONLY) != 0)
4488 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4491 if (!oldlvl && iflag) {
4496 for (jp = curjob; jp; jp = jp->prev_job)
4502 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4504 TRACE(("In parent shell: child = %d\n", pid));
4506 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4511 if (mode != FORK_NOJOB && jp->jobctl) {
4514 if (jp->nprocs == 0)
4517 pgrp = jp->ps[0].pid;
4518 /* This can fail because we are doing it in the child also */
4522 if (mode == FORK_BG) {
4523 backgndpid = pid; /* set $! */
4524 set_curjob(jp, CUR_RUNNING);
4527 struct procstat *ps = &jp->ps[jp->nprocs++];
4533 ps->cmd = commandtext(n);
4539 forkshell(struct job *jp, union node *n, int mode)
4543 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4546 TRACE(("Fork failed, errno=%d", errno));
4549 ash_msg_and_raise_error("cannot fork");
4552 forkchild(jp, n, mode);
4554 forkparent(jp, n, mode, pid);
4559 * Wait for job to finish.
4561 * Under job control we have the problem that while a child process is
4562 * running interrupts generated by the user are sent to the child but not
4563 * to the shell. This means that an infinite loop started by an inter-
4564 * active user may be hard to kill. With job control turned off, an
4565 * interactive user may place an interactive program inside a loop. If
4566 * the interactive program catches interrupts, the user doesn't want
4567 * these interrupts to also abort the loop. The approach we take here
4568 * is to have the shell ignore interrupt signals while waiting for a
4569 * foreground process to terminate, and then send itself an interrupt
4570 * signal if the child process was terminated by an interrupt signal.
4571 * Unfortunately, some programs want to do a bit of cleanup and then
4572 * exit on interrupt; unless these processes terminate themselves by
4573 * sending a signal to themselves (instead of calling exit) they will
4574 * confuse this approach.
4576 * Called with interrupts off.
4579 waitforjob(struct job *jp)
4583 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4584 while (jp->state == JOBRUNNING) {
4585 dowait(DOWAIT_BLOCK, jp);
4590 xtcsetpgrp(ttyfd, rootpid);
4592 * This is truly gross.
4593 * If we're doing job control, then we did a TIOCSPGRP which
4594 * caused us (the shell) to no longer be in the controlling
4595 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4596 * intuit from the subprocess exit status whether a SIGINT
4597 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4602 if (jp->state == JOBDONE)
4609 * return 1 if there are stopped jobs, otherwise 0
4621 if (jp && jp->state == JOBSTOPPED) {
4622 out2str("You have stopped jobs.\n");
4631 /* ============ redir.c
4633 * Code for dealing with input/output redirection.
4636 #define EMPTY -2 /* marks an unused slot in redirtab */
4638 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4640 # define PIPESIZE PIPE_BUF
4644 * Open a file in noclobber mode.
4645 * The code was copied from bash.
4648 noclobberopen(const char *fname)
4651 struct stat finfo, finfo2;
4654 * If the file exists and is a regular file, return an error
4657 r = stat(fname, &finfo);
4658 if (r == 0 && S_ISREG(finfo.st_mode)) {
4664 * If the file was not present (r != 0), make sure we open it
4665 * exclusively so that if it is created before we open it, our open
4666 * will fail. Make sure that we do not truncate an existing file.
4667 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4668 * file was not a regular file, we leave O_EXCL off.
4671 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4672 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4674 /* If the open failed, return the file descriptor right away. */
4679 * OK, the open succeeded, but the file may have been changed from a
4680 * non-regular file to a regular file between the stat and the open.
4681 * We are assuming that the O_EXCL open handles the case where FILENAME
4682 * did not exist and is symlinked to an existing file between the stat
4687 * If we can open it and fstat the file descriptor, and neither check
4688 * revealed that it was a regular file, and the file has not been
4689 * replaced, return the file descriptor.
4691 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4692 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4695 /* The file has been replaced. badness. */
4702 * Handle here documents. Normally we fork off a process to write the
4703 * data to a pipe. If the document is short, we can stuff the data in
4704 * the pipe without forking.
4706 /* openhere needs this forward reference */
4707 static void expandhere(union node *arg, int fd);
4709 openhere(union node *redir)
4715 ash_msg_and_raise_error("pipe call failed");
4716 if (redir->type == NHERE) {
4717 len = strlen(redir->nhere.doc->narg.text);
4718 if (len <= PIPESIZE) {
4719 full_write(pip[1], redir->nhere.doc->narg.text, len);
4723 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4725 signal(SIGINT, SIG_IGN);
4726 signal(SIGQUIT, SIG_IGN);
4727 signal(SIGHUP, SIG_IGN);
4729 signal(SIGTSTP, SIG_IGN);
4731 signal(SIGPIPE, SIG_DFL);
4732 if (redir->type == NHERE)
4733 full_write(pip[1], redir->nhere.doc->narg.text, len);
4735 expandhere(redir->nhere.doc, pip[1]);
4744 openredirect(union node *redir)
4749 switch (redir->nfile.type) {
4751 fname = redir->nfile.expfname;
4752 f = open(fname, O_RDONLY);
4757 fname = redir->nfile.expfname;
4758 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4763 /* Take care of noclobber mode. */
4765 fname = redir->nfile.expfname;
4766 f = noclobberopen(fname);
4773 fname = redir->nfile.expfname;
4774 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4779 fname = redir->nfile.expfname;
4780 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4788 /* Fall through to eliminate warning. */
4795 f = openhere(redir);
4801 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4803 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4807 * Copy a file descriptor to be >= to. Returns -1
4808 * if the source file descriptor is closed, EMPTY if there are no unused
4809 * file descriptors left.
4812 copyfd(int from, int to)
4816 newfd = fcntl(from, F_DUPFD, to);
4818 if (errno == EMFILE)
4820 ash_msg_and_raise_error("%d: %m", from);
4826 dupredirect(union node *redir, int f)
4828 int fd = redir->nfile.fd;
4830 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4831 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4832 copyfd(redir->ndup.dupfd, fd);
4844 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4845 * old file descriptors are stashed away so that the redirection can be
4846 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4847 * standard output, and the standard error if it becomes a duplicate of
4848 * stdout, is saved in memory.
4850 /* flags passed to redirect */
4851 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4852 #define REDIR_SAVEFD2 03 /* set preverrout */
4854 redirect(union node *redir, int flags)
4857 struct redirtab *sv;
4868 if (flags & REDIR_PUSH) {
4870 q = ckmalloc(sizeof(struct redirtab));
4871 q->next = redirlist;
4873 q->nullredirs = nullredirs - 1;
4874 for (i = 0; i < 10; i++)
4875 q->renamed[i] = EMPTY;
4882 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4883 && n->ndup.dupfd == fd)
4884 continue; /* redirect from/to same file descriptor */
4886 newfd = openredirect(n);
4889 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4890 i = fcntl(fd, F_DUPFD, 10);
4897 ash_msg_and_raise_error("%d: %m", fd);
4907 dupredirect(n, newfd);
4908 } while ((n = n->nfile.next));
4910 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4911 preverrout_fd = sv->renamed[2];
4915 * Undo the effects of the last redirection.
4920 struct redirtab *rp;
4923 if (--nullredirs >= 0)
4927 for (i = 0; i < 10; i++) {
4928 if (rp->renamed[i] != EMPTY) {
4931 copyfd(rp->renamed[i], i);
4933 close(rp->renamed[i]);
4936 redirlist = rp->next;
4937 nullredirs = rp->nullredirs;
4943 * Undo all redirections. Called on error or interrupt.
4947 * Discard all saved file descriptors.
4950 clearredir(int drop)
4961 redirectsafe(union node *redir, int flags)
4964 volatile int saveint;
4965 struct jmploc *volatile savehandler = exception_handler;
4966 struct jmploc jmploc;
4969 err = setjmp(jmploc.loc) * 2;
4971 exception_handler = &jmploc;
4972 redirect(redir, flags);
4974 exception_handler = savehandler;
4975 if (err && exception != EXERROR)
4976 longjmp(exception_handler->loc, 1);
4977 RESTORE_INT(saveint);
4982 /* ============ Routines to expand arguments to commands
4984 * We have to deal with backquotes, shell variables, and file metacharacters.
4990 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4991 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4992 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4993 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4994 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4995 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4996 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4997 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4998 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5002 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5003 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5004 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5005 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5006 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5009 * Structure specifying which parts of the string should be searched
5010 * for IFS characters.
5013 struct ifsregion *next; /* next region in list */
5014 int begoff; /* offset of start of region */
5015 int endoff; /* offset of end of region */
5016 int nulonly; /* search for nul bytes only */
5020 struct strlist *list;
5021 struct strlist **lastp;
5024 /* output of current string */
5025 static char *expdest;
5026 /* list of back quote expressions */
5027 static struct nodelist *argbackq;
5028 /* first struct in list of ifs regions */
5029 static struct ifsregion ifsfirst;
5030 /* last struct in list */
5031 static struct ifsregion *ifslastp;
5032 /* holds expanded arg list */
5033 static struct arglist exparg;
5043 expdest = makestrspace(32, expdest);
5044 #if ENABLE_ASH_MATH_SUPPORT_64
5045 len = fmtstr(expdest, 32, "%lld", (long long) num);
5047 len = fmtstr(expdest, 32, "%ld", num);
5049 STADJUST(len, expdest);
5054 esclen(const char *start, const char *p)
5058 while (p > start && *--p == CTLESC) {
5065 * Remove any CTLESC characters from a string.
5068 _rmescapes(char *str, int flag)
5071 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5076 p = strpbrk(str, qchars);
5082 if (flag & RMESCAPE_ALLOC) {
5083 size_t len = p - str;
5084 size_t fulllen = len + strlen(p) + 1;
5086 if (flag & RMESCAPE_GROW) {
5087 r = makestrspace(fulllen, expdest);
5088 } else if (flag & RMESCAPE_HEAP) {
5089 r = ckmalloc(fulllen);
5091 r = stalloc(fulllen);
5095 q = memcpy(q, str, len) + len;
5098 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5099 globbing = flag & RMESCAPE_GLOB;
5100 notescaped = globbing;
5102 if (*p == CTLQUOTEMARK) {
5103 inquotes = ~inquotes;
5105 notescaped = globbing;
5109 /* naked back slash */
5115 if (notescaped && inquotes && *p != '/') {
5119 notescaped = globbing;
5124 if (flag & RMESCAPE_GROW) {
5126 STADJUST(q - r + 1, expdest);
5130 #define rmescapes(p) _rmescapes((p), 0)
5132 #define pmatch(a, b) !fnmatch((a), (b), 0)
5135 * Prepare a pattern for a expmeta (internal glob(3)) call.
5137 * Returns an stalloced string.
5140 preglob(const char *pattern, int quoted, int flag)
5142 flag |= RMESCAPE_GLOB;
5144 flag |= RMESCAPE_QUOTED;
5146 return _rmescapes((char *)pattern, flag);
5150 * Put a string on the stack.
5153 memtodest(const char *p, size_t len, int syntax, int quotes)
5157 q = makestrspace(len * 2, q);
5160 int c = signed_char2int(*p++);
5163 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5172 strtodest(const char *p, int syntax, int quotes)
5174 memtodest(p, strlen(p), syntax, quotes);
5178 * Record the fact that we have to scan this region of the
5179 * string for IFS characters.
5182 recordregion(int start, int end, int nulonly)
5184 struct ifsregion *ifsp;
5186 if (ifslastp == NULL) {
5190 ifsp = ckmalloc(sizeof(*ifsp));
5192 ifslastp->next = ifsp;
5196 ifslastp->begoff = start;
5197 ifslastp->endoff = end;
5198 ifslastp->nulonly = nulonly;
5202 removerecordregions(int endoff)
5204 if (ifslastp == NULL)
5207 if (ifsfirst.endoff > endoff) {
5208 while (ifsfirst.next != NULL) {
5209 struct ifsregion *ifsp;
5211 ifsp = ifsfirst.next->next;
5212 free(ifsfirst.next);
5213 ifsfirst.next = ifsp;
5216 if (ifsfirst.begoff > endoff)
5219 ifslastp = &ifsfirst;
5220 ifsfirst.endoff = endoff;
5225 ifslastp = &ifsfirst;
5226 while (ifslastp->next && ifslastp->next->begoff < endoff)
5227 ifslastp=ifslastp->next;
5228 while (ifslastp->next != NULL) {
5229 struct ifsregion *ifsp;
5231 ifsp = ifslastp->next->next;
5232 free(ifslastp->next);
5233 ifslastp->next = ifsp;
5236 if (ifslastp->endoff > endoff)
5237 ifslastp->endoff = endoff;
5241 exptilde(char *startp, char *p, int flag)
5247 int quotes = flag & (EXP_FULL | EXP_CASE);
5252 while ((c = *++p) != '\0') {
5259 if (flag & EXP_VARTILDE)
5269 if (*name == '\0') {
5270 home = lookupvar(homestr);
5272 pw = getpwnam(name);
5277 if (!home || !*home)
5280 startloc = expdest - (char *)stackblock();
5281 strtodest(home, SQSYNTAX, quotes);
5282 recordregion(startloc, expdest - (char *)stackblock(), 0);
5290 * Execute a command inside back quotes. If it's a builtin command, we
5291 * want to save its output in a block obtained from malloc. Otherwise
5292 * we fork off a subprocess and get the output of the command via a pipe.
5293 * Should be called with interrupts off.
5295 struct backcmd { /* result of evalbackcmd */
5296 int fd; /* file descriptor to read from */
5297 char *buf; /* buffer */
5298 int nleft; /* number of chars in buffer */
5299 struct job *jp; /* job structure for command */
5302 /* These forward decls are needed to use "eval" code for backticks handling: */
5303 static int back_exitstatus; /* exit status of backquoted command */
5304 #define EV_EXIT 01 /* exit after evaluating tree */
5305 static void evaltree(union node *, int);
5308 evalbackcmd(union node *n, struct backcmd *result)
5320 saveherefd = herefd;
5328 ash_msg_and_raise_error("pipe call failed");
5330 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5339 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5343 result->fd = pip[0];
5346 herefd = saveherefd;
5348 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5349 result->fd, result->buf, result->nleft, result->jp));
5353 * Expand stuff in backwards quotes.
5356 expbackq(union node *cmd, int quoted, int quotes)
5364 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5365 struct stackmark smark;
5368 setstackmark(&smark);
5370 startloc = dest - (char *)stackblock();
5372 evalbackcmd(cmd, &in);
5373 popstackmark(&smark);
5380 memtodest(p, i, syntax, quotes);
5384 i = safe_read(in.fd, buf, sizeof(buf));
5385 TRACE(("expbackq: read returns %d\n", i));
5395 back_exitstatus = waitforjob(in.jp);
5399 /* Eat all trailing newlines */
5401 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5406 recordregion(startloc, dest - (char *)stackblock(), 0);
5407 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5408 (dest - (char *)stackblock()) - startloc,
5409 (dest - (char *)stackblock()) - startloc,
5410 stackblock() + startloc));
5413 #if ENABLE_ASH_MATH_SUPPORT
5415 * Expand arithmetic expression. Backup to start of expression,
5416 * evaluate, place result in (backed up) result, adjust string position.
5429 * This routine is slightly over-complicated for
5430 * efficiency. Next we scan backwards looking for the
5431 * start of arithmetic.
5433 start = stackblock();
5440 while (*p != CTLARI) {
5444 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5449 esc = esclen(start, p);
5459 removerecordregions(begoff);
5468 len = cvtnum(dash_arith(p + 2));
5471 recordregion(begoff, begoff + len, 0);
5475 /* argstr needs it */
5476 static char *evalvar(char *p, int flag);
5479 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5480 * characters to allow for further processing. Otherwise treat
5481 * $@ like $* since no splitting will be performed.
5484 argstr(char *p, int flag)
5486 static const char spclchars[] = {
5494 CTLBACKQ | CTLQUOTE,
5495 #if ENABLE_ASH_MATH_SUPPORT
5500 const char *reject = spclchars;
5502 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5503 int breakall = flag & EXP_WORD;
5508 if (!(flag & EXP_VARTILDE)) {
5510 } else if (flag & EXP_VARTILDE2) {
5515 if (flag & EXP_TILDE) {
5521 if (*q == CTLESC && (flag & EXP_QWORD))
5524 p = exptilde(p, q, flag);
5527 startloc = expdest - (char *)stackblock();
5529 length += strcspn(p + length, reject);
5531 if (c && (!(c & 0x80)
5532 #if ENABLE_ASH_MATH_SUPPORT
5536 /* c == '=' || c == ':' || c == CTLENDARI */
5541 expdest = stack_nputstr(p, length, expdest);
5542 newloc = expdest - (char *)stackblock();
5543 if (breakall && !inquotes && newloc > startloc) {
5544 recordregion(startloc, newloc, 0);
5555 if (flag & EXP_VARTILDE2) {
5559 flag |= EXP_VARTILDE2;
5564 * sort of a hack - expand tildes in variable
5565 * assignments (after the first '=' and after ':'s).
5574 case CTLENDVAR: /* ??? */
5577 /* "$@" syntax adherence hack */
5580 !memcmp(p, dolatstr, 4) &&
5581 (p[4] == CTLQUOTEMARK || (
5582 p[4] == CTLENDVAR &&
5583 p[5] == CTLQUOTEMARK
5586 p = evalvar(p + 1, flag) + 1;
5589 inquotes = !inquotes;
5602 p = evalvar(p, flag);
5606 case CTLBACKQ|CTLQUOTE:
5607 expbackq(argbackq->n, c, quotes);
5608 argbackq = argbackq->next;
5610 #if ENABLE_ASH_MATH_SUPPORT
5623 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5634 const char *s = loc2;
5640 match = pmatch(str, s);
5644 if (quotes && *loc == CTLESC)
5653 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5660 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5663 const char *s = loc2;
5668 match = pmatch(str, s);
5675 esc = esclen(startp, loc);
5686 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5688 varunset(const char *end, const char *var, const char *umsg, int varflags)
5694 msg = "parameter not set";
5696 if (*end == CTLENDVAR) {
5697 if (varflags & VSNUL)
5702 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5706 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5710 int saveherefd = herefd;
5711 struct nodelist *saveargbackq = argbackq;
5713 char *rmesc, *rmescend;
5715 char *(*scan)(char *, char *, char *, char *, int , int);
5718 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5719 STPUTC('\0', expdest);
5720 herefd = saveherefd;
5721 argbackq = saveargbackq;
5722 startp = stackblock() + startloc;
5726 setvar(str, startp, 0);
5727 amount = startp - expdest;
5728 STADJUST(amount, expdest);
5732 varunset(p, str, startp, varflags);
5736 subtype -= VSTRIMRIGHT;
5738 if (subtype < 0 || subtype > 3)
5743 rmescend = stackblock() + strloc;
5745 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5746 if (rmesc != startp) {
5748 startp = stackblock() + startloc;
5752 str = stackblock() + strloc;
5753 preglob(str, varflags & VSQUOTE, 0);
5755 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5756 zero = subtype >> 1;
5757 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5758 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5760 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5763 memmove(startp, loc, str - loc);
5764 loc = startp + (str - loc) - 1;
5767 amount = loc - expdest;
5768 STADJUST(amount, expdest);
5774 * Add the value of a specialized variable to the stack string.
5777 varvalue(char *name, int varflags, int flags)
5787 int quoted = varflags & VSQUOTE;
5788 int subtype = varflags & VSTYPE;
5789 int quotes = flags & (EXP_FULL | EXP_CASE);
5791 if (quoted && (flags & EXP_FULL))
5792 sep = 1 << CHAR_BIT;
5794 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5803 num = shellparam.nparam;
5813 p = makestrspace(NOPTS, expdest);
5814 for (i = NOPTS - 1; i >= 0; i--) {
5816 USTPUTC(optletters(i), p);
5827 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5828 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5834 while ((p = *ap++)) {
5837 partlen = strlen(p);
5840 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5841 memtodest(p, partlen, syntax, quotes);
5847 if (subtype == VSPLUS || subtype == VSLENGTH) {
5869 if (num < 0 || num > shellparam.nparam)
5871 p = num ? shellparam.p[num - 1] : arg0;
5874 p = lookupvar(name);
5880 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5881 memtodest(p, len, syntax, quotes);
5885 if (subtype == VSPLUS || subtype == VSLENGTH)
5886 STADJUST(-len, expdest);
5891 * Expand a variable, and return a pointer to the next character in the
5895 evalvar(char *p, int flag)
5908 quotes = flag & (EXP_FULL | EXP_CASE);
5910 subtype = varflags & VSTYPE;
5911 quoted = varflags & VSQUOTE;
5913 easy = (!quoted || (*var == '@' && shellparam.nparam));
5914 startloc = expdest - (char *)stackblock();
5915 p = strchr(p, '=') + 1;
5918 varlen = varvalue(var, varflags, flag);
5919 if (varflags & VSNUL)
5922 if (subtype == VSPLUS) {
5923 varlen = -1 - varlen;
5927 if (subtype == VSMINUS) {
5931 p, flag | EXP_TILDE |
5932 (quoted ? EXP_QWORD : EXP_WORD)
5941 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5943 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5946 * Remove any recorded regions beyond
5949 removerecordregions(startloc);
5959 if (varlen < 0 && uflag)
5960 varunset(p, var, 0, 0);
5962 if (subtype == VSLENGTH) {
5963 cvtnum(varlen > 0 ? varlen : 0);
5967 if (subtype == VSNORMAL) {
5971 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5980 case VSTRIMRIGHTMAX:
5989 * Terminate the string and start recording the pattern
5992 STPUTC('\0', expdest);
5993 patloc = expdest - (char *)stackblock();
5994 if (subevalvar(p, NULL, patloc, subtype,
5995 startloc, varflags, quotes) == 0) {
5996 int amount = expdest - (
5997 (char *)stackblock() + patloc - 1
5999 STADJUST(-amount, expdest);
6001 /* Remove any recorded regions beyond start of variable */
6002 removerecordregions(startloc);
6007 if (subtype != VSNORMAL) { /* skip to end of alternative */
6013 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6015 argbackq = argbackq->next;
6016 } else if (c == CTLVAR) {
6017 if ((*p++ & VSTYPE) != VSNORMAL)
6019 } else if (c == CTLENDVAR) {
6029 * Break the argument string into pieces based upon IFS and add the
6030 * strings to the argument list. The regions of the string to be
6031 * searched for IFS characters have been stored by recordregion.
6034 ifsbreakup(char *string, struct arglist *arglist)
6036 struct ifsregion *ifsp;
6041 const char *ifs, *realifs;
6046 if (ifslastp != NULL) {
6049 realifs = ifsset() ? ifsval() : defifs;
6052 p = string + ifsp->begoff;
6053 nulonly = ifsp->nulonly;
6054 ifs = nulonly ? nullstr : realifs;
6056 while (p < string + ifsp->endoff) {
6060 if (!strchr(ifs, *p)) {
6065 ifsspc = (strchr(defifs, *p) != NULL);
6066 /* Ignore IFS whitespace at start */
6067 if (q == start && ifsspc) {
6073 sp = stalloc(sizeof(*sp));
6075 *arglist->lastp = sp;
6076 arglist->lastp = &sp->next;
6080 if (p >= string + ifsp->endoff) {
6086 if (strchr(ifs, *p) == NULL ) {
6089 } else if (strchr(defifs, *p) == NULL) {
6104 } while (ifsp != NULL);
6113 sp = stalloc(sizeof(*sp));
6115 *arglist->lastp = sp;
6116 arglist->lastp = &sp->next;
6122 struct ifsregion *p;
6127 struct ifsregion *ifsp;
6133 ifsfirst.next = NULL;
6138 * Add a file name to the list.
6141 addfname(const char *name)
6145 sp = stalloc(sizeof(*sp));
6146 sp->text = ststrdup(name);
6148 exparg.lastp = &sp->next;
6151 static char *expdir;
6154 * Do metacharacter (i.e. *, ?, [...]) expansion.
6157 expmeta(char *enddir, char *name)
6172 for (p = name; *p; p++) {
6173 if (*p == '*' || *p == '?')
6175 else if (*p == '[') {
6182 if (*q == '/' || *q == '\0')
6189 } else if (*p == '\\')
6191 else if (*p == '/') {
6198 if (metaflag == 0) { /* we've reached the end of the file name */
6199 if (enddir != expdir)
6207 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6218 } while (p < start);
6220 if (enddir == expdir) {
6222 } else if (enddir == expdir + 1 && *expdir == '/') {
6231 if (enddir != expdir)
6233 if (*endname == 0) {
6245 while (! intpending && (dp = readdir(dirp)) != NULL) {
6246 if (dp->d_name[0] == '.' && ! matchdot)
6248 if (pmatch(start, dp->d_name)) {
6250 strcpy(enddir, dp->d_name);
6253 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6256 expmeta(p, endname);
6265 static struct strlist *
6266 msort(struct strlist *list, int len)
6268 struct strlist *p, *q = NULL;
6269 struct strlist **lpp;
6277 for (n = half; --n >= 0; ) {
6281 q->next = NULL; /* terminate first half of list */
6282 q = msort(list, half); /* sort first half of list */
6283 p = msort(p, len - half); /* sort second half */
6286 #if ENABLE_LOCALE_SUPPORT
6287 if (strcoll(p->text, q->text) < 0)
6289 if (strcmp(p->text, q->text) < 0)
6313 * Sort the results of file name expansion. It calculates the number of
6314 * strings to sort and then calls msort (short for merge sort) to do the
6317 static struct strlist *
6318 expsort(struct strlist *str)
6324 for (sp = str; sp; sp = sp->next)
6326 return msort(str, len);
6330 expandmeta(struct strlist *str, int flag)
6332 static const char metachars[] = {
6335 /* TODO - EXP_REDIR */
6338 struct strlist **savelastp;
6344 if (!strpbrk(str->text, metachars))
6346 savelastp = exparg.lastp;
6349 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6351 int i = strlen(str->text);
6352 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6360 if (exparg.lastp == savelastp) {
6365 *exparg.lastp = str;
6366 rmescapes(str->text);
6367 exparg.lastp = &str->next;
6369 *exparg.lastp = NULL;
6370 *savelastp = sp = expsort(*savelastp);
6371 while (sp->next != NULL)
6373 exparg.lastp = &sp->next;
6380 * Perform variable substitution and command substitution on an argument,
6381 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6382 * perform splitting and file name expansion. When arglist is NULL, perform
6383 * here document expansion.
6386 expandarg(union node *arg, struct arglist *arglist, int flag)
6391 argbackq = arg->narg.backquote;
6392 STARTSTACKSTR(expdest);
6393 ifsfirst.next = NULL;
6395 argstr(arg->narg.text, flag);
6396 p = _STPUTC('\0', expdest);
6398 if (arglist == NULL) {
6399 return; /* here document expanded */
6401 p = grabstackstr(p);
6402 exparg.lastp = &exparg.list;
6406 if (flag & EXP_FULL) {
6407 ifsbreakup(p, &exparg);
6408 *exparg.lastp = NULL;
6409 exparg.lastp = &exparg.list;
6410 expandmeta(exparg.list, flag);
6412 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6414 sp = stalloc(sizeof(*sp));
6417 exparg.lastp = &sp->next;
6421 *exparg.lastp = NULL;
6423 *arglist->lastp = exparg.list;
6424 arglist->lastp = exparg.lastp;
6429 * Expand shell variables and backquotes inside a here document.
6432 expandhere(union node *arg, int fd)
6435 expandarg(arg, (struct arglist *)NULL, 0);
6436 full_write(fd, stackblock(), expdest - (char *)stackblock());
6440 * Returns true if the pattern matches the string.
6443 patmatch(char *pattern, const char *string)
6445 return pmatch(preglob(pattern, 0, 0), string);
6449 * See if a pattern matches in a case statement.
6452 casematch(union node *pattern, char *val)
6454 struct stackmark smark;
6457 setstackmark(&smark);
6458 argbackq = pattern->narg.backquote;
6459 STARTSTACKSTR(expdest);
6461 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6462 STACKSTRNUL(expdest);
6463 result = patmatch(stackblock(), val);
6464 popstackmark(&smark);
6469 /* ============ find_command */
6471 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
6473 is_safe_applet(char *name)
6475 /* It isn't a bug to have non-existent applet here... */
6476 /* ...just a waste of space... */
6477 static const char safe_applets[][8] = {
6481 USE_CHMOD (, "chmod" )
6482 USE_CHOWN (, "chown" )
6486 USE_ECHO (, "echo" )
6487 USE_FIND (, "find" )
6488 USE_HEXDUMP(, "hexdump")
6491 USE_MKDIR (, "mkdir" )
6493 USE_SORT (, "sort" )
6494 USE_TEST (, "test" )
6495 USE_TOUCH (, "touch" )
6496 USE_XARGS (, "xargs" )
6498 int n = sizeof(safe_applets) / sizeof(safe_applets[0]);
6500 for (i = 0; i < n; i++)
6501 if (strcmp(safe_applets[i], name) == 0)
6510 int (*builtin)(int, char **);
6511 /* unsigned flags; */
6513 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6514 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6515 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6521 const struct builtincmd *cmd;
6522 struct funcnode *func;
6525 /* values of cmdtype */
6526 #define CMDUNKNOWN -1 /* no entry in table for command */
6527 #define CMDNORMAL 0 /* command is an executable program */
6528 #define CMDFUNCTION 1 /* command is a shell function */
6529 #define CMDBUILTIN 2 /* command is a shell builtin */
6531 /* action to find_command() */
6532 #define DO_ERR 0x01 /* prints errors */
6533 #define DO_ABS 0x02 /* checks absolute paths */
6534 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6535 #define DO_ALTPATH 0x08 /* using alternate path */
6536 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6538 static void find_command(char *, struct cmdentry *, int, const char *);
6541 /* ============ Hashing commands */
6544 * When commands are first encountered, they are entered in a hash table.
6545 * This ensures that a full path search will not have to be done for them
6546 * on each invocation.
6548 * We should investigate converting to a linear search, even though that
6549 * would make the command name "hash" a misnomer.
6552 #define CMDTABLESIZE 31 /* should be prime */
6553 #define ARB 1 /* actual size determined at run time */
6556 struct tblentry *next; /* next entry in hash chain */
6557 union param param; /* definition of builtin function */
6558 short cmdtype; /* index identifying command */
6559 char rehash; /* if set, cd done since entry created */
6560 char cmdname[ARB]; /* name of command */
6563 static struct tblentry *cmdtable[CMDTABLESIZE];
6564 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6567 tryexec(char *cmd, char **argv, char **envp)
6571 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
6572 if (strchr(cmd, '/') == NULL) {
6573 struct BB_applet *a;
6576 a = find_applet_by_name(cmd);
6578 if (is_safe_applet(cmd)) {
6583 exit(a->main(c - argv, argv));
6585 /* re-exec ourselves with the new arguments */
6586 execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
6587 /* If they called chroot or otherwise made the binary no longer
6588 * executable, fall through */
6596 execve(cmd, argv, envp);
6597 } while (errno == EINTR);
6599 execve(cmd, argv, envp);
6603 } else if (errno == ENOEXEC) {
6607 for (ap = argv; *ap; ap++)
6609 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6611 *ap = cmd = (char *)DEFAULT_SHELL;
6614 while ((*ap++ = *argv++))
6622 * Exec a program. Never returns. If you change this routine, you may
6623 * have to change the find_command routine as well.
6625 #define environment() listvars(VEXPORT, VUNSET, 0)
6626 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6628 shellexec(char **argv, const char *path, int idx)
6636 envp = environment();
6637 if (strchr(argv[0], '/')
6638 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
6639 || find_applet_by_name(argv[0])
6642 tryexec(argv[0], argv, envp);
6646 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6647 if (--idx < 0 && pathopt == NULL) {
6648 tryexec(cmdname, argv, envp);
6649 if (errno != ENOENT && errno != ENOTDIR)
6656 /* Map to POSIX errors */
6668 exitstatus = exerrno;
6669 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6670 argv[0], e, suppressint ));
6671 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6676 printentry(struct tblentry *cmdp)
6682 idx = cmdp->param.index;
6685 name = padvance(&path, cmdp->cmdname);
6687 } while (--idx >= 0);
6688 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6692 * Clear out command entries. The argument specifies the first entry in
6693 * PATH which has changed.
6696 clearcmdentry(int firstchange)
6698 struct tblentry **tblp;
6699 struct tblentry **pp;
6700 struct tblentry *cmdp;
6703 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6705 while ((cmdp = *pp) != NULL) {
6706 if ((cmdp->cmdtype == CMDNORMAL &&
6707 cmdp->param.index >= firstchange)
6708 || (cmdp->cmdtype == CMDBUILTIN &&
6709 builtinloc >= firstchange)
6722 * Locate a command in the command hash table. If "add" is nonzero,
6723 * add the command to the table if it is not already present. The
6724 * variable "lastcmdentry" is set to point to the address of the link
6725 * pointing to the entry, so that delete_cmd_entry can delete the
6728 * Interrupts must be off if called with add != 0.
6730 static struct tblentry **lastcmdentry;
6732 static struct tblentry *
6733 cmdlookup(const char *name, int add)
6735 unsigned int hashval;
6737 struct tblentry *cmdp;
6738 struct tblentry **pp;
6741 hashval = (unsigned char)*p << 4;
6743 hashval += (unsigned char)*p++;
6745 pp = &cmdtable[hashval % CMDTABLESIZE];
6746 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6747 if (strcmp(cmdp->cmdname, name) == 0)
6751 if (add && cmdp == NULL) {
6752 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6753 + strlen(name) + 1);
6755 cmdp->cmdtype = CMDUNKNOWN;
6756 strcpy(cmdp->cmdname, name);
6763 * Delete the command entry returned on the last lookup.
6766 delete_cmd_entry(void)
6768 struct tblentry *cmdp;
6771 cmdp = *lastcmdentry;
6772 *lastcmdentry = cmdp->next;
6773 if (cmdp->cmdtype == CMDFUNCTION)
6774 freefunc(cmdp->param.func);
6780 * Add a new command entry, replacing any existing command entry for
6781 * the same name - except special builtins.
6784 addcmdentry(char *name, struct cmdentry *entry)
6786 struct tblentry *cmdp;
6788 cmdp = cmdlookup(name, 1);
6789 if (cmdp->cmdtype == CMDFUNCTION) {
6790 freefunc(cmdp->param.func);
6792 cmdp->cmdtype = entry->cmdtype;
6793 cmdp->param = entry->u;
6798 hashcmd(int argc, char **argv)
6800 struct tblentry **pp;
6801 struct tblentry *cmdp;
6803 struct cmdentry entry;
6806 while ((c = nextopt("r")) != '\0') {
6810 if (*argptr == NULL) {
6811 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6812 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6813 if (cmdp->cmdtype == CMDNORMAL)
6820 while ((name = *argptr) != NULL) {
6821 cmdp = cmdlookup(name, 0);
6823 && (cmdp->cmdtype == CMDNORMAL
6824 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6826 find_command(name, &entry, DO_ERR, pathval());
6827 if (entry.cmdtype == CMDUNKNOWN)
6835 * Called when a cd is done. Marks all commands so the next time they
6836 * are executed they will be rehashed.
6841 struct tblentry **pp;
6842 struct tblentry *cmdp;
6844 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6845 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6846 if (cmdp->cmdtype == CMDNORMAL || (
6847 cmdp->cmdtype == CMDBUILTIN &&
6848 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6857 * Fix command hash table when PATH changed.
6858 * Called before PATH is changed. The argument is the new value of PATH;
6859 * pathval() still returns the old value at this point.
6860 * Called with interrupts off.
6863 changepath(const char *newval)
6865 const char *old, *new;
6872 firstchange = 9999; /* assume no change */
6878 if ((*old == '\0' && *new == ':')
6879 || (*old == ':' && *new == '\0'))
6881 old = new; /* ignore subsequent differences */
6885 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6892 if (builtinloc < 0 && idx_bltin >= 0)
6893 builtinloc = idx_bltin; /* zap builtins */
6894 if (builtinloc >= 0 && idx_bltin < 0)
6896 clearcmdentry(firstchange);
6897 builtinloc = idx_bltin;
6912 #define TENDBQUOTE 12
6930 /* first char is indicating which tokens mark the end of a list */
6931 static const char *const tokname_array[] = {
6945 #define KWDOFFSET 13
6946 /* the following are keywords */
6968 static char buf[16];
6972 sprintf(buf + (tok >= TSEMI), "%s%c",
6973 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6977 /* Wrapper around strcmp for qsort/bsearch/... */
6979 pstrcmp(const void *a, const void *b)
6981 return strcmp((const char *) a, (*(const char *const *) b) + 1);
6984 static const char *const *
6985 findkwd(const char *s)
6987 return bsearch(s, tokname_array + KWDOFFSET,
6988 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
6989 sizeof(const char *), pstrcmp);
6993 * Locate and print what a word is...
6995 #if ENABLE_ASH_CMDCMD
6997 describe_command(char *command, int describe_command_verbose)
6999 #define describe_command_verbose 1
7001 describe_command(char *command)
7004 struct cmdentry entry;
7005 struct tblentry *cmdp;
7006 #if ENABLE_ASH_ALIAS
7007 const struct alias *ap;
7009 const char *path = pathval();
7011 if (describe_command_verbose) {
7015 /* First look at the keywords */
7016 if (findkwd(command)) {
7017 out1str(describe_command_verbose ? " is a shell keyword" : command);
7021 #if ENABLE_ASH_ALIAS
7022 /* Then look at the aliases */
7023 ap = lookupalias(command, 0);
7025 if (describe_command_verbose) {
7026 out1fmt(" is an alias for %s", ap->val);
7035 /* Then check if it is a tracked alias */
7036 cmdp = cmdlookup(command, 0);
7038 entry.cmdtype = cmdp->cmdtype;
7039 entry.u = cmdp->param;
7041 /* Finally use brute force */
7042 find_command(command, &entry, DO_ABS, path);
7045 switch (entry.cmdtype) {
7047 int j = entry.u.index;
7053 p = padvance(&path, command);
7057 if (describe_command_verbose) {
7059 (cmdp ? " a tracked alias for" : nullstr), p
7068 if (describe_command_verbose) {
7069 out1str(" is a shell function");
7076 if (describe_command_verbose) {
7077 out1fmt(" is a %sshell builtin",
7078 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7079 "special " : nullstr
7087 if (describe_command_verbose) {
7088 out1str(": not found\n");
7093 outstr("\n", stdout);
7098 typecmd(int argc, char **argv)
7103 for (i = 1; i < argc; i++) {
7104 #if ENABLE_ASH_CMDCMD
7105 err |= describe_command(argv[i], 1);
7107 err |= describe_command(argv[i]);
7113 #if ENABLE_ASH_CMDCMD
7115 commandcmd(int argc, char **argv)
7123 while ((c = nextopt("pvV")) != '\0')
7125 verify |= VERIFY_VERBOSE;
7127 verify |= VERIFY_BRIEF;
7133 return describe_command(*argptr, verify - VERIFY_BRIEF);
7140 /* ============ eval.c */
7142 static int funcblocksize; /* size of structures in function */
7143 static int funcstringsize; /* size of strings in node */
7144 static void *funcblock; /* block to allocate function from */
7145 static char *funcstring; /* block to allocate strings from */
7147 /* flags in argument to evaltree */
7148 #define EV_EXIT 01 /* exit after evaluating tree */
7149 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7150 #define EV_BACKCMD 04 /* command executing within back quotes */
7152 static const short nodesize[26] = {
7153 SHELL_ALIGN(sizeof(struct ncmd)),
7154 SHELL_ALIGN(sizeof(struct npipe)),
7155 SHELL_ALIGN(sizeof(struct nredir)),
7156 SHELL_ALIGN(sizeof(struct nredir)),
7157 SHELL_ALIGN(sizeof(struct nredir)),
7158 SHELL_ALIGN(sizeof(struct nbinary)),
7159 SHELL_ALIGN(sizeof(struct nbinary)),
7160 SHELL_ALIGN(sizeof(struct nbinary)),
7161 SHELL_ALIGN(sizeof(struct nif)),
7162 SHELL_ALIGN(sizeof(struct nbinary)),
7163 SHELL_ALIGN(sizeof(struct nbinary)),
7164 SHELL_ALIGN(sizeof(struct nfor)),
7165 SHELL_ALIGN(sizeof(struct ncase)),
7166 SHELL_ALIGN(sizeof(struct nclist)),
7167 SHELL_ALIGN(sizeof(struct narg)),
7168 SHELL_ALIGN(sizeof(struct narg)),
7169 SHELL_ALIGN(sizeof(struct nfile)),
7170 SHELL_ALIGN(sizeof(struct nfile)),
7171 SHELL_ALIGN(sizeof(struct nfile)),
7172 SHELL_ALIGN(sizeof(struct nfile)),
7173 SHELL_ALIGN(sizeof(struct nfile)),
7174 SHELL_ALIGN(sizeof(struct ndup)),
7175 SHELL_ALIGN(sizeof(struct ndup)),
7176 SHELL_ALIGN(sizeof(struct nhere)),
7177 SHELL_ALIGN(sizeof(struct nhere)),
7178 SHELL_ALIGN(sizeof(struct nnot)),
7181 static void calcsize(union node *n);
7184 sizenodelist(struct nodelist *lp)
7187 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7194 calcsize(union node *n)
7198 funcblocksize += nodesize[n->type];
7201 calcsize(n->ncmd.redirect);
7202 calcsize(n->ncmd.args);
7203 calcsize(n->ncmd.assign);
7206 sizenodelist(n->npipe.cmdlist);
7211 calcsize(n->nredir.redirect);
7212 calcsize(n->nredir.n);
7219 calcsize(n->nbinary.ch2);
7220 calcsize(n->nbinary.ch1);
7223 calcsize(n->nif.elsepart);
7224 calcsize(n->nif.ifpart);
7225 calcsize(n->nif.test);
7228 funcstringsize += strlen(n->nfor.var) + 1;
7229 calcsize(n->nfor.body);
7230 calcsize(n->nfor.args);
7233 calcsize(n->ncase.cases);
7234 calcsize(n->ncase.expr);
7237 calcsize(n->nclist.body);
7238 calcsize(n->nclist.pattern);
7239 calcsize(n->nclist.next);
7243 sizenodelist(n->narg.backquote);
7244 funcstringsize += strlen(n->narg.text) + 1;
7245 calcsize(n->narg.next);
7252 calcsize(n->nfile.fname);
7253 calcsize(n->nfile.next);
7257 calcsize(n->ndup.vname);
7258 calcsize(n->ndup.next);
7262 calcsize(n->nhere.doc);
7263 calcsize(n->nhere.next);
7266 calcsize(n->nnot.com);
7272 nodeckstrdup(char *s)
7274 char *rtn = funcstring;
7276 strcpy(funcstring, s);
7277 funcstring += strlen(s) + 1;
7281 static union node *copynode(union node *);
7283 static struct nodelist *
7284 copynodelist(struct nodelist *lp)
7286 struct nodelist *start;
7287 struct nodelist **lpp;
7292 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7293 (*lpp)->n = copynode(lp->n);
7295 lpp = &(*lpp)->next;
7302 copynode(union node *n)
7309 funcblock = (char *) funcblock + nodesize[n->type];
7313 new->ncmd.redirect = copynode(n->ncmd.redirect);
7314 new->ncmd.args = copynode(n->ncmd.args);
7315 new->ncmd.assign = copynode(n->ncmd.assign);
7318 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7319 new->npipe.backgnd = n->npipe.backgnd;
7324 new->nredir.redirect = copynode(n->nredir.redirect);
7325 new->nredir.n = copynode(n->nredir.n);
7332 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7333 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7336 new->nif.elsepart = copynode(n->nif.elsepart);
7337 new->nif.ifpart = copynode(n->nif.ifpart);
7338 new->nif.test = copynode(n->nif.test);
7341 new->nfor.var = nodeckstrdup(n->nfor.var);
7342 new->nfor.body = copynode(n->nfor.body);
7343 new->nfor.args = copynode(n->nfor.args);
7346 new->ncase.cases = copynode(n->ncase.cases);
7347 new->ncase.expr = copynode(n->ncase.expr);
7350 new->nclist.body = copynode(n->nclist.body);
7351 new->nclist.pattern = copynode(n->nclist.pattern);
7352 new->nclist.next = copynode(n->nclist.next);
7356 new->narg.backquote = copynodelist(n->narg.backquote);
7357 new->narg.text = nodeckstrdup(n->narg.text);
7358 new->narg.next = copynode(n->narg.next);
7365 new->nfile.fname = copynode(n->nfile.fname);
7366 new->nfile.fd = n->nfile.fd;
7367 new->nfile.next = copynode(n->nfile.next);
7371 new->ndup.vname = copynode(n->ndup.vname);
7372 new->ndup.dupfd = n->ndup.dupfd;
7373 new->ndup.fd = n->ndup.fd;
7374 new->ndup.next = copynode(n->ndup.next);
7378 new->nhere.doc = copynode(n->nhere.doc);
7379 new->nhere.fd = n->nhere.fd;
7380 new->nhere.next = copynode(n->nhere.next);
7383 new->nnot.com = copynode(n->nnot.com);
7386 new->type = n->type;
7391 * Make a copy of a parse tree.
7393 static struct funcnode *
7394 copyfunc(union node *n)
7399 funcblocksize = offsetof(struct funcnode, n);
7402 blocksize = funcblocksize;
7403 f = ckmalloc(blocksize + funcstringsize);
7404 funcblock = (char *) f + offsetof(struct funcnode, n);
7405 funcstring = (char *) f + blocksize;
7412 * Define a shell function.
7415 defun(char *name, union node *func)
7417 struct cmdentry entry;
7420 entry.cmdtype = CMDFUNCTION;
7421 entry.u.func = copyfunc(func);
7422 addcmdentry(name, &entry);
7426 static int evalskip; /* set if we are skipping commands */
7427 /* reasons for skipping commands (see comment on breakcmd routine) */
7428 #define SKIPBREAK (1 << 0)
7429 #define SKIPCONT (1 << 1)
7430 #define SKIPFUNC (1 << 2)
7431 #define SKIPFILE (1 << 3)
7432 #define SKIPEVAL (1 << 4)
7433 static int skipcount; /* number of levels to skip */
7434 static int funcnest; /* depth of function calls */
7436 /* forward decl way out to parsing code - dotrap needs it */
7437 static int evalstring(char *s, int mask);
7440 * Called to execute a trap. Perhaps we should avoid entering new trap
7441 * handlers while we are executing a trap handler.
7452 savestatus = exitstatus;
7456 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7464 skip = evalstring(p, SKIPEVAL);
7465 exitstatus = savestatus;
7473 /* forward declarations - evaluation is fairly recursive business... */
7474 static void evalloop(union node *, int);
7475 static void evalfor(union node *, int);
7476 static void evalcase(union node *, int);
7477 static void evalsubshell(union node *, int);
7478 static void expredir(union node *);
7479 static void evalpipe(union node *, int);
7480 static void evalcommand(union node *, int);
7481 static int evalbltin(const struct builtincmd *, int, char **);
7482 static void prehash(union node *);
7485 * Evaluate a parse tree. The value is left in the global variable
7489 evaltree(union node *n, int flags)
7492 void (*evalfn)(union node *, int);
7496 TRACE(("evaltree(NULL) called\n"));
7499 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7500 getpid(), n, n->type, flags));
7504 out1fmt("Node type = %d\n", n->type);
7509 evaltree(n->nnot.com, EV_TESTED);
7510 status = !exitstatus;
7513 expredir(n->nredir.redirect);
7514 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7516 evaltree(n->nredir.n, flags & EV_TESTED);
7517 status = exitstatus;
7522 evalfn = evalcommand;
7524 if (eflag && !(flags & EV_TESTED))
7536 evalfn = evalsubshell;
7548 #error NAND + 1 != NOR
7550 #if NOR + 1 != NSEMI
7551 #error NOR + 1 != NSEMI
7553 isor = n->type - NAND;
7556 (flags | ((isor >> 1) - 1)) & EV_TESTED
7558 if (!exitstatus == isor)
7570 evaltree(n->nif.test, EV_TESTED);
7573 if (exitstatus == 0) {
7576 } else if (n->nif.elsepart) {
7577 n = n->nif.elsepart;
7582 defun(n->narg.text, n->narg.next);
7586 exitstatus = status;
7590 if ((checkexit & exitstatus))
7591 evalskip |= SKIPEVAL;
7592 else if (pendingsig && dotrap())
7595 if (flags & EV_EXIT) {
7597 raise_exception(EXEXIT);
7601 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7604 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7606 static int loopnest; /* current loop nesting level */
7609 evalloop(union node *n, int flags)
7619 evaltree(n->nbinary.ch1, EV_TESTED);
7622 if (evalskip == SKIPCONT && --skipcount <= 0) {
7626 if (evalskip == SKIPBREAK && --skipcount <= 0)
7631 if (n->type != NWHILE)
7635 evaltree(n->nbinary.ch2, flags);
7636 status = exitstatus;
7641 exitstatus = status;
7645 evalfor(union node *n, int flags)
7647 struct arglist arglist;
7650 struct stackmark smark;
7652 setstackmark(&smark);
7653 arglist.lastp = &arglist.list;
7654 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7655 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7660 *arglist.lastp = NULL;
7665 for (sp = arglist.list; sp; sp = sp->next) {
7666 setvar(n->nfor.var, sp->text, 0);
7667 evaltree(n->nfor.body, flags);
7669 if (evalskip == SKIPCONT && --skipcount <= 0) {
7673 if (evalskip == SKIPBREAK && --skipcount <= 0)
7680 popstackmark(&smark);
7684 evalcase(union node *n, int flags)
7688 struct arglist arglist;
7689 struct stackmark smark;
7691 setstackmark(&smark);
7692 arglist.lastp = &arglist.list;
7693 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7695 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7696 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7697 if (casematch(patp, arglist.list->text)) {
7698 if (evalskip == 0) {
7699 evaltree(cp->nclist.body, flags);
7706 popstackmark(&smark);
7710 * Kick off a subshell to evaluate a tree.
7713 evalsubshell(union node *n, int flags)
7716 int backgnd = (n->type == NBACKGND);
7719 expredir(n->nredir.redirect);
7720 if (!backgnd && flags & EV_EXIT && !trap[0])
7724 if (forkshell(jp, n, backgnd) == 0) {
7728 flags &=~ EV_TESTED;
7730 redirect(n->nredir.redirect, 0);
7731 evaltreenr(n->nredir.n, flags);
7736 status = waitforjob(jp);
7737 exitstatus = status;
7742 * Compute the names of the files in a redirection list.
7744 static void fixredir(union node *, const char *, int);
7746 expredir(union node *n)
7750 for (redir = n; redir; redir = redir->nfile.next) {
7753 memset(&fn, 0, sizeof(fn));
7754 fn.lastp = &fn.list;
7755 switch (redir->type) {
7761 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7762 redir->nfile.expfname = fn.list->text;
7766 if (redir->ndup.vname) {
7767 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7768 if (fn.list == NULL)
7769 ash_msg_and_raise_error("redir error");
7770 fixredir(redir, fn.list->text, 1);
7778 * Evaluate a pipeline. All the processes in the pipeline are children
7779 * of the process creating the pipeline. (This differs from some versions
7780 * of the shell, which make the last process in a pipeline the parent
7784 evalpipe(union node *n, int flags)
7787 struct nodelist *lp;
7792 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7794 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7798 jp = makejob(n, pipelen);
7800 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7804 if (pipe(pip) < 0) {
7806 ash_msg_and_raise_error("pipe call failed");
7809 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7822 evaltreenr(lp->n, flags);
7830 if (n->npipe.backgnd == 0) {
7831 exitstatus = waitforjob(jp);
7832 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7838 * Controls whether the shell is interactive or not.
7841 setinteractive(int on)
7843 static int is_interactive;
7845 if (++on == is_interactive)
7847 is_interactive = on;
7851 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7852 if (is_interactive > 1) {
7853 /* Looks like they want an interactive shell */
7854 static smallint do_banner;
7859 "%s Built-in shell (ash)\n"
7860 "Enter 'help' for a list of built-in commands."
7869 #if ENABLE_FEATURE_EDITING_VI
7870 #define setvimode(on) do { \
7871 if (on) line_input_state->flags |= VI_MODE; \
7872 else line_input_state->flags &= ~VI_MODE; \
7875 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7884 setinteractive(iflag);
7889 static struct localvar *localvars;
7892 * Called after a function returns.
7893 * Interrupts must be off.
7898 struct localvar *lvp;
7901 while ((lvp = localvars) != NULL) {
7902 localvars = lvp->next;
7904 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7905 if (vp == NULL) { /* $- saved */
7906 memcpy(optlist, lvp->text, sizeof(optlist));
7907 free((char*)lvp->text);
7909 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7913 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7914 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7915 free((char*)vp->text);
7916 vp->flags = lvp->flags;
7917 vp->text = lvp->text;
7924 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7926 volatile struct shparam saveparam;
7927 struct localvar *volatile savelocalvars;
7928 struct jmploc *volatile savehandler;
7929 struct jmploc jmploc;
7932 saveparam = shellparam;
7933 savelocalvars = localvars;
7934 e = setjmp(jmploc.loc);
7939 savehandler = exception_handler;
7940 exception_handler = &jmploc;
7942 shellparam.malloc = 0;
7946 shellparam.nparam = argc - 1;
7947 shellparam.p = argv + 1;
7948 #if ENABLE_ASH_GETOPTS
7949 shellparam.optind = 1;
7950 shellparam.optoff = -1;
7952 evaltree(&func->n, flags & EV_TESTED);
7958 localvars = savelocalvars;
7959 freeparam(&shellparam);
7960 shellparam = saveparam;
7961 exception_handler = savehandler;
7963 evalskip &= ~SKIPFUNC;
7967 #if ENABLE_ASH_CMDCMD
7969 parse_command_args(char **argv, const char **path)
7982 if (c == '-' && !*cp) {
7992 /* run 'typecmd' for other options */
8003 * Make a variable a local variable. When a variable is made local, it's
8004 * value and flags are saved in a localvar structure. The saved values
8005 * will be restored when the shell function returns. We handle the name
8006 * "-" as a special case.
8011 struct localvar *lvp;
8016 lvp = ckmalloc(sizeof(struct localvar));
8017 if (LONE_DASH(name)) {
8019 p = ckmalloc(sizeof(optlist));
8020 lvp->text = memcpy(p, optlist, sizeof(optlist));
8025 vpp = hashvar(name);
8026 vp = *findvar(vpp, name);
8027 eq = strchr(name, '=');
8030 setvareq(name, VSTRFIXED);
8032 setvar(name, NULL, VSTRFIXED);
8033 vp = *vpp; /* the new variable */
8034 lvp->flags = VUNSET;
8036 lvp->text = vp->text;
8037 lvp->flags = vp->flags;
8038 vp->flags |= VSTRFIXED|VTEXTFIXED;
8044 lvp->next = localvars;
8050 * The "local" command.
8053 localcmd(int argc, char **argv)
8058 while ((name = *argv++) != NULL) {
8065 falsecmd(int argc, char **argv)
8071 truecmd(int argc, char **argv)
8077 execcmd(int argc, char **argv)
8080 iflag = 0; /* exit on error */
8083 shellexec(argv + 1, pathval(), 0);
8089 * The return command.
8092 returncmd(int argc, char **argv)
8095 * If called outside a function, do what ksh does;
8096 * skip the rest of the file.
8098 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8099 return argv[1] ? number(argv[1]) : exitstatus;
8102 /* Forward declarations for builtintab[] */
8103 static int breakcmd(int, char **);
8104 static int dotcmd(int, char **);
8105 static int evalcmd(int, char **);
8106 #if ENABLE_ASH_BUILTIN_ECHO
8107 static int echocmd(int, char **);
8109 #if ENABLE_ASH_BUILTIN_TEST
8110 static int testcmd(int, char **);
8112 static int exitcmd(int, char **);
8113 static int exportcmd(int, char **);
8114 #if ENABLE_ASH_GETOPTS
8115 static int getoptscmd(int, char **);
8117 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8118 static int helpcmd(int argc, char **argv);
8120 #if ENABLE_ASH_MATH_SUPPORT
8121 static int letcmd(int, char **);
8123 static int readcmd(int, char **);
8124 static int setcmd(int, char **);
8125 static int shiftcmd(int, char **);
8126 static int timescmd(int, char **);
8127 static int trapcmd(int, char **);
8128 static int umaskcmd(int, char **);
8129 static int unsetcmd(int, char **);
8130 static int ulimitcmd(int, char **);
8132 #define BUILTIN_NOSPEC "0"
8133 #define BUILTIN_SPECIAL "1"
8134 #define BUILTIN_REGULAR "2"
8135 #define BUILTIN_SPEC_REG "3"
8136 #define BUILTIN_ASSIGN "4"
8137 #define BUILTIN_SPEC_ASSG "5"
8138 #define BUILTIN_REG_ASSG "6"
8139 #define BUILTIN_SPEC_REG_ASSG "7"
8141 /* make sure to keep these in proper order since it is searched via bsearch() */
8142 static const struct builtincmd builtintab[] = {
8143 { BUILTIN_SPEC_REG ".", dotcmd },
8144 { BUILTIN_SPEC_REG ":", truecmd },
8145 #if ENABLE_ASH_BUILTIN_TEST
8146 { BUILTIN_REGULAR "[", testcmd },
8147 { BUILTIN_REGULAR "[[", testcmd },
8149 #if ENABLE_ASH_ALIAS
8150 { BUILTIN_REG_ASSG "alias", aliascmd },
8153 { BUILTIN_REGULAR "bg", fg_bgcmd },
8155 { BUILTIN_SPEC_REG "break", breakcmd },
8156 { BUILTIN_REGULAR "cd", cdcmd },
8157 { BUILTIN_NOSPEC "chdir", cdcmd },
8158 #if ENABLE_ASH_CMDCMD
8159 { BUILTIN_REGULAR "command", commandcmd },
8161 { BUILTIN_SPEC_REG "continue", breakcmd },
8162 #if ENABLE_ASH_BUILTIN_ECHO
8163 { BUILTIN_REGULAR "echo", echocmd },
8165 { BUILTIN_SPEC_REG "eval", evalcmd },
8166 { BUILTIN_SPEC_REG "exec", execcmd },
8167 { BUILTIN_SPEC_REG "exit", exitcmd },
8168 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8169 { BUILTIN_REGULAR "false", falsecmd },
8171 { BUILTIN_REGULAR "fg", fg_bgcmd },
8173 #if ENABLE_ASH_GETOPTS
8174 { BUILTIN_REGULAR "getopts", getoptscmd },
8176 { BUILTIN_NOSPEC "hash", hashcmd },
8177 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8178 { BUILTIN_NOSPEC "help", helpcmd },
8181 { BUILTIN_REGULAR "jobs", jobscmd },
8182 { BUILTIN_REGULAR "kill", killcmd },
8184 #if ENABLE_ASH_MATH_SUPPORT
8185 { BUILTIN_NOSPEC "let", letcmd },
8187 { BUILTIN_ASSIGN "local", localcmd },
8188 { BUILTIN_NOSPEC "pwd", pwdcmd },
8189 { BUILTIN_REGULAR "read", readcmd },
8190 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8191 { BUILTIN_SPEC_REG "return", returncmd },
8192 { BUILTIN_SPEC_REG "set", setcmd },
8193 { BUILTIN_SPEC_REG "shift", shiftcmd },
8194 { BUILTIN_SPEC_REG "source", dotcmd },
8195 #if ENABLE_ASH_BUILTIN_TEST
8196 { BUILTIN_REGULAR "test", testcmd },
8198 { BUILTIN_SPEC_REG "times", timescmd },
8199 { BUILTIN_SPEC_REG "trap", trapcmd },
8200 { BUILTIN_REGULAR "true", truecmd },
8201 { BUILTIN_NOSPEC "type", typecmd },
8202 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8203 { BUILTIN_REGULAR "umask", umaskcmd },
8204 #if ENABLE_ASH_ALIAS
8205 { BUILTIN_REGULAR "unalias", unaliascmd },
8207 { BUILTIN_SPEC_REG "unset", unsetcmd },
8208 { BUILTIN_REGULAR "wait", waitcmd },
8211 #define NUMBUILTINS (sizeof(builtintab) / sizeof(builtintab[0]))
8213 #define COMMANDCMD (builtintab + 5 + \
8214 2 * ENABLE_ASH_BUILTIN_TEST + \
8215 ENABLE_ASH_ALIAS + \
8216 ENABLE_ASH_JOB_CONTROL)
8217 #define EXECCMD (builtintab + 7 + \
8218 2 * ENABLE_ASH_BUILTIN_TEST + \
8219 ENABLE_ASH_ALIAS + \
8220 ENABLE_ASH_JOB_CONTROL + \
8221 ENABLE_ASH_CMDCMD + \
8222 ENABLE_ASH_BUILTIN_ECHO)
8225 * Search the table of builtin commands.
8227 static struct builtincmd *
8228 find_builtin(const char *name)
8230 struct builtincmd *bp;
8233 name, builtintab, NUMBUILTINS, sizeof(builtintab[0]),
8240 * Execute a simple command.
8242 static int back_exitstatus; /* exit status of backquoted command */
8244 isassignment(const char *p)
8246 const char *q = endofname(p);
8252 bltincmd(int argc, char **argv)
8254 /* Preserve exitstatus of a previous possible redirection
8255 * as POSIX mandates */
8256 return back_exitstatus;
8259 evalcommand(union node *cmd, int flags)
8261 static const struct builtincmd bltin = {
8264 struct stackmark smark;
8266 struct arglist arglist;
8267 struct arglist varlist;
8270 const struct strlist *sp;
8271 struct cmdentry cmdentry;
8279 struct builtincmd *bcmd;
8280 int pseudovarflag = 0;
8282 /* First expand the arguments. */
8283 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8284 setstackmark(&smark);
8285 back_exitstatus = 0;
8287 cmdentry.cmdtype = CMDBUILTIN;
8288 cmdentry.u.cmd = &bltin;
8289 varlist.lastp = &varlist.list;
8290 *varlist.lastp = NULL;
8291 arglist.lastp = &arglist.list;
8292 *arglist.lastp = NULL;
8295 if (cmd->ncmd.args) {
8296 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8297 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8300 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8301 struct strlist **spp;
8303 spp = arglist.lastp;
8304 if (pseudovarflag && isassignment(argp->narg.text))
8305 expandarg(argp, &arglist, EXP_VARTILDE);
8307 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8309 for (sp = *spp; sp; sp = sp->next)
8313 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8314 for (sp = arglist.list; sp; sp = sp->next) {
8315 TRACE(("evalcommand arg: %s\n", sp->text));
8316 *nargv++ = sp->text;
8321 if (iflag && funcnest == 0 && argc > 0)
8322 lastarg = nargv[-1];
8325 expredir(cmd->ncmd.redirect);
8326 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8329 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8330 struct strlist **spp;
8333 spp = varlist.lastp;
8334 expandarg(argp, &varlist, EXP_VARTILDE);
8337 * Modify the command lookup path, if a PATH= assignment
8341 if (varequal(p, path))
8345 /* Print the command if xflag is set. */
8348 const char *p = " %s";
8351 dprintf(preverrout_fd, p, expandstr(ps4val()));
8354 for (n = 0; n < 2; n++) {
8356 dprintf(preverrout_fd, p, sp->text);
8364 full_write(preverrout_fd, "\n", 1);
8370 /* Now locate the command. */
8372 const char *oldpath;
8373 int cmd_flag = DO_ERR;
8378 find_command(argv[0], &cmdentry, cmd_flag, path);
8379 if (cmdentry.cmdtype == CMDUNKNOWN) {
8385 /* implement bltin and command here */
8386 if (cmdentry.cmdtype != CMDBUILTIN)
8389 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8390 if (cmdentry.u.cmd == EXECCMD)
8392 #if ENABLE_ASH_CMDCMD
8393 if (cmdentry.u.cmd == COMMANDCMD) {
8395 nargv = parse_command_args(argv, &path);
8398 argc -= nargv - argv;
8400 cmd_flag |= DO_NOFUNC;
8408 /* We have a redirection error. */
8410 raise_exception(EXERROR);
8412 exitstatus = status;
8416 /* Execute the command. */
8417 switch (cmdentry.cmdtype) {
8419 /* Fork off a child process if necessary. */
8420 if (!(flags & EV_EXIT) || trap[0]) {
8422 jp = makejob(cmd, 1);
8423 if (forkshell(jp, cmd, FORK_FG) != 0) {
8424 exitstatus = waitforjob(jp);
8430 listsetvar(varlist.list, VEXPORT|VSTACK);
8431 shellexec(argv, path, cmdentry.u.index);
8435 cmdenviron = varlist.list;
8437 struct strlist *list = cmdenviron;
8439 if (spclbltin > 0 || argc == 0) {
8441 if (cmd_is_exec && argc > 1)
8444 listsetvar(list, i);
8446 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8461 exit_status = j + 128;
8462 exitstatus = exit_status;
8464 if (i == EXINT || spclbltin > 0) {
8466 longjmp(exception_handler->loc, 1);
8473 listsetvar(varlist.list, 0);
8474 if (evalfun(cmdentry.u.func, argc, argv, flags))
8480 popredir(cmd_is_exec);
8482 /* dsl: I think this is intended to be used to support
8483 * '_' in 'vi' command mode during line editing...
8484 * However I implemented that within libedit itself.
8486 setvar("_", lastarg, 0);
8487 popstackmark(&smark);
8491 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8493 char *volatile savecmdname;
8494 struct jmploc *volatile savehandler;
8495 struct jmploc jmploc;
8498 savecmdname = commandname;
8499 i = setjmp(jmploc.loc);
8502 savehandler = exception_handler;
8503 exception_handler = &jmploc;
8504 commandname = argv[0];
8506 optptr = NULL; /* initialize nextopt */
8507 exitstatus = (*cmd->builtin)(argc, argv);
8508 flush_stdout_stderr();
8510 exitstatus |= ferror(stdout);
8512 commandname = savecmdname;
8514 exception_handler = savehandler;
8520 goodname(const char *p)
8522 return !*endofname(p);
8527 * Search for a command. This is called before we fork so that the
8528 * location of the command will be available in the parent as well as
8529 * the child. The check for "goodname" is an overly conservative
8530 * check that the name will not be subject to expansion.
8533 prehash(union node *n)
8535 struct cmdentry entry;
8537 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8538 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8542 /* ============ Builtin commands
8544 * Builtin commands whose functions are closely tied to evaluation
8545 * are implemented here.
8549 * Handle break and continue commands. Break, continue, and return are
8550 * all handled by setting the evalskip flag. The evaluation routines
8551 * above all check this flag, and if it is set they start skipping
8552 * commands rather than executing them. The variable skipcount is
8553 * the number of loops to break/continue, or the number of function
8554 * levels to return. (The latter is always 1.) It should probably
8555 * be an error to break out of more loops than exist, but it isn't
8556 * in the standard shell so we don't make it one here.
8559 breakcmd(int argc, char **argv)
8561 int n = argc > 1 ? number(argv[1]) : 1;
8564 ash_msg_and_raise_error(illnum, argv[1]);
8568 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8575 /* ============ input.c
8577 * This implements the input routines used by the parser.
8580 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8583 INPUT_PUSH_FILE = 1,
8584 INPUT_NOFILE_OK = 2,
8588 * NEOF is returned by parsecmd when it encounters an end of file. It
8589 * must be distinct from NULL, so we use the address of a variable that
8590 * happens to be handy.
8592 static int plinno = 1; /* input line number */
8593 /* number of characters left in input buffer */
8594 static int parsenleft; /* copy of parsefile->nleft */
8595 static int parselleft; /* copy of parsefile->lleft */
8596 /* next character in input buffer */
8597 static char *parsenextc; /* copy of parsefile->nextc */
8599 static int checkkwd;
8600 /* values of checkkwd variable */
8601 #define CHKALIAS 0x1
8608 struct strpush *sp = parsefile->strpush;
8611 #if ENABLE_ASH_ALIAS
8613 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8614 checkkwd |= CHKALIAS;
8616 if (sp->string != sp->ap->val) {
8619 sp->ap->flag &= ~ALIASINUSE;
8620 if (sp->ap->flag & ALIASDEAD) {
8621 unalias(sp->ap->name);
8625 parsenextc = sp->prevstring;
8626 parsenleft = sp->prevnleft;
8627 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8628 parsefile->strpush = sp->prev;
8629 if (sp != &(parsefile->basestrpush))
8638 char *buf = parsefile->buf;
8642 #if ENABLE_FEATURE_EDITING
8643 if (!iflag || parsefile->fd)
8644 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8646 #if ENABLE_FEATURE_TAB_COMPLETION
8647 line_input_state->path_lookup = pathval();
8649 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8651 /* Ctrl+C pressed */
8660 if (nr < 0 && errno == 0) {
8661 /* Ctrl+D presend */
8666 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8670 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8671 int flags = fcntl(0, F_GETFL, 0);
8672 if (flags >= 0 && flags & O_NONBLOCK) {
8673 flags &=~ O_NONBLOCK;
8674 if (fcntl(0, F_SETFL, flags) >= 0) {
8675 out2str("sh: turning off NDELAY mode\n");
8685 * Refill the input buffer and return the next input character:
8687 * 1) If a string was pushed back on the input, pop it;
8688 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8689 * from a string so we can't refill the buffer, return EOF.
8690 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8691 * 4) Process input up to the next newline, deleting nul characters.
8700 while (parsefile->strpush) {
8701 #if ENABLE_ASH_ALIAS
8702 if (parsenleft == -1 && parsefile->strpush->ap &&
8703 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8708 if (--parsenleft >= 0)
8709 return signed_char2int(*parsenextc++);
8711 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8713 flush_stdout_stderr();
8720 parselleft = parsenleft = EOF_NLEFT;
8727 /* delete nul characters */
8735 memmove(q, q + 1, more);
8739 parsenleft = q - parsenextc - 1;
8745 parsenleft = q - parsenextc - 1;
8757 out2str(parsenextc);
8762 return signed_char2int(*parsenextc++);
8765 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8769 return pgetc_as_macro();
8772 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8773 #define pgetc_macro() pgetc()
8775 #define pgetc_macro() pgetc_as_macro()
8779 * Same as pgetc(), but ignores PEOA.
8781 #if ENABLE_ASH_ALIAS
8789 } while (c == PEOA);
8796 return pgetc_macro();
8801 * Read a line from the script.
8804 pfgets(char *line, int len)
8810 while (--nleft > 0) {
8826 * Undo the last call to pgetc. Only one character may be pushed back.
8827 * PEOF may be pushed back.
8837 * Push a string back onto the input at this current parsefile level.
8838 * We handle aliases this way.
8841 pushstring(char *s, void *ap)
8848 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8849 if (parsefile->strpush) {
8850 sp = ckmalloc(sizeof(struct strpush));
8851 sp->prev = parsefile->strpush;
8852 parsefile->strpush = sp;
8854 sp = parsefile->strpush = &(parsefile->basestrpush);
8855 sp->prevstring = parsenextc;
8856 sp->prevnleft = parsenleft;
8857 #if ENABLE_ASH_ALIAS
8858 sp->ap = (struct alias *)ap;
8860 ((struct alias *)ap)->flag |= ALIASINUSE;
8870 * To handle the "." command, a stack of input files is used. Pushfile
8871 * adds a new entry to the stack and popfile restores the previous level.
8876 struct parsefile *pf;
8878 parsefile->nleft = parsenleft;
8879 parsefile->lleft = parselleft;
8880 parsefile->nextc = parsenextc;
8881 parsefile->linno = plinno;
8882 pf = ckmalloc(sizeof(*pf));
8883 pf->prev = parsefile;
8886 pf->basestrpush.prev = NULL;
8893 struct parsefile *pf = parsefile;
8902 parsefile = pf->prev;
8904 parsenleft = parsefile->nleft;
8905 parselleft = parsefile->lleft;
8906 parsenextc = parsefile->nextc;
8907 plinno = parsefile->linno;
8912 * Return to top level.
8917 while (parsefile != &basepf)
8922 * Close the file(s) that the shell is reading commands from. Called
8923 * after a fork is done.
8929 if (parsefile->fd > 0) {
8930 close(parsefile->fd);
8936 * Like setinputfile, but takes an open file descriptor. Call this with
8940 setinputfd(int fd, int push)
8942 fcntl(fd, F_SETFD, FD_CLOEXEC);
8948 if (parsefile->buf == NULL)
8949 parsefile->buf = ckmalloc(IBUFSIZ);
8950 parselleft = parsenleft = 0;
8955 * Set the input to take input from a file. If push is set, push the
8956 * old input onto the stack first.
8959 setinputfile(const char *fname, int flags)
8965 fd = open(fname, O_RDONLY);
8967 if (flags & INPUT_NOFILE_OK)
8969 ash_msg_and_raise_error("can't open %s", fname);
8972 fd2 = copyfd(fd, 10);
8975 ash_msg_and_raise_error("out of file descriptors");
8978 setinputfd(fd, flags & INPUT_PUSH_FILE);
8985 * Like setinputfile, but takes input from a string.
8988 setinputstring(char *string)
8992 parsenextc = string;
8993 parsenleft = strlen(string);
8994 parsefile->buf = NULL;
9000 /* ============ mail.c
9002 * Routines to check for mail.
9007 #define MAXMBOXES 10
9009 /* times of mailboxes */
9010 static time_t mailtime[MAXMBOXES];
9011 /* Set if MAIL or MAILPATH is changed. */
9012 static int mail_var_path_changed;
9015 * Print appropriate message(s) if mail has arrived.
9016 * If mail_var_path_changed is set,
9017 * then the value of MAIL has mail_var_path_changed,
9018 * so we just update the values.
9027 struct stackmark smark;
9030 setstackmark(&smark);
9031 mpath = mpathset() ? mpathval() : mailval();
9032 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9033 p = padvance(&mpath, nullstr);
9038 for (q = p; *q; q++);
9043 q[-1] = '\0'; /* delete trailing '/' */
9044 if (stat(p, &statb) < 0) {
9048 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9051 pathopt ? pathopt : "you have mail"
9054 *mtp = statb.st_mtime;
9056 mail_var_path_changed = 0;
9057 popstackmark(&smark);
9061 changemail(const char *val)
9063 mail_var_path_changed++;
9066 #endif /* ASH_MAIL */
9069 /* ============ ??? */
9072 * Set the shell parameters.
9075 setparam(char **argv)
9081 for (nparam = 0; argv[nparam]; nparam++);
9082 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9084 *ap++ = ckstrdup(*argv++);
9087 freeparam(&shellparam);
9088 shellparam.malloc = 1;
9089 shellparam.nparam = nparam;
9090 shellparam.p = newparam;
9091 #if ENABLE_ASH_GETOPTS
9092 shellparam.optind = 1;
9093 shellparam.optoff = -1;
9098 * Process shell options. The global variable argptr contains a pointer
9099 * to the argument list; we advance it past the options.
9102 minus_o(char *name, int val)
9107 for (i = 0; i < NOPTS; i++) {
9108 if (strcmp(name, optnames(i)) == 0) {
9113 ash_msg_and_raise_error("illegal option -o %s", name);
9115 out1str("Current option settings\n");
9116 for (i = 0; i < NOPTS; i++)
9117 out1fmt("%-16s%s\n", optnames(i),
9118 optlist[i] ? "on" : "off");
9121 setoption(int flag, int val)
9125 for (i = 0; i < NOPTS; i++) {
9126 if (optletters(i) == flag) {
9131 ash_msg_and_raise_error("illegal option -%c", flag);
9135 options(int cmdline)
9143 while ((p = *argptr) != NULL) {
9148 if (p[0] == '\0' || LONE_DASH(p)) {
9150 /* "-" means turn off -x and -v */
9153 /* "--" means reset params */
9154 else if (*argptr == NULL)
9157 break; /* "-" or "--" terminates options */
9159 } else if (c == '+') {
9165 while ((c = *p++) != '\0') {
9166 if (c == 'c' && cmdline) {
9167 minusc = p; /* command is after shell args*/
9168 } else if (c == 'o') {
9169 minus_o(*argptr, val);
9172 } else if (cmdline && (c == '-')) { // long options
9173 if (strcmp(p, "login") == 0)
9184 * The shift builtin command.
9187 shiftcmd(int argc, char **argv)
9194 n = number(argv[1]);
9195 if (n > shellparam.nparam)
9196 ash_msg_and_raise_error("can't shift that many");
9198 shellparam.nparam -= n;
9199 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9200 if (shellparam.malloc)
9204 while ((*ap2++ = *ap1++) != NULL);
9205 #if ENABLE_ASH_GETOPTS
9206 shellparam.optind = 1;
9207 shellparam.optoff = -1;
9214 * POSIX requires that 'set' (but not export or readonly) output the
9215 * variables in lexicographic order - by the locale's collating order (sigh).
9216 * Maybe we could keep them in an ordered balanced binary tree
9217 * instead of hashed lists.
9218 * For now just roll 'em through qsort for printing...
9221 showvars(const char *sep_prefix, int on, int off)
9226 ep = listvars(on, off, &epend);
9227 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9229 sep = *sep_prefix ? " " : sep_prefix;
9231 for (; ep < epend; ep++) {
9235 p = strchrnul(*ep, '=');
9238 q = single_quote(++p);
9239 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9245 * The set command builtin.
9248 setcmd(int argc, char **argv)
9251 return showvars(nullstr, 0, VUNSET);
9255 if (*argptr != NULL) {
9262 #if ENABLE_ASH_RANDOM_SUPPORT
9263 /* Roughly copied from bash.. */
9265 change_random(const char *value)
9267 if (value == NULL) {
9268 /* "get", generate */
9271 rseed = rseed * 1103515245 + 12345;
9272 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9273 /* set without recursion */
9274 setvar(vrandom.text, buf, VNOFUNC);
9275 vrandom.flags &= ~VNOFUNC;
9278 rseed = strtoul(value, (char **)NULL, 10);
9283 #if ENABLE_ASH_GETOPTS
9285 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9294 if (*param_optind < 1)
9296 optnext = optfirst + *param_optind - 1;
9298 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9301 p = optnext[-1] + *optoff;
9302 if (p == NULL || *p == '\0') {
9303 /* Current word is done, advance */
9305 if (p == NULL || *p != '-' || *++p == '\0') {
9312 if (LONE_DASH(p)) /* check for "--" */
9317 for (q = optstr; *q != c; ) {
9319 if (optstr[0] == ':') {
9322 err |= setvarsafe("OPTARG", s, 0);
9324 fprintf(stderr, "Illegal option -%c\n", c);
9335 if (*p == '\0' && (p = *optnext) == NULL) {
9336 if (optstr[0] == ':') {
9339 err |= setvarsafe("OPTARG", s, 0);
9342 fprintf(stderr, "No arg for -%c option\n", c);
9351 err |= setvarsafe("OPTARG", p, 0);
9354 err |= setvarsafe("OPTARG", nullstr, 0);
9356 *optoff = p ? p - *(optnext - 1) : -1;
9357 *param_optind = optnext - optfirst + 1;
9358 fmtstr(s, sizeof(s), "%d", *param_optind);
9359 err |= setvarsafe("OPTIND", s, VNOFUNC);
9362 err |= setvarsafe(optvar, s, 0);
9366 flush_stdout_stderr();
9367 raise_exception(EXERROR);
9373 * The getopts builtin. Shellparam.optnext points to the next argument
9374 * to be processed. Shellparam.optptr points to the next character to
9375 * be processed in the current argument. If shellparam.optnext is NULL,
9376 * then it's the first time getopts has been called.
9379 getoptscmd(int argc, char **argv)
9384 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9386 optbase = shellparam.p;
9387 if (shellparam.optind > shellparam.nparam + 1) {
9388 shellparam.optind = 1;
9389 shellparam.optoff = -1;
9393 if (shellparam.optind > argc - 2) {
9394 shellparam.optind = 1;
9395 shellparam.optoff = -1;
9399 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9400 &shellparam.optoff);
9402 #endif /* ASH_GETOPTS */
9405 /* ============ Shell parser */
9407 static int tokpushback; /* last token pushed back */
9408 #define NEOF ((union node *)&tokpushback)
9409 static int parsebackquote; /* nonzero if we are inside backquotes */
9410 static int lasttoken; /* last token read */
9411 static char *wordtext; /* text of last word returned by readtoken */
9412 static struct nodelist *backquotelist;
9413 static union node *redirnode;
9414 static struct heredoc *heredoc;
9415 static int quoteflag; /* set if (part of) last token was quoted */
9417 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9419 raise_error_syntax(const char *msg)
9421 ash_msg_and_raise_error("syntax error: %s", msg);
9426 * Called when an unexpected token is read during the parse. The argument
9427 * is the token that is expected, or -1 if more than one type of token can
9428 * occur at this point.
9430 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9432 raise_error_unexpected_syntax(int token)
9437 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9439 sprintf(msg + l, " (expecting %s)", tokname(token));
9440 raise_error_syntax(msg);
9444 #define EOFMARKLEN 79
9447 struct heredoc *next; /* next here document in list */
9448 union node *here; /* redirection node */
9449 char *eofmark; /* string indicating end of input */
9450 int striptabs; /* if set, strip leading tabs */
9453 static struct heredoc *heredoclist; /* list of here documents to read */
9455 /* parsing is heavily cross-recursive, need these forward decls */
9456 static union node *andor(void);
9457 static union node *pipeline(void);
9458 static union node *parse_command(void);
9459 static void parseheredoc(void);
9460 static char peektoken(void);
9461 static int readtoken(void);
9466 union node *n1, *n2, *n3;
9469 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9470 if (nlflag == 2 && peektoken())
9476 if (tok == TBACKGND) {
9477 if (n2->type == NPIPE) {
9478 n2->npipe.backgnd = 1;
9480 if (n2->type != NREDIR) {
9481 n3 = stalloc(sizeof(struct nredir));
9483 n3->nredir.redirect = NULL;
9486 n2->type = NBACKGND;
9492 n3 = stalloc(sizeof(struct nbinary));
9494 n3->nbinary.ch1 = n1;
9495 n3->nbinary.ch2 = n2;
9511 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9519 pungetc(); /* push back EOF on input */
9523 raise_error_unexpected_syntax(-1);
9533 union node *n1, *n2, *n3;
9541 } else if (t == TOR) {
9547 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9549 n3 = stalloc(sizeof(struct nbinary));
9551 n3->nbinary.ch1 = n1;
9552 n3->nbinary.ch2 = n2;
9560 union node *n1, *n2, *pipenode;
9561 struct nodelist *lp, *prev;
9565 TRACE(("pipeline: entered\n"));
9566 if (readtoken() == TNOT) {
9568 checkkwd = CHKKWD | CHKALIAS;
9571 n1 = parse_command();
9572 if (readtoken() == TPIPE) {
9573 pipenode = stalloc(sizeof(struct npipe));
9574 pipenode->type = NPIPE;
9575 pipenode->npipe.backgnd = 0;
9576 lp = stalloc(sizeof(struct nodelist));
9577 pipenode->npipe.cmdlist = lp;
9581 lp = stalloc(sizeof(struct nodelist));
9582 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9583 lp->n = parse_command();
9585 } while (readtoken() == TPIPE);
9591 n2 = stalloc(sizeof(struct nnot));
9604 n = stalloc(sizeof(struct narg));
9606 n->narg.next = NULL;
9607 n->narg.text = wordtext;
9608 n->narg.backquote = backquotelist;
9613 fixredir(union node *n, const char *text, int err)
9615 TRACE(("Fix redir %s %d\n", text, err));
9617 n->ndup.vname = NULL;
9619 if (isdigit(text[0]) && text[1] == '\0')
9620 n->ndup.dupfd = text[0] - '0';
9621 else if (LONE_DASH(text))
9625 raise_error_syntax("Bad fd number");
9626 n->ndup.vname = makename();
9631 * Returns true if the text contains nothing to expand (no dollar signs
9635 noexpand(char *text)
9641 while ((c = *p++) != '\0') {
9642 if (c == CTLQUOTEMARK)
9646 else if (SIT(c, BASESYNTAX) == CCTL)
9655 union node *n = redirnode;
9657 if (readtoken() != TWORD)
9658 raise_error_unexpected_syntax(-1);
9659 if (n->type == NHERE) {
9660 struct heredoc *here = heredoc;
9666 TRACE(("Here document %d\n", n->type));
9667 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9668 raise_error_syntax("Illegal eof marker for << redirection");
9669 rmescapes(wordtext);
9670 here->eofmark = wordtext;
9672 if (heredoclist == NULL)
9675 for (p = heredoclist; p->next; p = p->next);
9678 } else if (n->type == NTOFD || n->type == NFROMFD) {
9679 fixredir(n, wordtext, 0);
9681 n->nfile.fname = makename();
9688 union node *args, **app;
9689 union node *n = NULL;
9690 union node *vars, **vpp;
9691 union node **rpp, *redir;
9701 savecheckkwd = CHKALIAS;
9703 checkkwd = savecheckkwd;
9704 switch (readtoken()) {
9706 n = stalloc(sizeof(struct narg));
9708 n->narg.text = wordtext;
9709 n->narg.backquote = backquotelist;
9710 if (savecheckkwd && isassignment(wordtext)) {
9712 vpp = &n->narg.next;
9715 app = &n->narg.next;
9720 *rpp = n = redirnode;
9721 rpp = &n->nfile.next;
9722 parsefname(); /* read name of redirection file */
9725 if (args && app == &args->narg.next
9728 struct builtincmd *bcmd;
9731 /* We have a function */
9732 if (readtoken() != TRP)
9733 raise_error_unexpected_syntax(TRP);
9734 name = n->narg.text;
9736 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9738 raise_error_syntax("Bad function name");
9741 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9742 n->narg.next = parse_command();
9755 n = stalloc(sizeof(struct ncmd));
9757 n->ncmd.args = args;
9758 n->ncmd.assign = vars;
9759 n->ncmd.redirect = redir;
9766 union node *n1, *n2;
9767 union node *ap, **app;
9768 union node *cp, **cpp;
9769 union node *redir, **rpp;
9776 switch (readtoken()) {
9778 raise_error_unexpected_syntax(-1);
9781 n1 = stalloc(sizeof(struct nif));
9783 n1->nif.test = list(0);
9784 if (readtoken() != TTHEN)
9785 raise_error_unexpected_syntax(TTHEN);
9786 n1->nif.ifpart = list(0);
9788 while (readtoken() == TELIF) {
9789 n2->nif.elsepart = stalloc(sizeof(struct nif));
9790 n2 = n2->nif.elsepart;
9792 n2->nif.test = list(0);
9793 if (readtoken() != TTHEN)
9794 raise_error_unexpected_syntax(TTHEN);
9795 n2->nif.ifpart = list(0);
9797 if (lasttoken == TELSE)
9798 n2->nif.elsepart = list(0);
9800 n2->nif.elsepart = NULL;
9808 n1 = stalloc(sizeof(struct nbinary));
9809 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9810 n1->nbinary.ch1 = list(0);
9813 TRACE(("expecting DO got %s %s\n", tokname(got),
9814 got == TWORD ? wordtext : ""));
9815 raise_error_unexpected_syntax(TDO);
9817 n1->nbinary.ch2 = list(0);
9822 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9823 raise_error_syntax("Bad for loop variable");
9824 n1 = stalloc(sizeof(struct nfor));
9826 n1->nfor.var = wordtext;
9827 checkkwd = CHKKWD | CHKALIAS;
9828 if (readtoken() == TIN) {
9830 while (readtoken() == TWORD) {
9831 n2 = stalloc(sizeof(struct narg));
9833 n2->narg.text = wordtext;
9834 n2->narg.backquote = backquotelist;
9836 app = &n2->narg.next;
9840 if (lasttoken != TNL && lasttoken != TSEMI)
9841 raise_error_unexpected_syntax(-1);
9843 n2 = stalloc(sizeof(struct narg));
9845 n2->narg.text = (char *)dolatstr;
9846 n2->narg.backquote = NULL;
9847 n2->narg.next = NULL;
9850 * Newline or semicolon here is optional (but note
9851 * that the original Bourne shell only allowed NL).
9853 if (lasttoken != TNL && lasttoken != TSEMI)
9856 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9857 if (readtoken() != TDO)
9858 raise_error_unexpected_syntax(TDO);
9859 n1->nfor.body = list(0);
9863 n1 = stalloc(sizeof(struct ncase));
9865 if (readtoken() != TWORD)
9866 raise_error_unexpected_syntax(TWORD);
9867 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9869 n2->narg.text = wordtext;
9870 n2->narg.backquote = backquotelist;
9871 n2->narg.next = NULL;
9873 checkkwd = CHKKWD | CHKALIAS;
9874 } while (readtoken() == TNL);
9875 if (lasttoken != TIN)
9876 raise_error_unexpected_syntax(TIN);
9877 cpp = &n1->ncase.cases;
9879 checkkwd = CHKNL | CHKKWD;
9881 while (t != TESAC) {
9882 if (lasttoken == TLP)
9884 *cpp = cp = stalloc(sizeof(struct nclist));
9886 app = &cp->nclist.pattern;
9888 *app = ap = stalloc(sizeof(struct narg));
9890 ap->narg.text = wordtext;
9891 ap->narg.backquote = backquotelist;
9892 if (readtoken() != TPIPE)
9894 app = &ap->narg.next;
9897 ap->narg.next = NULL;
9898 if (lasttoken != TRP)
9899 raise_error_unexpected_syntax(TRP);
9900 cp->nclist.body = list(2);
9902 cpp = &cp->nclist.next;
9904 checkkwd = CHKNL | CHKKWD;
9908 raise_error_unexpected_syntax(TENDCASE);
9915 n1 = stalloc(sizeof(struct nredir));
9916 n1->type = NSUBSHELL;
9917 n1->nredir.n = list(0);
9918 n1->nredir.redirect = NULL;
9931 if (readtoken() != t)
9932 raise_error_unexpected_syntax(t);
9935 /* Now check for redirection which may follow command */
9936 checkkwd = CHKKWD | CHKALIAS;
9938 while (readtoken() == TREDIR) {
9939 *rpp = n2 = redirnode;
9940 rpp = &n2->nfile.next;
9946 if (n1->type != NSUBSHELL) {
9947 n2 = stalloc(sizeof(struct nredir));
9952 n1->nredir.redirect = redir;
9958 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9959 * is not NULL, read a here document. In the latter case, eofmark is the
9960 * word which marks the end of the document and striptabs is true if
9961 * leading tabs should be stripped from the document. The argument firstc
9962 * is the first character of the input token or document.
9964 * Because C does not have internal subroutines, I have simulated them
9965 * using goto's to implement the subroutine linkage. The following macros
9966 * will run code that appears at the end of readtoken1.
9969 static int parsebackquote; /* nonzero if we are inside backquotes */
9971 #define CHECKEND() {goto checkend; checkend_return:;}
9972 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9973 #define PARSESUB() {goto parsesub; parsesub_return:;}
9974 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9975 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9976 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9979 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9984 char line[EOFMARKLEN + 1];
9985 struct nodelist *bqlist = 0;
9988 int varnest = 0; /* levels of variables expansion */
9989 int arinest = 0; /* levels of arithmetic expansion */
9990 int parenlevel = 0; /* levels of parens in arithmetic */
9991 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9993 int prevsyntax = 0; /* syntax before arithmetic */
9995 /* Avoid longjmp clobbering */
10001 (void) &parenlevel;
10004 (void) &prevsyntax;
10008 startlinno = plinno;
10010 if (syntax == DQSYNTAX)
10019 STARTSTACKSTR(out);
10020 loop: { /* for each line, until end of word */
10021 CHECKEND(); /* set c to PEOF if at end of here document */
10022 for (;;) { /* until end of line or end of word */
10023 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10024 switch (SIT(c, syntax)) {
10025 case CNL: /* '\n' */
10026 if (syntax == BASESYNTAX)
10027 goto endword; /* exit outer loop */
10033 goto loop; /* continue outer loop */
10038 if (eofmark == NULL || dblquote)
10039 USTPUTC(CTLESC, out);
10042 case CBACK: /* backslash */
10045 USTPUTC(CTLESC, out);
10046 USTPUTC('\\', out);
10048 } else if (c == '\n') {
10053 c != '\\' && c != '`' &&
10058 USTPUTC(CTLESC, out);
10059 USTPUTC('\\', out);
10061 if (SIT(c, SQSYNTAX) == CCTL)
10062 USTPUTC(CTLESC, out);
10070 if (eofmark == NULL) {
10071 USTPUTC(CTLQUOTEMARK, out);
10079 if (eofmark != NULL && arinest == 0
10084 if (dqvarnest == 0) {
10085 syntax = BASESYNTAX;
10092 case CVAR: /* '$' */
10093 PARSESUB(); /* parse substitution */
10095 case CENDVAR: /* '}' */
10098 if (dqvarnest > 0) {
10101 USTPUTC(CTLENDVAR, out);
10106 #if ENABLE_ASH_MATH_SUPPORT
10107 case CLP: /* '(' in arithmetic */
10111 case CRP: /* ')' in arithmetic */
10112 if (parenlevel > 0) {
10116 if (pgetc() == ')') {
10117 if (--arinest == 0) {
10118 USTPUTC(CTLENDARI, out);
10119 syntax = prevsyntax;
10120 if (syntax == DQSYNTAX)
10128 * unbalanced parens
10129 * (don't 2nd guess - no error)
10137 case CBQUOTE: /* '`' */
10141 goto endword; /* exit outer loop */
10146 goto endword; /* exit outer loop */
10147 #if ENABLE_ASH_ALIAS
10157 #if ENABLE_ASH_MATH_SUPPORT
10158 if (syntax == ARISYNTAX)
10159 raise_error_syntax("Missing '))'");
10161 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10162 raise_error_syntax("Unterminated quoted string");
10163 if (varnest != 0) {
10164 startlinno = plinno;
10166 raise_error_syntax("Missing '}'");
10168 USTPUTC('\0', out);
10169 len = out - (char *)stackblock();
10170 out = stackblock();
10171 if (eofmark == NULL) {
10172 if ((c == '>' || c == '<')
10175 && (*out == '\0' || isdigit(*out))) {
10177 return lasttoken = TREDIR;
10182 quoteflag = quotef;
10183 backquotelist = bqlist;
10184 grabstackblock(len);
10188 /* end of readtoken routine */
10191 * Check to see whether we are at the end of the here document. When this
10192 * is called, c is set to the first character of the next input line. If
10193 * we are at the end of the here document, this routine sets the c to PEOF.
10197 #if ENABLE_ASH_ALIAS
10203 while (c == '\t') {
10207 if (c == *eofmark) {
10208 if (pfgets(line, sizeof(line)) != NULL) {
10212 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10213 if (*p == '\n' && *q == '\0') {
10216 needprompt = doprompt;
10218 pushstring(line, NULL);
10223 goto checkend_return;
10227 * Parse a redirection operator. The variable "out" points to a string
10228 * specifying the fd to be redirected. The variable "c" contains the
10229 * first character of the redirection operator.
10235 np = stalloc(sizeof(struct nfile));
10240 np->type = NAPPEND;
10242 np->type = NCLOBBER;
10249 } else { /* c == '<' */
10254 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10255 np = stalloc(sizeof(struct nhere));
10259 heredoc = stalloc(sizeof(struct heredoc));
10260 heredoc->here = np;
10263 heredoc->striptabs = 1;
10265 heredoc->striptabs = 0;
10271 np->type = NFROMFD;
10275 np->type = NFROMTO;
10285 np->nfile.fd = fd - '0';
10287 goto parseredir_return;
10291 * Parse a substitution. At this point, we have read the dollar sign
10292 * and nothing else.
10295 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10296 * (assuming ascii char codes, as the original implementation did) */
10297 #define is_special(c) \
10298 ((((unsigned int)c) - 33 < 32) \
10299 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10305 static const char types[] = "}-+?=";
10309 c <= PEOA_OR_PEOF ||
10310 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10314 } else if (c == '(') { /* $(command) or $((arith)) */
10315 if (pgetc() == '(') {
10316 #if ENABLE_ASH_MATH_SUPPORT
10319 raise_error_syntax("We unsupport $((arith))");
10326 USTPUTC(CTLVAR, out);
10327 typeloc = out - (char *)stackblock();
10328 USTPUTC(VSNORMAL, out);
10329 subtype = VSNORMAL;
10337 subtype = VSLENGTH;
10341 if (c > PEOA_OR_PEOF && is_name(c)) {
10345 } while (c > PEOA_OR_PEOF && is_in_name(c));
10346 } else if (isdigit(c)) {
10350 } while (isdigit(c));
10351 } else if (is_special(c)) {
10355 badsub: raise_error_syntax("Bad substitution");
10359 if (subtype == 0) {
10366 p = strchr(types, c);
10369 subtype = p - types + VSNORMAL;
10375 subtype = c == '#' ? VSTRIMLEFT :
10388 if (dblquote || arinest)
10390 *((char *)stackblock() + typeloc) = subtype | flags;
10391 if (subtype != VSNORMAL) {
10393 if (dblquote || arinest) {
10398 goto parsesub_return;
10402 * Called to parse command substitutions. Newstyle is set if the command
10403 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10404 * list of commands (passed by reference), and savelen is the number of
10405 * characters on the top of the stack which must be preserved.
10408 struct nodelist **nlpp;
10411 char *volatile str;
10412 struct jmploc jmploc;
10413 struct jmploc *volatile savehandler;
10415 int saveprompt = 0;
10417 (void) &saveprompt;
10420 savepbq = parsebackquote;
10421 if (setjmp(jmploc.loc)) {
10424 parsebackquote = 0;
10425 exception_handler = savehandler;
10426 longjmp(exception_handler->loc, 1);
10430 savelen = out - (char *)stackblock();
10432 str = ckmalloc(savelen);
10433 memcpy(str, stackblock(), savelen);
10435 savehandler = exception_handler;
10436 exception_handler = &jmploc;
10439 /* We must read until the closing backquote, giving special
10440 treatment to some slashes, and then push the string and
10441 reread it as input, interpreting it normally. */
10448 STARTSTACKSTR(pout);
10465 * If eating a newline, avoid putting
10466 * the newline into the new character
10467 * stream (via the STPUTC after the
10472 if (pc != '\\' && pc != '`' && pc != '$'
10473 && (!dblquote || pc != '"'))
10474 STPUTC('\\', pout);
10475 if (pc > PEOA_OR_PEOF) {
10481 #if ENABLE_ASH_ALIAS
10484 startlinno = plinno;
10485 raise_error_syntax("EOF in backquote substitution");
10489 needprompt = doprompt;
10498 STPUTC('\0', pout);
10499 psavelen = pout - (char *)stackblock();
10500 if (psavelen > 0) {
10501 pstr = grabstackstr(pout);
10502 setinputstring(pstr);
10507 nlpp = &(*nlpp)->next;
10508 *nlpp = stalloc(sizeof(**nlpp));
10509 (*nlpp)->next = NULL;
10510 parsebackquote = oldstyle;
10513 saveprompt = doprompt;
10520 doprompt = saveprompt;
10521 else if (readtoken() != TRP)
10522 raise_error_unexpected_syntax(TRP);
10527 * Start reading from old file again, ignoring any pushed back
10528 * tokens left from the backquote parsing
10533 while (stackblocksize() <= savelen)
10535 STARTSTACKSTR(out);
10537 memcpy(out, str, savelen);
10538 STADJUST(savelen, out);
10544 parsebackquote = savepbq;
10545 exception_handler = savehandler;
10546 if (arinest || dblquote)
10547 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10549 USTPUTC(CTLBACKQ, out);
10551 goto parsebackq_oldreturn;
10552 goto parsebackq_newreturn;
10555 #if ENABLE_ASH_MATH_SUPPORT
10557 * Parse an arithmetic expansion (indicate start of one and set state)
10560 if (++arinest == 1) {
10561 prevsyntax = syntax;
10562 syntax = ARISYNTAX;
10563 USTPUTC(CTLARI, out);
10570 * we collapse embedded arithmetic expansion to
10571 * parenthesis, which should be equivalent
10575 goto parsearith_return;
10579 } /* end of readtoken */
10582 * Read the next input token.
10583 * If the token is a word, we set backquotelist to the list of cmds in
10584 * backquotes. We set quoteflag to true if any part of the word was
10586 * If the token is TREDIR, then we set redirnode to a structure containing
10588 * In all cases, the variable startlinno is set to the number of the line
10589 * on which the token starts.
10591 * [Change comment: here documents and internal procedures]
10592 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10593 * word parsing code into a separate routine. In this case, readtoken
10594 * doesn't need to have any internal procedures, but parseword does.
10595 * We could also make parseoperator in essence the main routine, and
10596 * have parseword (readtoken1?) handle both words and redirection.]
10598 #define NEW_xxreadtoken
10599 #ifdef NEW_xxreadtoken
10600 /* singles must be first! */
10601 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10603 static const char xxreadtoken_tokens[] = {
10604 TNL, TLP, TRP, /* only single occurrence allowed */
10605 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10606 TEOF, /* corresponds to trailing nul */
10607 TAND, TOR, TENDCASE, /* if double occurrence */
10610 #define xxreadtoken_doubles \
10611 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10612 #define xxreadtoken_singles \
10613 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10627 startlinno = plinno;
10628 for (;;) { /* until token or start of word found */
10631 if ((c != ' ') && (c != '\t')
10632 #if ENABLE_ASH_ALIAS
10637 while ((c = pgetc()) != '\n' && c != PEOF);
10639 } else if (c == '\\') {
10640 if (pgetc() != '\n') {
10644 startlinno = ++plinno;
10649 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10654 needprompt = doprompt;
10657 p = strchr(xxreadtoken_chars, c);
10660 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10663 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10664 if (pgetc() == *p) { /* double occurrence? */
10665 p += xxreadtoken_doubles + 1;
10671 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10677 #define RETURN(token) return lasttoken = token
10690 startlinno = plinno;
10691 for (;;) { /* until token or start of word found */
10694 case ' ': case '\t':
10695 #if ENABLE_ASH_ALIAS
10700 while ((c = pgetc()) != '\n' && c != PEOF);
10704 if (pgetc() == '\n') {
10705 startlinno = ++plinno;
10714 needprompt = doprompt;
10719 if (pgetc() == '&')
10724 if (pgetc() == '|')
10729 if (pgetc() == ';')
10742 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10745 #endif /* NEW_xxreadtoken */
10752 int alreadyseen = tokpushback;
10755 #if ENABLE_ASH_ALIAS
10764 if (checkkwd & CHKNL) {
10771 if (t != TWORD || quoteflag) {
10776 * check for keywords
10778 if (checkkwd & CHKKWD) {
10779 const char *const *pp;
10781 pp = findkwd(wordtext);
10783 lasttoken = t = pp - tokname_array;
10784 TRACE(("keyword %s recognized\n", tokname(t)));
10789 if (checkkwd & CHKALIAS) {
10790 #if ENABLE_ASH_ALIAS
10792 ap = lookupalias(wordtext, 1);
10795 pushstring(ap->val, ap);
10805 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10807 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10819 return tokname_array[t][0];
10823 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10824 * valid parse tree indicating a blank line.)
10826 static union node *
10827 parsecmd(int interact)
10832 doprompt = interact;
10834 setprompt(doprompt);
10846 * Input any here documents.
10851 struct heredoc *here;
10854 here = heredoclist;
10861 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10862 here->eofmark, here->striptabs);
10863 n = stalloc(sizeof(struct narg));
10864 n->narg.type = NARG;
10865 n->narg.next = NULL;
10866 n->narg.text = wordtext;
10867 n->narg.backquote = backquotelist;
10868 here->here->nhere.doc = n;
10875 * called by editline -- any expansions to the prompt should be added here.
10877 #if ENABLE_ASH_EXPAND_PRMT
10878 static const char *
10879 expandstr(const char *ps)
10883 /* XXX Fix (char *) cast. */
10884 setinputstring((char *)ps);
10885 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10888 n.narg.type = NARG;
10889 n.narg.next = NULL;
10890 n.narg.text = wordtext;
10891 n.narg.backquote = backquotelist;
10893 expandarg(&n, NULL, 0);
10894 return stackblock();
10899 * Execute a command or commands contained in a string.
10902 evalstring(char *s, int mask)
10905 struct stackmark smark;
10909 setstackmark(&smark);
10912 while ((n = parsecmd(0)) != NEOF) {
10914 popstackmark(&smark);
10927 * The eval command.
10930 evalcmd(int argc, char **argv)
10939 STARTSTACKSTR(concat);
10942 concat = stack_putstr(p, concat);
10946 STPUTC(' ', concat);
10948 STPUTC('\0', concat);
10949 p = grabstackstr(concat);
10951 evalstring(p, ~SKIPEVAL);
10958 * Read and execute commands. "Top" is nonzero for the top level command
10959 * loop; it turns on prompting if the shell is interactive.
10965 struct stackmark smark;
10969 TRACE(("cmdloop(%d) called\n", top));
10973 setstackmark(&smark);
10976 showjobs(stderr, SHOW_CHANGED);
10979 if (iflag && top) {
10981 #if ENABLE_ASH_MAIL
10985 n = parsecmd(inter);
10986 /* showtree(n); DEBUG */
10988 if (!top || numeof >= 50)
10990 if (!stoppedjobs()) {
10993 out2str("\nUse \"exit\" to leave shell.\n");
10996 } else if (nflag == 0) {
10997 job_warning = (job_warning == 2) ? 1 : 0;
11001 popstackmark(&smark);
11006 return skip & SKIPEVAL;
11013 * Take commands from a file. To be compatible we should do a path
11014 * search for the file, which is necessary to find sub-commands.
11017 find_dot_file(char *name)
11020 const char *path = pathval();
11023 /* don't try this for absolute or relative paths */
11024 if (strchr(name, '/'))
11027 while ((fullname = padvance(&path, name)) != NULL) {
11028 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11030 * Don't bother freeing here, since it will
11031 * be freed by the caller.
11035 stunalloc(fullname);
11038 /* not found in the PATH */
11039 ash_msg_and_raise_error("%s: not found", name);
11044 dotcmd(int argc, char **argv)
11046 struct strlist *sp;
11047 volatile struct shparam saveparam;
11050 for (sp = cmdenviron; sp; sp = sp->next)
11051 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11053 if (argc >= 2) { /* That's what SVR2 does */
11056 fullname = find_dot_file(argv[1]);
11059 saveparam = shellparam;
11060 shellparam.malloc = 0;
11061 shellparam.nparam = argc - 2;
11062 shellparam.p = argv + 2;
11065 setinputfile(fullname, INPUT_PUSH_FILE);
11066 commandname = fullname;
11071 freeparam(&shellparam);
11072 shellparam = saveparam;
11074 status = exitstatus;
11080 exitcmd(int argc, char **argv)
11085 exitstatus = number(argv[1]);
11086 raise_exception(EXEXIT);
11090 #if ENABLE_ASH_BUILTIN_ECHO
11092 echocmd(int argc, char **argv)
11094 return bb_echo(argv);
11098 #if ENABLE_ASH_BUILTIN_TEST
11100 testcmd(int argc, char **argv)
11102 return bb_test(argc, argv);
11107 * Read a file containing shell functions.
11110 readcmdfile(char *name)
11112 setinputfile(name, INPUT_PUSH_FILE);
11118 /* ============ find_command inplementation */
11121 * Resolve a command name. If you change this routine, you may have to
11122 * change the shellexec routine as well.
11125 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11127 struct tblentry *cmdp;
11134 struct builtincmd *bcmd;
11136 /* If name contains a slash, don't use PATH or hash table */
11137 if (strchr(name, '/') != NULL) {
11138 entry->u.index = -1;
11139 if (act & DO_ABS) {
11140 while (stat(name, &statb) < 0) {
11142 if (errno == EINTR)
11145 entry->cmdtype = CMDUNKNOWN;
11149 entry->cmdtype = CMDNORMAL;
11153 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
11154 if (find_applet_by_name(name)) {
11155 entry->cmdtype = CMDNORMAL;
11156 entry->u.index = -1;
11159 /* Already caught above
11160 if (is_safe_applet(name)) {
11161 entry->cmdtype = CMDNORMAL;
11162 entry->u.index = -1;
11167 updatetbl = (path == pathval());
11170 if (strstr(path, "%builtin") != NULL)
11171 act |= DO_ALTBLTIN;
11174 /* If name is in the table, check answer will be ok */
11175 cmdp = cmdlookup(name, 0);
11176 if (cmdp != NULL) {
11179 switch (cmdp->cmdtype) {
11197 } else if (cmdp->rehash == 0)
11198 /* if not invalidated by cd, we're done */
11202 /* If %builtin not in path, check for builtin next */
11203 bcmd = find_builtin(name);
11205 if (IS_BUILTIN_REGULAR(bcmd))
11206 goto builtin_success;
11207 if (act & DO_ALTPATH) {
11208 if (!(act & DO_ALTBLTIN))
11209 goto builtin_success;
11210 } else if (builtinloc <= 0) {
11211 goto builtin_success;
11215 /* We have to search path. */
11216 prev = -1; /* where to start */
11217 if (cmdp && cmdp->rehash) { /* doing a rehash */
11218 if (cmdp->cmdtype == CMDBUILTIN)
11221 prev = cmdp->param.index;
11227 while ((fullname = padvance(&path, name)) != NULL) {
11228 stunalloc(fullname);
11231 if (prefix(pathopt, "builtin")) {
11233 goto builtin_success;
11235 } else if (!(act & DO_NOFUNC) &&
11236 prefix(pathopt, "func")) {
11237 /* handled below */
11239 /* ignore unimplemented options */
11243 /* if rehash, don't redo absolute path names */
11244 if (fullname[0] == '/' && idx <= prev) {
11247 TRACE(("searchexec \"%s\": no change\n", name));
11250 while (stat(fullname, &statb) < 0) {
11252 if (errno == EINTR)
11255 if (errno != ENOENT && errno != ENOTDIR)
11259 e = EACCES; /* if we fail, this will be the error */
11260 if (!S_ISREG(statb.st_mode))
11262 if (pathopt) { /* this is a %func directory */
11263 stalloc(strlen(fullname) + 1);
11264 readcmdfile(fullname);
11265 cmdp = cmdlookup(name, 0);
11266 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11267 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11268 stunalloc(fullname);
11271 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11273 entry->cmdtype = CMDNORMAL;
11274 entry->u.index = idx;
11278 cmdp = cmdlookup(name, 1);
11279 cmdp->cmdtype = CMDNORMAL;
11280 cmdp->param.index = idx;
11285 /* We failed. If there was an entry for this command, delete it */
11286 if (cmdp && updatetbl)
11287 delete_cmd_entry();
11289 ash_msg("%s: %s", name, errmsg(e, "not found"));
11290 entry->cmdtype = CMDUNKNOWN;
11295 entry->cmdtype = CMDBUILTIN;
11296 entry->u.cmd = bcmd;
11300 cmdp = cmdlookup(name, 1);
11301 cmdp->cmdtype = CMDBUILTIN;
11302 cmdp->param.cmd = bcmd;
11306 entry->cmdtype = cmdp->cmdtype;
11307 entry->u = cmdp->param;
11311 /* ============ trap.c */
11314 * The trap builtin.
11317 trapcmd(int argc, char **argv)
11326 for (signo = 0; signo < NSIG; signo++) {
11327 if (trap[signo] != NULL) {
11330 sn = get_signame(signo);
11331 out1fmt("trap -- %s %s\n",
11332 single_quote(trap[signo]), sn);
11342 signo = get_signum(*ap);
11344 ash_msg_and_raise_error("%s: bad trap", *ap);
11347 if (LONE_DASH(action))
11350 action = ckstrdup(action);
11354 trap[signo] = action;
11364 /* ============ Builtins */
11366 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11368 * Lists available builtins
11371 helpcmd(int argc, char **argv)
11375 out1fmt("\nBuilt-in commands:\n-------------------\n");
11376 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11377 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11378 builtintab[i].name + 1);
11384 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
11385 for (i = 0; i < NUM_APPLETS; i++) {
11386 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11394 return EXIT_SUCCESS;
11396 #endif /* FEATURE_SH_EXTRA_QUIET */
11399 * The export and readonly commands.
11402 exportcmd(int argc, char **argv)
11408 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11410 if (nextopt("p") != 'p') {
11415 p = strchr(name, '=');
11419 vp = *findvar(hashvar(name), name);
11425 setvar(name, p, flag);
11426 } while ((name = *++aptr) != NULL);
11430 showvars(argv[0], flag, 0);
11435 * Delete a function if it exists.
11438 unsetfunc(const char *name)
11440 struct tblentry *cmdp;
11442 cmdp = cmdlookup(name, 0);
11443 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11444 delete_cmd_entry();
11448 * The unset builtin command. We unset the function before we unset the
11449 * variable to allow a function to be unset when there is a readonly variable
11450 * with the same name.
11453 unsetcmd(int argc, char **argv)
11460 while ((i = nextopt("vf")) != '\0') {
11464 for (ap = argptr; *ap; ap++) {
11480 #include <sys/times.h>
11482 static const unsigned char timescmd_str[] = {
11483 ' ', offsetof(struct tms, tms_utime),
11484 '\n', offsetof(struct tms, tms_stime),
11485 ' ', offsetof(struct tms, tms_cutime),
11486 '\n', offsetof(struct tms, tms_cstime),
11491 timescmd(int ac, char **av)
11493 long clk_tck, s, t;
11494 const unsigned char *p;
11497 clk_tck = sysconf(_SC_CLK_TCK);
11502 t = *(clock_t *)(((char *) &buf) + p[1]);
11504 out1fmt("%ldm%ld.%.3lds%c",
11506 ((t - s * clk_tck) * 1000) / clk_tck,
11508 } while (*(p += 2));
11513 #if ENABLE_ASH_MATH_SUPPORT
11515 dash_arith(const char *s)
11521 result = arith(s, &errcode);
11524 ash_msg_and_raise_error("exponent less than 0");
11526 ash_msg_and_raise_error("divide by zero");
11528 ash_msg_and_raise_error("expression recursion loop detected");
11529 raise_error_syntax(s);
11537 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11538 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11540 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11543 letcmd(int argc, char **argv)
11550 ash_msg_and_raise_error("expression expected");
11551 for (ap = argv + 1; *ap; ap++) {
11552 i = dash_arith(*ap);
11557 #endif /* ASH_MATH_SUPPORT */
11560 /* ============ miscbltin.c
11562 * Miscellaneous builtins.
11567 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11568 typedef enum __rlimit_resource rlim_t;
11572 * The read builtin. The -e option causes backslashes to escape the
11573 * following character.
11575 * This uses unbuffered input, which may be avoidable in some cases.
11578 readcmd(int argc, char **argv)
11590 #if ENABLE_ASH_READ_NCHARS
11594 struct termios tty, old_tty;
11596 #if ENABLE_ASH_READ_TIMEOUT
11600 ts.tv_sec = ts.tv_usec = 0;
11605 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11606 while ((i = nextopt("p:rt:n:s")) != '\0')
11607 #elif ENABLE_ASH_READ_NCHARS
11608 while ((i = nextopt("p:rn:s")) != '\0')
11609 #elif ENABLE_ASH_READ_TIMEOUT
11610 while ((i = nextopt("p:rt:")) != '\0')
11612 while ((i = nextopt("p:r")) != '\0')
11617 prompt = optionarg;
11619 #if ENABLE_ASH_READ_NCHARS
11621 nchars = strtol(optionarg, &p, 10);
11623 ash_msg_and_raise_error("invalid count");
11624 nch_flag = (nchars > 0);
11630 #if ENABLE_ASH_READ_TIMEOUT
11632 ts.tv_sec = strtol(optionarg, &p, 10);
11638 ts.tv_usec = strtol(p, &p2, 10);
11640 ash_msg_and_raise_error("invalid timeout");
11642 /* normalize to usec */
11644 ash_msg_and_raise_error("invalid timeout");
11645 while (scale++ < 6)
11649 ash_msg_and_raise_error("invalid timeout");
11651 if ( ! ts.tv_sec && ! ts.tv_usec)
11652 ash_msg_and_raise_error("invalid timeout");
11662 if (prompt && isatty(0)) {
11667 ash_msg_and_raise_error("arg count");
11668 ifs = bltinlookup("IFS");
11671 #if ENABLE_ASH_READ_NCHARS
11672 if (nch_flag || silent) {
11673 tcgetattr(0, &tty);
11676 tty.c_lflag &= ~ICANON;
11677 tty.c_cc[VMIN] = nchars;
11680 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11683 tcsetattr(0, TCSANOW, &tty);
11686 #if ENABLE_ASH_READ_TIMEOUT
11687 if (ts.tv_sec || ts.tv_usec) {
11691 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11693 #if ENABLE_ASH_READ_NCHARS
11695 tcsetattr(0, TCSANOW, &old_tty);
11705 #if ENABLE_ASH_READ_NCHARS
11706 while (!nch_flag || nchars--)
11711 if (read(0, &c, 1) != 1) {
11723 if (!rflag && c == '\\') {
11729 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11733 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11735 setvar(*ap, stackblock(), 0);
11744 #if ENABLE_ASH_READ_NCHARS
11745 if (nch_flag || silent)
11746 tcsetattr(0, TCSANOW, &old_tty);
11750 /* Remove trailing blanks */
11751 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11753 setvar(*ap, stackblock(), 0);
11754 while (*++ap != NULL)
11755 setvar(*ap, nullstr, 0);
11760 umaskcmd(int argc, char **argv)
11762 static const char permuser[3] = "ugo";
11763 static const char permmode[3] = "rwx";
11764 static const short int permmask[] = {
11765 S_IRUSR, S_IWUSR, S_IXUSR,
11766 S_IRGRP, S_IWGRP, S_IXGRP,
11767 S_IROTH, S_IWOTH, S_IXOTH
11773 int symbolic_mode = 0;
11775 while (nextopt("S") != '\0') {
11786 if (symbolic_mode) {
11790 for (i = 0; i < 3; i++) {
11793 *p++ = permuser[i];
11795 for (j = 0; j < 3; j++) {
11796 if ((mask & permmask[3 * i + j]) == 0) {
11797 *p++ = permmode[j];
11805 out1fmt("%.4o\n", mask);
11808 if (isdigit((unsigned char) *ap)) {
11811 if (*ap >= '8' || *ap < '0')
11812 ash_msg_and_raise_error(illnum, argv[1]);
11813 mask = (mask << 3) + (*ap - '0');
11814 } while (*++ap != '\0');
11817 mask = ~mask & 0777;
11818 if (!bb_parse_mode(ap, &mask)) {
11819 ash_msg_and_raise_error("illegal mode: %s", ap);
11821 umask(~mask & 0777);
11830 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11831 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11832 * ash by J.T. Conklin.
11840 int factor; /* multiply by to get rlim_{cur,max} values */
11844 static const struct limits limits[] = {
11846 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11848 #ifdef RLIMIT_FSIZE
11849 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11852 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11854 #ifdef RLIMIT_STACK
11855 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11858 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11861 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11863 #ifdef RLIMIT_MEMLOCK
11864 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11866 #ifdef RLIMIT_NPROC
11867 { "process", RLIMIT_NPROC, 1, 'p' },
11869 #ifdef RLIMIT_NOFILE
11870 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11873 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11875 #ifdef RLIMIT_LOCKS
11876 { "locks", RLIMIT_LOCKS, 1, 'w' },
11878 { NULL, 0, 0, '\0' }
11881 enum limtype { SOFT = 0x1, HARD = 0x2 };
11884 printlim(enum limtype how, const struct rlimit *limit,
11885 const struct limits *l)
11889 val = limit->rlim_max;
11891 val = limit->rlim_cur;
11893 if (val == RLIM_INFINITY)
11894 out1fmt("unlimited\n");
11897 out1fmt("%lld\n", (long long) val);
11902 ulimitcmd(int argc, char **argv)
11906 enum limtype how = SOFT | HARD;
11907 const struct limits *l;
11910 struct rlimit limit;
11913 while ((optc = nextopt("HSa"
11917 #ifdef RLIMIT_FSIZE
11923 #ifdef RLIMIT_STACK
11932 #ifdef RLIMIT_MEMLOCK
11935 #ifdef RLIMIT_NPROC
11938 #ifdef RLIMIT_NOFILE
11944 #ifdef RLIMIT_LOCKS
11962 for (l = limits; l->option != what; l++)
11965 set = *argptr ? 1 : 0;
11969 if (all || argptr[1])
11970 ash_msg_and_raise_error("too many arguments");
11971 if (strncmp(p, "unlimited\n", 9) == 0)
11972 val = RLIM_INFINITY;
11976 while ((c = *p++) >= '0' && c <= '9') {
11977 val = (val * 10) + (long)(c - '0');
11978 if (val < (rlim_t) 0)
11982 ash_msg_and_raise_error("bad number");
11987 for (l = limits; l->name; l++) {
11988 getrlimit(l->cmd, &limit);
11989 out1fmt("%-20s ", l->name);
11990 printlim(how, &limit, l);
11995 getrlimit(l->cmd, &limit);
11998 limit.rlim_max = val;
12000 limit.rlim_cur = val;
12001 if (setrlimit(l->cmd, &limit) < 0)
12002 ash_msg_and_raise_error("error setting limit (%m)");
12004 printlim(how, &limit, l);
12010 /* ============ Math support */
12012 #if ENABLE_ASH_MATH_SUPPORT
12014 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12016 Permission is hereby granted, free of charge, to any person obtaining
12017 a copy of this software and associated documentation files (the
12018 "Software"), to deal in the Software without restriction, including
12019 without limitation the rights to use, copy, modify, merge, publish,
12020 distribute, sublicense, and/or sell copies of the Software, and to
12021 permit persons to whom the Software is furnished to do so, subject to
12022 the following conditions:
12024 The above copyright notice and this permission notice shall be
12025 included in all copies or substantial portions of the Software.
12027 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12028 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12029 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12030 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12031 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12032 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12033 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12036 /* This is my infix parser/evaluator. It is optimized for size, intended
12037 * as a replacement for yacc-based parsers. However, it may well be faster
12038 * than a comparable parser written in yacc. The supported operators are
12039 * listed in #defines below. Parens, order of operations, and error handling
12040 * are supported. This code is thread safe. The exact expression format should
12041 * be that which POSIX specifies for shells. */
12043 /* The code uses a simple two-stack algorithm. See
12044 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12045 * for a detailed explanation of the infix-to-postfix algorithm on which
12046 * this is based (this code differs in that it applies operators immediately
12047 * to the stack instead of adding them to a queue to end up with an
12050 /* To use the routine, call it with an expression string and error return
12054 * Aug 24, 2001 Manuel Novoa III
12056 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12058 * 1) In arith_apply():
12059 * a) Cached values of *numptr and &(numptr[-1]).
12060 * b) Removed redundant test for zero denominator.
12063 * a) Eliminated redundant code for processing operator tokens by moving
12064 * to a table-based implementation. Also folded handling of parens
12066 * b) Combined all 3 loops which called arith_apply to reduce generated
12067 * code size at the cost of speed.
12069 * 3) The following expressions were treated as valid by the original code:
12070 * 1() , 0! , 1 ( *3 ) .
12071 * These bugs have been fixed by internally enclosing the expression in
12072 * parens and then checking that all binary ops and right parens are
12073 * preceded by a valid expression (NUM_TOKEN).
12075 * Note: It may be desirable to replace Aaron's test for whitespace with
12076 * ctype's isspace() if it is used by another busybox applet or if additional
12077 * whitespace chars should be considered. Look below the "#include"s for a
12078 * precompiler test.
12082 * Aug 26, 2001 Manuel Novoa III
12084 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12086 * Merge in Aaron's comments previously posted to the busybox list,
12087 * modified slightly to take account of my changes to the code.
12092 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12094 * - allow access to variable,
12095 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12096 * - realize assign syntax (VAR=expr, +=, *= etc)
12097 * - realize exponentiation (** operator)
12098 * - realize comma separated - expr, expr
12099 * - realise ++expr --expr expr++ expr--
12100 * - realise expr ? expr : expr (but, second expr calculate always)
12101 * - allow hexadecimal and octal numbers
12102 * - was restored loses XOR operator
12103 * - remove one goto label, added three ;-)
12104 * - protect $((num num)) as true zero expr (Manuel`s error)
12105 * - always use special isspace(), see comment from bash ;-)
12108 #define arith_isspace(arithval) \
12109 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12111 typedef unsigned char operator;
12113 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12114 * precedence, and 3 high bits are an ID unique across operators of that
12115 * precedence. The ID portion is so that multiple operators can have the
12116 * same precedence, ensuring that the leftmost one is evaluated first.
12117 * Consider * and /. */
12119 #define tok_decl(prec,id) (((id)<<5)|(prec))
12120 #define PREC(op) ((op) & 0x1F)
12122 #define TOK_LPAREN tok_decl(0,0)
12124 #define TOK_COMMA tok_decl(1,0)
12126 #define TOK_ASSIGN tok_decl(2,0)
12127 #define TOK_AND_ASSIGN tok_decl(2,1)
12128 #define TOK_OR_ASSIGN tok_decl(2,2)
12129 #define TOK_XOR_ASSIGN tok_decl(2,3)
12130 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12131 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12132 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12133 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12135 #define TOK_MUL_ASSIGN tok_decl(3,0)
12136 #define TOK_DIV_ASSIGN tok_decl(3,1)
12137 #define TOK_REM_ASSIGN tok_decl(3,2)
12139 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12140 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12142 /* conditional is right associativity too */
12143 #define TOK_CONDITIONAL tok_decl(4,0)
12144 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12146 #define TOK_OR tok_decl(5,0)
12148 #define TOK_AND tok_decl(6,0)
12150 #define TOK_BOR tok_decl(7,0)
12152 #define TOK_BXOR tok_decl(8,0)
12154 #define TOK_BAND tok_decl(9,0)
12156 #define TOK_EQ tok_decl(10,0)
12157 #define TOK_NE tok_decl(10,1)
12159 #define TOK_LT tok_decl(11,0)
12160 #define TOK_GT tok_decl(11,1)
12161 #define TOK_GE tok_decl(11,2)
12162 #define TOK_LE tok_decl(11,3)
12164 #define TOK_LSHIFT tok_decl(12,0)
12165 #define TOK_RSHIFT tok_decl(12,1)
12167 #define TOK_ADD tok_decl(13,0)
12168 #define TOK_SUB tok_decl(13,1)
12170 #define TOK_MUL tok_decl(14,0)
12171 #define TOK_DIV tok_decl(14,1)
12172 #define TOK_REM tok_decl(14,2)
12174 /* exponent is right associativity */
12175 #define TOK_EXPONENT tok_decl(15,1)
12177 /* For now unary operators. */
12178 #define UNARYPREC 16
12179 #define TOK_BNOT tok_decl(UNARYPREC,0)
12180 #define TOK_NOT tok_decl(UNARYPREC,1)
12182 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12183 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12185 #define PREC_PRE (UNARYPREC+2)
12187 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12188 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12190 #define PREC_POST (UNARYPREC+3)
12192 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12193 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12195 #define SPEC_PREC (UNARYPREC+4)
12197 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12198 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12200 #define NUMPTR (*numstackptr)
12203 tok_have_assign(operator op)
12205 operator prec = PREC(op);
12207 convert_prec_is_assing(prec);
12208 return (prec == PREC(TOK_ASSIGN) ||
12209 prec == PREC_PRE || prec == PREC_POST);
12213 is_right_associativity(operator prec)
12215 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12216 || prec == PREC(TOK_CONDITIONAL));
12219 typedef struct ARITCH_VAR_NUM {
12221 arith_t contidional_second_val;
12222 char contidional_second_val_initialized;
12223 char *var; /* if NULL then is regular number,
12224 else is variable name */
12227 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12229 struct CHK_VAR_RECURSIVE_LOOPED *next;
12230 } chk_var_recursive_looped_t;
12232 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12235 arith_lookup_val(v_n_t *t)
12238 const char * p = lookupvar(t->var);
12243 /* recursive try as expression */
12244 chk_var_recursive_looped_t *cur;
12245 chk_var_recursive_looped_t cur_save;
12247 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12248 if (strcmp(cur->var, t->var) == 0) {
12249 /* expression recursion loop detected */
12253 /* save current lookuped var name */
12254 cur = prev_chk_var_recursive;
12255 cur_save.var = t->var;
12256 cur_save.next = cur;
12257 prev_chk_var_recursive = &cur_save;
12259 t->val = arith (p, &errcode);
12260 /* restore previous ptr after recursiving */
12261 prev_chk_var_recursive = cur;
12264 /* allow undefined var as 0 */
12270 /* "applying" a token means performing it on the top elements on the integer
12271 * stack. For a unary operator it will only change the top element, but a
12272 * binary operator will pop two arguments and push a result */
12274 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12277 arith_t numptr_val, rez;
12278 int ret_arith_lookup_val;
12280 /* There is no operator that can work without arguments */
12281 if (NUMPTR == numstack) goto err;
12282 numptr_m1 = NUMPTR - 1;
12284 /* check operand is var with noninteger value */
12285 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12286 if (ret_arith_lookup_val)
12287 return ret_arith_lookup_val;
12289 rez = numptr_m1->val;
12290 if (op == TOK_UMINUS)
12292 else if (op == TOK_NOT)
12294 else if (op == TOK_BNOT)
12296 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12298 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12300 else if (op != TOK_UPLUS) {
12301 /* Binary operators */
12303 /* check and binary operators need two arguments */
12304 if (numptr_m1 == numstack) goto err;
12306 /* ... and they pop one */
12309 if (op == TOK_CONDITIONAL) {
12310 if (! numptr_m1->contidional_second_val_initialized) {
12311 /* protect $((expr1 ? expr2)) without ": expr" */
12314 rez = numptr_m1->contidional_second_val;
12315 } else if (numptr_m1->contidional_second_val_initialized) {
12316 /* protect $((expr1 : expr2)) without "expr ? " */
12319 numptr_m1 = NUMPTR - 1;
12320 if (op != TOK_ASSIGN) {
12321 /* check operand is var with noninteger value for not '=' */
12322 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12323 if (ret_arith_lookup_val)
12324 return ret_arith_lookup_val;
12326 if (op == TOK_CONDITIONAL) {
12327 numptr_m1->contidional_second_val = rez;
12329 rez = numptr_m1->val;
12330 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12332 else if (op == TOK_OR)
12333 rez = numptr_val || rez;
12334 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12336 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12338 else if (op == TOK_AND)
12339 rez = rez && numptr_val;
12340 else if (op == TOK_EQ)
12341 rez = (rez == numptr_val);
12342 else if (op == TOK_NE)
12343 rez = (rez != numptr_val);
12344 else if (op == TOK_GE)
12345 rez = (rez >= numptr_val);
12346 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12347 rez >>= numptr_val;
12348 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12349 rez <<= numptr_val;
12350 else if (op == TOK_GT)
12351 rez = (rez > numptr_val);
12352 else if (op == TOK_LT)
12353 rez = (rez < numptr_val);
12354 else if (op == TOK_LE)
12355 rez = (rez <= numptr_val);
12356 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12358 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12360 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12362 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12364 else if (op == TOK_CONDITIONAL_SEP) {
12365 if (numptr_m1 == numstack) {
12366 /* protect $((expr : expr)) without "expr ? " */
12369 numptr_m1->contidional_second_val_initialized = op;
12370 numptr_m1->contidional_second_val = numptr_val;
12371 } else if (op == TOK_CONDITIONAL) {
12373 numptr_val : numptr_m1->contidional_second_val;
12374 } else if (op == TOK_EXPONENT) {
12375 if (numptr_val < 0)
12376 return -3; /* exponent less than 0 */
12381 while (numptr_val--)
12385 } else if (numptr_val==0) /* zero divisor check */
12387 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12389 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12392 if (tok_have_assign(op)) {
12393 char buf[sizeof(arith_t_type)*3 + 2];
12395 if (numptr_m1->var == NULL) {
12399 /* save to shell variable */
12400 #if ENABLE_ASH_MATH_SUPPORT_64
12401 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12403 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12405 setvar(numptr_m1->var, buf, 0);
12406 /* after saving, make previous value for v++ or v-- */
12407 if (op == TOK_POST_INC)
12409 else if (op == TOK_POST_DEC)
12412 numptr_m1->val = rez;
12413 /* protect geting var value, is number now */
12414 numptr_m1->var = NULL;
12420 /* longest must be first */
12421 static const char op_tokens[] = {
12422 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12423 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12424 '<','<', 0, TOK_LSHIFT,
12425 '>','>', 0, TOK_RSHIFT,
12426 '|','|', 0, TOK_OR,
12427 '&','&', 0, TOK_AND,
12428 '!','=', 0, TOK_NE,
12429 '<','=', 0, TOK_LE,
12430 '>','=', 0, TOK_GE,
12431 '=','=', 0, TOK_EQ,
12432 '|','=', 0, TOK_OR_ASSIGN,
12433 '&','=', 0, TOK_AND_ASSIGN,
12434 '*','=', 0, TOK_MUL_ASSIGN,
12435 '/','=', 0, TOK_DIV_ASSIGN,
12436 '%','=', 0, TOK_REM_ASSIGN,
12437 '+','=', 0, TOK_PLUS_ASSIGN,
12438 '-','=', 0, TOK_MINUS_ASSIGN,
12439 '-','-', 0, TOK_POST_DEC,
12440 '^','=', 0, TOK_XOR_ASSIGN,
12441 '+','+', 0, TOK_POST_INC,
12442 '*','*', 0, TOK_EXPONENT,
12446 '=', 0, TOK_ASSIGN,
12458 '?', 0, TOK_CONDITIONAL,
12459 ':', 0, TOK_CONDITIONAL_SEP,
12460 ')', 0, TOK_RPAREN,
12461 '(', 0, TOK_LPAREN,
12465 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12468 arith(const char *expr, int *perrcode)
12470 char arithval; /* Current character under analysis */
12471 operator lasttok, op;
12474 const char *p = endexpression;
12477 size_t datasizes = strlen(expr) + 2;
12479 /* Stack of integers */
12480 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12481 * in any given correct or incorrect expression is left as an exercise to
12483 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12484 *numstackptr = numstack;
12485 /* Stack of operator tokens */
12486 operator *stack = alloca((datasizes) * sizeof(operator)),
12489 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12490 *perrcode = errcode = 0;
12494 if (arithval == 0) {
12495 if (p == endexpression) {
12496 /* Null expression. */
12500 /* This is only reached after all tokens have been extracted from the
12501 * input stream. If there are still tokens on the operator stack, they
12502 * are to be applied in order. At the end, there should be a final
12503 * result on the integer stack */
12505 if (expr != endexpression + 1) {
12506 /* If we haven't done so already, */
12507 /* append a closing right paren */
12508 expr = endexpression;
12509 /* and let the loop process it. */
12512 /* At this point, we're done with the expression. */
12513 if (numstackptr != numstack+1) {
12514 /* ... but if there isn't, it's bad */
12516 return (*perrcode = -1);
12518 if (numstack->var) {
12519 /* expression is $((var)) only, lookup now */
12520 errcode = arith_lookup_val(numstack);
12523 *perrcode = errcode;
12524 return numstack->val;
12527 /* Continue processing the expression. */
12528 if (arith_isspace(arithval)) {
12529 /* Skip whitespace */
12532 p = endofname(expr);
12534 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12536 numstackptr->var = alloca(var_name_size);
12537 safe_strncpy(numstackptr->var, expr, var_name_size);
12540 numstackptr->contidional_second_val_initialized = 0;
12545 if (isdigit(arithval)) {
12546 numstackptr->var = NULL;
12547 #if ENABLE_ASH_MATH_SUPPORT_64
12548 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12550 numstackptr->val = strtol(expr, (char **) &expr, 0);
12554 for (p = op_tokens; ; p++) {
12558 /* strange operator not found */
12561 for (o = expr; *p && *o == *p; p++)
12568 /* skip tail uncompared token */
12571 /* skip zero delim */
12576 /* post grammar: a++ reduce to num */
12577 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12580 /* Plus and minus are binary (not unary) _only_ if the last
12581 * token was as number, or a right paren (which pretends to be
12582 * a number, since it evaluates to one). Think about it.
12583 * It makes sense. */
12584 if (lasttok != TOK_NUM) {
12600 /* We don't want a unary operator to cause recursive descent on the
12601 * stack, because there can be many in a row and it could cause an
12602 * operator to be evaluated before its argument is pushed onto the
12603 * integer stack. */
12604 /* But for binary operators, "apply" everything on the operator
12605 * stack until we find an operator with a lesser priority than the
12606 * one we have just extracted. */
12607 /* Left paren is given the lowest priority so it will never be
12608 * "applied" in this way.
12609 * if associativity is right and priority eq, applied also skip
12612 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12613 /* not left paren or unary */
12614 if (lasttok != TOK_NUM) {
12615 /* binary op must be preceded by a num */
12618 while (stackptr != stack) {
12619 if (op == TOK_RPAREN) {
12620 /* The algorithm employed here is simple: while we don't
12621 * hit an open paren nor the bottom of the stack, pop
12622 * tokens and apply them */
12623 if (stackptr[-1] == TOK_LPAREN) {
12625 /* Any operator directly after a */
12627 /* close paren should consider itself binary */
12631 operator prev_prec = PREC(stackptr[-1]);
12633 convert_prec_is_assing(prec);
12634 convert_prec_is_assing(prev_prec);
12635 if (prev_prec < prec)
12637 /* check right assoc */
12638 if (prev_prec == prec && is_right_associativity(prec))
12641 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12642 if (errcode) goto ret;
12644 if (op == TOK_RPAREN) {
12649 /* Push this operator to the stack and remember it. */
12650 *stackptr++ = lasttok = op;
12655 #endif /* ASH_MATH_SUPPORT */
12658 /* ============ main() and helpers */
12661 * Called to exit the shell.
12663 static void exitshell(void) ATTRIBUTE_NORETURN;
12671 status = exitstatus;
12672 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12673 if (setjmp(loc.loc)) {
12674 if (exception == EXEXIT)
12675 /* dash bug: it just does _exit(exitstatus) here
12676 * but we have to do setjobctl(0) first!
12677 * (bug is still not fixed in dash-0.5.3 - if you run dash
12678 * under Midnight Commander, on exit from dash MC is backgrounded) */
12679 status = exitstatus;
12682 exception_handler = &loc;
12688 flush_stdout_stderr();
12698 /* from input.c: */
12699 basepf.nextc = basepf.buf = basebuf;
12702 signal(SIGCHLD, SIG_DFL);
12707 char ppid[sizeof(int)*3 + 1];
12709 struct stat st1, st2;
12712 for (envp = environ; envp && *envp; envp++) {
12713 if (strchr(*envp, '=')) {
12714 setvareq(*envp, VEXPORT|VTEXTFIXED);
12718 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12719 setvar("PPID", ppid, 0);
12721 p = lookupvar("PWD");
12723 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12724 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12731 * Process the shell command line arguments.
12734 procargs(int argc, char **argv)
12737 const char *xminusc;
12744 for (i = 0; i < NOPTS; i++)
12750 if (*xargv == NULL) {
12752 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12755 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12759 for (i = 0; i < NOPTS; i++)
12760 if (optlist[i] == 2)
12765 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12770 } else if (!sflag) {
12771 setinputfile(*xargv, 0);
12774 commandname = arg0;
12777 shellparam.p = xargv;
12778 #if ENABLE_ASH_GETOPTS
12779 shellparam.optind = 1;
12780 shellparam.optoff = -1;
12782 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12784 shellparam.nparam++;
12791 * Read /etc/profile or .profile.
12794 read_profile(const char *name)
12798 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12807 * This routine is called when an error or an interrupt occurs in an
12808 * interactive shell and control is returned to the main command loop.
12816 /* from input.c: */
12817 parselleft = parsenleft = 0; /* clear input buffer */
12819 /* from parser.c: */
12822 /* from redir.c: */
12827 static short profile_buf[16384];
12828 extern int etext();
12832 * Main routine. We initialize things, parse the arguments, execute
12833 * profiles if we're a login shell, and then call cmdloop to execute
12834 * commands. The setjmp call sets up the location to jump to when an
12835 * exception occurs. When an exception occurs the variable "state"
12836 * is used to figure out how far we had gotten.
12838 int ash_main(int argc, char **argv);
12839 int ash_main(int argc, char **argv)
12842 volatile int state;
12843 struct jmploc jmploc;
12844 struct stackmark smark;
12847 dash_errno = __errno_location();
12851 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12854 #if ENABLE_FEATURE_EDITING
12855 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12858 if (setjmp(jmploc.loc)) {
12868 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12872 outcslow('\n', stderr);
12874 popstackmark(&smark);
12875 FORCE_INT_ON; /* enable interrupts */
12884 exception_handler = &jmploc;
12887 trace_puts("Shell args: ");
12888 trace_puts_args(argv);
12890 rootpid = getpid();
12892 #if ENABLE_ASH_RANDOM_SUPPORT
12893 rseed = rootpid + time(NULL);
12896 setstackmark(&smark);
12897 procargs(argc, argv);
12898 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12900 const char *hp = lookupvar("HISTFILE");
12903 hp = lookupvar("HOME");
12905 char *defhp = concat_path_file(hp, ".ash_history");
12906 setvar("HISTFILE", defhp, 0);
12912 if (argv[0] && argv[0][0] == '-')
12916 read_profile("/etc/profile");
12919 read_profile(".profile");
12925 getuid() == geteuid() && getgid() == getegid() &&
12929 shinit = lookupvar("ENV");
12930 if (shinit != NULL && *shinit != '\0') {
12931 read_profile(shinit);
12937 evalstring(minusc, 0);
12939 if (sflag || minusc == NULL) {
12940 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12942 const char *hp = lookupvar("HISTFILE");
12945 line_input_state->hist_file = hp;
12948 state4: /* XXX ??? - why isn't this before the "if" statement */
12956 extern void _mcleanup(void);
12965 const char *applet_name = "debug stuff usage";
12966 int main(int argc, char **argv)
12968 return ash_main(argc, argv);
12974 * Copyright (c) 1989, 1991, 1993, 1994
12975 * The Regents of the University of California. All rights reserved.
12977 * This code is derived from software contributed to Berkeley by
12978 * Kenneth Almquist.
12980 * Redistribution and use in source and binary forms, with or without
12981 * modification, are permitted provided that the following conditions
12983 * 1. Redistributions of source code must retain the above copyright
12984 * notice, this list of conditions and the following disclaimer.
12985 * 2. Redistributions in binary form must reproduce the above copyright
12986 * notice, this list of conditions and the following disclaimer in the
12987 * documentation and/or other materials provided with the distribution.
12988 * 3. Neither the name of the University nor the names of its contributors
12989 * may be used to endorse or promote products derived from this software
12990 * without specific prior written permission.
12992 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12993 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12994 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12995 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12996 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12997 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12998 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12999 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13000 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13001 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF