1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
12 * This code is derived from software contributed to Berkeley by
15 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
17 * Original BSD copyright notice is retained at the end of this file.
21 * rewrite arith.y to micro stack based cryptic algorithm by
22 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
24 * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
27 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
28 * used in busybox and size optimizations,
29 * rewrote arith (see notes to this), added locale support,
30 * rewrote dynamic variables.
35 * The follow should be set to reflect the type of system you have:
36 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
37 * define SYSV if you are running under System V.
38 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
39 * define DEBUG=2 to compile in and turn on debugging.
41 * When debugging is on, debugging info will be written to ./trace and
42 * a quit signal will generate a core dump.
47 #if ENABLE_ASH_JOB_CONTROL
56 #include "busybox.h" /* for struct bb_applet */
60 #if JOBS || ENABLE_ASH_READ_NCHARS
63 extern char **environ;
65 #if defined(__uClinux__)
66 #error "Do not even bother, ash will not run on uClinux"
70 /* ============ Misc helpers */
72 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
74 /* C99 say: "char" declaration may be signed or unsigned default */
75 #define signed_char2int(sc) ((int)((signed char)sc))
78 /* ============ Shell options */
80 static const char *const optletters_optnames[] = {
101 #define optletters(n) optletters_optnames[(n)][0]
102 #define optnames(n) (&optletters_optnames[(n)][1])
104 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
106 static char optlist[NOPTS];
108 #define eflag optlist[0]
109 #define fflag optlist[1]
110 #define Iflag optlist[2]
111 #define iflag optlist[3]
112 #define mflag optlist[4]
113 #define nflag optlist[5]
114 #define sflag optlist[6]
115 #define xflag optlist[7]
116 #define vflag optlist[8]
117 #define Cflag optlist[9]
118 #define aflag optlist[10]
119 #define bflag optlist[11]
120 #define uflag optlist[12]
121 #define viflag optlist[13]
123 #define nolog optlist[14]
124 #define debug optlist[15]
128 /* ============ Misc data */
130 static char nullstr[1]; /* zero length string */
131 static const char homestr[] = "HOME";
132 static const char snlfmt[] = "%s\n";
133 static const char illnum[] = "Illegal number: %s";
135 static char *minusc; /* argument to -c option */
137 static int isloginsh;
138 /* pid of main shell */
140 /* shell level: 0 for the main shell, 1 for its children, and so on */
142 #define rootshell (!shlvl)
143 /* trap handler commands */
144 static char *trap[NSIG];
145 /* current value of signal */
146 static char sigmode[NSIG - 1];
147 /* indicates specified signal received */
148 static char gotsig[NSIG - 1];
149 static char *arg0; /* value of $0 */
152 /* ============ Interrupts / exceptions */
155 * We enclose jmp_buf in a structure so that we can declare pointers to
156 * jump locations. The global variable handler contains the location to
157 * jump to when an exception occurs, and the global variable exception
158 * contains a code identifying the exception. To implement nested
159 * exception handlers, the user should save the value of handler on entry
160 * to an inner scope, set handler to point to a jmploc structure for the
161 * inner scope, and restore handler on exit from the scope.
166 static struct jmploc *exception_handler;
167 static int exception;
169 #define EXINT 0 /* SIGINT received */
170 #define EXERROR 1 /* a generic error */
171 #define EXSHELLPROC 2 /* execute a shell procedure */
172 #define EXEXEC 3 /* command execution failed */
173 #define EXEXIT 4 /* exit the shell */
174 #define EXSIG 5 /* trapped signal in wait(1) */
175 static volatile int suppressint;
176 static volatile sig_atomic_t intpending;
177 /* do we generate EXSIG events */
179 /* last pending signal */
180 static volatile sig_atomic_t pendingsig;
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
188 #define S_DFL 1 /* default signal handling (SIG_DFL) */
189 #define S_CATCH 2 /* signal is caught */
190 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
191 #define S_HARD_IGN 4 /* signal is ignored permenantly */
192 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
195 * These macros allow the user to suspend the handling of interrupt signals
196 * over a period of time. This is similar to SIGHOLD to or sigblock, but
197 * much more efficient and portable. (But hacking the kernel is so much
198 * more fun than worrying about efficiency and portability. :-))
207 * Called to raise an exception. Since C doesn't include exceptions, we
208 * just do a longjmp to the exception handler. The type of exception is
209 * stored in the global variable "exception".
211 static void raise_exception(int) ATTRIBUTE_NORETURN;
213 raise_exception(int e)
216 if (exception_handler == NULL)
221 longjmp(exception_handler->loc, 1);
225 * Called from trap.c when a SIGINT is received. (If the user specifies
226 * that SIGINT is to be trapped or ignored using the trap builtin, then
227 * this routine is not called.) Suppressint is nonzero when interrupts
228 * are held using the INT_OFF macro. (The test for iflag is just
229 * defensive programming.)
231 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
233 raise_interrupt(void)
239 /* Signal is not automatically re-enabled after it is raised,
242 sigprocmask(SIG_SETMASK, &mask, 0);
243 /* pendingsig = 0; - now done in onsig() */
246 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
247 if (!(rootshell && iflag)) {
248 signal(SIGINT, SIG_DFL);
257 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
261 if (--suppressint == 0 && intpending) {
265 #define INT_ON int_on()
273 #define FORCE_INT_ON force_int_on()
278 if (--suppressint == 0 && intpending) \
281 #define FORCE_INT_ON \
288 #endif /* ASH_OPTIMIZE_FOR_SIZE */
290 #define SAVE_INT(v) ((v) = suppressint)
292 #define RESTORE_INT(v) \
296 if (suppressint == 0 && intpending) \
305 raise_exception(EXSIG); \
307 /* EXSIG is turned off by evalbltin(). */
310 * Ignore a signal. Only one usage site - in forkchild()
315 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
316 signal(signo, SIG_IGN);
318 sigmode[signo - 1] = S_HARD_IGN;
322 * Signal handler. Only one usage site - in setsignal()
327 gotsig[signo - 1] = 1;
330 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
340 /* ============ Stdout/stderr output */
343 outstr(const char *p, FILE *file)
351 flush_stdout_stderr(void)
368 outcslow(int c, FILE *dest)
376 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
378 out1fmt(const char *fmt, ...)
385 r = vprintf(fmt, ap);
391 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
393 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
400 ret = vsnprintf(outbuf, length, fmt, ap);
407 out1str(const char *p)
413 out2str(const char *p)
420 /* ============ Parser structures */
422 /* control characters in argument strings */
423 #define CTLESC '\201' /* escape next character */
424 #define CTLVAR '\202' /* variable defn */
425 #define CTLENDVAR '\203'
426 #define CTLBACKQ '\204'
427 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
428 /* CTLBACKQ | CTLQUOTE == '\205' */
429 #define CTLARI '\206' /* arithmetic expression */
430 #define CTLENDARI '\207'
431 #define CTLQUOTEMARK '\210'
433 /* variable substitution byte (follows CTLVAR) */
434 #define VSTYPE 0x0f /* type of variable substitution */
435 #define VSNUL 0x10 /* colon--treat the empty string as unset */
436 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
438 /* values of VSTYPE field */
439 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
440 #define VSMINUS 0x2 /* ${var-text} */
441 #define VSPLUS 0x3 /* ${var+text} */
442 #define VSQUESTION 0x4 /* ${var?message} */
443 #define VSASSIGN 0x5 /* ${var=text} */
444 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
445 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
446 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
447 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
448 #define VSLENGTH 0xa /* ${#var} */
450 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
485 union node *redirect;
491 struct nodelist *cmdlist;
497 union node *redirect;
510 union node *elsepart;
537 struct nodelist *backquote;
572 struct nredir nredir;
573 struct nbinary nbinary;
577 struct nclist nclist;
586 struct nodelist *next;
599 freefunc(struct funcnode *f)
601 if (f && --f->count < 0)
606 /* ============ Debugging output */
610 static FILE *tracefile;
613 trace_printf(const char *fmt, ...)
620 vfprintf(tracefile, fmt, va);
625 trace_vprintf(const char *fmt, va_list va)
629 vfprintf(tracefile, fmt, va);
633 trace_puts(const char *s)
641 trace_puts_quoted(char *s)
648 putc('"', tracefile);
649 for (p = s; *p; p++) {
651 case '\n': c = 'n'; goto backslash;
652 case '\t': c = 't'; goto backslash;
653 case '\r': c = 'r'; goto backslash;
654 case '"': c = '"'; goto backslash;
655 case '\\': c = '\\'; goto backslash;
656 case CTLESC: c = 'e'; goto backslash;
657 case CTLVAR: c = 'v'; goto backslash;
658 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
659 case CTLBACKQ: c = 'q'; goto backslash;
660 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
662 putc('\\', tracefile);
666 if (*p >= ' ' && *p <= '~')
669 putc('\\', tracefile);
670 putc(*p >> 6 & 03, tracefile);
671 putc(*p >> 3 & 07, tracefile);
672 putc(*p & 07, tracefile);
677 putc('"', tracefile);
681 trace_puts_args(char **ap)
688 trace_puts_quoted(*ap);
690 putc('\n', tracefile);
693 putc(' ', tracefile);
708 /* leave open because libedit might be using it */
711 strcpy(s, "./trace");
713 if (!freopen(s, "a", tracefile)) {
714 fprintf(stderr, "Can't re-open %s\n", s);
719 tracefile = fopen(s, "a");
720 if (tracefile == NULL) {
721 fprintf(stderr, "Can't open %s\n", s);
727 flags = fcntl(fileno(tracefile), F_GETFL, 0);
729 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
731 setlinebuf(tracefile);
732 fputs("\nTracing started.\n", tracefile);
736 indent(int amount, char *pfx, FILE *fp)
740 for (i = 0; i < amount; i++) {
741 if (pfx && i == amount - 1)
747 /* little circular references here... */
748 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
751 sharg(union node *arg, FILE *fp)
754 struct nodelist *bqlist;
757 if (arg->type != NARG) {
758 out1fmt("<node type %d>\n", arg->type);
761 bqlist = arg->narg.backquote;
762 for (p = arg->narg.text; *p; p++) {
771 if (subtype == VSLENGTH)
780 switch (subtype & VSTYPE) {
813 out1fmt("<subtype %d>", subtype);
820 case CTLBACKQ|CTLQUOTE:
823 shtree(bqlist->n, -1, NULL, fp);
834 shcmd(union node *cmd, FILE *fp)
842 for (np = cmd->ncmd.args; np; np = np->narg.next) {
848 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
851 switch (np->nfile.type) {
852 case NTO: s = ">"; dftfd = 1; break;
853 case NCLOBBER: s = ">|"; dftfd = 1; break;
854 case NAPPEND: s = ">>"; dftfd = 1; break;
855 case NTOFD: s = ">&"; dftfd = 1; break;
856 case NFROM: s = "<"; dftfd = 0; break;
857 case NFROMFD: s = "<&"; dftfd = 0; break;
858 case NFROMTO: s = "<>"; dftfd = 0; break;
859 default: s = "*error*"; dftfd = 0; break;
861 if (np->nfile.fd != dftfd)
862 fprintf(fp, "%d", np->nfile.fd);
864 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
865 fprintf(fp, "%d", np->ndup.dupfd);
867 sharg(np->nfile.fname, fp);
874 shtree(union node *n, int ind, char *pfx, FILE *fp)
882 indent(ind, pfx, fp);
893 shtree(n->nbinary.ch1, ind, NULL, fp);
896 shtree(n->nbinary.ch2, ind, NULL, fp);
904 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
909 if (n->npipe.backgnd)
915 fprintf(fp, "<node type %d>", n->type);
923 showtree(union node *n)
925 trace_puts("showtree called\n");
926 shtree(n, 1, NULL, stdout);
929 #define TRACE(param) trace_printf param
930 #define TRACEV(param) trace_vprintf param
935 #define TRACEV(param)
940 /* ============ Parser data */
943 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
946 struct strlist *next;
955 struct strpush *prev; /* preceding string on stack */
959 struct alias *ap; /* if push was associated with an alias */
961 char *string; /* remember the string since it may change */
965 struct parsefile *prev; /* preceding file on stack */
966 int linno; /* current line */
967 int fd; /* file descriptor (or -1 if string) */
968 int nleft; /* number of chars left in this line */
969 int lleft; /* number of chars left in this buffer */
970 char *nextc; /* next char in buffer */
971 char *buf; /* input buffer */
972 struct strpush *strpush; /* for pushing strings at this level */
973 struct strpush basestrpush; /* so pushing one is fast */
976 static struct parsefile basepf; /* top level input file */
977 static struct parsefile *parsefile = &basepf; /* current input file */
978 static int startlinno; /* line # where last token started */
979 static char *commandname; /* currently executing command */
980 static struct strlist *cmdenviron; /* environment for builtin command */
981 static int exitstatus; /* exit status of last command */
984 /* ============ Message printing */
987 ash_vmsg(const char *msg, va_list ap)
989 fprintf(stderr, "%s: ", arg0);
991 if (strcmp(arg0, commandname))
992 fprintf(stderr, "%s: ", commandname);
993 if (!iflag || parsefile->fd)
994 fprintf(stderr, "line %d: ", startlinno);
996 vfprintf(stderr, msg, ap);
997 outcslow('\n', stderr);
1001 * Exverror is called to raise the error exception. If the second argument
1002 * is not NULL then error prints an error message using printf style
1003 * formatting. It then raises the error exception.
1005 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1007 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1011 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1013 TRACE(("\") pid=%d\n", getpid()));
1015 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1020 flush_stdout_stderr();
1021 raise_exception(cond);
1025 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1027 ash_msg_and_raise_error(const char *msg, ...)
1032 ash_vmsg_and_raise(EXERROR, msg, ap);
1037 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1039 ash_msg_and_raise(int cond, const char *msg, ...)
1044 ash_vmsg_and_raise(cond, msg, ap);
1050 * error/warning routines for external builtins
1053 ash_msg(const char *fmt, ...)
1063 * Return a string describing an error. The returned string may be a
1064 * pointer to a static buffer that will be overwritten on the next call.
1065 * Action describes the operation that got the error.
1068 errmsg(int e, const char *em)
1070 if (e == ENOENT || e == ENOTDIR) {
1077 /* ============ Memory allocation */
1080 * It appears that grabstackstr() will barf with such alignments
1081 * because stalloc() will return a string allocated in a new stackblock.
1083 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1085 /* Most machines require the value returned from malloc to be aligned
1086 * in some way. The following macro will get this right
1087 * on many machines. */
1088 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1089 /* Minimum size of a block */
1090 MINSIZE = SHELL_ALIGN(504),
1093 struct stack_block {
1094 struct stack_block *prev;
1095 char space[MINSIZE];
1099 struct stack_block *stackp;
1102 struct stackmark *marknext;
1105 static struct stack_block stackbase;
1106 static struct stack_block *stackp = &stackbase;
1107 static struct stackmark *markp;
1108 static char *stacknxt = stackbase.space;
1109 static size_t stacknleft = MINSIZE;
1110 static char *sstrend = stackbase.space + MINSIZE;
1111 static int herefd = -1;
1113 #define stackblock() ((void *)stacknxt)
1114 #define stackblocksize() stacknleft
1117 ckrealloc(void * p, size_t nbytes)
1119 p = realloc(p, nbytes);
1121 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1126 ckmalloc(size_t nbytes)
1128 return ckrealloc(NULL, nbytes);
1132 * Make a copy of a string in safe storage.
1135 ckstrdup(const char *s)
1137 char *p = strdup(s);
1139 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1144 * Parse trees for commands are allocated in lifo order, so we use a stack
1145 * to make this more efficient, and also to avoid all sorts of exception
1146 * handling code to handle interrupts in the middle of a parse.
1148 * The size 504 was chosen because the Ultrix malloc handles that size
1152 stalloc(size_t nbytes)
1157 aligned = SHELL_ALIGN(nbytes);
1158 if (aligned > stacknleft) {
1161 struct stack_block *sp;
1163 blocksize = aligned;
1164 if (blocksize < MINSIZE)
1165 blocksize = MINSIZE;
1166 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1167 if (len < blocksize)
1168 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1172 stacknxt = sp->space;
1173 stacknleft = blocksize;
1174 sstrend = stacknxt + blocksize;
1179 stacknxt += aligned;
1180 stacknleft -= aligned;
1188 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1189 write(2, "stunalloc\n", 10);
1193 stacknleft += stacknxt - (char *)p;
1198 * Like strdup but works with the ash stack.
1201 ststrdup(const char *p)
1203 size_t len = strlen(p) + 1;
1204 return memcpy(stalloc(len), p, len);
1208 setstackmark(struct stackmark *mark)
1210 mark->stackp = stackp;
1211 mark->stacknxt = stacknxt;
1212 mark->stacknleft = stacknleft;
1213 mark->marknext = markp;
1218 popstackmark(struct stackmark *mark)
1220 struct stack_block *sp;
1226 markp = mark->marknext;
1227 while (stackp != mark->stackp) {
1232 stacknxt = mark->stacknxt;
1233 stacknleft = mark->stacknleft;
1234 sstrend = mark->stacknxt + mark->stacknleft;
1239 * When the parser reads in a string, it wants to stick the string on the
1240 * stack and only adjust the stack pointer when it knows how big the
1241 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1242 * of space on top of the stack and stackblocklen returns the length of
1243 * this block. Growstackblock will grow this space by at least one byte,
1244 * possibly moving it (like realloc). Grabstackblock actually allocates the
1245 * part of the block that has been used.
1248 growstackblock(void)
1252 newlen = stacknleft * 2;
1253 if (newlen < stacknleft)
1254 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1258 if (stacknxt == stackp->space && stackp != &stackbase) {
1259 struct stack_block *oldstackp;
1260 struct stackmark *xmark;
1261 struct stack_block *sp;
1262 struct stack_block *prevstackp;
1268 prevstackp = sp->prev;
1269 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1270 sp = ckrealloc(sp, grosslen);
1271 sp->prev = prevstackp;
1273 stacknxt = sp->space;
1274 stacknleft = newlen;
1275 sstrend = sp->space + newlen;
1278 * Stack marks pointing to the start of the old block
1279 * must be relocated to point to the new block
1282 while (xmark != NULL && xmark->stackp == oldstackp) {
1283 xmark->stackp = stackp;
1284 xmark->stacknxt = stacknxt;
1285 xmark->stacknleft = stacknleft;
1286 xmark = xmark->marknext;
1290 char *oldspace = stacknxt;
1291 int oldlen = stacknleft;
1292 char *p = stalloc(newlen);
1294 /* free the space we just allocated */
1295 stacknxt = memcpy(p, oldspace, oldlen);
1296 stacknleft += newlen;
1301 grabstackblock(size_t len)
1303 len = SHELL_ALIGN(len);
1309 * The following routines are somewhat easier to use than the above.
1310 * The user declares a variable of type STACKSTR, which may be declared
1311 * to be a register. The macro STARTSTACKSTR initializes things. Then
1312 * the user uses the macro STPUTC to add characters to the string. In
1313 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1314 * grown as necessary. When the user is done, she can just leave the
1315 * string there and refer to it using stackblock(). Or she can allocate
1316 * the space for it using grabstackstr(). If it is necessary to allow
1317 * someone else to use the stack temporarily and then continue to grow
1318 * the string, the user should use grabstack to allocate the space, and
1319 * then call ungrabstr(p) to return to the previous mode of operation.
1321 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1322 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1323 * is space for at least one character.
1328 size_t len = stackblocksize();
1329 if (herefd >= 0 && len >= 1024) {
1330 full_write(herefd, stackblock(), len);
1331 return stackblock();
1334 return stackblock() + len;
1338 * Called from CHECKSTRSPACE.
1341 makestrspace(size_t newlen, char *p)
1343 size_t len = p - stacknxt;
1344 size_t size = stackblocksize();
1349 size = stackblocksize();
1351 if (nleft >= newlen)
1355 return stackblock() + len;
1359 stack_nputstr(const char *s, size_t n, char *p)
1361 p = makestrspace(n, p);
1362 p = memcpy(p, s, n) + n;
1367 stack_putstr(const char *s, char *p)
1369 return stack_nputstr(s, strlen(s), p);
1373 _STPUTC(int c, char *p)
1381 #define STARTSTACKSTR(p) ((p) = stackblock())
1382 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1383 #define CHECKSTRSPACE(n, p) \
1387 size_t m = sstrend - q; \
1389 (p) = makestrspace(l, q); \
1391 #define USTPUTC(c, p) (*p++ = (c))
1392 #define STACKSTRNUL(p) \
1394 if ((p) == sstrend) \
1395 p = growstackstr(); \
1398 #define STUNPUTC(p) (--p)
1399 #define STTOPC(p) (p[-1])
1400 #define STADJUST(amount, p) (p += (amount))
1402 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1403 #define ungrabstackstr(s, p) stunalloc((s))
1404 #define stackstrend() ((void *)sstrend)
1407 /* ============ String helpers */
1410 * prefix -- see if pfx is a prefix of string.
1413 prefix(const char *string, const char *pfx)
1416 if (*pfx++ != *string++)
1419 return (char *) string;
1423 * Check for a valid number. This should be elsewhere.
1426 is_number(const char *p)
1431 } while (*++p != '\0');
1436 * Convert a string of digits to an integer, printing an error message on
1440 number(const char *s)
1443 ash_msg_and_raise_error(illnum, s);
1448 * Produce a possibly single quoted string suitable as input to the shell.
1449 * The return string is allocated on the stack.
1452 single_quote(const char *s)
1462 len = strchrnul(s, '\'') - s;
1464 q = p = makestrspace(len + 3, p);
1467 q = memcpy(q, s, len) + len;
1473 len = strspn(s, "'");
1477 q = p = makestrspace(len + 3, p);
1480 q = memcpy(q, s, len) + len;
1489 return stackblock();
1493 /* ============ nextopt */
1495 static char **argptr; /* argument list for builtin commands */
1496 static char *optionarg; /* set by nextopt (like getopt) */
1497 static char *optptr; /* used by nextopt */
1500 * XXX - should get rid of. have all builtins use getopt(3). the
1501 * library getopt must have the BSD extension static variable "optreset"
1502 * otherwise it can't be used within the shell safely.
1504 * Standard option processing (a la getopt) for builtin routines. The
1505 * only argument that is passed to nextopt is the option string; the
1506 * other arguments are unnecessary. It return the character, or '\0' on
1510 nextopt(const char *optstring)
1517 if (p == NULL || *p == '\0') {
1519 if (p == NULL || *p != '-' || *++p == '\0')
1522 if (LONE_DASH(p)) /* check for "--" */
1526 for (q = optstring; *q != c; ) {
1528 ash_msg_and_raise_error("illegal option -%c", c);
1533 if (*p == '\0' && (p = *argptr++) == NULL)
1534 ash_msg_and_raise_error("no arg for -%c option", c);
1543 /* ============ Math support definitions */
1545 #if ENABLE_ASH_MATH_SUPPORT_64
1546 typedef int64_t arith_t;
1547 #define arith_t_type long long
1549 typedef long arith_t;
1550 #define arith_t_type long
1553 #if ENABLE_ASH_MATH_SUPPORT
1554 static arith_t dash_arith(const char *);
1555 static arith_t arith(const char *expr, int *perrcode);
1558 #if ENABLE_ASH_RANDOM_SUPPORT
1559 static unsigned long rseed;
1566 /* ============ Shell variables */
1569 #define VEXPORT 0x01 /* variable is exported */
1570 #define VREADONLY 0x02 /* variable cannot be modified */
1571 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1572 #define VTEXTFIXED 0x08 /* text is statically allocated */
1573 #define VSTACK 0x10 /* text is allocated on the stack */
1574 #define VUNSET 0x20 /* the variable is not set */
1575 #define VNOFUNC 0x40 /* don't call the callback function */
1576 #define VNOSET 0x80 /* do not set variable - just readonly test */
1577 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1579 # define VDYNAMIC 0x200 /* dynamic variable */
1585 static const char defifsvar[] = "IFS= \t\n";
1586 #define defifs (defifsvar + 4)
1588 static const char defifs[] = " \t\n";
1592 int nparam; /* # of positional parameters (without $0) */
1593 unsigned char malloc; /* if parameter list dynamically allocated */
1594 char **p; /* parameter list */
1595 #if ENABLE_ASH_GETOPTS
1596 int optind; /* next parameter to be processed by getopts */
1597 int optoff; /* used by getopts */
1601 static struct shparam shellparam; /* $@ current positional parameters */
1604 * Free the list of positional parameters.
1607 freeparam(volatile struct shparam *param)
1611 if (param->malloc) {
1612 for (ap = param->p; *ap; ap++)
1618 #if ENABLE_ASH_GETOPTS
1620 getoptsreset(const char *value)
1622 shellparam.optind = number(value);
1623 shellparam.optoff = -1;
1628 struct var *next; /* next entry in hash list */
1629 int flags; /* flags are defined above */
1630 const char *text; /* name=value */
1631 void (*func)(const char *); /* function to be called when */
1632 /* the variable gets set/unset */
1636 struct localvar *next; /* next local variable in list */
1637 struct var *vp; /* the variable that was made local */
1638 int flags; /* saved flags */
1639 const char *text; /* saved text */
1642 /* Forward decls for varinit[] */
1643 #if ENABLE_LOCALE_SUPPORT
1645 change_lc_all(const char *value)
1647 if (value && *value != '\0')
1648 setlocale(LC_ALL, value);
1651 change_lc_ctype(const char *value)
1653 if (value && *value != '\0')
1654 setlocale(LC_CTYPE, value);
1658 static void chkmail(void);
1659 static void changemail(const char *);
1661 static void changepath(const char *);
1662 #if ENABLE_ASH_RANDOM_SUPPORT
1663 static void change_random(const char *);
1666 static struct var varinit[] = {
1668 { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
1670 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
1673 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1674 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1676 { NULL, VSTRFIXED|VTEXTFIXED, bb_PATH_root_path, changepath },
1677 { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
1678 { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
1679 { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
1680 #if ENABLE_ASH_GETOPTS
1681 { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1683 #if ENABLE_ASH_RANDOM_SUPPORT
1684 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1686 #if ENABLE_LOCALE_SUPPORT
1687 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1688 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1690 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1691 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1695 #define vifs varinit[0]
1697 #define vmail (&vifs)[1]
1698 #define vmpath (&vmail)[1]
1702 #define vpath (&vmpath)[1]
1703 #define vps1 (&vpath)[1]
1704 #define vps2 (&vps1)[1]
1705 #define vps4 (&vps2)[1]
1706 #define voptind (&vps4)[1]
1707 #if ENABLE_ASH_GETOPTS
1708 #define vrandom (&voptind)[1]
1710 #define vrandom (&vps4)[1]
1714 * The following macros access the values of the above variables.
1715 * They have to skip over the name. They return the null string
1716 * for unset variables.
1718 #define ifsval() (vifs.text + 4)
1719 #define ifsset() ((vifs.flags & VUNSET) == 0)
1720 #define mailval() (vmail.text + 5)
1721 #define mpathval() (vmpath.text + 9)
1722 #define pathval() (vpath.text + 5)
1723 #define ps1val() (vps1.text + 4)
1724 #define ps2val() (vps2.text + 4)
1725 #define ps4val() (vps4.text + 4)
1726 #define optindval() (voptind.text + 7)
1728 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1731 * The parsefile structure pointed to by the global variable parsefile
1732 * contains information about the current file being read.
1735 struct redirtab *next;
1740 static struct redirtab *redirlist;
1741 static int nullredirs;
1742 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1746 static struct var *vartab[VTABSIZE];
1748 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1749 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1752 * Return of a legal variable name (a letter or underscore followed by zero or
1753 * more letters, underscores, and digits).
1756 endofname(const char *name)
1764 if (!is_in_name(*p))
1771 * Compares two strings up to the first = or '\0'. The first
1772 * string must be terminated by '='; the second may be terminated by
1773 * either '=' or '\0'.
1776 varcmp(const char *p, const char *q)
1780 while ((c = *p) == (d = *q)) {
1795 varequal(const char *a, const char *b)
1797 return !varcmp(a, b);
1801 * Find the appropriate entry in the hash table from the name.
1803 static struct var **
1804 hashvar(const char *p)
1808 hashval = ((unsigned char) *p) << 4;
1809 while (*p && *p != '=')
1810 hashval += (unsigned char) *p++;
1811 return &vartab[hashval % VTABSIZE];
1815 vpcmp(const void *a, const void *b)
1817 return varcmp(*(const char **)a, *(const char **)b);
1821 * This routine initializes the builtin variables.
1831 * PS1 depends on uid
1833 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1834 vps1.text = "PS1=\\w \\$ ";
1837 vps1.text = "PS1=# ";
1840 end = vp + ARRAY_SIZE(varinit);
1842 vpp = hashvar(vp->text);
1845 } while (++vp < end);
1848 static struct var **
1849 findvar(struct var **vpp, const char *name)
1851 for (; *vpp; vpp = &(*vpp)->next) {
1852 if (varequal((*vpp)->text, name)) {
1860 * Find the value of a variable. Returns NULL if not set.
1863 lookupvar(const char *name)
1867 v = *findvar(hashvar(name), name);
1871 * Dynamic variables are implemented roughly the same way they are
1872 * in bash. Namely, they're "special" so long as they aren't unset.
1873 * As soon as they're unset, they're no longer dynamic, and dynamic
1874 * lookup will no longer happen at that point. -- PFM.
1876 if ((v->flags & VDYNAMIC))
1879 if (!(v->flags & VUNSET))
1880 return strchrnul(v->text, '=') + 1;
1886 * Search the environment of a builtin command.
1889 bltinlookup(const char *name)
1893 for (sp = cmdenviron; sp; sp = sp->next) {
1894 if (varequal(sp->text, name))
1895 return strchrnul(sp->text, '=') + 1;
1897 return lookupvar(name);
1901 * Same as setvar except that the variable and value are passed in
1902 * the first argument as name=value. Since the first argument will
1903 * be actually stored in the table, it should not be a string that
1905 * Called with interrupts off.
1908 setvareq(char *s, int flags)
1910 struct var *vp, **vpp;
1913 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1914 vp = *findvar(vpp, s);
1916 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1919 if (flags & VNOSAVE)
1922 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1928 if (vp->func && (flags & VNOFUNC) == 0)
1929 (*vp->func)(strchrnul(s, '=') + 1);
1931 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1932 free((char*)vp->text);
1934 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1939 vp = ckmalloc(sizeof(*vp));
1944 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1951 * Set the value of a variable. The flags argument is ored with the
1952 * flags of the variable. If val is NULL, the variable is unset.
1955 setvar(const char *name, const char *val, int flags)
1962 q = endofname(name);
1963 p = strchrnul(q, '=');
1965 if (!namelen || p != q)
1966 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1971 vallen = strlen(val);
1974 nameeq = ckmalloc(namelen + vallen + 2);
1975 p = memcpy(nameeq, name, namelen) + namelen;
1978 p = memcpy(p, val, vallen) + vallen;
1981 setvareq(nameeq, flags | VNOSAVE);
1985 #if ENABLE_ASH_GETOPTS
1987 * Safe version of setvar, returns 1 on success 0 on failure.
1990 setvarsafe(const char *name, const char *val, int flags)
1993 volatile int saveint;
1994 struct jmploc *volatile savehandler = exception_handler;
1995 struct jmploc jmploc;
1998 if (setjmp(jmploc.loc))
2001 exception_handler = &jmploc;
2002 setvar(name, val, flags);
2005 exception_handler = savehandler;
2006 RESTORE_INT(saveint);
2012 * Unset the specified variable.
2015 unsetvar(const char *s)
2021 vpp = findvar(hashvar(s), s);
2025 int flags = vp->flags;
2028 if (flags & VREADONLY)
2031 vp->flags &= ~VDYNAMIC;
2035 if ((flags & VSTRFIXED) == 0) {
2037 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2038 free((char*)vp->text);
2044 vp->flags &= ~VEXPORT;
2054 * Process a linked list of variable assignments.
2057 listsetvar(struct strlist *list_set_var, int flags)
2059 struct strlist *lp = list_set_var;
2065 setvareq(lp->text, flags);
2072 * Generate a list of variables satisfying the given conditions.
2075 listvars(int on, int off, char ***end)
2086 for (vp = *vpp; vp; vp = vp->next) {
2087 if ((vp->flags & mask) == on) {
2088 if (ep == stackstrend())
2089 ep = growstackstr();
2090 *ep++ = (char *) vp->text;
2093 } while (++vpp < vartab + VTABSIZE);
2094 if (ep == stackstrend())
2095 ep = growstackstr();
2099 return grabstackstr(ep);
2103 /* ============ Path search helper
2105 * The variable path (passed by reference) should be set to the start
2106 * of the path before the first call; padvance will update
2107 * this value as it proceeds. Successive calls to padvance will return
2108 * the possible path expansions in sequence. If an option (indicated by
2109 * a percent sign) appears in the path entry then the global variable
2110 * pathopt will be set to point to it; otherwise pathopt will be set to
2113 static const char *pathopt; /* set by padvance */
2116 padvance(const char **path, const char *name)
2126 for (p = start; *p && *p != ':' && *p != '%'; p++);
2127 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2128 while (stackblocksize() < len)
2132 memcpy(q, start, p - start);
2140 while (*p && *p != ':') p++;
2146 return stalloc(len);
2150 /* ============ Prompt */
2152 static int doprompt; /* if set, prompt the user */
2153 static int needprompt; /* true if interactive and at start of line */
2155 #if ENABLE_FEATURE_EDITING
2156 static line_input_t *line_input_state;
2157 static const char *cmdedit_prompt;
2159 putprompt(const char *s)
2161 if (ENABLE_ASH_EXPAND_PRMT) {
2162 free((char*)cmdedit_prompt);
2163 cmdedit_prompt = ckstrdup(s);
2170 putprompt(const char *s)
2176 #if ENABLE_ASH_EXPAND_PRMT
2177 /* expandstr() needs parsing machinery, so it is far away ahead... */
2178 static const char *expandstr(const char *ps);
2180 #define expandstr(s) s
2184 setprompt(int whichprompt)
2187 #if ENABLE_ASH_EXPAND_PRMT
2188 struct stackmark smark;
2193 switch (whichprompt) {
2203 #if ENABLE_ASH_EXPAND_PRMT
2204 setstackmark(&smark);
2205 stalloc(stackblocksize());
2207 putprompt(expandstr(prompt));
2208 #if ENABLE_ASH_EXPAND_PRMT
2209 popstackmark(&smark);
2214 /* ============ The cd and pwd commands */
2216 #define CD_PHYSICAL 1
2219 static int docd(const char *, int);
2221 static char *curdir = nullstr; /* current working directory */
2222 static char *physdir = nullstr; /* physical working directory */
2231 while ((i = nextopt("LP"))) {
2233 flags ^= CD_PHYSICAL;
2242 * Update curdir (the name of the current directory) in response to a
2246 updatepwd(const char *dir)
2253 cdcomppath = ststrdup(dir);
2256 if (curdir == nullstr)
2258 new = stack_putstr(curdir, new);
2260 new = makestrspace(strlen(dir) + 2, new);
2261 lim = stackblock() + 1;
2265 if (new > lim && *lim == '/')
2270 if (dir[1] == '/' && dir[2] != '/') {
2276 p = strtok(cdcomppath, "/");
2280 if (p[1] == '.' && p[2] == '\0') {
2292 new = stack_putstr(p, new);
2300 return stackblock();
2304 * Find out what the current directory is. If we already know the current
2305 * directory, this routine returns immediately.
2310 char *dir = getcwd(0, 0);
2311 return dir ? dir : nullstr;
2315 setpwd(const char *val, int setold)
2319 oldcur = dir = curdir;
2322 setvar("OLDPWD", oldcur, VEXPORT);
2325 if (physdir != nullstr) {
2326 if (physdir != oldcur)
2330 if (oldcur == val || !val) {
2336 dir = ckstrdup(val);
2337 if (oldcur != dir && oldcur != nullstr) {
2342 setvar("PWD", dir, VEXPORT);
2345 static void hashcd(void);
2348 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2349 * know that the current directory has changed.
2352 docd(const char *dest, int flags)
2354 const char *dir = 0;
2357 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2360 if (!(flags & CD_PHYSICAL)) {
2361 dir = updatepwd(dest);
2376 cdcmd(int argc, char **argv)
2388 dest = bltinlookup(homestr);
2389 else if (LONE_DASH(dest)) {
2390 dest = bltinlookup("OLDPWD");
2412 path = bltinlookup("CDPATH");
2421 p = padvance(&path, dest);
2422 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2426 if (!docd(p, flags))
2431 ash_msg_and_raise_error("can't cd to %s", dest);
2434 if (flags & CD_PRINT)
2435 out1fmt(snlfmt, curdir);
2440 pwdcmd(int argc, char **argv)
2443 const char *dir = curdir;
2447 if (physdir == nullstr)
2451 out1fmt(snlfmt, dir);
2456 /* ============ ... */
2458 #define IBUFSIZ (BUFSIZ + 1)
2459 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2461 /* Syntax classes */
2462 #define CWORD 0 /* character is nothing special */
2463 #define CNL 1 /* newline character */
2464 #define CBACK 2 /* a backslash character */
2465 #define CSQUOTE 3 /* single quote */
2466 #define CDQUOTE 4 /* double quote */
2467 #define CENDQUOTE 5 /* a terminating quote */
2468 #define CBQUOTE 6 /* backwards single quote */
2469 #define CVAR 7 /* a dollar sign */
2470 #define CENDVAR 8 /* a '}' character */
2471 #define CLP 9 /* a left paren in arithmetic */
2472 #define CRP 10 /* a right paren in arithmetic */
2473 #define CENDFILE 11 /* end of file */
2474 #define CCTL 12 /* like CWORD, except it must be escaped */
2475 #define CSPCL 13 /* these terminate a word */
2476 #define CIGN 14 /* character should be ignored */
2478 #if ENABLE_ASH_ALIAS
2482 #define PEOA_OR_PEOF PEOA
2486 #define PEOA_OR_PEOF PEOF
2489 /* number syntax index */
2490 #define BASESYNTAX 0 /* not in quotes */
2491 #define DQSYNTAX 1 /* in double quotes */
2492 #define SQSYNTAX 2 /* in single quotes */
2493 #define ARISYNTAX 3 /* in arithmetic */
2495 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2496 #define USE_SIT_FUNCTION
2499 #if ENABLE_ASH_MATH_SUPPORT
2500 static const char S_I_T[][4] = {
2501 #if ENABLE_ASH_ALIAS
2502 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2504 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2505 { CNL, CNL, CNL, CNL }, /* 2, \n */
2506 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2507 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2508 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2509 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2510 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2511 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2512 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2513 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2514 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2515 #ifndef USE_SIT_FUNCTION
2516 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2517 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2518 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2522 static const char S_I_T[][3] = {
2523 #if ENABLE_ASH_ALIAS
2524 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2526 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2527 { CNL, CNL, CNL }, /* 2, \n */
2528 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2529 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2530 { CVAR, CVAR, CWORD }, /* 5, $ */
2531 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2532 { CSPCL, CWORD, CWORD }, /* 7, ( */
2533 { CSPCL, CWORD, CWORD }, /* 8, ) */
2534 { CBACK, CBACK, CCTL }, /* 9, \ */
2535 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2536 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2537 #ifndef USE_SIT_FUNCTION
2538 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2539 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2540 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2543 #endif /* ASH_MATH_SUPPORT */
2545 #ifdef USE_SIT_FUNCTION
2548 SIT(int c, int syntax)
2550 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2551 #if ENABLE_ASH_ALIAS
2552 static const char syntax_index_table[] = {
2553 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2554 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2555 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2559 static const char syntax_index_table[] = {
2560 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2561 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2562 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2569 if (c == PEOF) /* 2^8+2 */
2571 #if ENABLE_ASH_ALIAS
2572 if (c == PEOA) /* 2^8+1 */
2576 #define U_C(c) ((unsigned char)(c))
2578 if ((unsigned char)c >= (unsigned char)(CTLESC)
2579 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2583 s = strchr(spec_symbls, c);
2584 if (s == NULL || *s == '\0')
2586 indx = syntax_index_table[(s - spec_symbls)];
2588 return S_I_T[indx][syntax];
2591 #else /* !USE_SIT_FUNCTION */
2593 #if ENABLE_ASH_ALIAS
2594 #define CSPCL_CIGN_CIGN_CIGN 0
2595 #define CSPCL_CWORD_CWORD_CWORD 1
2596 #define CNL_CNL_CNL_CNL 2
2597 #define CWORD_CCTL_CCTL_CWORD 3
2598 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2599 #define CVAR_CVAR_CWORD_CVAR 5
2600 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2601 #define CSPCL_CWORD_CWORD_CLP 7
2602 #define CSPCL_CWORD_CWORD_CRP 8
2603 #define CBACK_CBACK_CCTL_CBACK 9
2604 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2605 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2606 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2607 #define CWORD_CWORD_CWORD_CWORD 13
2608 #define CCTL_CCTL_CCTL_CCTL 14
2610 #define CSPCL_CWORD_CWORD_CWORD 0
2611 #define CNL_CNL_CNL_CNL 1
2612 #define CWORD_CCTL_CCTL_CWORD 2
2613 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2614 #define CVAR_CVAR_CWORD_CVAR 4
2615 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2616 #define CSPCL_CWORD_CWORD_CLP 6
2617 #define CSPCL_CWORD_CWORD_CRP 7
2618 #define CBACK_CBACK_CCTL_CBACK 8
2619 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2620 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2621 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2622 #define CWORD_CWORD_CWORD_CWORD 12
2623 #define CCTL_CCTL_CCTL_CCTL 13
2626 static const char syntax_index_table[258] = {
2627 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2628 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2629 #if ENABLE_ASH_ALIAS
2630 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2632 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2633 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2634 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2635 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2636 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2637 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2638 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2639 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2640 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2641 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2642 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2643 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2644 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2645 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2646 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2647 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2648 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2649 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2770 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2771 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2793 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2794 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2795 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2797 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2799 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2800 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2801 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2802 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2803 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2805 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2806 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2807 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2808 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2820 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2821 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2823 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2824 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2852 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2853 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2854 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2857 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2861 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2885 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2886 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2890 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2892 #endif /* USE_SIT_FUNCTION */
2895 /* ============ Alias handling */
2897 #if ENABLE_ASH_ALIAS
2899 #define ALIASINUSE 1
2911 static struct alias *atab[ATABSIZE];
2913 static struct alias **
2914 __lookupalias(const char *name) {
2915 unsigned int hashval;
2922 ch = (unsigned char)*p;
2926 ch = (unsigned char)*++p;
2928 app = &atab[hashval % ATABSIZE];
2930 for (; *app; app = &(*app)->next) {
2931 if (strcmp(name, (*app)->name) == 0) {
2939 static struct alias *
2940 lookupalias(const char *name, int check)
2942 struct alias *ap = *__lookupalias(name);
2944 if (check && ap && (ap->flag & ALIASINUSE))
2949 static struct alias *
2950 freealias(struct alias *ap)
2954 if (ap->flag & ALIASINUSE) {
2955 ap->flag |= ALIASDEAD;
2967 setalias(const char *name, const char *val)
2969 struct alias *ap, **app;
2971 app = __lookupalias(name);
2975 if (!(ap->flag & ALIASINUSE)) {
2978 ap->val = ckstrdup(val);
2979 ap->flag &= ~ALIASDEAD;
2982 ap = ckmalloc(sizeof(struct alias));
2983 ap->name = ckstrdup(name);
2984 ap->val = ckstrdup(val);
2993 unalias(const char *name)
2997 app = __lookupalias(name);
3001 *app = freealias(*app);
3012 struct alias *ap, **app;
3016 for (i = 0; i < ATABSIZE; i++) {
3018 for (ap = *app; ap; ap = *app) {
3019 *app = freealias(*app);
3029 printalias(const struct alias *ap)
3031 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3035 * TODO - sort output
3038 aliascmd(int argc, char **argv)
3047 for (i = 0; i < ATABSIZE; i++)
3048 for (ap = atab[i]; ap; ap = ap->next) {
3053 while ((n = *++argv) != NULL) {
3054 v = strchr(n+1, '=');
3055 if (v == NULL) { /* n+1: funny ksh stuff */
3056 ap = *__lookupalias(n);
3058 fprintf(stderr, "%s: %s not found\n", "alias", n);
3072 unaliascmd(int argc, char **argv)
3076 while ((i = nextopt("a")) != '\0') {
3082 for (i = 0; *argptr; argptr++) {
3083 if (unalias(*argptr)) {
3084 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3092 #endif /* ASH_ALIAS */
3095 /* ============ jobs.c */
3097 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3100 #define FORK_NOJOB 2
3102 /* mode flags for showjob(s) */
3103 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3104 #define SHOW_PID 0x04 /* include process pid */
3105 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3108 * A job structure contains information about a job. A job is either a
3109 * single process or a set of processes contained in a pipeline. In the
3110 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3115 pid_t pid; /* process id */
3116 int status; /* last process status from wait() */
3117 char *cmd; /* text of command being run */
3121 struct procstat ps0; /* status of process */
3122 struct procstat *ps; /* status or processes when more than one */
3124 int stopstatus; /* status of a stopped job */
3127 nprocs: 16, /* number of processes */
3129 #define JOBRUNNING 0 /* at least one proc running */
3130 #define JOBSTOPPED 1 /* all procs are stopped */
3131 #define JOBDONE 2 /* all procs are completed */
3133 sigint: 1, /* job was killed by SIGINT */
3134 jobctl: 1, /* job running under job control */
3136 waited: 1, /* true if this entry has been waited for */
3137 used: 1, /* true if this entry is in used */
3138 changed: 1; /* true if status has changed */
3139 struct job *prev_job; /* previous job */
3142 static pid_t backgndpid; /* pid of last background process */
3143 static int job_warning; /* user was warned about stopped jobs */
3145 static int jobctl; /* true if doing job control */
3148 static struct job *makejob(union node *, int);
3149 static int forkshell(struct job *, union node *, int);
3150 static int waitforjob(struct job *);
3153 #define setjobctl(on) /* do nothing */
3155 static void setjobctl(int);
3156 static void showjobs(FILE *, int);
3160 * Set the signal handler for the specified signal. The routine figures
3161 * out what it should be set to.
3164 setsignal(int signo)
3168 struct sigaction act;
3173 else if (*t != '\0')
3177 if (rootshell && action == S_DFL) {
3180 if (iflag || minusc || sflag == 0)
3203 t = &sigmode[signo - 1];
3207 * current setting unknown
3209 if (sigaction(signo, 0, &act) == -1) {
3211 * Pretend it worked; maybe we should give a warning
3212 * here, but other shells don't. We don't alter
3213 * sigmode, so that we retry every time.
3217 if (act.sa_handler == SIG_IGN) {
3219 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3221 tsig = S_IGN; /* don't hard ignore these */
3225 tsig = S_RESET; /* force to be set */
3228 if (tsig == S_HARD_IGN || tsig == action)
3232 act.sa_handler = onsig;
3235 act.sa_handler = SIG_IGN;
3238 act.sa_handler = SIG_DFL;
3242 sigfillset(&act.sa_mask);
3243 sigaction(signo, &act, 0);
3246 /* mode flags for set_curjob */
3247 #define CUR_DELETE 2
3248 #define CUR_RUNNING 1
3249 #define CUR_STOPPED 0
3251 /* mode flags for dowait */
3252 #define DOWAIT_NORMAL 0
3253 #define DOWAIT_BLOCK 1
3256 /* pgrp of shell on invocation */
3257 static int initialpgrp;
3258 static int ttyfd = -1;
3261 static struct job *jobtab;
3263 static unsigned njobs;
3265 static struct job *curjob;
3266 /* number of presumed living untracked jobs */
3270 set_curjob(struct job *jp, unsigned mode)
3273 struct job **jpp, **curp;
3275 /* first remove from list */
3276 jpp = curp = &curjob;
3281 jpp = &jp1->prev_job;
3283 *jpp = jp1->prev_job;
3285 /* Then re-insert in correct position */
3293 /* job being deleted */
3296 /* newly created job or backgrounded job,
3297 put after all stopped jobs. */
3301 if (!jp1 || jp1->state != JOBSTOPPED)
3304 jpp = &jp1->prev_job;
3310 /* newly stopped job - becomes curjob */
3311 jp->prev_job = *jpp;
3319 jobno(const struct job *jp)
3321 return jp - jobtab + 1;
3326 * Convert a job name to a job structure.
3329 getjob(const char *name, int getctl)
3333 const char *err_msg = "No such job: %s";
3337 char *(*match)(const char *, const char *);
3352 if (c == '+' || c == '%') {
3354 err_msg = "No current job";
3360 err_msg = "No previous job";
3371 jp = jobtab + num - 1;
3388 if (match(jp->ps[0].cmd, p)) {
3392 err_msg = "%s: ambiguous";
3399 err_msg = "job %s not created under job control";
3400 if (getctl && jp->jobctl == 0)
3405 ash_msg_and_raise_error(err_msg, name);
3409 * Mark a job structure as unused.
3412 freejob(struct job *jp)
3414 struct procstat *ps;
3418 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3419 if (ps->cmd != nullstr)
3422 if (jp->ps != &jp->ps0)
3425 set_curjob(jp, CUR_DELETE);
3431 xtcsetpgrp(int fd, pid_t pgrp)
3433 if (tcsetpgrp(fd, pgrp))
3434 ash_msg_and_raise_error("cannot set tty process group (%m)");
3438 * Turn job control on and off.
3440 * Note: This code assumes that the third arg to ioctl is a character
3441 * pointer, which is true on Berkeley systems but not System V. Since
3442 * System V doesn't have job control yet, this isn't a problem now.
3444 * Called with interrupts off.
3452 if (on == jobctl || rootshell == 0)
3456 ofd = fd = open(_PATH_TTY, O_RDWR);
3458 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3459 * That sometimes helps to acquire controlling tty.
3460 * Obviously, a workaround for bugs when someone
3461 * failed to provide a controlling tty to bash! :) */
3463 while (!isatty(fd) && --fd >= 0)
3466 fd = fcntl(fd, F_DUPFD, 10);
3470 fcntl(fd, F_SETFD, FD_CLOEXEC);
3471 do { /* while we are in the background */
3472 pgrp = tcgetpgrp(fd);
3475 ash_msg("can't access tty; job control turned off");
3479 if (pgrp == getpgrp())
3490 xtcsetpgrp(fd, pgrp);
3492 /* turning job control off */
3495 /* was xtcsetpgrp, but this can make exiting ash
3496 * with pty already deleted loop forever */
3497 tcsetpgrp(fd, pgrp);
3511 killcmd(int argc, char **argv)
3513 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3516 if (argv[i][0] == '%') {
3517 struct job *jp = getjob(argv[i], 0);
3518 unsigned pid = jp->ps[0].pid;
3519 /* Enough space for ' -NNN<nul>' */
3520 argv[i] = alloca(sizeof(int)*3 + 3);
3521 /* kill_main has matching code to expect
3522 * leading space. Needed to not confuse
3523 * negative pids with "kill -SIGNAL_NO" syntax */
3524 sprintf(argv[i], " -%u", pid);
3526 } while (argv[++i]);
3528 return kill_main(argc, argv);
3532 showpipe(struct job *jp, FILE *out)
3534 struct procstat *sp;
3535 struct procstat *spend;
3537 spend = jp->ps + jp->nprocs;
3538 for (sp = jp->ps + 1; sp < spend; sp++)
3539 fprintf(out, " | %s", sp->cmd);
3540 outcslow('\n', out);
3541 flush_stdout_stderr();
3546 restartjob(struct job *jp, int mode)
3548 struct procstat *ps;
3554 if (jp->state == JOBDONE)
3556 jp->state = JOBRUNNING;
3558 if (mode == FORK_FG)
3559 xtcsetpgrp(ttyfd, pgid);
3560 killpg(pgid, SIGCONT);
3564 if (WIFSTOPPED(ps->status)) {
3570 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3576 fg_bgcmd(int argc, char **argv)
3583 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3588 jp = getjob(*argv, 1);
3589 if (mode == FORK_BG) {
3590 set_curjob(jp, CUR_RUNNING);
3591 fprintf(out, "[%d] ", jobno(jp));
3593 outstr(jp->ps->cmd, out);
3595 retval = restartjob(jp, mode);
3596 } while (*argv && *++argv);
3602 sprint_status(char *s, int status, int sigonly)
3608 if (!WIFEXITED(status)) {
3610 if (WIFSTOPPED(status))
3611 st = WSTOPSIG(status);
3614 st = WTERMSIG(status);
3616 if (st == SIGINT || st == SIGPIPE)
3619 if (WIFSTOPPED(status))
3624 col = fmtstr(s, 32, strsignal(st));
3625 if (WCOREDUMP(status)) {
3626 col += fmtstr(s + col, 16, " (core dumped)");
3628 } else if (!sigonly) {
3629 st = WEXITSTATUS(status);
3631 col = fmtstr(s, 16, "Done(%d)", st);
3633 col = fmtstr(s, 16, "Done");
3640 * Do a wait system call. If job control is compiled in, we accept
3641 * stopped processes. If block is zero, we return a value of zero
3642 * rather than blocking.
3644 * System V doesn't have a non-blocking wait system call. It does
3645 * have a SIGCLD signal that is sent to a process when one of it's
3646 * children dies. The obvious way to use SIGCLD would be to install
3647 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3648 * was received, and have waitproc bump another counter when it got
3649 * the status of a process. Waitproc would then know that a wait
3650 * system call would not block if the two counters were different.
3651 * This approach doesn't work because if a process has children that
3652 * have not been waited for, System V will send it a SIGCLD when it
3653 * installs a signal handler for SIGCLD. What this means is that when
3654 * a child exits, the shell will be sent SIGCLD signals continuously
3655 * until is runs out of stack space, unless it does a wait call before
3656 * restoring the signal handler. The code below takes advantage of
3657 * this (mis)feature by installing a signal handler for SIGCLD and
3658 * then checking to see whether it was called. If there are any
3659 * children to be waited for, it will be.
3661 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3662 * waits at all. In this case, the user will not be informed when
3663 * a background process until the next time she runs a real program
3664 * (as opposed to running a builtin command or just typing return),
3665 * and the jobs command may give out of date information.
3668 waitproc(int block, int *status)
3678 return wait3(status, flags, (struct rusage *)NULL);
3682 * Wait for a process to terminate.
3685 dowait(int block, struct job *job)
3690 struct job *thisjob;
3693 TRACE(("dowait(%d) called\n", block));
3694 pid = waitproc(block, &status);
3695 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3700 for (jp = curjob; jp; jp = jp->prev_job) {
3701 struct procstat *sp;
3702 struct procstat *spend;
3703 if (jp->state == JOBDONE)
3706 spend = jp->ps + jp->nprocs;
3709 if (sp->pid == pid) {
3710 TRACE(("Job %d: changing status of proc %d "
3711 "from 0x%x to 0x%x\n",
3712 jobno(jp), pid, sp->status, status));
3713 sp->status = status;
3716 if (sp->status == -1)
3719 if (state == JOBRUNNING)
3721 if (WIFSTOPPED(sp->status)) {
3722 jp->stopstatus = sp->status;
3726 } while (++sp < spend);
3731 if (!WIFSTOPPED(status))
3738 if (state != JOBRUNNING) {
3739 thisjob->changed = 1;
3741 if (thisjob->state != state) {
3742 TRACE(("Job %d: changing state from %d to %d\n",
3743 jobno(thisjob), thisjob->state, state));
3744 thisjob->state = state;
3746 if (state == JOBSTOPPED) {
3747 set_curjob(thisjob, CUR_STOPPED);
3756 if (thisjob && thisjob == job) {
3760 len = sprint_status(s, status, 1);
3772 showjob(FILE *out, struct job *jp, int mode)
3774 struct procstat *ps;
3775 struct procstat *psend;
3782 if (mode & SHOW_PGID) {
3783 /* just output process (group) id of pipeline */
3784 fprintf(out, "%d\n", ps->pid);
3788 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3793 else if (curjob && jp == curjob->prev_job)
3796 if (mode & SHOW_PID)
3797 col += fmtstr(s + col, 16, "%d ", ps->pid);
3799 psend = ps + jp->nprocs;
3801 if (jp->state == JOBRUNNING) {
3802 strcpy(s + col, "Running");
3803 col += sizeof("Running") - 1;
3805 int status = psend[-1].status;
3806 if (jp->state == JOBSTOPPED)
3807 status = jp->stopstatus;
3808 col += sprint_status(s + col, status, 0);
3814 /* for each process */
3815 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
3817 fprintf(out, "%s%*c%s",
3818 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3820 if (!(mode & SHOW_PID)) {
3824 if (++ps == psend) {
3825 outcslow('\n', out);
3832 if (jp->state == JOBDONE) {
3833 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3839 jobscmd(int argc, char **argv)
3845 while ((m = nextopt("lp"))) {
3856 showjob(out, getjob(*argv,0), mode);
3859 showjobs(out, mode);
3865 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3866 * statuses have changed since the last call to showjobs.
3869 showjobs(FILE *out, int mode)
3873 TRACE(("showjobs(%x) called\n", mode));
3875 /* If not even one one job changed, there is nothing to do */
3876 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3879 for (jp = curjob; jp; jp = jp->prev_job) {
3880 if (!(mode & SHOW_CHANGED) || jp->changed)
3881 showjob(out, jp, mode);
3887 getstatus(struct job *job)
3892 status = job->ps[job->nprocs - 1].status;
3893 retval = WEXITSTATUS(status);
3894 if (!WIFEXITED(status)) {
3896 retval = WSTOPSIG(status);
3897 if (!WIFSTOPPED(status))
3900 /* XXX: limits number of signals */
3901 retval = WTERMSIG(status);
3903 if (retval == SIGINT)
3909 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3910 jobno(job), job->nprocs, status, retval));
3915 waitcmd(int argc, char **argv)
3928 /* wait for all jobs */
3933 /* no running procs */
3936 if (jp->state == JOBRUNNING)
3941 dowait(DOWAIT_BLOCK, 0);
3947 if (**argv != '%') {
3948 pid_t pid = number(*argv);
3952 if (job->ps[job->nprocs - 1].pid == pid)
3954 job = job->prev_job;
3960 job = getjob(*argv, 0);
3961 /* loop until process terminated or stopped */
3962 while (job->state == JOBRUNNING)
3963 dowait(DOWAIT_BLOCK, 0);
3965 retval = getstatus(job);
3979 struct job *jp, *jq;
3981 len = njobs * sizeof(*jp);
3983 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
3985 offset = (char *)jp - (char *)jq;
3987 /* Relocate pointers */
3990 jq = (struct job *)((char *)jq + l);
3994 #define joff(p) ((struct job *)((char *)(p) + l))
3995 #define jmove(p) (p) = (void *)((char *)(p) + offset)
3996 if (joff(jp)->ps == &jq->ps0)
3997 jmove(joff(jp)->ps);
3998 if (joff(jp)->prev_job)
3999 jmove(joff(jp)->prev_job);
4009 jp = (struct job *)((char *)jp + len);
4013 } while (--jq >= jp);
4018 * Return a new job structure.
4019 * Called with interrupts off.
4022 makejob(union node *node, int nprocs)
4027 for (i = njobs, jp = jobtab; ; jp++) {
4034 if (jp->state != JOBDONE || !jp->waited)
4043 memset(jp, 0, sizeof(*jp));
4048 jp->prev_job = curjob;
4053 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4055 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4062 * Return a string identifying a command (to be printed by the
4065 static char *cmdnextc;
4068 cmdputs(const char *s)
4070 const char *p, *str;
4071 char c, cc[2] = " ";
4075 static const char vstype[VSTYPE + 1][4] = {
4076 "", "}", "-", "+", "?", "=",
4077 "%", "%%", "#", "##"
4080 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4082 while ((c = *p++) != 0) {
4090 if ((subtype & VSTYPE) == VSLENGTH)
4094 if (!(subtype & VSQUOTE) == !(quoted & 1))
4100 str = "\"}" + !(quoted & 1);
4107 case CTLBACKQ+CTLQUOTE:
4110 #if ENABLE_ASH_MATH_SUPPORT
4125 if ((subtype & VSTYPE) != VSNORMAL)
4127 str = vstype[subtype & VSTYPE];
4128 if (subtype & VSNUL)
4137 /* These can only happen inside quotes */
4150 while ((c = *str++)) {
4155 USTPUTC('"', nextc);
4161 /* cmdtxt() and cmdlist() call each other */
4162 static void cmdtxt(union node *n);
4165 cmdlist(union node *np, int sep)
4167 for (; np; np = np->narg.next) {
4171 if (sep && np->narg.next)
4177 cmdtxt(union node *n)
4180 struct nodelist *lp;
4192 lp = n->npipe.cmdlist;
4210 cmdtxt(n->nbinary.ch1);
4226 cmdtxt(n->nif.test);
4229 if (n->nif.elsepart) {
4232 n = n->nif.elsepart;
4248 cmdtxt(n->nbinary.ch1);
4258 cmdputs(n->nfor.var);
4260 cmdlist(n->nfor.args, 1);
4265 cmdputs(n->narg.text);
4269 cmdlist(n->ncmd.args, 1);
4270 cmdlist(n->ncmd.redirect, 0);
4283 cmdputs(n->ncase.expr->narg.text);
4285 for (np = n->ncase.cases; np; np = np->nclist.next) {
4286 cmdtxt(np->nclist.pattern);
4288 cmdtxt(np->nclist.body);
4314 s[0] = n->nfile.fd + '0';
4318 if (n->type == NTOFD || n->type == NFROMFD) {
4319 s[0] = n->ndup.dupfd + '0';
4329 commandtext(union node *n)
4333 STARTSTACKSTR(cmdnextc);
4335 name = stackblock();
4336 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4337 name, cmdnextc, cmdnextc));
4338 return ckstrdup(name);
4343 * Fork off a subshell. If we are doing job control, give the subshell its
4344 * own process group. Jp is a job structure that the job is to be added to.
4345 * N is the command that will be evaluated by the child. Both jp and n may
4346 * be NULL. The mode parameter can be one of the following:
4347 * FORK_FG - Fork off a foreground process.
4348 * FORK_BG - Fork off a background process.
4349 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4350 * process group even if job control is on.
4352 * When job control is turned off, background processes have their standard
4353 * input redirected to /dev/null (except for the second and later processes
4356 * Called with interrupts off.
4359 * Clear traps on a fork.
4366 for (tp = trap; tp < &trap[NSIG]; tp++) {
4367 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
4372 setsignal(tp - trap);
4377 /* lives far away from here, needed for forkchild */
4378 static void closescript(void);
4380 forkchild(struct job *jp, union node *n, int mode)
4384 TRACE(("Child shell %d\n", getpid()));
4391 /* do job control only in root shell */
4393 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4396 if (jp->nprocs == 0)
4399 pgrp = jp->ps[0].pid;
4400 /* This can fail because we are doing it in the parent also */
4401 (void)setpgid(0, pgrp);
4402 if (mode == FORK_FG)
4403 xtcsetpgrp(ttyfd, pgrp);
4408 if (mode == FORK_BG) {
4411 if (jp->nprocs == 0) {
4413 if (open(bb_dev_null, O_RDONLY) != 0)
4414 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4417 if (!oldlvl && iflag) {
4422 for (jp = curjob; jp; jp = jp->prev_job)
4428 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4430 TRACE(("In parent shell: child = %d\n", pid));
4432 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4437 if (mode != FORK_NOJOB && jp->jobctl) {
4440 if (jp->nprocs == 0)
4443 pgrp = jp->ps[0].pid;
4444 /* This can fail because we are doing it in the child also */
4448 if (mode == FORK_BG) {
4449 backgndpid = pid; /* set $! */
4450 set_curjob(jp, CUR_RUNNING);
4453 struct procstat *ps = &jp->ps[jp->nprocs++];
4459 ps->cmd = commandtext(n);
4465 forkshell(struct job *jp, union node *n, int mode)
4469 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4472 TRACE(("Fork failed, errno=%d", errno));
4475 ash_msg_and_raise_error("cannot fork");
4478 forkchild(jp, n, mode);
4480 forkparent(jp, n, mode, pid);
4485 * Wait for job to finish.
4487 * Under job control we have the problem that while a child process is
4488 * running interrupts generated by the user are sent to the child but not
4489 * to the shell. This means that an infinite loop started by an inter-
4490 * active user may be hard to kill. With job control turned off, an
4491 * interactive user may place an interactive program inside a loop. If
4492 * the interactive program catches interrupts, the user doesn't want
4493 * these interrupts to also abort the loop. The approach we take here
4494 * is to have the shell ignore interrupt signals while waiting for a
4495 * foreground process to terminate, and then send itself an interrupt
4496 * signal if the child process was terminated by an interrupt signal.
4497 * Unfortunately, some programs want to do a bit of cleanup and then
4498 * exit on interrupt; unless these processes terminate themselves by
4499 * sending a signal to themselves (instead of calling exit) they will
4500 * confuse this approach.
4502 * Called with interrupts off.
4505 waitforjob(struct job *jp)
4509 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4510 while (jp->state == JOBRUNNING) {
4511 dowait(DOWAIT_BLOCK, jp);
4516 xtcsetpgrp(ttyfd, rootpid);
4518 * This is truly gross.
4519 * If we're doing job control, then we did a TIOCSPGRP which
4520 * caused us (the shell) to no longer be in the controlling
4521 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4522 * intuit from the subprocess exit status whether a SIGINT
4523 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4528 if (jp->state == JOBDONE)
4535 * return 1 if there are stopped jobs, otherwise 0
4547 if (jp && jp->state == JOBSTOPPED) {
4548 out2str("You have stopped jobs.\n");
4557 /* ============ redir.c
4559 * Code for dealing with input/output redirection.
4562 #define EMPTY -2 /* marks an unused slot in redirtab */
4564 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4566 # define PIPESIZE PIPE_BUF
4570 * Open a file in noclobber mode.
4571 * The code was copied from bash.
4574 noclobberopen(const char *fname)
4577 struct stat finfo, finfo2;
4580 * If the file exists and is a regular file, return an error
4583 r = stat(fname, &finfo);
4584 if (r == 0 && S_ISREG(finfo.st_mode)) {
4590 * If the file was not present (r != 0), make sure we open it
4591 * exclusively so that if it is created before we open it, our open
4592 * will fail. Make sure that we do not truncate an existing file.
4593 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4594 * file was not a regular file, we leave O_EXCL off.
4597 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4598 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4600 /* If the open failed, return the file descriptor right away. */
4605 * OK, the open succeeded, but the file may have been changed from a
4606 * non-regular file to a regular file between the stat and the open.
4607 * We are assuming that the O_EXCL open handles the case where FILENAME
4608 * did not exist and is symlinked to an existing file between the stat
4613 * If we can open it and fstat the file descriptor, and neither check
4614 * revealed that it was a regular file, and the file has not been
4615 * replaced, return the file descriptor.
4617 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4618 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4621 /* The file has been replaced. badness. */
4628 * Handle here documents. Normally we fork off a process to write the
4629 * data to a pipe. If the document is short, we can stuff the data in
4630 * the pipe without forking.
4632 /* openhere needs this forward reference */
4633 static void expandhere(union node *arg, int fd);
4635 openhere(union node *redir)
4641 ash_msg_and_raise_error("pipe call failed");
4642 if (redir->type == NHERE) {
4643 len = strlen(redir->nhere.doc->narg.text);
4644 if (len <= PIPESIZE) {
4645 full_write(pip[1], redir->nhere.doc->narg.text, len);
4649 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4651 signal(SIGINT, SIG_IGN);
4652 signal(SIGQUIT, SIG_IGN);
4653 signal(SIGHUP, SIG_IGN);
4655 signal(SIGTSTP, SIG_IGN);
4657 signal(SIGPIPE, SIG_DFL);
4658 if (redir->type == NHERE)
4659 full_write(pip[1], redir->nhere.doc->narg.text, len);
4661 expandhere(redir->nhere.doc, pip[1]);
4670 openredirect(union node *redir)
4675 switch (redir->nfile.type) {
4677 fname = redir->nfile.expfname;
4678 f = open(fname, O_RDONLY);
4683 fname = redir->nfile.expfname;
4684 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4689 /* Take care of noclobber mode. */
4691 fname = redir->nfile.expfname;
4692 f = noclobberopen(fname);
4699 fname = redir->nfile.expfname;
4700 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4705 fname = redir->nfile.expfname;
4706 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4714 /* Fall through to eliminate warning. */
4721 f = openhere(redir);
4727 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4729 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4733 * Copy a file descriptor to be >= to. Returns -1
4734 * if the source file descriptor is closed, EMPTY if there are no unused
4735 * file descriptors left.
4738 copyfd(int from, int to)
4742 newfd = fcntl(from, F_DUPFD, to);
4744 if (errno == EMFILE)
4746 ash_msg_and_raise_error("%d: %m", from);
4752 dupredirect(union node *redir, int f)
4754 int fd = redir->nfile.fd;
4756 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4757 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4758 copyfd(redir->ndup.dupfd, fd);
4770 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4771 * old file descriptors are stashed away so that the redirection can be
4772 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4773 * standard output, and the standard error if it becomes a duplicate of
4774 * stdout, is saved in memory.
4776 /* flags passed to redirect */
4777 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4778 #define REDIR_SAVEFD2 03 /* set preverrout */
4780 redirect(union node *redir, int flags)
4783 struct redirtab *sv;
4794 if (flags & REDIR_PUSH) {
4796 q = ckmalloc(sizeof(struct redirtab));
4797 q->next = redirlist;
4799 q->nullredirs = nullredirs - 1;
4800 for (i = 0; i < 10; i++)
4801 q->renamed[i] = EMPTY;
4808 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4809 && n->ndup.dupfd == fd)
4810 continue; /* redirect from/to same file descriptor */
4812 newfd = openredirect(n);
4815 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4816 i = fcntl(fd, F_DUPFD, 10);
4823 ash_msg_and_raise_error("%d: %m", fd);
4833 dupredirect(n, newfd);
4834 } while ((n = n->nfile.next));
4836 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4837 preverrout_fd = sv->renamed[2];
4841 * Undo the effects of the last redirection.
4846 struct redirtab *rp;
4849 if (--nullredirs >= 0)
4853 for (i = 0; i < 10; i++) {
4854 if (rp->renamed[i] != EMPTY) {
4857 copyfd(rp->renamed[i], i);
4859 close(rp->renamed[i]);
4862 redirlist = rp->next;
4863 nullredirs = rp->nullredirs;
4869 * Undo all redirections. Called on error or interrupt.
4873 * Discard all saved file descriptors.
4876 clearredir(int drop)
4887 redirectsafe(union node *redir, int flags)
4890 volatile int saveint;
4891 struct jmploc *volatile savehandler = exception_handler;
4892 struct jmploc jmploc;
4895 err = setjmp(jmploc.loc) * 2;
4897 exception_handler = &jmploc;
4898 redirect(redir, flags);
4900 exception_handler = savehandler;
4901 if (err && exception != EXERROR)
4902 longjmp(exception_handler->loc, 1);
4903 RESTORE_INT(saveint);
4908 /* ============ Routines to expand arguments to commands
4910 * We have to deal with backquotes, shell variables, and file metacharacters.
4916 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4917 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4918 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4919 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4920 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4921 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4922 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4923 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4924 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
4928 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4929 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4930 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4931 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4932 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4935 * Structure specifying which parts of the string should be searched
4936 * for IFS characters.
4939 struct ifsregion *next; /* next region in list */
4940 int begoff; /* offset of start of region */
4941 int endoff; /* offset of end of region */
4942 int nulonly; /* search for nul bytes only */
4946 struct strlist *list;
4947 struct strlist **lastp;
4950 /* output of current string */
4951 static char *expdest;
4952 /* list of back quote expressions */
4953 static struct nodelist *argbackq;
4954 /* first struct in list of ifs regions */
4955 static struct ifsregion ifsfirst;
4956 /* last struct in list */
4957 static struct ifsregion *ifslastp;
4958 /* holds expanded arg list */
4959 static struct arglist exparg;
4969 expdest = makestrspace(32, expdest);
4970 #if ENABLE_ASH_MATH_SUPPORT_64
4971 len = fmtstr(expdest, 32, "%lld", (long long) num);
4973 len = fmtstr(expdest, 32, "%ld", num);
4975 STADJUST(len, expdest);
4980 esclen(const char *start, const char *p)
4984 while (p > start && *--p == CTLESC) {
4991 * Remove any CTLESC characters from a string.
4994 _rmescapes(char *str, int flag)
4996 static const char qchars[] = { CTLESC, CTLQUOTEMARK, '\0' };
5003 p = strpbrk(str, qchars);
5009 if (flag & RMESCAPE_ALLOC) {
5010 size_t len = p - str;
5011 size_t fulllen = len + strlen(p) + 1;
5013 if (flag & RMESCAPE_GROW) {
5014 r = makestrspace(fulllen, expdest);
5015 } else if (flag & RMESCAPE_HEAP) {
5016 r = ckmalloc(fulllen);
5018 r = stalloc(fulllen);
5022 q = memcpy(q, str, len) + len;
5025 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5026 globbing = flag & RMESCAPE_GLOB;
5027 notescaped = globbing;
5029 if (*p == CTLQUOTEMARK) {
5030 inquotes = ~inquotes;
5032 notescaped = globbing;
5036 /* naked back slash */
5042 if (notescaped && inquotes && *p != '/') {
5046 notescaped = globbing;
5051 if (flag & RMESCAPE_GROW) {
5053 STADJUST(q - r + 1, expdest);
5057 #define rmescapes(p) _rmescapes((p), 0)
5059 #define pmatch(a, b) !fnmatch((a), (b), 0)
5062 * Prepare a pattern for a expmeta (internal glob(3)) call.
5064 * Returns an stalloced string.
5067 preglob(const char *pattern, int quoted, int flag)
5069 flag |= RMESCAPE_GLOB;
5071 flag |= RMESCAPE_QUOTED;
5073 return _rmescapes((char *)pattern, flag);
5077 * Put a string on the stack.
5080 memtodest(const char *p, size_t len, int syntax, int quotes)
5084 q = makestrspace(len * 2, q);
5087 int c = signed_char2int(*p++);
5090 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5099 strtodest(const char *p, int syntax, int quotes)
5101 memtodest(p, strlen(p), syntax, quotes);
5105 * Record the fact that we have to scan this region of the
5106 * string for IFS characters.
5109 recordregion(int start, int end, int nulonly)
5111 struct ifsregion *ifsp;
5113 if (ifslastp == NULL) {
5117 ifsp = ckmalloc(sizeof(*ifsp));
5119 ifslastp->next = ifsp;
5123 ifslastp->begoff = start;
5124 ifslastp->endoff = end;
5125 ifslastp->nulonly = nulonly;
5129 removerecordregions(int endoff)
5131 if (ifslastp == NULL)
5134 if (ifsfirst.endoff > endoff) {
5135 while (ifsfirst.next != NULL) {
5136 struct ifsregion *ifsp;
5138 ifsp = ifsfirst.next->next;
5139 free(ifsfirst.next);
5140 ifsfirst.next = ifsp;
5143 if (ifsfirst.begoff > endoff)
5146 ifslastp = &ifsfirst;
5147 ifsfirst.endoff = endoff;
5152 ifslastp = &ifsfirst;
5153 while (ifslastp->next && ifslastp->next->begoff < endoff)
5154 ifslastp=ifslastp->next;
5155 while (ifslastp->next != NULL) {
5156 struct ifsregion *ifsp;
5158 ifsp = ifslastp->next->next;
5159 free(ifslastp->next);
5160 ifslastp->next = ifsp;
5163 if (ifslastp->endoff > endoff)
5164 ifslastp->endoff = endoff;
5168 exptilde(char *startp, char *p, int flag)
5174 int quotes = flag & (EXP_FULL | EXP_CASE);
5179 while ((c = *++p) != '\0') {
5186 if (flag & EXP_VARTILDE)
5196 if (*name == '\0') {
5197 home = lookupvar(homestr);
5199 pw = getpwnam(name);
5204 if (!home || !*home)
5207 startloc = expdest - (char *)stackblock();
5208 strtodest(home, SQSYNTAX, quotes);
5209 recordregion(startloc, expdest - (char *)stackblock(), 0);
5217 * Execute a command inside back quotes. If it's a builtin command, we
5218 * want to save its output in a block obtained from malloc. Otherwise
5219 * we fork off a subprocess and get the output of the command via a pipe.
5220 * Should be called with interrupts off.
5222 struct backcmd { /* result of evalbackcmd */
5223 int fd; /* file descriptor to read from */
5224 char *buf; /* buffer */
5225 int nleft; /* number of chars in buffer */
5226 struct job *jp; /* job structure for command */
5229 /* These forward decls are needed to use "eval" code for backticks handling: */
5230 static int back_exitstatus; /* exit status of backquoted command */
5231 #define EV_EXIT 01 /* exit after evaluating tree */
5232 static void evaltree(union node *, int);
5235 evalbackcmd(union node *n, struct backcmd *result)
5247 saveherefd = herefd;
5255 ash_msg_and_raise_error("pipe call failed");
5257 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5266 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5270 result->fd = pip[0];
5273 herefd = saveherefd;
5275 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5276 result->fd, result->buf, result->nleft, result->jp));
5280 * Expand stuff in backwards quotes.
5283 expbackq(union node *cmd, int quoted, int quotes)
5291 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5292 struct stackmark smark;
5295 setstackmark(&smark);
5297 startloc = dest - (char *)stackblock();
5299 evalbackcmd(cmd, &in);
5300 popstackmark(&smark);
5307 memtodest(p, i, syntax, quotes);
5311 i = safe_read(in.fd, buf, sizeof(buf));
5312 TRACE(("expbackq: read returns %d\n", i));
5322 back_exitstatus = waitforjob(in.jp);
5326 /* Eat all trailing newlines */
5328 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5333 recordregion(startloc, dest - (char *)stackblock(), 0);
5334 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5335 (dest - (char *)stackblock()) - startloc,
5336 (dest - (char *)stackblock()) - startloc,
5337 stackblock() + startloc));
5340 #if ENABLE_ASH_MATH_SUPPORT
5342 * Expand arithmetic expression. Backup to start of expression,
5343 * evaluate, place result in (backed up) result, adjust string position.
5356 * This routine is slightly over-complicated for
5357 * efficiency. Next we scan backwards looking for the
5358 * start of arithmetic.
5360 start = stackblock();
5367 while (*p != CTLARI) {
5371 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5376 esc = esclen(start, p);
5386 removerecordregions(begoff);
5395 len = cvtnum(dash_arith(p + 2));
5398 recordregion(begoff, begoff + len, 0);
5402 /* argstr needs it */
5403 static char *evalvar(char *p, int flag);
5406 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5407 * characters to allow for further processing. Otherwise treat
5408 * $@ like $* since no splitting will be performed.
5411 argstr(char *p, int flag)
5413 static const char spclchars[] = {
5421 CTLBACKQ | CTLQUOTE,
5422 #if ENABLE_ASH_MATH_SUPPORT
5427 const char *reject = spclchars;
5429 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5430 int breakall = flag & EXP_WORD;
5435 if (!(flag & EXP_VARTILDE)) {
5437 } else if (flag & EXP_VARTILDE2) {
5442 if (flag & EXP_TILDE) {
5448 if (*q == CTLESC && (flag & EXP_QWORD))
5451 p = exptilde(p, q, flag);
5454 startloc = expdest - (char *)stackblock();
5456 length += strcspn(p + length, reject);
5458 if (c && (!(c & 0x80)
5459 #if ENABLE_ASH_MATH_SUPPORT
5463 /* c == '=' || c == ':' || c == CTLENDARI */
5468 expdest = stack_nputstr(p, length, expdest);
5469 newloc = expdest - (char *)stackblock();
5470 if (breakall && !inquotes && newloc > startloc) {
5471 recordregion(startloc, newloc, 0);
5482 if (flag & EXP_VARTILDE2) {
5486 flag |= EXP_VARTILDE2;
5491 * sort of a hack - expand tildes in variable
5492 * assignments (after the first '=' and after ':'s).
5501 case CTLENDVAR: /* ??? */
5504 /* "$@" syntax adherence hack */
5507 !memcmp(p, dolatstr, 4) &&
5508 (p[4] == CTLQUOTEMARK || (
5509 p[4] == CTLENDVAR &&
5510 p[5] == CTLQUOTEMARK
5513 p = evalvar(p + 1, flag) + 1;
5516 inquotes = !inquotes;
5529 p = evalvar(p, flag);
5533 case CTLBACKQ|CTLQUOTE:
5534 expbackq(argbackq->n, c, quotes);
5535 argbackq = argbackq->next;
5537 #if ENABLE_ASH_MATH_SUPPORT
5550 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5561 const char *s = loc2;
5567 match = pmatch(str, s);
5571 if (quotes && *loc == CTLESC)
5580 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5587 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5590 const char *s = loc2;
5595 match = pmatch(str, s);
5602 esc = esclen(startp, loc);
5613 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5615 varunset(const char *end, const char *var, const char *umsg, int varflags)
5621 msg = "parameter not set";
5623 if (*end == CTLENDVAR) {
5624 if (varflags & VSNUL)
5629 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5633 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5637 int saveherefd = herefd;
5638 struct nodelist *saveargbackq = argbackq;
5640 char *rmesc, *rmescend;
5642 char *(*scan)(char *, char *, char *, char *, int , int);
5645 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5646 STPUTC('\0', expdest);
5647 herefd = saveherefd;
5648 argbackq = saveargbackq;
5649 startp = stackblock() + startloc;
5653 setvar(str, startp, 0);
5654 amount = startp - expdest;
5655 STADJUST(amount, expdest);
5659 varunset(p, str, startp, varflags);
5663 subtype -= VSTRIMRIGHT;
5665 if (subtype < 0 || subtype > 3)
5670 rmescend = stackblock() + strloc;
5672 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5673 if (rmesc != startp) {
5675 startp = stackblock() + startloc;
5679 str = stackblock() + strloc;
5680 preglob(str, varflags & VSQUOTE, 0);
5682 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5683 zero = subtype >> 1;
5684 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5685 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5687 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5690 memmove(startp, loc, str - loc);
5691 loc = startp + (str - loc) - 1;
5694 amount = loc - expdest;
5695 STADJUST(amount, expdest);
5701 * Add the value of a specialized variable to the stack string.
5704 varvalue(char *name, int varflags, int flags)
5714 int quoted = varflags & VSQUOTE;
5715 int subtype = varflags & VSTYPE;
5716 int quotes = flags & (EXP_FULL | EXP_CASE);
5718 if (quoted && (flags & EXP_FULL))
5719 sep = 1 << CHAR_BIT;
5721 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5730 num = shellparam.nparam;
5740 p = makestrspace(NOPTS, expdest);
5741 for (i = NOPTS - 1; i >= 0; i--) {
5743 USTPUTC(optletters(i), p);
5754 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5755 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5761 while ((p = *ap++)) {
5764 partlen = strlen(p);
5767 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5768 memtodest(p, partlen, syntax, quotes);
5774 if (subtype == VSPLUS || subtype == VSLENGTH) {
5796 if (num < 0 || num > shellparam.nparam)
5798 p = num ? shellparam.p[num - 1] : arg0;
5801 p = lookupvar(name);
5807 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5808 memtodest(p, len, syntax, quotes);
5812 if (subtype == VSPLUS || subtype == VSLENGTH)
5813 STADJUST(-len, expdest);
5818 * Expand a variable, and return a pointer to the next character in the
5822 evalvar(char *p, int flag)
5835 quotes = flag & (EXP_FULL | EXP_CASE);
5837 subtype = varflags & VSTYPE;
5838 quoted = varflags & VSQUOTE;
5840 easy = (!quoted || (*var == '@' && shellparam.nparam));
5841 startloc = expdest - (char *)stackblock();
5842 p = strchr(p, '=') + 1;
5845 varlen = varvalue(var, varflags, flag);
5846 if (varflags & VSNUL)
5849 if (subtype == VSPLUS) {
5850 varlen = -1 - varlen;
5854 if (subtype == VSMINUS) {
5858 p, flag | EXP_TILDE |
5859 (quoted ? EXP_QWORD : EXP_WORD)
5868 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5870 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5873 * Remove any recorded regions beyond
5876 removerecordregions(startloc);
5886 if (varlen < 0 && uflag)
5887 varunset(p, var, 0, 0);
5889 if (subtype == VSLENGTH) {
5890 cvtnum(varlen > 0 ? varlen : 0);
5894 if (subtype == VSNORMAL) {
5898 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5907 case VSTRIMRIGHTMAX:
5916 * Terminate the string and start recording the pattern
5919 STPUTC('\0', expdest);
5920 patloc = expdest - (char *)stackblock();
5921 if (subevalvar(p, NULL, patloc, subtype,
5922 startloc, varflags, quotes) == 0) {
5923 int amount = expdest - (
5924 (char *)stackblock() + patloc - 1
5926 STADJUST(-amount, expdest);
5928 /* Remove any recorded regions beyond start of variable */
5929 removerecordregions(startloc);
5934 if (subtype != VSNORMAL) { /* skip to end of alternative */
5940 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5942 argbackq = argbackq->next;
5943 } else if (c == CTLVAR) {
5944 if ((*p++ & VSTYPE) != VSNORMAL)
5946 } else if (c == CTLENDVAR) {
5956 * Break the argument string into pieces based upon IFS and add the
5957 * strings to the argument list. The regions of the string to be
5958 * searched for IFS characters have been stored by recordregion.
5961 ifsbreakup(char *string, struct arglist *arglist)
5963 struct ifsregion *ifsp;
5968 const char *ifs, *realifs;
5973 if (ifslastp != NULL) {
5976 realifs = ifsset() ? ifsval() : defifs;
5979 p = string + ifsp->begoff;
5980 nulonly = ifsp->nulonly;
5981 ifs = nulonly ? nullstr : realifs;
5983 while (p < string + ifsp->endoff) {
5987 if (!strchr(ifs, *p)) {
5992 ifsspc = (strchr(defifs, *p) != NULL);
5993 /* Ignore IFS whitespace at start */
5994 if (q == start && ifsspc) {
6000 sp = stalloc(sizeof(*sp));
6002 *arglist->lastp = sp;
6003 arglist->lastp = &sp->next;
6007 if (p >= string + ifsp->endoff) {
6013 if (strchr(ifs, *p) == NULL ) {
6016 } else if (strchr(defifs, *p) == NULL) {
6031 } while (ifsp != NULL);
6040 sp = stalloc(sizeof(*sp));
6042 *arglist->lastp = sp;
6043 arglist->lastp = &sp->next;
6049 struct ifsregion *p;
6054 struct ifsregion *ifsp;
6060 ifsfirst.next = NULL;
6065 * Add a file name to the list.
6068 addfname(const char *name)
6072 sp = stalloc(sizeof(*sp));
6073 sp->text = ststrdup(name);
6075 exparg.lastp = &sp->next;
6078 static char *expdir;
6081 * Do metacharacter (i.e. *, ?, [...]) expansion.
6084 expmeta(char *enddir, char *name)
6099 for (p = name; *p; p++) {
6100 if (*p == '*' || *p == '?')
6102 else if (*p == '[') {
6109 if (*q == '/' || *q == '\0')
6116 } else if (*p == '\\')
6118 else if (*p == '/') {
6125 if (metaflag == 0) { /* we've reached the end of the file name */
6126 if (enddir != expdir)
6134 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6145 } while (p < start);
6147 if (enddir == expdir) {
6149 } else if (enddir == expdir + 1 && *expdir == '/') {
6158 if (enddir != expdir)
6160 if (*endname == 0) {
6172 while (! intpending && (dp = readdir(dirp)) != NULL) {
6173 if (dp->d_name[0] == '.' && ! matchdot)
6175 if (pmatch(start, dp->d_name)) {
6177 strcpy(enddir, dp->d_name);
6180 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6183 expmeta(p, endname);
6192 static struct strlist *
6193 msort(struct strlist *list, int len)
6195 struct strlist *p, *q = NULL;
6196 struct strlist **lpp;
6204 for (n = half; --n >= 0; ) {
6208 q->next = NULL; /* terminate first half of list */
6209 q = msort(list, half); /* sort first half of list */
6210 p = msort(p, len - half); /* sort second half */
6213 #if ENABLE_LOCALE_SUPPORT
6214 if (strcoll(p->text, q->text) < 0)
6216 if (strcmp(p->text, q->text) < 0)
6240 * Sort the results of file name expansion. It calculates the number of
6241 * strings to sort and then calls msort (short for merge sort) to do the
6244 static struct strlist *
6245 expsort(struct strlist *str)
6251 for (sp = str; sp; sp = sp->next)
6253 return msort(str, len);
6257 expandmeta(struct strlist *str, int flag)
6259 static const char metachars[] = {
6262 /* TODO - EXP_REDIR */
6265 struct strlist **savelastp;
6271 if (!strpbrk(str->text, metachars))
6273 savelastp = exparg.lastp;
6276 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6278 int i = strlen(str->text);
6279 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6287 if (exparg.lastp == savelastp) {
6292 *exparg.lastp = str;
6293 rmescapes(str->text);
6294 exparg.lastp = &str->next;
6296 *exparg.lastp = NULL;
6297 *savelastp = sp = expsort(*savelastp);
6298 while (sp->next != NULL)
6300 exparg.lastp = &sp->next;
6307 * Perform variable substitution and command substitution on an argument,
6308 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6309 * perform splitting and file name expansion. When arglist is NULL, perform
6310 * here document expansion.
6313 expandarg(union node *arg, struct arglist *arglist, int flag)
6318 argbackq = arg->narg.backquote;
6319 STARTSTACKSTR(expdest);
6320 ifsfirst.next = NULL;
6322 argstr(arg->narg.text, flag);
6323 p = _STPUTC('\0', expdest);
6325 if (arglist == NULL) {
6326 return; /* here document expanded */
6328 p = grabstackstr(p);
6329 exparg.lastp = &exparg.list;
6333 if (flag & EXP_FULL) {
6334 ifsbreakup(p, &exparg);
6335 *exparg.lastp = NULL;
6336 exparg.lastp = &exparg.list;
6337 expandmeta(exparg.list, flag);
6339 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6341 sp = stalloc(sizeof(*sp));
6344 exparg.lastp = &sp->next;
6348 *exparg.lastp = NULL;
6350 *arglist->lastp = exparg.list;
6351 arglist->lastp = exparg.lastp;
6356 * Expand shell variables and backquotes inside a here document.
6359 expandhere(union node *arg, int fd)
6362 expandarg(arg, (struct arglist *)NULL, 0);
6363 full_write(fd, stackblock(), expdest - (char *)stackblock());
6367 * Returns true if the pattern matches the string.
6370 patmatch(char *pattern, const char *string)
6372 return pmatch(preglob(pattern, 0, 0), string);
6376 * See if a pattern matches in a case statement.
6379 casematch(union node *pattern, char *val)
6381 struct stackmark smark;
6384 setstackmark(&smark);
6385 argbackq = pattern->narg.backquote;
6386 STARTSTACKSTR(expdest);
6388 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6389 STACKSTRNUL(expdest);
6390 result = patmatch(stackblock(), val);
6391 popstackmark(&smark);
6396 /* ============ find_command */
6400 int (*builtin)(int, char **);
6401 /* unsigned flags; */
6403 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6404 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6405 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6411 const struct builtincmd *cmd;
6412 struct funcnode *func;
6415 /* values of cmdtype */
6416 #define CMDUNKNOWN -1 /* no entry in table for command */
6417 #define CMDNORMAL 0 /* command is an executable program */
6418 #define CMDFUNCTION 1 /* command is a shell function */
6419 #define CMDBUILTIN 2 /* command is a shell builtin */
6421 /* action to find_command() */
6422 #define DO_ERR 0x01 /* prints errors */
6423 #define DO_ABS 0x02 /* checks absolute paths */
6424 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6425 #define DO_ALTPATH 0x08 /* using alternate path */
6426 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6428 static void find_command(char *, struct cmdentry *, int, const char *);
6431 /* ============ Hashing commands */
6434 * When commands are first encountered, they are entered in a hash table.
6435 * This ensures that a full path search will not have to be done for them
6436 * on each invocation.
6438 * We should investigate converting to a linear search, even though that
6439 * would make the command name "hash" a misnomer.
6442 #define CMDTABLESIZE 31 /* should be prime */
6443 #define ARB 1 /* actual size determined at run time */
6446 struct tblentry *next; /* next entry in hash chain */
6447 union param param; /* definition of builtin function */
6448 short cmdtype; /* index identifying command */
6449 char rehash; /* if set, cd done since entry created */
6450 char cmdname[ARB]; /* name of command */
6453 static struct tblentry *cmdtable[CMDTABLESIZE];
6454 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6457 tryexec(char *cmd, char **argv, char **envp)
6461 #if ENABLE_FEATURE_SH_STANDALONE
6462 if (strchr(cmd, '/') == NULL) {
6463 const struct bb_applet *a;
6465 a = find_applet_by_name(cmd);
6469 run_current_applet_and_exit(argv);
6471 /* re-exec ourselves with the new arguments */
6472 execve(bb_busybox_exec_path, argv, envp);
6473 /* If they called chroot or otherwise made the binary no longer
6474 * executable, fall through */
6482 execve(cmd, argv, envp);
6483 } while (errno == EINTR);
6485 execve(cmd, argv, envp);
6489 } else if (errno == ENOEXEC) {
6493 for (ap = argv; *ap; ap++)
6495 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6497 ap[0] = cmd = (char *)DEFAULT_SHELL;
6500 while ((*ap++ = *argv++))
6508 * Exec a program. Never returns. If you change this routine, you may
6509 * have to change the find_command routine as well.
6511 #define environment() listvars(VEXPORT, VUNSET, 0)
6512 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6514 shellexec(char **argv, const char *path, int idx)
6522 envp = environment();
6523 if (strchr(argv[0], '/')
6524 #if ENABLE_FEATURE_SH_STANDALONE
6525 || find_applet_by_name(argv[0])
6528 tryexec(argv[0], argv, envp);
6532 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6533 if (--idx < 0 && pathopt == NULL) {
6534 tryexec(cmdname, argv, envp);
6535 if (errno != ENOENT && errno != ENOTDIR)
6542 /* Map to POSIX errors */
6554 exitstatus = exerrno;
6555 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6556 argv[0], e, suppressint ));
6557 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6562 printentry(struct tblentry *cmdp)
6568 idx = cmdp->param.index;
6571 name = padvance(&path, cmdp->cmdname);
6573 } while (--idx >= 0);
6574 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6578 * Clear out command entries. The argument specifies the first entry in
6579 * PATH which has changed.
6582 clearcmdentry(int firstchange)
6584 struct tblentry **tblp;
6585 struct tblentry **pp;
6586 struct tblentry *cmdp;
6589 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6591 while ((cmdp = *pp) != NULL) {
6592 if ((cmdp->cmdtype == CMDNORMAL &&
6593 cmdp->param.index >= firstchange)
6594 || (cmdp->cmdtype == CMDBUILTIN &&
6595 builtinloc >= firstchange)
6608 * Locate a command in the command hash table. If "add" is nonzero,
6609 * add the command to the table if it is not already present. The
6610 * variable "lastcmdentry" is set to point to the address of the link
6611 * pointing to the entry, so that delete_cmd_entry can delete the
6614 * Interrupts must be off if called with add != 0.
6616 static struct tblentry **lastcmdentry;
6618 static struct tblentry *
6619 cmdlookup(const char *name, int add)
6621 unsigned int hashval;
6623 struct tblentry *cmdp;
6624 struct tblentry **pp;
6627 hashval = (unsigned char)*p << 4;
6629 hashval += (unsigned char)*p++;
6631 pp = &cmdtable[hashval % CMDTABLESIZE];
6632 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6633 if (strcmp(cmdp->cmdname, name) == 0)
6637 if (add && cmdp == NULL) {
6638 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6639 + strlen(name) + 1);
6641 cmdp->cmdtype = CMDUNKNOWN;
6642 strcpy(cmdp->cmdname, name);
6649 * Delete the command entry returned on the last lookup.
6652 delete_cmd_entry(void)
6654 struct tblentry *cmdp;
6657 cmdp = *lastcmdentry;
6658 *lastcmdentry = cmdp->next;
6659 if (cmdp->cmdtype == CMDFUNCTION)
6660 freefunc(cmdp->param.func);
6666 * Add a new command entry, replacing any existing command entry for
6667 * the same name - except special builtins.
6670 addcmdentry(char *name, struct cmdentry *entry)
6672 struct tblentry *cmdp;
6674 cmdp = cmdlookup(name, 1);
6675 if (cmdp->cmdtype == CMDFUNCTION) {
6676 freefunc(cmdp->param.func);
6678 cmdp->cmdtype = entry->cmdtype;
6679 cmdp->param = entry->u;
6684 hashcmd(int argc, char **argv)
6686 struct tblentry **pp;
6687 struct tblentry *cmdp;
6689 struct cmdentry entry;
6692 while ((c = nextopt("r")) != '\0') {
6696 if (*argptr == NULL) {
6697 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6698 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6699 if (cmdp->cmdtype == CMDNORMAL)
6706 while ((name = *argptr) != NULL) {
6707 cmdp = cmdlookup(name, 0);
6709 && (cmdp->cmdtype == CMDNORMAL
6710 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6712 find_command(name, &entry, DO_ERR, pathval());
6713 if (entry.cmdtype == CMDUNKNOWN)
6721 * Called when a cd is done. Marks all commands so the next time they
6722 * are executed they will be rehashed.
6727 struct tblentry **pp;
6728 struct tblentry *cmdp;
6730 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6731 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6732 if (cmdp->cmdtype == CMDNORMAL || (
6733 cmdp->cmdtype == CMDBUILTIN &&
6734 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6743 * Fix command hash table when PATH changed.
6744 * Called before PATH is changed. The argument is the new value of PATH;
6745 * pathval() still returns the old value at this point.
6746 * Called with interrupts off.
6749 changepath(const char *newval)
6751 const char *old, *new;
6758 firstchange = 9999; /* assume no change */
6764 if ((*old == '\0' && *new == ':')
6765 || (*old == ':' && *new == '\0'))
6767 old = new; /* ignore subsequent differences */
6771 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6778 if (builtinloc < 0 && idx_bltin >= 0)
6779 builtinloc = idx_bltin; /* zap builtins */
6780 if (builtinloc >= 0 && idx_bltin < 0)
6782 clearcmdentry(firstchange);
6783 builtinloc = idx_bltin;
6798 #define TENDBQUOTE 12
6816 /* first char is indicating which tokens mark the end of a list */
6817 static const char *const tokname_array[] = {
6831 #define KWDOFFSET 13
6832 /* the following are keywords */
6854 static char buf[16];
6857 //if (tok < TSEMI) return tokname_array[tok] + 1;
6858 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6863 sprintf(buf + (tok >= TSEMI), "%s%c",
6864 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6868 /* Wrapper around strcmp for qsort/bsearch/... */
6870 pstrcmp(const void *a, const void *b)
6872 return strcmp((char*) a, (*(char**) b) + 1);
6875 static const char *const *
6876 findkwd(const char *s)
6878 return bsearch(s, tokname_array + KWDOFFSET,
6879 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6880 sizeof(tokname_array[0]), pstrcmp);
6884 * Locate and print what a word is...
6887 describe_command(char *command, int describe_command_verbose)
6889 struct cmdentry entry;
6890 struct tblentry *cmdp;
6891 #if ENABLE_ASH_ALIAS
6892 const struct alias *ap;
6894 const char *path = pathval();
6896 if (describe_command_verbose) {
6900 /* First look at the keywords */
6901 if (findkwd(command)) {
6902 out1str(describe_command_verbose ? " is a shell keyword" : command);
6906 #if ENABLE_ASH_ALIAS
6907 /* Then look at the aliases */
6908 ap = lookupalias(command, 0);
6910 if (!describe_command_verbose) {
6915 out1fmt(" is an alias for %s", ap->val);
6919 /* Then check if it is a tracked alias */
6920 cmdp = cmdlookup(command, 0);
6922 entry.cmdtype = cmdp->cmdtype;
6923 entry.u = cmdp->param;
6925 /* Finally use brute force */
6926 find_command(command, &entry, DO_ABS, path);
6929 switch (entry.cmdtype) {
6931 int j = entry.u.index;
6937 p = padvance(&path, command);
6941 if (describe_command_verbose) {
6943 (cmdp ? " a tracked alias for" : nullstr), p
6952 if (describe_command_verbose) {
6953 out1str(" is a shell function");
6960 if (describe_command_verbose) {
6961 out1fmt(" is a %sshell builtin",
6962 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
6963 "special " : nullstr
6971 if (describe_command_verbose) {
6972 out1str(": not found\n");
6977 outstr("\n", stdout);
6982 typecmd(int argc, char **argv)
6988 /* type -p ... ? (we don't bother checking for 'p') */
6989 if (argv[1] && argv[1][0] == '-') {
6994 err |= describe_command(argv[i++], verbose);
6999 #if ENABLE_ASH_CMDCMD
7001 commandcmd(int argc, char **argv)
7009 while ((c = nextopt("pvV")) != '\0')
7011 verify |= VERIFY_VERBOSE;
7013 verify |= VERIFY_BRIEF;
7019 return describe_command(*argptr, verify - VERIFY_BRIEF);
7026 /* ============ eval.c */
7028 static int funcblocksize; /* size of structures in function */
7029 static int funcstringsize; /* size of strings in node */
7030 static void *funcblock; /* block to allocate function from */
7031 static char *funcstring; /* block to allocate strings from */
7033 /* flags in argument to evaltree */
7034 #define EV_EXIT 01 /* exit after evaluating tree */
7035 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7036 #define EV_BACKCMD 04 /* command executing within back quotes */
7038 static const short nodesize[26] = {
7039 SHELL_ALIGN(sizeof(struct ncmd)),
7040 SHELL_ALIGN(sizeof(struct npipe)),
7041 SHELL_ALIGN(sizeof(struct nredir)),
7042 SHELL_ALIGN(sizeof(struct nredir)),
7043 SHELL_ALIGN(sizeof(struct nredir)),
7044 SHELL_ALIGN(sizeof(struct nbinary)),
7045 SHELL_ALIGN(sizeof(struct nbinary)),
7046 SHELL_ALIGN(sizeof(struct nbinary)),
7047 SHELL_ALIGN(sizeof(struct nif)),
7048 SHELL_ALIGN(sizeof(struct nbinary)),
7049 SHELL_ALIGN(sizeof(struct nbinary)),
7050 SHELL_ALIGN(sizeof(struct nfor)),
7051 SHELL_ALIGN(sizeof(struct ncase)),
7052 SHELL_ALIGN(sizeof(struct nclist)),
7053 SHELL_ALIGN(sizeof(struct narg)),
7054 SHELL_ALIGN(sizeof(struct narg)),
7055 SHELL_ALIGN(sizeof(struct nfile)),
7056 SHELL_ALIGN(sizeof(struct nfile)),
7057 SHELL_ALIGN(sizeof(struct nfile)),
7058 SHELL_ALIGN(sizeof(struct nfile)),
7059 SHELL_ALIGN(sizeof(struct nfile)),
7060 SHELL_ALIGN(sizeof(struct ndup)),
7061 SHELL_ALIGN(sizeof(struct ndup)),
7062 SHELL_ALIGN(sizeof(struct nhere)),
7063 SHELL_ALIGN(sizeof(struct nhere)),
7064 SHELL_ALIGN(sizeof(struct nnot)),
7067 static void calcsize(union node *n);
7070 sizenodelist(struct nodelist *lp)
7073 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7080 calcsize(union node *n)
7084 funcblocksize += nodesize[n->type];
7087 calcsize(n->ncmd.redirect);
7088 calcsize(n->ncmd.args);
7089 calcsize(n->ncmd.assign);
7092 sizenodelist(n->npipe.cmdlist);
7097 calcsize(n->nredir.redirect);
7098 calcsize(n->nredir.n);
7105 calcsize(n->nbinary.ch2);
7106 calcsize(n->nbinary.ch1);
7109 calcsize(n->nif.elsepart);
7110 calcsize(n->nif.ifpart);
7111 calcsize(n->nif.test);
7114 funcstringsize += strlen(n->nfor.var) + 1;
7115 calcsize(n->nfor.body);
7116 calcsize(n->nfor.args);
7119 calcsize(n->ncase.cases);
7120 calcsize(n->ncase.expr);
7123 calcsize(n->nclist.body);
7124 calcsize(n->nclist.pattern);
7125 calcsize(n->nclist.next);
7129 sizenodelist(n->narg.backquote);
7130 funcstringsize += strlen(n->narg.text) + 1;
7131 calcsize(n->narg.next);
7138 calcsize(n->nfile.fname);
7139 calcsize(n->nfile.next);
7143 calcsize(n->ndup.vname);
7144 calcsize(n->ndup.next);
7148 calcsize(n->nhere.doc);
7149 calcsize(n->nhere.next);
7152 calcsize(n->nnot.com);
7158 nodeckstrdup(char *s)
7160 char *rtn = funcstring;
7162 strcpy(funcstring, s);
7163 funcstring += strlen(s) + 1;
7167 static union node *copynode(union node *);
7169 static struct nodelist *
7170 copynodelist(struct nodelist *lp)
7172 struct nodelist *start;
7173 struct nodelist **lpp;
7178 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7179 (*lpp)->n = copynode(lp->n);
7181 lpp = &(*lpp)->next;
7188 copynode(union node *n)
7195 funcblock = (char *) funcblock + nodesize[n->type];
7199 new->ncmd.redirect = copynode(n->ncmd.redirect);
7200 new->ncmd.args = copynode(n->ncmd.args);
7201 new->ncmd.assign = copynode(n->ncmd.assign);
7204 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7205 new->npipe.backgnd = n->npipe.backgnd;
7210 new->nredir.redirect = copynode(n->nredir.redirect);
7211 new->nredir.n = copynode(n->nredir.n);
7218 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7219 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7222 new->nif.elsepart = copynode(n->nif.elsepart);
7223 new->nif.ifpart = copynode(n->nif.ifpart);
7224 new->nif.test = copynode(n->nif.test);
7227 new->nfor.var = nodeckstrdup(n->nfor.var);
7228 new->nfor.body = copynode(n->nfor.body);
7229 new->nfor.args = copynode(n->nfor.args);
7232 new->ncase.cases = copynode(n->ncase.cases);
7233 new->ncase.expr = copynode(n->ncase.expr);
7236 new->nclist.body = copynode(n->nclist.body);
7237 new->nclist.pattern = copynode(n->nclist.pattern);
7238 new->nclist.next = copynode(n->nclist.next);
7242 new->narg.backquote = copynodelist(n->narg.backquote);
7243 new->narg.text = nodeckstrdup(n->narg.text);
7244 new->narg.next = copynode(n->narg.next);
7251 new->nfile.fname = copynode(n->nfile.fname);
7252 new->nfile.fd = n->nfile.fd;
7253 new->nfile.next = copynode(n->nfile.next);
7257 new->ndup.vname = copynode(n->ndup.vname);
7258 new->ndup.dupfd = n->ndup.dupfd;
7259 new->ndup.fd = n->ndup.fd;
7260 new->ndup.next = copynode(n->ndup.next);
7264 new->nhere.doc = copynode(n->nhere.doc);
7265 new->nhere.fd = n->nhere.fd;
7266 new->nhere.next = copynode(n->nhere.next);
7269 new->nnot.com = copynode(n->nnot.com);
7272 new->type = n->type;
7277 * Make a copy of a parse tree.
7279 static struct funcnode *
7280 copyfunc(union node *n)
7285 funcblocksize = offsetof(struct funcnode, n);
7288 blocksize = funcblocksize;
7289 f = ckmalloc(blocksize + funcstringsize);
7290 funcblock = (char *) f + offsetof(struct funcnode, n);
7291 funcstring = (char *) f + blocksize;
7298 * Define a shell function.
7301 defun(char *name, union node *func)
7303 struct cmdentry entry;
7306 entry.cmdtype = CMDFUNCTION;
7307 entry.u.func = copyfunc(func);
7308 addcmdentry(name, &entry);
7312 static int evalskip; /* set if we are skipping commands */
7313 /* reasons for skipping commands (see comment on breakcmd routine) */
7314 #define SKIPBREAK (1 << 0)
7315 #define SKIPCONT (1 << 1)
7316 #define SKIPFUNC (1 << 2)
7317 #define SKIPFILE (1 << 3)
7318 #define SKIPEVAL (1 << 4)
7319 static int skipcount; /* number of levels to skip */
7320 static int funcnest; /* depth of function calls */
7322 /* forward decl way out to parsing code - dotrap needs it */
7323 static int evalstring(char *s, int mask);
7326 * Called to execute a trap. Perhaps we should avoid entering new trap
7327 * handlers while we are executing a trap handler.
7338 savestatus = exitstatus;
7342 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7350 skip = evalstring(p, SKIPEVAL);
7351 exitstatus = savestatus;
7359 /* forward declarations - evaluation is fairly recursive business... */
7360 static void evalloop(union node *, int);
7361 static void evalfor(union node *, int);
7362 static void evalcase(union node *, int);
7363 static void evalsubshell(union node *, int);
7364 static void expredir(union node *);
7365 static void evalpipe(union node *, int);
7366 static void evalcommand(union node *, int);
7367 static int evalbltin(const struct builtincmd *, int, char **);
7368 static void prehash(union node *);
7371 * Evaluate a parse tree. The value is left in the global variable
7375 evaltree(union node *n, int flags)
7378 void (*evalfn)(union node *, int);
7382 TRACE(("evaltree(NULL) called\n"));
7385 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7386 getpid(), n, n->type, flags));
7390 out1fmt("Node type = %d\n", n->type);
7395 evaltree(n->nnot.com, EV_TESTED);
7396 status = !exitstatus;
7399 expredir(n->nredir.redirect);
7400 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7402 evaltree(n->nredir.n, flags & EV_TESTED);
7403 status = exitstatus;
7408 evalfn = evalcommand;
7410 if (eflag && !(flags & EV_TESTED))
7422 evalfn = evalsubshell;
7434 #error NAND + 1 != NOR
7436 #if NOR + 1 != NSEMI
7437 #error NOR + 1 != NSEMI
7439 isor = n->type - NAND;
7442 (flags | ((isor >> 1) - 1)) & EV_TESTED
7444 if (!exitstatus == isor)
7456 evaltree(n->nif.test, EV_TESTED);
7459 if (exitstatus == 0) {
7462 } else if (n->nif.elsepart) {
7463 n = n->nif.elsepart;
7468 defun(n->narg.text, n->narg.next);
7472 exitstatus = status;
7476 if ((checkexit & exitstatus))
7477 evalskip |= SKIPEVAL;
7478 else if (pendingsig && dotrap())
7481 if (flags & EV_EXIT) {
7483 raise_exception(EXEXIT);
7487 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7490 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7492 static int loopnest; /* current loop nesting level */
7495 evalloop(union node *n, int flags)
7505 evaltree(n->nbinary.ch1, EV_TESTED);
7508 if (evalskip == SKIPCONT && --skipcount <= 0) {
7512 if (evalskip == SKIPBREAK && --skipcount <= 0)
7517 if (n->type != NWHILE)
7521 evaltree(n->nbinary.ch2, flags);
7522 status = exitstatus;
7527 exitstatus = status;
7531 evalfor(union node *n, int flags)
7533 struct arglist arglist;
7536 struct stackmark smark;
7538 setstackmark(&smark);
7539 arglist.lastp = &arglist.list;
7540 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7541 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7546 *arglist.lastp = NULL;
7551 for (sp = arglist.list; sp; sp = sp->next) {
7552 setvar(n->nfor.var, sp->text, 0);
7553 evaltree(n->nfor.body, flags);
7555 if (evalskip == SKIPCONT && --skipcount <= 0) {
7559 if (evalskip == SKIPBREAK && --skipcount <= 0)
7566 popstackmark(&smark);
7570 evalcase(union node *n, int flags)
7574 struct arglist arglist;
7575 struct stackmark smark;
7577 setstackmark(&smark);
7578 arglist.lastp = &arglist.list;
7579 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7581 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7582 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7583 if (casematch(patp, arglist.list->text)) {
7584 if (evalskip == 0) {
7585 evaltree(cp->nclist.body, flags);
7592 popstackmark(&smark);
7596 * Kick off a subshell to evaluate a tree.
7599 evalsubshell(union node *n, int flags)
7602 int backgnd = (n->type == NBACKGND);
7605 expredir(n->nredir.redirect);
7606 if (!backgnd && flags & EV_EXIT && !trap[0])
7610 if (forkshell(jp, n, backgnd) == 0) {
7614 flags &=~ EV_TESTED;
7616 redirect(n->nredir.redirect, 0);
7617 evaltreenr(n->nredir.n, flags);
7622 status = waitforjob(jp);
7623 exitstatus = status;
7628 * Compute the names of the files in a redirection list.
7630 static void fixredir(union node *, const char *, int);
7632 expredir(union node *n)
7636 for (redir = n; redir; redir = redir->nfile.next) {
7639 memset(&fn, 0, sizeof(fn));
7640 fn.lastp = &fn.list;
7641 switch (redir->type) {
7647 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7648 redir->nfile.expfname = fn.list->text;
7652 if (redir->ndup.vname) {
7653 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7654 if (fn.list == NULL)
7655 ash_msg_and_raise_error("redir error");
7656 fixredir(redir, fn.list->text, 1);
7664 * Evaluate a pipeline. All the processes in the pipeline are children
7665 * of the process creating the pipeline. (This differs from some versions
7666 * of the shell, which make the last process in a pipeline the parent
7670 evalpipe(union node *n, int flags)
7673 struct nodelist *lp;
7678 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7680 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7684 jp = makejob(n, pipelen);
7686 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7690 if (pipe(pip) < 0) {
7692 ash_msg_and_raise_error("pipe call failed");
7695 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7708 evaltreenr(lp->n, flags);
7716 if (n->npipe.backgnd == 0) {
7717 exitstatus = waitforjob(jp);
7718 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7724 * Controls whether the shell is interactive or not.
7727 setinteractive(int on)
7729 static int is_interactive;
7731 if (++on == is_interactive)
7733 is_interactive = on;
7737 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7738 if (is_interactive > 1) {
7739 /* Looks like they want an interactive shell */
7740 static smallint did_banner;
7745 "%s built-in shell (ash)\n"
7746 "Enter 'help' for a list of built-in commands."
7755 #if ENABLE_FEATURE_EDITING_VI
7756 #define setvimode(on) do { \
7757 if (on) line_input_state->flags |= VI_MODE; \
7758 else line_input_state->flags &= ~VI_MODE; \
7761 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7770 setinteractive(iflag);
7775 static struct localvar *localvars;
7778 * Called after a function returns.
7779 * Interrupts must be off.
7784 struct localvar *lvp;
7787 while ((lvp = localvars) != NULL) {
7788 localvars = lvp->next;
7790 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7791 if (vp == NULL) { /* $- saved */
7792 memcpy(optlist, lvp->text, sizeof(optlist));
7793 free((char*)lvp->text);
7795 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7799 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7800 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7801 free((char*)vp->text);
7802 vp->flags = lvp->flags;
7803 vp->text = lvp->text;
7810 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7812 volatile struct shparam saveparam;
7813 struct localvar *volatile savelocalvars;
7814 struct jmploc *volatile savehandler;
7815 struct jmploc jmploc;
7818 saveparam = shellparam;
7819 savelocalvars = localvars;
7820 e = setjmp(jmploc.loc);
7825 savehandler = exception_handler;
7826 exception_handler = &jmploc;
7828 shellparam.malloc = 0;
7832 shellparam.nparam = argc - 1;
7833 shellparam.p = argv + 1;
7834 #if ENABLE_ASH_GETOPTS
7835 shellparam.optind = 1;
7836 shellparam.optoff = -1;
7838 evaltree(&func->n, flags & EV_TESTED);
7844 localvars = savelocalvars;
7845 freeparam(&shellparam);
7846 shellparam = saveparam;
7847 exception_handler = savehandler;
7849 evalskip &= ~SKIPFUNC;
7853 #if ENABLE_ASH_CMDCMD
7855 parse_command_args(char **argv, const char **path)
7868 if (c == '-' && !*cp) {
7875 *path = bb_default_path;
7878 /* run 'typecmd' for other options */
7889 * Make a variable a local variable. When a variable is made local, it's
7890 * value and flags are saved in a localvar structure. The saved values
7891 * will be restored when the shell function returns. We handle the name
7892 * "-" as a special case.
7897 struct localvar *lvp;
7902 lvp = ckmalloc(sizeof(struct localvar));
7903 if (LONE_DASH(name)) {
7905 p = ckmalloc(sizeof(optlist));
7906 lvp->text = memcpy(p, optlist, sizeof(optlist));
7911 vpp = hashvar(name);
7912 vp = *findvar(vpp, name);
7913 eq = strchr(name, '=');
7916 setvareq(name, VSTRFIXED);
7918 setvar(name, NULL, VSTRFIXED);
7919 vp = *vpp; /* the new variable */
7920 lvp->flags = VUNSET;
7922 lvp->text = vp->text;
7923 lvp->flags = vp->flags;
7924 vp->flags |= VSTRFIXED|VTEXTFIXED;
7930 lvp->next = localvars;
7936 * The "local" command.
7939 localcmd(int argc, char **argv)
7944 while ((name = *argv++) != NULL) {
7951 falsecmd(int argc, char **argv)
7957 truecmd(int argc, char **argv)
7963 execcmd(int argc, char **argv)
7966 iflag = 0; /* exit on error */
7969 shellexec(argv + 1, pathval(), 0);
7975 * The return command.
7978 returncmd(int argc, char **argv)
7981 * If called outside a function, do what ksh does;
7982 * skip the rest of the file.
7984 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
7985 return argv[1] ? number(argv[1]) : exitstatus;
7988 /* Forward declarations for builtintab[] */
7989 static int breakcmd(int, char **);
7990 static int dotcmd(int, char **);
7991 static int evalcmd(int, char **);
7992 #if ENABLE_ASH_BUILTIN_ECHO
7993 static int echocmd(int, char **);
7995 #if ENABLE_ASH_BUILTIN_TEST
7996 static int testcmd(int, char **);
7998 static int exitcmd(int, char **);
7999 static int exportcmd(int, char **);
8000 #if ENABLE_ASH_GETOPTS
8001 static int getoptscmd(int, char **);
8003 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8004 static int helpcmd(int argc, char **argv);
8006 #if ENABLE_ASH_MATH_SUPPORT
8007 static int letcmd(int, char **);
8009 static int readcmd(int, char **);
8010 static int setcmd(int, char **);
8011 static int shiftcmd(int, char **);
8012 static int timescmd(int, char **);
8013 static int trapcmd(int, char **);
8014 static int umaskcmd(int, char **);
8015 static int unsetcmd(int, char **);
8016 static int ulimitcmd(int, char **);
8018 #define BUILTIN_NOSPEC "0"
8019 #define BUILTIN_SPECIAL "1"
8020 #define BUILTIN_REGULAR "2"
8021 #define BUILTIN_SPEC_REG "3"
8022 #define BUILTIN_ASSIGN "4"
8023 #define BUILTIN_SPEC_ASSG "5"
8024 #define BUILTIN_REG_ASSG "6"
8025 #define BUILTIN_SPEC_REG_ASSG "7"
8027 /* make sure to keep these in proper order since it is searched via bsearch() */
8028 static const struct builtincmd builtintab[] = {
8029 { BUILTIN_SPEC_REG ".", dotcmd },
8030 { BUILTIN_SPEC_REG ":", truecmd },
8031 #if ENABLE_ASH_BUILTIN_TEST
8032 { BUILTIN_REGULAR "[", testcmd },
8033 { BUILTIN_REGULAR "[[", testcmd },
8035 #if ENABLE_ASH_ALIAS
8036 { BUILTIN_REG_ASSG "alias", aliascmd },
8039 { BUILTIN_REGULAR "bg", fg_bgcmd },
8041 { BUILTIN_SPEC_REG "break", breakcmd },
8042 { BUILTIN_REGULAR "cd", cdcmd },
8043 { BUILTIN_NOSPEC "chdir", cdcmd },
8044 #if ENABLE_ASH_CMDCMD
8045 { BUILTIN_REGULAR "command", commandcmd },
8047 { BUILTIN_SPEC_REG "continue", breakcmd },
8048 #if ENABLE_ASH_BUILTIN_ECHO
8049 { BUILTIN_REGULAR "echo", echocmd },
8051 { BUILTIN_SPEC_REG "eval", evalcmd },
8052 { BUILTIN_SPEC_REG "exec", execcmd },
8053 { BUILTIN_SPEC_REG "exit", exitcmd },
8054 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8055 { BUILTIN_REGULAR "false", falsecmd },
8057 { BUILTIN_REGULAR "fg", fg_bgcmd },
8059 #if ENABLE_ASH_GETOPTS
8060 { BUILTIN_REGULAR "getopts", getoptscmd },
8062 { BUILTIN_NOSPEC "hash", hashcmd },
8063 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8064 { BUILTIN_NOSPEC "help", helpcmd },
8067 { BUILTIN_REGULAR "jobs", jobscmd },
8068 { BUILTIN_REGULAR "kill", killcmd },
8070 #if ENABLE_ASH_MATH_SUPPORT
8071 { BUILTIN_NOSPEC "let", letcmd },
8073 { BUILTIN_ASSIGN "local", localcmd },
8074 { BUILTIN_NOSPEC "pwd", pwdcmd },
8075 { BUILTIN_REGULAR "read", readcmd },
8076 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8077 { BUILTIN_SPEC_REG "return", returncmd },
8078 { BUILTIN_SPEC_REG "set", setcmd },
8079 { BUILTIN_SPEC_REG "shift", shiftcmd },
8080 { BUILTIN_SPEC_REG "source", dotcmd },
8081 #if ENABLE_ASH_BUILTIN_TEST
8082 { BUILTIN_REGULAR "test", testcmd },
8084 { BUILTIN_SPEC_REG "times", timescmd },
8085 { BUILTIN_SPEC_REG "trap", trapcmd },
8086 { BUILTIN_REGULAR "true", truecmd },
8087 { BUILTIN_NOSPEC "type", typecmd },
8088 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8089 { BUILTIN_REGULAR "umask", umaskcmd },
8090 #if ENABLE_ASH_ALIAS
8091 { BUILTIN_REGULAR "unalias", unaliascmd },
8093 { BUILTIN_SPEC_REG "unset", unsetcmd },
8094 { BUILTIN_REGULAR "wait", waitcmd },
8098 #define COMMANDCMD (builtintab + 5 + \
8099 2 * ENABLE_ASH_BUILTIN_TEST + \
8100 ENABLE_ASH_ALIAS + \
8101 ENABLE_ASH_JOB_CONTROL)
8102 #define EXECCMD (builtintab + 7 + \
8103 2 * ENABLE_ASH_BUILTIN_TEST + \
8104 ENABLE_ASH_ALIAS + \
8105 ENABLE_ASH_JOB_CONTROL + \
8106 ENABLE_ASH_CMDCMD + \
8107 ENABLE_ASH_BUILTIN_ECHO)
8110 * Search the table of builtin commands.
8112 static struct builtincmd *
8113 find_builtin(const char *name)
8115 struct builtincmd *bp;
8118 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8125 * Execute a simple command.
8127 static int back_exitstatus; /* exit status of backquoted command */
8129 isassignment(const char *p)
8131 const char *q = endofname(p);
8137 bltincmd(int argc, char **argv)
8139 /* Preserve exitstatus of a previous possible redirection
8140 * as POSIX mandates */
8141 return back_exitstatus;
8144 evalcommand(union node *cmd, int flags)
8146 static const struct builtincmd bltin = {
8149 struct stackmark smark;
8151 struct arglist arglist;
8152 struct arglist varlist;
8155 const struct strlist *sp;
8156 struct cmdentry cmdentry;
8164 struct builtincmd *bcmd;
8165 int pseudovarflag = 0;
8167 /* First expand the arguments. */
8168 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8169 setstackmark(&smark);
8170 back_exitstatus = 0;
8172 cmdentry.cmdtype = CMDBUILTIN;
8173 cmdentry.u.cmd = &bltin;
8174 varlist.lastp = &varlist.list;
8175 *varlist.lastp = NULL;
8176 arglist.lastp = &arglist.list;
8177 *arglist.lastp = NULL;
8180 if (cmd->ncmd.args) {
8181 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8182 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8185 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8186 struct strlist **spp;
8188 spp = arglist.lastp;
8189 if (pseudovarflag && isassignment(argp->narg.text))
8190 expandarg(argp, &arglist, EXP_VARTILDE);
8192 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8194 for (sp = *spp; sp; sp = sp->next)
8198 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8199 for (sp = arglist.list; sp; sp = sp->next) {
8200 TRACE(("evalcommand arg: %s\n", sp->text));
8201 *nargv++ = sp->text;
8206 if (iflag && funcnest == 0 && argc > 0)
8207 lastarg = nargv[-1];
8210 expredir(cmd->ncmd.redirect);
8211 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8214 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8215 struct strlist **spp;
8218 spp = varlist.lastp;
8219 expandarg(argp, &varlist, EXP_VARTILDE);
8222 * Modify the command lookup path, if a PATH= assignment
8226 if (varequal(p, path))
8230 /* Print the command if xflag is set. */
8233 const char *p = " %s";
8236 dprintf(preverrout_fd, p, expandstr(ps4val()));
8239 for (n = 0; n < 2; n++) {
8241 dprintf(preverrout_fd, p, sp->text);
8249 full_write(preverrout_fd, "\n", 1);
8255 /* Now locate the command. */
8257 const char *oldpath;
8258 int cmd_flag = DO_ERR;
8263 find_command(argv[0], &cmdentry, cmd_flag, path);
8264 if (cmdentry.cmdtype == CMDUNKNOWN) {
8270 /* implement bltin and command here */
8271 if (cmdentry.cmdtype != CMDBUILTIN)
8274 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8275 if (cmdentry.u.cmd == EXECCMD)
8277 #if ENABLE_ASH_CMDCMD
8278 if (cmdentry.u.cmd == COMMANDCMD) {
8280 nargv = parse_command_args(argv, &path);
8283 argc -= nargv - argv;
8285 cmd_flag |= DO_NOFUNC;
8293 /* We have a redirection error. */
8295 raise_exception(EXERROR);
8297 exitstatus = status;
8301 /* Execute the command. */
8302 switch (cmdentry.cmdtype) {
8304 /* Fork off a child process if necessary. */
8305 if (!(flags & EV_EXIT) || trap[0]) {
8307 jp = makejob(cmd, 1);
8308 if (forkshell(jp, cmd, FORK_FG) != 0) {
8309 exitstatus = waitforjob(jp);
8315 listsetvar(varlist.list, VEXPORT|VSTACK);
8316 shellexec(argv, path, cmdentry.u.index);
8320 cmdenviron = varlist.list;
8322 struct strlist *list = cmdenviron;
8324 if (spclbltin > 0 || argc == 0) {
8326 if (cmd_is_exec && argc > 1)
8329 listsetvar(list, i);
8331 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8346 exit_status = j + 128;
8347 exitstatus = exit_status;
8349 if (i == EXINT || spclbltin > 0) {
8351 longjmp(exception_handler->loc, 1);
8358 listsetvar(varlist.list, 0);
8359 if (evalfun(cmdentry.u.func, argc, argv, flags))
8365 popredir(cmd_is_exec);
8367 /* dsl: I think this is intended to be used to support
8368 * '_' in 'vi' command mode during line editing...
8369 * However I implemented that within libedit itself.
8371 setvar("_", lastarg, 0);
8372 popstackmark(&smark);
8376 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8378 char *volatile savecmdname;
8379 struct jmploc *volatile savehandler;
8380 struct jmploc jmploc;
8383 savecmdname = commandname;
8384 i = setjmp(jmploc.loc);
8387 savehandler = exception_handler;
8388 exception_handler = &jmploc;
8389 commandname = argv[0];
8391 optptr = NULL; /* initialize nextopt */
8392 exitstatus = (*cmd->builtin)(argc, argv);
8393 flush_stdout_stderr();
8395 exitstatus |= ferror(stdout);
8397 commandname = savecmdname;
8399 exception_handler = savehandler;
8405 goodname(const char *p)
8407 return !*endofname(p);
8412 * Search for a command. This is called before we fork so that the
8413 * location of the command will be available in the parent as well as
8414 * the child. The check for "goodname" is an overly conservative
8415 * check that the name will not be subject to expansion.
8418 prehash(union node *n)
8420 struct cmdentry entry;
8422 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8423 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8427 /* ============ Builtin commands
8429 * Builtin commands whose functions are closely tied to evaluation
8430 * are implemented here.
8434 * Handle break and continue commands. Break, continue, and return are
8435 * all handled by setting the evalskip flag. The evaluation routines
8436 * above all check this flag, and if it is set they start skipping
8437 * commands rather than executing them. The variable skipcount is
8438 * the number of loops to break/continue, or the number of function
8439 * levels to return. (The latter is always 1.) It should probably
8440 * be an error to break out of more loops than exist, but it isn't
8441 * in the standard shell so we don't make it one here.
8444 breakcmd(int argc, char **argv)
8446 int n = argc > 1 ? number(argv[1]) : 1;
8449 ash_msg_and_raise_error(illnum, argv[1]);
8453 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8460 /* ============ input.c
8462 * This implements the input routines used by the parser.
8465 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8468 INPUT_PUSH_FILE = 1,
8469 INPUT_NOFILE_OK = 2,
8473 * NEOF is returned by parsecmd when it encounters an end of file. It
8474 * must be distinct from NULL, so we use the address of a variable that
8475 * happens to be handy.
8477 static int plinno = 1; /* input line number */
8478 /* number of characters left in input buffer */
8479 static int parsenleft; /* copy of parsefile->nleft */
8480 static int parselleft; /* copy of parsefile->lleft */
8481 /* next character in input buffer */
8482 static char *parsenextc; /* copy of parsefile->nextc */
8484 static int checkkwd;
8485 /* values of checkkwd variable */
8486 #define CHKALIAS 0x1
8493 struct strpush *sp = parsefile->strpush;
8496 #if ENABLE_ASH_ALIAS
8498 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8499 checkkwd |= CHKALIAS;
8501 if (sp->string != sp->ap->val) {
8504 sp->ap->flag &= ~ALIASINUSE;
8505 if (sp->ap->flag & ALIASDEAD) {
8506 unalias(sp->ap->name);
8510 parsenextc = sp->prevstring;
8511 parsenleft = sp->prevnleft;
8512 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8513 parsefile->strpush = sp->prev;
8514 if (sp != &(parsefile->basestrpush))
8523 char *buf = parsefile->buf;
8527 #if ENABLE_FEATURE_EDITING
8528 if (!iflag || parsefile->fd)
8529 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8531 #if ENABLE_FEATURE_TAB_COMPLETION
8532 line_input_state->path_lookup = pathval();
8534 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8536 /* Ctrl+C pressed */
8545 if (nr < 0 && errno == 0) {
8546 /* Ctrl+D presend */
8551 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8555 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8556 int flags = fcntl(0, F_GETFL, 0);
8557 if (flags >= 0 && flags & O_NONBLOCK) {
8558 flags &=~ O_NONBLOCK;
8559 if (fcntl(0, F_SETFL, flags) >= 0) {
8560 out2str("sh: turning off NDELAY mode\n");
8570 * Refill the input buffer and return the next input character:
8572 * 1) If a string was pushed back on the input, pop it;
8573 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8574 * from a string so we can't refill the buffer, return EOF.
8575 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8576 * 4) Process input up to the next newline, deleting nul characters.
8585 while (parsefile->strpush) {
8586 #if ENABLE_ASH_ALIAS
8587 if (parsenleft == -1 && parsefile->strpush->ap &&
8588 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8593 if (--parsenleft >= 0)
8594 return signed_char2int(*parsenextc++);
8596 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8598 flush_stdout_stderr();
8605 parselleft = parsenleft = EOF_NLEFT;
8612 /* delete nul characters */
8620 memmove(q, q + 1, more);
8624 parsenleft = q - parsenextc - 1;
8630 parsenleft = q - parsenextc - 1;
8642 out2str(parsenextc);
8647 return signed_char2int(*parsenextc++);
8650 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8654 return pgetc_as_macro();
8657 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8658 #define pgetc_macro() pgetc()
8660 #define pgetc_macro() pgetc_as_macro()
8664 * Same as pgetc(), but ignores PEOA.
8666 #if ENABLE_ASH_ALIAS
8674 } while (c == PEOA);
8681 return pgetc_macro();
8686 * Read a line from the script.
8689 pfgets(char *line, int len)
8695 while (--nleft > 0) {
8711 * Undo the last call to pgetc. Only one character may be pushed back.
8712 * PEOF may be pushed back.
8722 * Push a string back onto the input at this current parsefile level.
8723 * We handle aliases this way.
8726 pushstring(char *s, void *ap)
8733 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8734 if (parsefile->strpush) {
8735 sp = ckmalloc(sizeof(struct strpush));
8736 sp->prev = parsefile->strpush;
8737 parsefile->strpush = sp;
8739 sp = parsefile->strpush = &(parsefile->basestrpush);
8740 sp->prevstring = parsenextc;
8741 sp->prevnleft = parsenleft;
8742 #if ENABLE_ASH_ALIAS
8743 sp->ap = (struct alias *)ap;
8745 ((struct alias *)ap)->flag |= ALIASINUSE;
8755 * To handle the "." command, a stack of input files is used. Pushfile
8756 * adds a new entry to the stack and popfile restores the previous level.
8761 struct parsefile *pf;
8763 parsefile->nleft = parsenleft;
8764 parsefile->lleft = parselleft;
8765 parsefile->nextc = parsenextc;
8766 parsefile->linno = plinno;
8767 pf = ckmalloc(sizeof(*pf));
8768 pf->prev = parsefile;
8771 pf->basestrpush.prev = NULL;
8778 struct parsefile *pf = parsefile;
8787 parsefile = pf->prev;
8789 parsenleft = parsefile->nleft;
8790 parselleft = parsefile->lleft;
8791 parsenextc = parsefile->nextc;
8792 plinno = parsefile->linno;
8797 * Return to top level.
8802 while (parsefile != &basepf)
8807 * Close the file(s) that the shell is reading commands from. Called
8808 * after a fork is done.
8814 if (parsefile->fd > 0) {
8815 close(parsefile->fd);
8821 * Like setinputfile, but takes an open file descriptor. Call this with
8825 setinputfd(int fd, int push)
8827 fcntl(fd, F_SETFD, FD_CLOEXEC);
8833 if (parsefile->buf == NULL)
8834 parsefile->buf = ckmalloc(IBUFSIZ);
8835 parselleft = parsenleft = 0;
8840 * Set the input to take input from a file. If push is set, push the
8841 * old input onto the stack first.
8844 setinputfile(const char *fname, int flags)
8850 fd = open(fname, O_RDONLY);
8852 if (flags & INPUT_NOFILE_OK)
8854 ash_msg_and_raise_error("can't open %s", fname);
8857 fd2 = copyfd(fd, 10);
8860 ash_msg_and_raise_error("out of file descriptors");
8863 setinputfd(fd, flags & INPUT_PUSH_FILE);
8870 * Like setinputfile, but takes input from a string.
8873 setinputstring(char *string)
8877 parsenextc = string;
8878 parsenleft = strlen(string);
8879 parsefile->buf = NULL;
8885 /* ============ mail.c
8887 * Routines to check for mail.
8892 #define MAXMBOXES 10
8894 /* times of mailboxes */
8895 static time_t mailtime[MAXMBOXES];
8896 /* Set if MAIL or MAILPATH is changed. */
8897 static int mail_var_path_changed;
8900 * Print appropriate message(s) if mail has arrived.
8901 * If mail_var_path_changed is set,
8902 * then the value of MAIL has mail_var_path_changed,
8903 * so we just update the values.
8912 struct stackmark smark;
8915 setstackmark(&smark);
8916 mpath = mpathset() ? mpathval() : mailval();
8917 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8918 p = padvance(&mpath, nullstr);
8923 for (q = p; *q; q++);
8928 q[-1] = '\0'; /* delete trailing '/' */
8929 if (stat(p, &statb) < 0) {
8933 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
8936 pathopt ? pathopt : "you have mail"
8939 *mtp = statb.st_mtime;
8941 mail_var_path_changed = 0;
8942 popstackmark(&smark);
8946 changemail(const char *val)
8948 mail_var_path_changed++;
8951 #endif /* ASH_MAIL */
8954 /* ============ ??? */
8957 * Set the shell parameters.
8960 setparam(char **argv)
8966 for (nparam = 0; argv[nparam]; nparam++);
8967 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
8969 *ap++ = ckstrdup(*argv++);
8972 freeparam(&shellparam);
8973 shellparam.malloc = 1;
8974 shellparam.nparam = nparam;
8975 shellparam.p = newparam;
8976 #if ENABLE_ASH_GETOPTS
8977 shellparam.optind = 1;
8978 shellparam.optoff = -1;
8983 * Process shell options. The global variable argptr contains a pointer
8984 * to the argument list; we advance it past the options.
8987 minus_o(char *name, int val)
8992 for (i = 0; i < NOPTS; i++) {
8993 if (strcmp(name, optnames(i)) == 0) {
8998 ash_msg_and_raise_error("illegal option -o %s", name);
9000 out1str("Current option settings\n");
9001 for (i = 0; i < NOPTS; i++)
9002 out1fmt("%-16s%s\n", optnames(i),
9003 optlist[i] ? "on" : "off");
9006 setoption(int flag, int val)
9010 for (i = 0; i < NOPTS; i++) {
9011 if (optletters(i) == flag) {
9016 ash_msg_and_raise_error("illegal option -%c", flag);
9020 options(int cmdline)
9028 while ((p = *argptr) != NULL) {
9033 if (p[0] == '\0' || LONE_DASH(p)) {
9035 /* "-" means turn off -x and -v */
9038 /* "--" means reset params */
9039 else if (*argptr == NULL)
9042 break; /* "-" or "--" terminates options */
9044 } else if (c == '+') {
9050 while ((c = *p++) != '\0') {
9051 if (c == 'c' && cmdline) {
9052 minusc = p; /* command is after shell args*/
9053 } else if (c == 'o') {
9054 minus_o(*argptr, val);
9057 } else if (cmdline && (c == '-')) { // long options
9058 if (strcmp(p, "login") == 0)
9069 * The shift builtin command.
9072 shiftcmd(int argc, char **argv)
9079 n = number(argv[1]);
9080 if (n > shellparam.nparam)
9081 ash_msg_and_raise_error("can't shift that many");
9083 shellparam.nparam -= n;
9084 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9085 if (shellparam.malloc)
9089 while ((*ap2++ = *ap1++) != NULL);
9090 #if ENABLE_ASH_GETOPTS
9091 shellparam.optind = 1;
9092 shellparam.optoff = -1;
9099 * POSIX requires that 'set' (but not export or readonly) output the
9100 * variables in lexicographic order - by the locale's collating order (sigh).
9101 * Maybe we could keep them in an ordered balanced binary tree
9102 * instead of hashed lists.
9103 * For now just roll 'em through qsort for printing...
9106 showvars(const char *sep_prefix, int on, int off)
9111 ep = listvars(on, off, &epend);
9112 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9114 sep = *sep_prefix ? " " : sep_prefix;
9116 for (; ep < epend; ep++) {
9120 p = strchrnul(*ep, '=');
9123 q = single_quote(++p);
9124 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9130 * The set command builtin.
9133 setcmd(int argc, char **argv)
9136 return showvars(nullstr, 0, VUNSET);
9140 if (*argptr != NULL) {
9147 #if ENABLE_ASH_RANDOM_SUPPORT
9148 /* Roughly copied from bash.. */
9150 change_random(const char *value)
9152 if (value == NULL) {
9153 /* "get", generate */
9156 rseed = rseed * 1103515245 + 12345;
9157 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9158 /* set without recursion */
9159 setvar(vrandom.text, buf, VNOFUNC);
9160 vrandom.flags &= ~VNOFUNC;
9163 rseed = strtoul(value, (char **)NULL, 10);
9168 #if ENABLE_ASH_GETOPTS
9170 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9179 if (*param_optind < 1)
9181 optnext = optfirst + *param_optind - 1;
9183 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9186 p = optnext[-1] + *optoff;
9187 if (p == NULL || *p == '\0') {
9188 /* Current word is done, advance */
9190 if (p == NULL || *p != '-' || *++p == '\0') {
9197 if (LONE_DASH(p)) /* check for "--" */
9202 for (q = optstr; *q != c; ) {
9204 if (optstr[0] == ':') {
9207 err |= setvarsafe("OPTARG", s, 0);
9209 fprintf(stderr, "Illegal option -%c\n", c);
9220 if (*p == '\0' && (p = *optnext) == NULL) {
9221 if (optstr[0] == ':') {
9224 err |= setvarsafe("OPTARG", s, 0);
9227 fprintf(stderr, "No arg for -%c option\n", c);
9236 err |= setvarsafe("OPTARG", p, 0);
9239 err |= setvarsafe("OPTARG", nullstr, 0);
9241 *optoff = p ? p - *(optnext - 1) : -1;
9242 *param_optind = optnext - optfirst + 1;
9243 fmtstr(s, sizeof(s), "%d", *param_optind);
9244 err |= setvarsafe("OPTIND", s, VNOFUNC);
9247 err |= setvarsafe(optvar, s, 0);
9251 flush_stdout_stderr();
9252 raise_exception(EXERROR);
9258 * The getopts builtin. Shellparam.optnext points to the next argument
9259 * to be processed. Shellparam.optptr points to the next character to
9260 * be processed in the current argument. If shellparam.optnext is NULL,
9261 * then it's the first time getopts has been called.
9264 getoptscmd(int argc, char **argv)
9269 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9271 optbase = shellparam.p;
9272 if (shellparam.optind > shellparam.nparam + 1) {
9273 shellparam.optind = 1;
9274 shellparam.optoff = -1;
9278 if (shellparam.optind > argc - 2) {
9279 shellparam.optind = 1;
9280 shellparam.optoff = -1;
9284 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9285 &shellparam.optoff);
9287 #endif /* ASH_GETOPTS */
9290 /* ============ Shell parser */
9292 static int tokpushback; /* last token pushed back */
9293 #define NEOF ((union node *)&tokpushback)
9294 static int parsebackquote; /* nonzero if we are inside backquotes */
9295 static int lasttoken; /* last token read */
9296 static char *wordtext; /* text of last word returned by readtoken */
9297 static struct nodelist *backquotelist;
9298 static union node *redirnode;
9299 static struct heredoc *heredoc;
9300 static int quoteflag; /* set if (part of) last token was quoted */
9302 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9304 raise_error_syntax(const char *msg)
9306 ash_msg_and_raise_error("syntax error: %s", msg);
9311 * Called when an unexpected token is read during the parse. The argument
9312 * is the token that is expected, or -1 if more than one type of token can
9313 * occur at this point.
9315 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9317 raise_error_unexpected_syntax(int token)
9322 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9324 sprintf(msg + l, " (expecting %s)", tokname(token));
9325 raise_error_syntax(msg);
9329 #define EOFMARKLEN 79
9332 struct heredoc *next; /* next here document in list */
9333 union node *here; /* redirection node */
9334 char *eofmark; /* string indicating end of input */
9335 int striptabs; /* if set, strip leading tabs */
9338 static struct heredoc *heredoclist; /* list of here documents to read */
9340 /* parsing is heavily cross-recursive, need these forward decls */
9341 static union node *andor(void);
9342 static union node *pipeline(void);
9343 static union node *parse_command(void);
9344 static void parseheredoc(void);
9345 static char peektoken(void);
9346 static int readtoken(void);
9351 union node *n1, *n2, *n3;
9354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9355 if (nlflag == 2 && peektoken())
9361 if (tok == TBACKGND) {
9362 if (n2->type == NPIPE) {
9363 n2->npipe.backgnd = 1;
9365 if (n2->type != NREDIR) {
9366 n3 = stalloc(sizeof(struct nredir));
9368 n3->nredir.redirect = NULL;
9371 n2->type = NBACKGND;
9377 n3 = stalloc(sizeof(struct nbinary));
9379 n3->nbinary.ch1 = n1;
9380 n3->nbinary.ch2 = n2;
9396 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9404 pungetc(); /* push back EOF on input */
9408 raise_error_unexpected_syntax(-1);
9418 union node *n1, *n2, *n3;
9426 } else if (t == TOR) {
9432 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9434 n3 = stalloc(sizeof(struct nbinary));
9436 n3->nbinary.ch1 = n1;
9437 n3->nbinary.ch2 = n2;
9445 union node *n1, *n2, *pipenode;
9446 struct nodelist *lp, *prev;
9450 TRACE(("pipeline: entered\n"));
9451 if (readtoken() == TNOT) {
9453 checkkwd = CHKKWD | CHKALIAS;
9456 n1 = parse_command();
9457 if (readtoken() == TPIPE) {
9458 pipenode = stalloc(sizeof(struct npipe));
9459 pipenode->type = NPIPE;
9460 pipenode->npipe.backgnd = 0;
9461 lp = stalloc(sizeof(struct nodelist));
9462 pipenode->npipe.cmdlist = lp;
9466 lp = stalloc(sizeof(struct nodelist));
9467 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9468 lp->n = parse_command();
9470 } while (readtoken() == TPIPE);
9476 n2 = stalloc(sizeof(struct nnot));
9489 n = stalloc(sizeof(struct narg));
9491 n->narg.next = NULL;
9492 n->narg.text = wordtext;
9493 n->narg.backquote = backquotelist;
9498 fixredir(union node *n, const char *text, int err)
9500 TRACE(("Fix redir %s %d\n", text, err));
9502 n->ndup.vname = NULL;
9504 if (isdigit(text[0]) && text[1] == '\0')
9505 n->ndup.dupfd = text[0] - '0';
9506 else if (LONE_DASH(text))
9510 raise_error_syntax("Bad fd number");
9511 n->ndup.vname = makename();
9516 * Returns true if the text contains nothing to expand (no dollar signs
9520 noexpand(char *text)
9526 while ((c = *p++) != '\0') {
9527 if (c == CTLQUOTEMARK)
9531 else if (SIT(c, BASESYNTAX) == CCTL)
9540 union node *n = redirnode;
9542 if (readtoken() != TWORD)
9543 raise_error_unexpected_syntax(-1);
9544 if (n->type == NHERE) {
9545 struct heredoc *here = heredoc;
9551 TRACE(("Here document %d\n", n->type));
9552 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9553 raise_error_syntax("Illegal eof marker for << redirection");
9554 rmescapes(wordtext);
9555 here->eofmark = wordtext;
9557 if (heredoclist == NULL)
9560 for (p = heredoclist; p->next; p = p->next);
9563 } else if (n->type == NTOFD || n->type == NFROMFD) {
9564 fixredir(n, wordtext, 0);
9566 n->nfile.fname = makename();
9573 union node *args, **app;
9574 union node *n = NULL;
9575 union node *vars, **vpp;
9576 union node **rpp, *redir;
9586 savecheckkwd = CHKALIAS;
9588 checkkwd = savecheckkwd;
9589 switch (readtoken()) {
9591 n = stalloc(sizeof(struct narg));
9593 n->narg.text = wordtext;
9594 n->narg.backquote = backquotelist;
9595 if (savecheckkwd && isassignment(wordtext)) {
9597 vpp = &n->narg.next;
9600 app = &n->narg.next;
9605 *rpp = n = redirnode;
9606 rpp = &n->nfile.next;
9607 parsefname(); /* read name of redirection file */
9610 if (args && app == &args->narg.next
9613 struct builtincmd *bcmd;
9616 /* We have a function */
9617 if (readtoken() != TRP)
9618 raise_error_unexpected_syntax(TRP);
9619 name = n->narg.text;
9621 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9623 raise_error_syntax("Bad function name");
9626 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9627 n->narg.next = parse_command();
9640 n = stalloc(sizeof(struct ncmd));
9642 n->ncmd.args = args;
9643 n->ncmd.assign = vars;
9644 n->ncmd.redirect = redir;
9651 union node *n1, *n2;
9652 union node *ap, **app;
9653 union node *cp, **cpp;
9654 union node *redir, **rpp;
9661 switch (readtoken()) {
9663 raise_error_unexpected_syntax(-1);
9666 n1 = stalloc(sizeof(struct nif));
9668 n1->nif.test = list(0);
9669 if (readtoken() != TTHEN)
9670 raise_error_unexpected_syntax(TTHEN);
9671 n1->nif.ifpart = list(0);
9673 while (readtoken() == TELIF) {
9674 n2->nif.elsepart = stalloc(sizeof(struct nif));
9675 n2 = n2->nif.elsepart;
9677 n2->nif.test = list(0);
9678 if (readtoken() != TTHEN)
9679 raise_error_unexpected_syntax(TTHEN);
9680 n2->nif.ifpart = list(0);
9682 if (lasttoken == TELSE)
9683 n2->nif.elsepart = list(0);
9685 n2->nif.elsepart = NULL;
9693 n1 = stalloc(sizeof(struct nbinary));
9694 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9695 n1->nbinary.ch1 = list(0);
9698 TRACE(("expecting DO got %s %s\n", tokname(got),
9699 got == TWORD ? wordtext : ""));
9700 raise_error_unexpected_syntax(TDO);
9702 n1->nbinary.ch2 = list(0);
9707 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9708 raise_error_syntax("Bad for loop variable");
9709 n1 = stalloc(sizeof(struct nfor));
9711 n1->nfor.var = wordtext;
9712 checkkwd = CHKKWD | CHKALIAS;
9713 if (readtoken() == TIN) {
9715 while (readtoken() == TWORD) {
9716 n2 = stalloc(sizeof(struct narg));
9718 n2->narg.text = wordtext;
9719 n2->narg.backquote = backquotelist;
9721 app = &n2->narg.next;
9725 if (lasttoken != TNL && lasttoken != TSEMI)
9726 raise_error_unexpected_syntax(-1);
9728 n2 = stalloc(sizeof(struct narg));
9730 n2->narg.text = (char *)dolatstr;
9731 n2->narg.backquote = NULL;
9732 n2->narg.next = NULL;
9735 * Newline or semicolon here is optional (but note
9736 * that the original Bourne shell only allowed NL).
9738 if (lasttoken != TNL && lasttoken != TSEMI)
9741 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9742 if (readtoken() != TDO)
9743 raise_error_unexpected_syntax(TDO);
9744 n1->nfor.body = list(0);
9748 n1 = stalloc(sizeof(struct ncase));
9750 if (readtoken() != TWORD)
9751 raise_error_unexpected_syntax(TWORD);
9752 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9754 n2->narg.text = wordtext;
9755 n2->narg.backquote = backquotelist;
9756 n2->narg.next = NULL;
9758 checkkwd = CHKKWD | CHKALIAS;
9759 } while (readtoken() == TNL);
9760 if (lasttoken != TIN)
9761 raise_error_unexpected_syntax(TIN);
9762 cpp = &n1->ncase.cases;
9764 checkkwd = CHKNL | CHKKWD;
9766 while (t != TESAC) {
9767 if (lasttoken == TLP)
9769 *cpp = cp = stalloc(sizeof(struct nclist));
9771 app = &cp->nclist.pattern;
9773 *app = ap = stalloc(sizeof(struct narg));
9775 ap->narg.text = wordtext;
9776 ap->narg.backquote = backquotelist;
9777 if (readtoken() != TPIPE)
9779 app = &ap->narg.next;
9782 ap->narg.next = NULL;
9783 if (lasttoken != TRP)
9784 raise_error_unexpected_syntax(TRP);
9785 cp->nclist.body = list(2);
9787 cpp = &cp->nclist.next;
9789 checkkwd = CHKNL | CHKKWD;
9793 raise_error_unexpected_syntax(TENDCASE);
9800 n1 = stalloc(sizeof(struct nredir));
9801 n1->type = NSUBSHELL;
9802 n1->nredir.n = list(0);
9803 n1->nredir.redirect = NULL;
9816 if (readtoken() != t)
9817 raise_error_unexpected_syntax(t);
9820 /* Now check for redirection which may follow command */
9821 checkkwd = CHKKWD | CHKALIAS;
9823 while (readtoken() == TREDIR) {
9824 *rpp = n2 = redirnode;
9825 rpp = &n2->nfile.next;
9831 if (n1->type != NSUBSHELL) {
9832 n2 = stalloc(sizeof(struct nredir));
9837 n1->nredir.redirect = redir;
9843 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9844 * is not NULL, read a here document. In the latter case, eofmark is the
9845 * word which marks the end of the document and striptabs is true if
9846 * leading tabs should be stripped from the document. The argument firstc
9847 * is the first character of the input token or document.
9849 * Because C does not have internal subroutines, I have simulated them
9850 * using goto's to implement the subroutine linkage. The following macros
9851 * will run code that appears at the end of readtoken1.
9854 static int parsebackquote; /* nonzero if we are inside backquotes */
9856 #define CHECKEND() {goto checkend; checkend_return:;}
9857 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9858 #define PARSESUB() {goto parsesub; parsesub_return:;}
9859 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9860 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9861 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9864 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9869 char line[EOFMARKLEN + 1];
9870 struct nodelist *bqlist = 0;
9873 int varnest = 0; /* levels of variables expansion */
9874 int arinest = 0; /* levels of arithmetic expansion */
9875 int parenlevel = 0; /* levels of parens in arithmetic */
9876 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9878 int prevsyntax = 0; /* syntax before arithmetic */
9880 /* Avoid longjmp clobbering */
9893 startlinno = plinno;
9895 if (syntax == DQSYNTAX)
9905 loop: { /* for each line, until end of word */
9906 CHECKEND(); /* set c to PEOF if at end of here document */
9907 for (;;) { /* until end of line or end of word */
9908 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9909 switch (SIT(c, syntax)) {
9910 case CNL: /* '\n' */
9911 if (syntax == BASESYNTAX)
9912 goto endword; /* exit outer loop */
9918 goto loop; /* continue outer loop */
9923 if (eofmark == NULL || dblquote)
9924 USTPUTC(CTLESC, out);
9927 case CBACK: /* backslash */
9930 USTPUTC(CTLESC, out);
9933 } else if (c == '\n') {
9938 c != '\\' && c != '`' &&
9943 USTPUTC(CTLESC, out);
9946 if (SIT(c, SQSYNTAX) == CCTL)
9947 USTPUTC(CTLESC, out);
9955 if (eofmark == NULL) {
9956 USTPUTC(CTLQUOTEMARK, out);
9964 if (eofmark != NULL && arinest == 0
9969 if (dqvarnest == 0) {
9970 syntax = BASESYNTAX;
9977 case CVAR: /* '$' */
9978 PARSESUB(); /* parse substitution */
9980 case CENDVAR: /* '}' */
9983 if (dqvarnest > 0) {
9986 USTPUTC(CTLENDVAR, out);
9991 #if ENABLE_ASH_MATH_SUPPORT
9992 case CLP: /* '(' in arithmetic */
9996 case CRP: /* ')' in arithmetic */
9997 if (parenlevel > 0) {
10001 if (pgetc() == ')') {
10002 if (--arinest == 0) {
10003 USTPUTC(CTLENDARI, out);
10004 syntax = prevsyntax;
10005 if (syntax == DQSYNTAX)
10013 * unbalanced parens
10014 * (don't 2nd guess - no error)
10022 case CBQUOTE: /* '`' */
10026 goto endword; /* exit outer loop */
10031 goto endword; /* exit outer loop */
10032 #if ENABLE_ASH_ALIAS
10042 #if ENABLE_ASH_MATH_SUPPORT
10043 if (syntax == ARISYNTAX)
10044 raise_error_syntax("Missing '))'");
10046 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10047 raise_error_syntax("Unterminated quoted string");
10048 if (varnest != 0) {
10049 startlinno = plinno;
10051 raise_error_syntax("Missing '}'");
10053 USTPUTC('\0', out);
10054 len = out - (char *)stackblock();
10055 out = stackblock();
10056 if (eofmark == NULL) {
10057 if ((c == '>' || c == '<')
10060 && (*out == '\0' || isdigit(*out))) {
10062 return lasttoken = TREDIR;
10067 quoteflag = quotef;
10068 backquotelist = bqlist;
10069 grabstackblock(len);
10073 /* end of readtoken routine */
10076 * Check to see whether we are at the end of the here document. When this
10077 * is called, c is set to the first character of the next input line. If
10078 * we are at the end of the here document, this routine sets the c to PEOF.
10082 #if ENABLE_ASH_ALIAS
10088 while (c == '\t') {
10092 if (c == *eofmark) {
10093 if (pfgets(line, sizeof(line)) != NULL) {
10097 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10098 if (*p == '\n' && *q == '\0') {
10101 needprompt = doprompt;
10103 pushstring(line, NULL);
10108 goto checkend_return;
10112 * Parse a redirection operator. The variable "out" points to a string
10113 * specifying the fd to be redirected. The variable "c" contains the
10114 * first character of the redirection operator.
10120 np = stalloc(sizeof(struct nfile));
10125 np->type = NAPPEND;
10127 np->type = NCLOBBER;
10134 } else { /* c == '<' */
10139 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10140 np = stalloc(sizeof(struct nhere));
10144 heredoc = stalloc(sizeof(struct heredoc));
10145 heredoc->here = np;
10148 heredoc->striptabs = 1;
10150 heredoc->striptabs = 0;
10156 np->type = NFROMFD;
10160 np->type = NFROMTO;
10170 np->nfile.fd = fd - '0';
10172 goto parseredir_return;
10176 * Parse a substitution. At this point, we have read the dollar sign
10177 * and nothing else.
10180 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10181 * (assuming ascii char codes, as the original implementation did) */
10182 #define is_special(c) \
10183 ((((unsigned int)c) - 33 < 32) \
10184 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10190 static const char types[] = "}-+?=";
10194 c <= PEOA_OR_PEOF ||
10195 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10199 } else if (c == '(') { /* $(command) or $((arith)) */
10200 if (pgetc() == '(') {
10201 #if ENABLE_ASH_MATH_SUPPORT
10204 raise_error_syntax("We unsupport $((arith))");
10211 USTPUTC(CTLVAR, out);
10212 typeloc = out - (char *)stackblock();
10213 USTPUTC(VSNORMAL, out);
10214 subtype = VSNORMAL;
10222 subtype = VSLENGTH;
10226 if (c > PEOA_OR_PEOF && is_name(c)) {
10230 } while (c > PEOA_OR_PEOF && is_in_name(c));
10231 } else if (isdigit(c)) {
10235 } while (isdigit(c));
10236 } else if (is_special(c)) {
10240 badsub: raise_error_syntax("Bad substitution");
10244 if (subtype == 0) {
10251 p = strchr(types, c);
10254 subtype = p - types + VSNORMAL;
10260 subtype = c == '#' ? VSTRIMLEFT :
10273 if (dblquote || arinest)
10275 *((char *)stackblock() + typeloc) = subtype | flags;
10276 if (subtype != VSNORMAL) {
10278 if (dblquote || arinest) {
10283 goto parsesub_return;
10287 * Called to parse command substitutions. Newstyle is set if the command
10288 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10289 * list of commands (passed by reference), and savelen is the number of
10290 * characters on the top of the stack which must be preserved.
10293 struct nodelist **nlpp;
10296 char *volatile str;
10297 struct jmploc jmploc;
10298 struct jmploc *volatile savehandler;
10300 int saveprompt = 0;
10302 (void) &saveprompt;
10305 savepbq = parsebackquote;
10306 if (setjmp(jmploc.loc)) {
10309 parsebackquote = 0;
10310 exception_handler = savehandler;
10311 longjmp(exception_handler->loc, 1);
10315 savelen = out - (char *)stackblock();
10317 str = ckmalloc(savelen);
10318 memcpy(str, stackblock(), savelen);
10320 savehandler = exception_handler;
10321 exception_handler = &jmploc;
10324 /* We must read until the closing backquote, giving special
10325 treatment to some slashes, and then push the string and
10326 reread it as input, interpreting it normally. */
10333 STARTSTACKSTR(pout);
10350 * If eating a newline, avoid putting
10351 * the newline into the new character
10352 * stream (via the STPUTC after the
10357 if (pc != '\\' && pc != '`' && pc != '$'
10358 && (!dblquote || pc != '"'))
10359 STPUTC('\\', pout);
10360 if (pc > PEOA_OR_PEOF) {
10366 #if ENABLE_ASH_ALIAS
10369 startlinno = plinno;
10370 raise_error_syntax("EOF in backquote substitution");
10374 needprompt = doprompt;
10383 STPUTC('\0', pout);
10384 psavelen = pout - (char *)stackblock();
10385 if (psavelen > 0) {
10386 pstr = grabstackstr(pout);
10387 setinputstring(pstr);
10392 nlpp = &(*nlpp)->next;
10393 *nlpp = stalloc(sizeof(**nlpp));
10394 (*nlpp)->next = NULL;
10395 parsebackquote = oldstyle;
10398 saveprompt = doprompt;
10405 doprompt = saveprompt;
10406 else if (readtoken() != TRP)
10407 raise_error_unexpected_syntax(TRP);
10412 * Start reading from old file again, ignoring any pushed back
10413 * tokens left from the backquote parsing
10418 while (stackblocksize() <= savelen)
10420 STARTSTACKSTR(out);
10422 memcpy(out, str, savelen);
10423 STADJUST(savelen, out);
10429 parsebackquote = savepbq;
10430 exception_handler = savehandler;
10431 if (arinest || dblquote)
10432 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10434 USTPUTC(CTLBACKQ, out);
10436 goto parsebackq_oldreturn;
10437 goto parsebackq_newreturn;
10440 #if ENABLE_ASH_MATH_SUPPORT
10442 * Parse an arithmetic expansion (indicate start of one and set state)
10445 if (++arinest == 1) {
10446 prevsyntax = syntax;
10447 syntax = ARISYNTAX;
10448 USTPUTC(CTLARI, out);
10455 * we collapse embedded arithmetic expansion to
10456 * parenthesis, which should be equivalent
10460 goto parsearith_return;
10464 } /* end of readtoken */
10467 * Read the next input token.
10468 * If the token is a word, we set backquotelist to the list of cmds in
10469 * backquotes. We set quoteflag to true if any part of the word was
10471 * If the token is TREDIR, then we set redirnode to a structure containing
10473 * In all cases, the variable startlinno is set to the number of the line
10474 * on which the token starts.
10476 * [Change comment: here documents and internal procedures]
10477 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10478 * word parsing code into a separate routine. In this case, readtoken
10479 * doesn't need to have any internal procedures, but parseword does.
10480 * We could also make parseoperator in essence the main routine, and
10481 * have parseword (readtoken1?) handle both words and redirection.]
10483 #define NEW_xxreadtoken
10484 #ifdef NEW_xxreadtoken
10485 /* singles must be first! */
10486 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10488 static const char xxreadtoken_tokens[] = {
10489 TNL, TLP, TRP, /* only single occurrence allowed */
10490 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10491 TEOF, /* corresponds to trailing nul */
10492 TAND, TOR, TENDCASE, /* if double occurrence */
10495 #define xxreadtoken_doubles \
10496 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10497 #define xxreadtoken_singles \
10498 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10512 startlinno = plinno;
10513 for (;;) { /* until token or start of word found */
10516 if ((c != ' ') && (c != '\t')
10517 #if ENABLE_ASH_ALIAS
10522 while ((c = pgetc()) != '\n' && c != PEOF);
10524 } else if (c == '\\') {
10525 if (pgetc() != '\n') {
10529 startlinno = ++plinno;
10534 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10539 needprompt = doprompt;
10542 p = strchr(xxreadtoken_chars, c);
10545 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10548 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10549 if (pgetc() == *p) { /* double occurrence? */
10550 p += xxreadtoken_doubles + 1;
10556 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10562 #define RETURN(token) return lasttoken = token
10575 startlinno = plinno;
10576 for (;;) { /* until token or start of word found */
10579 case ' ': case '\t':
10580 #if ENABLE_ASH_ALIAS
10585 while ((c = pgetc()) != '\n' && c != PEOF);
10589 if (pgetc() == '\n') {
10590 startlinno = ++plinno;
10599 needprompt = doprompt;
10604 if (pgetc() == '&')
10609 if (pgetc() == '|')
10614 if (pgetc() == ';')
10627 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10630 #endif /* NEW_xxreadtoken */
10637 int alreadyseen = tokpushback;
10640 #if ENABLE_ASH_ALIAS
10649 if (checkkwd & CHKNL) {
10656 if (t != TWORD || quoteflag) {
10661 * check for keywords
10663 if (checkkwd & CHKKWD) {
10664 const char *const *pp;
10666 pp = findkwd(wordtext);
10668 lasttoken = t = pp - tokname_array;
10669 TRACE(("keyword %s recognized\n", tokname(t)));
10674 if (checkkwd & CHKALIAS) {
10675 #if ENABLE_ASH_ALIAS
10677 ap = lookupalias(wordtext, 1);
10680 pushstring(ap->val, ap);
10690 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10692 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10704 return tokname_array[t][0];
10708 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10709 * valid parse tree indicating a blank line.)
10711 static union node *
10712 parsecmd(int interact)
10717 doprompt = interact;
10719 setprompt(doprompt);
10731 * Input any here documents.
10736 struct heredoc *here;
10739 here = heredoclist;
10746 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10747 here->eofmark, here->striptabs);
10748 n = stalloc(sizeof(struct narg));
10749 n->narg.type = NARG;
10750 n->narg.next = NULL;
10751 n->narg.text = wordtext;
10752 n->narg.backquote = backquotelist;
10753 here->here->nhere.doc = n;
10760 * called by editline -- any expansions to the prompt should be added here.
10762 #if ENABLE_ASH_EXPAND_PRMT
10763 static const char *
10764 expandstr(const char *ps)
10768 /* XXX Fix (char *) cast. */
10769 setinputstring((char *)ps);
10770 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10773 n.narg.type = NARG;
10774 n.narg.next = NULL;
10775 n.narg.text = wordtext;
10776 n.narg.backquote = backquotelist;
10778 expandarg(&n, NULL, 0);
10779 return stackblock();
10784 * Execute a command or commands contained in a string.
10787 evalstring(char *s, int mask)
10790 struct stackmark smark;
10794 setstackmark(&smark);
10797 while ((n = parsecmd(0)) != NEOF) {
10799 popstackmark(&smark);
10812 * The eval command.
10815 evalcmd(int argc, char **argv)
10824 STARTSTACKSTR(concat);
10827 concat = stack_putstr(p, concat);
10831 STPUTC(' ', concat);
10833 STPUTC('\0', concat);
10834 p = grabstackstr(concat);
10836 evalstring(p, ~SKIPEVAL);
10843 * Read and execute commands. "Top" is nonzero for the top level command
10844 * loop; it turns on prompting if the shell is interactive.
10850 struct stackmark smark;
10854 TRACE(("cmdloop(%d) called\n", top));
10858 setstackmark(&smark);
10861 showjobs(stderr, SHOW_CHANGED);
10864 if (iflag && top) {
10866 #if ENABLE_ASH_MAIL
10870 n = parsecmd(inter);
10871 /* showtree(n); DEBUG */
10873 if (!top || numeof >= 50)
10875 if (!stoppedjobs()) {
10878 out2str("\nUse \"exit\" to leave shell.\n");
10881 } else if (nflag == 0) {
10882 job_warning = (job_warning == 2) ? 1 : 0;
10886 popstackmark(&smark);
10891 return skip & SKIPEVAL;
10898 * Take commands from a file. To be compatible we should do a path
10899 * search for the file, which is necessary to find sub-commands.
10902 find_dot_file(char *name)
10905 const char *path = pathval();
10908 /* don't try this for absolute or relative paths */
10909 if (strchr(name, '/'))
10912 while ((fullname = padvance(&path, name)) != NULL) {
10913 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
10915 * Don't bother freeing here, since it will
10916 * be freed by the caller.
10920 stunalloc(fullname);
10923 /* not found in the PATH */
10924 ash_msg_and_raise_error("%s: not found", name);
10929 dotcmd(int argc, char **argv)
10931 struct strlist *sp;
10932 volatile struct shparam saveparam;
10935 for (sp = cmdenviron; sp; sp = sp->next)
10936 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
10938 if (argc >= 2) { /* That's what SVR2 does */
10941 fullname = find_dot_file(argv[1]);
10944 saveparam = shellparam;
10945 shellparam.malloc = 0;
10946 shellparam.nparam = argc - 2;
10947 shellparam.p = argv + 2;
10950 setinputfile(fullname, INPUT_PUSH_FILE);
10951 commandname = fullname;
10956 freeparam(&shellparam);
10957 shellparam = saveparam;
10959 status = exitstatus;
10965 exitcmd(int argc, char **argv)
10970 exitstatus = number(argv[1]);
10971 raise_exception(EXEXIT);
10975 #if ENABLE_ASH_BUILTIN_ECHO
10977 echocmd(int argc, char **argv)
10979 return bb_echo(argv);
10983 #if ENABLE_ASH_BUILTIN_TEST
10985 testcmd(int argc, char **argv)
10987 return test_main(argc, argv);
10992 * Read a file containing shell functions.
10995 readcmdfile(char *name)
10997 setinputfile(name, INPUT_PUSH_FILE);
11003 /* ============ find_command inplementation */
11006 * Resolve a command name. If you change this routine, you may have to
11007 * change the shellexec routine as well.
11010 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11012 struct tblentry *cmdp;
11019 struct builtincmd *bcmd;
11021 /* If name contains a slash, don't use PATH or hash table */
11022 if (strchr(name, '/') != NULL) {
11023 entry->u.index = -1;
11024 if (act & DO_ABS) {
11025 while (stat(name, &statb) < 0) {
11027 if (errno == EINTR)
11030 entry->cmdtype = CMDUNKNOWN;
11034 entry->cmdtype = CMDNORMAL;
11038 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11040 updatetbl = (path == pathval());
11043 if (strstr(path, "%builtin") != NULL)
11044 act |= DO_ALTBLTIN;
11047 /* If name is in the table, check answer will be ok */
11048 cmdp = cmdlookup(name, 0);
11049 if (cmdp != NULL) {
11052 switch (cmdp->cmdtype) {
11070 } else if (cmdp->rehash == 0)
11071 /* if not invalidated by cd, we're done */
11075 /* If %builtin not in path, check for builtin next */
11076 bcmd = find_builtin(name);
11078 if (IS_BUILTIN_REGULAR(bcmd))
11079 goto builtin_success;
11080 if (act & DO_ALTPATH) {
11081 if (!(act & DO_ALTBLTIN))
11082 goto builtin_success;
11083 } else if (builtinloc <= 0) {
11084 goto builtin_success;
11088 #if ENABLE_FEATURE_SH_STANDALONE
11089 if (find_applet_by_name(name)) {
11090 entry->cmdtype = CMDNORMAL;
11091 entry->u.index = -1;
11096 /* We have to search path. */
11097 prev = -1; /* where to start */
11098 if (cmdp && cmdp->rehash) { /* doing a rehash */
11099 if (cmdp->cmdtype == CMDBUILTIN)
11102 prev = cmdp->param.index;
11108 while ((fullname = padvance(&path, name)) != NULL) {
11109 stunalloc(fullname);
11112 if (prefix(pathopt, "builtin")) {
11114 goto builtin_success;
11116 } else if (!(act & DO_NOFUNC) &&
11117 prefix(pathopt, "func")) {
11118 /* handled below */
11120 /* ignore unimplemented options */
11124 /* if rehash, don't redo absolute path names */
11125 if (fullname[0] == '/' && idx <= prev) {
11128 TRACE(("searchexec \"%s\": no change\n", name));
11131 while (stat(fullname, &statb) < 0) {
11133 if (errno == EINTR)
11136 if (errno != ENOENT && errno != ENOTDIR)
11140 e = EACCES; /* if we fail, this will be the error */
11141 if (!S_ISREG(statb.st_mode))
11143 if (pathopt) { /* this is a %func directory */
11144 stalloc(strlen(fullname) + 1);
11145 readcmdfile(fullname);
11146 cmdp = cmdlookup(name, 0);
11147 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11148 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11149 stunalloc(fullname);
11152 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11154 entry->cmdtype = CMDNORMAL;
11155 entry->u.index = idx;
11159 cmdp = cmdlookup(name, 1);
11160 cmdp->cmdtype = CMDNORMAL;
11161 cmdp->param.index = idx;
11166 /* We failed. If there was an entry for this command, delete it */
11167 if (cmdp && updatetbl)
11168 delete_cmd_entry();
11170 ash_msg("%s: %s", name, errmsg(e, "not found"));
11171 entry->cmdtype = CMDUNKNOWN;
11176 entry->cmdtype = CMDBUILTIN;
11177 entry->u.cmd = bcmd;
11181 cmdp = cmdlookup(name, 1);
11182 cmdp->cmdtype = CMDBUILTIN;
11183 cmdp->param.cmd = bcmd;
11187 entry->cmdtype = cmdp->cmdtype;
11188 entry->u = cmdp->param;
11192 /* ============ trap.c */
11195 * The trap builtin.
11198 trapcmd(int argc, char **argv)
11207 for (signo = 0; signo < NSIG; signo++) {
11208 if (trap[signo] != NULL) {
11211 sn = get_signame(signo);
11212 out1fmt("trap -- %s %s\n",
11213 single_quote(trap[signo]), sn);
11223 signo = get_signum(*ap);
11225 ash_msg_and_raise_error("%s: bad trap", *ap);
11228 if (LONE_DASH(action))
11231 action = ckstrdup(action);
11235 trap[signo] = action;
11245 /* ============ Builtins */
11247 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11249 * Lists available builtins
11252 helpcmd(int argc, char **argv)
11256 out1fmt("\nBuilt-in commands:\n-------------------\n");
11257 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab) ; i++) {
11258 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11259 builtintab[i].name + 1);
11265 #if ENABLE_FEATURE_SH_STANDALONE
11266 for (i = 0; i < NUM_APPLETS; i++) {
11267 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11275 return EXIT_SUCCESS;
11277 #endif /* FEATURE_SH_EXTRA_QUIET */
11280 * The export and readonly commands.
11283 exportcmd(int argc, char **argv)
11289 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11291 if (nextopt("p") != 'p') {
11296 p = strchr(name, '=');
11300 vp = *findvar(hashvar(name), name);
11306 setvar(name, p, flag);
11307 } while ((name = *++aptr) != NULL);
11311 showvars(argv[0], flag, 0);
11316 * Delete a function if it exists.
11319 unsetfunc(const char *name)
11321 struct tblentry *cmdp;
11323 cmdp = cmdlookup(name, 0);
11324 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11325 delete_cmd_entry();
11329 * The unset builtin command. We unset the function before we unset the
11330 * variable to allow a function to be unset when there is a readonly variable
11331 * with the same name.
11334 unsetcmd(int argc, char **argv)
11341 while ((i = nextopt("vf")) != '\0') {
11345 for (ap = argptr; *ap; ap++) {
11361 #include <sys/times.h>
11363 static const unsigned char timescmd_str[] = {
11364 ' ', offsetof(struct tms, tms_utime),
11365 '\n', offsetof(struct tms, tms_stime),
11366 ' ', offsetof(struct tms, tms_cutime),
11367 '\n', offsetof(struct tms, tms_cstime),
11372 timescmd(int ac, char **av)
11374 long clk_tck, s, t;
11375 const unsigned char *p;
11378 clk_tck = sysconf(_SC_CLK_TCK);
11383 t = *(clock_t *)(((char *) &buf) + p[1]);
11385 out1fmt("%ldm%ld.%.3lds%c",
11387 ((t - s * clk_tck) * 1000) / clk_tck,
11389 } while (*(p += 2));
11394 #if ENABLE_ASH_MATH_SUPPORT
11396 dash_arith(const char *s)
11402 result = arith(s, &errcode);
11405 ash_msg_and_raise_error("exponent less than 0");
11407 ash_msg_and_raise_error("divide by zero");
11409 ash_msg_and_raise_error("expression recursion loop detected");
11410 raise_error_syntax(s);
11418 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11419 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11421 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11424 letcmd(int argc, char **argv)
11431 ash_msg_and_raise_error("expression expected");
11432 for (ap = argv + 1; *ap; ap++) {
11433 i = dash_arith(*ap);
11438 #endif /* ASH_MATH_SUPPORT */
11441 /* ============ miscbltin.c
11443 * Miscellaneous builtins.
11448 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11449 typedef enum __rlimit_resource rlim_t;
11453 * The read builtin. The -e option causes backslashes to escape the
11454 * following character.
11456 * This uses unbuffered input, which may be avoidable in some cases.
11459 readcmd(int argc, char **argv)
11471 #if ENABLE_ASH_READ_NCHARS
11475 struct termios tty, old_tty;
11477 #if ENABLE_ASH_READ_TIMEOUT
11481 ts.tv_sec = ts.tv_usec = 0;
11486 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11487 while ((i = nextopt("p:rt:n:s")) != '\0')
11488 #elif ENABLE_ASH_READ_NCHARS
11489 while ((i = nextopt("p:rn:s")) != '\0')
11490 #elif ENABLE_ASH_READ_TIMEOUT
11491 while ((i = nextopt("p:rt:")) != '\0')
11493 while ((i = nextopt("p:r")) != '\0')
11498 prompt = optionarg;
11500 #if ENABLE_ASH_READ_NCHARS
11502 nchars = strtol(optionarg, &p, 10);
11504 ash_msg_and_raise_error("invalid count");
11505 nch_flag = (nchars > 0);
11511 #if ENABLE_ASH_READ_TIMEOUT
11513 ts.tv_sec = strtol(optionarg, &p, 10);
11519 ts.tv_usec = strtol(p, &p2, 10);
11521 ash_msg_and_raise_error("invalid timeout");
11523 /* normalize to usec */
11525 ash_msg_and_raise_error("invalid timeout");
11526 while (scale++ < 6)
11530 ash_msg_and_raise_error("invalid timeout");
11532 if ( ! ts.tv_sec && ! ts.tv_usec)
11533 ash_msg_and_raise_error("invalid timeout");
11543 if (prompt && isatty(0)) {
11548 ash_msg_and_raise_error("arg count");
11549 ifs = bltinlookup("IFS");
11552 #if ENABLE_ASH_READ_NCHARS
11553 if (nch_flag || silent) {
11554 tcgetattr(0, &tty);
11557 tty.c_lflag &= ~ICANON;
11558 tty.c_cc[VMIN] = nchars;
11561 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11564 tcsetattr(0, TCSANOW, &tty);
11567 #if ENABLE_ASH_READ_TIMEOUT
11568 if (ts.tv_sec || ts.tv_usec) {
11572 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11574 #if ENABLE_ASH_READ_NCHARS
11576 tcsetattr(0, TCSANOW, &old_tty);
11586 #if ENABLE_ASH_READ_NCHARS
11587 while (!nch_flag || nchars--)
11592 if (read(0, &c, 1) != 1) {
11604 if (!rflag && c == '\\') {
11610 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11614 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11616 setvar(*ap, stackblock(), 0);
11625 #if ENABLE_ASH_READ_NCHARS
11626 if (nch_flag || silent)
11627 tcsetattr(0, TCSANOW, &old_tty);
11631 /* Remove trailing blanks */
11632 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11634 setvar(*ap, stackblock(), 0);
11635 while (*++ap != NULL)
11636 setvar(*ap, nullstr, 0);
11641 umaskcmd(int argc, char **argv)
11643 static const char permuser[3] = "ugo";
11644 static const char permmode[3] = "rwx";
11645 static const short int permmask[] = {
11646 S_IRUSR, S_IWUSR, S_IXUSR,
11647 S_IRGRP, S_IWGRP, S_IXGRP,
11648 S_IROTH, S_IWOTH, S_IXOTH
11654 int symbolic_mode = 0;
11656 while (nextopt("S") != '\0') {
11667 if (symbolic_mode) {
11671 for (i = 0; i < 3; i++) {
11674 *p++ = permuser[i];
11676 for (j = 0; j < 3; j++) {
11677 if ((mask & permmask[3 * i + j]) == 0) {
11678 *p++ = permmode[j];
11686 out1fmt("%.4o\n", mask);
11689 if (isdigit((unsigned char) *ap)) {
11692 if (*ap >= '8' || *ap < '0')
11693 ash_msg_and_raise_error(illnum, argv[1]);
11694 mask = (mask << 3) + (*ap - '0');
11695 } while (*++ap != '\0');
11698 mask = ~mask & 0777;
11699 if (!bb_parse_mode(ap, &mask)) {
11700 ash_msg_and_raise_error("illegal mode: %s", ap);
11702 umask(~mask & 0777);
11711 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11712 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11713 * ash by J.T. Conklin.
11721 int factor; /* multiply by to get rlim_{cur,max} values */
11725 static const struct limits limits[] = {
11727 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11729 #ifdef RLIMIT_FSIZE
11730 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11733 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11735 #ifdef RLIMIT_STACK
11736 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11739 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11742 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11744 #ifdef RLIMIT_MEMLOCK
11745 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11747 #ifdef RLIMIT_NPROC
11748 { "process", RLIMIT_NPROC, 1, 'p' },
11750 #ifdef RLIMIT_NOFILE
11751 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11754 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11756 #ifdef RLIMIT_LOCKS
11757 { "locks", RLIMIT_LOCKS, 1, 'w' },
11759 { NULL, 0, 0, '\0' }
11762 enum limtype { SOFT = 0x1, HARD = 0x2 };
11765 printlim(enum limtype how, const struct rlimit *limit,
11766 const struct limits *l)
11770 val = limit->rlim_max;
11772 val = limit->rlim_cur;
11774 if (val == RLIM_INFINITY)
11775 out1fmt("unlimited\n");
11778 out1fmt("%lld\n", (long long) val);
11783 ulimitcmd(int argc, char **argv)
11787 enum limtype how = SOFT | HARD;
11788 const struct limits *l;
11791 struct rlimit limit;
11794 while ((optc = nextopt("HSa"
11798 #ifdef RLIMIT_FSIZE
11804 #ifdef RLIMIT_STACK
11813 #ifdef RLIMIT_MEMLOCK
11816 #ifdef RLIMIT_NPROC
11819 #ifdef RLIMIT_NOFILE
11825 #ifdef RLIMIT_LOCKS
11843 for (l = limits; l->option != what; l++)
11846 set = *argptr ? 1 : 0;
11850 if (all || argptr[1])
11851 ash_msg_and_raise_error("too many arguments");
11852 if (strncmp(p, "unlimited\n", 9) == 0)
11853 val = RLIM_INFINITY;
11857 while ((c = *p++) >= '0' && c <= '9') {
11858 val = (val * 10) + (long)(c - '0');
11859 if (val < (rlim_t) 0)
11863 ash_msg_and_raise_error("bad number");
11868 for (l = limits; l->name; l++) {
11869 getrlimit(l->cmd, &limit);
11870 out1fmt("%-20s ", l->name);
11871 printlim(how, &limit, l);
11876 getrlimit(l->cmd, &limit);
11879 limit.rlim_max = val;
11881 limit.rlim_cur = val;
11882 if (setrlimit(l->cmd, &limit) < 0)
11883 ash_msg_and_raise_error("error setting limit (%m)");
11885 printlim(how, &limit, l);
11891 /* ============ Math support */
11893 #if ENABLE_ASH_MATH_SUPPORT
11895 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11897 Permission is hereby granted, free of charge, to any person obtaining
11898 a copy of this software and associated documentation files (the
11899 "Software"), to deal in the Software without restriction, including
11900 without limitation the rights to use, copy, modify, merge, publish,
11901 distribute, sublicense, and/or sell copies of the Software, and to
11902 permit persons to whom the Software is furnished to do so, subject to
11903 the following conditions:
11905 The above copyright notice and this permission notice shall be
11906 included in all copies or substantial portions of the Software.
11908 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11909 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11910 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
11911 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
11912 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11913 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11914 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11917 /* This is my infix parser/evaluator. It is optimized for size, intended
11918 * as a replacement for yacc-based parsers. However, it may well be faster
11919 * than a comparable parser written in yacc. The supported operators are
11920 * listed in #defines below. Parens, order of operations, and error handling
11921 * are supported. This code is thread safe. The exact expression format should
11922 * be that which POSIX specifies for shells. */
11924 /* The code uses a simple two-stack algorithm. See
11925 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
11926 * for a detailed explanation of the infix-to-postfix algorithm on which
11927 * this is based (this code differs in that it applies operators immediately
11928 * to the stack instead of adding them to a queue to end up with an
11931 /* To use the routine, call it with an expression string and error return
11935 * Aug 24, 2001 Manuel Novoa III
11937 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
11939 * 1) In arith_apply():
11940 * a) Cached values of *numptr and &(numptr[-1]).
11941 * b) Removed redundant test for zero denominator.
11944 * a) Eliminated redundant code for processing operator tokens by moving
11945 * to a table-based implementation. Also folded handling of parens
11947 * b) Combined all 3 loops which called arith_apply to reduce generated
11948 * code size at the cost of speed.
11950 * 3) The following expressions were treated as valid by the original code:
11951 * 1() , 0! , 1 ( *3 ) .
11952 * These bugs have been fixed by internally enclosing the expression in
11953 * parens and then checking that all binary ops and right parens are
11954 * preceded by a valid expression (NUM_TOKEN).
11956 * Note: It may be desirable to replace Aaron's test for whitespace with
11957 * ctype's isspace() if it is used by another busybox applet or if additional
11958 * whitespace chars should be considered. Look below the "#include"s for a
11959 * precompiler test.
11963 * Aug 26, 2001 Manuel Novoa III
11965 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
11967 * Merge in Aaron's comments previously posted to the busybox list,
11968 * modified slightly to take account of my changes to the code.
11973 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11975 * - allow access to variable,
11976 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
11977 * - realize assign syntax (VAR=expr, +=, *= etc)
11978 * - realize exponentiation (** operator)
11979 * - realize comma separated - expr, expr
11980 * - realise ++expr --expr expr++ expr--
11981 * - realise expr ? expr : expr (but, second expr calculate always)
11982 * - allow hexadecimal and octal numbers
11983 * - was restored loses XOR operator
11984 * - remove one goto label, added three ;-)
11985 * - protect $((num num)) as true zero expr (Manuel`s error)
11986 * - always use special isspace(), see comment from bash ;-)
11989 #define arith_isspace(arithval) \
11990 (arithval == ' ' || arithval == '\n' || arithval == '\t')
11992 typedef unsigned char operator;
11994 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
11995 * precedence, and 3 high bits are an ID unique across operators of that
11996 * precedence. The ID portion is so that multiple operators can have the
11997 * same precedence, ensuring that the leftmost one is evaluated first.
11998 * Consider * and /. */
12000 #define tok_decl(prec,id) (((id)<<5)|(prec))
12001 #define PREC(op) ((op) & 0x1F)
12003 #define TOK_LPAREN tok_decl(0,0)
12005 #define TOK_COMMA tok_decl(1,0)
12007 #define TOK_ASSIGN tok_decl(2,0)
12008 #define TOK_AND_ASSIGN tok_decl(2,1)
12009 #define TOK_OR_ASSIGN tok_decl(2,2)
12010 #define TOK_XOR_ASSIGN tok_decl(2,3)
12011 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12012 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12013 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12014 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12016 #define TOK_MUL_ASSIGN tok_decl(3,0)
12017 #define TOK_DIV_ASSIGN tok_decl(3,1)
12018 #define TOK_REM_ASSIGN tok_decl(3,2)
12020 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12021 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12023 /* conditional is right associativity too */
12024 #define TOK_CONDITIONAL tok_decl(4,0)
12025 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12027 #define TOK_OR tok_decl(5,0)
12029 #define TOK_AND tok_decl(6,0)
12031 #define TOK_BOR tok_decl(7,0)
12033 #define TOK_BXOR tok_decl(8,0)
12035 #define TOK_BAND tok_decl(9,0)
12037 #define TOK_EQ tok_decl(10,0)
12038 #define TOK_NE tok_decl(10,1)
12040 #define TOK_LT tok_decl(11,0)
12041 #define TOK_GT tok_decl(11,1)
12042 #define TOK_GE tok_decl(11,2)
12043 #define TOK_LE tok_decl(11,3)
12045 #define TOK_LSHIFT tok_decl(12,0)
12046 #define TOK_RSHIFT tok_decl(12,1)
12048 #define TOK_ADD tok_decl(13,0)
12049 #define TOK_SUB tok_decl(13,1)
12051 #define TOK_MUL tok_decl(14,0)
12052 #define TOK_DIV tok_decl(14,1)
12053 #define TOK_REM tok_decl(14,2)
12055 /* exponent is right associativity */
12056 #define TOK_EXPONENT tok_decl(15,1)
12058 /* For now unary operators. */
12059 #define UNARYPREC 16
12060 #define TOK_BNOT tok_decl(UNARYPREC,0)
12061 #define TOK_NOT tok_decl(UNARYPREC,1)
12063 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12064 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12066 #define PREC_PRE (UNARYPREC+2)
12068 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12069 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12071 #define PREC_POST (UNARYPREC+3)
12073 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12074 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12076 #define SPEC_PREC (UNARYPREC+4)
12078 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12079 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12081 #define NUMPTR (*numstackptr)
12084 tok_have_assign(operator op)
12086 operator prec = PREC(op);
12088 convert_prec_is_assing(prec);
12089 return (prec == PREC(TOK_ASSIGN) ||
12090 prec == PREC_PRE || prec == PREC_POST);
12094 is_right_associativity(operator prec)
12096 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12097 || prec == PREC(TOK_CONDITIONAL));
12100 typedef struct ARITCH_VAR_NUM {
12102 arith_t contidional_second_val;
12103 char contidional_second_val_initialized;
12104 char *var; /* if NULL then is regular number,
12105 else is variable name */
12108 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12110 struct CHK_VAR_RECURSIVE_LOOPED *next;
12111 } chk_var_recursive_looped_t;
12113 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12116 arith_lookup_val(v_n_t *t)
12119 const char * p = lookupvar(t->var);
12124 /* recursive try as expression */
12125 chk_var_recursive_looped_t *cur;
12126 chk_var_recursive_looped_t cur_save;
12128 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12129 if (strcmp(cur->var, t->var) == 0) {
12130 /* expression recursion loop detected */
12134 /* save current lookuped var name */
12135 cur = prev_chk_var_recursive;
12136 cur_save.var = t->var;
12137 cur_save.next = cur;
12138 prev_chk_var_recursive = &cur_save;
12140 t->val = arith (p, &errcode);
12141 /* restore previous ptr after recursiving */
12142 prev_chk_var_recursive = cur;
12145 /* allow undefined var as 0 */
12151 /* "applying" a token means performing it on the top elements on the integer
12152 * stack. For a unary operator it will only change the top element, but a
12153 * binary operator will pop two arguments and push a result */
12155 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12158 arith_t numptr_val, rez;
12159 int ret_arith_lookup_val;
12161 /* There is no operator that can work without arguments */
12162 if (NUMPTR == numstack) goto err;
12163 numptr_m1 = NUMPTR - 1;
12165 /* check operand is var with noninteger value */
12166 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12167 if (ret_arith_lookup_val)
12168 return ret_arith_lookup_val;
12170 rez = numptr_m1->val;
12171 if (op == TOK_UMINUS)
12173 else if (op == TOK_NOT)
12175 else if (op == TOK_BNOT)
12177 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12179 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12181 else if (op != TOK_UPLUS) {
12182 /* Binary operators */
12184 /* check and binary operators need two arguments */
12185 if (numptr_m1 == numstack) goto err;
12187 /* ... and they pop one */
12190 if (op == TOK_CONDITIONAL) {
12191 if (! numptr_m1->contidional_second_val_initialized) {
12192 /* protect $((expr1 ? expr2)) without ": expr" */
12195 rez = numptr_m1->contidional_second_val;
12196 } else if (numptr_m1->contidional_second_val_initialized) {
12197 /* protect $((expr1 : expr2)) without "expr ? " */
12200 numptr_m1 = NUMPTR - 1;
12201 if (op != TOK_ASSIGN) {
12202 /* check operand is var with noninteger value for not '=' */
12203 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12204 if (ret_arith_lookup_val)
12205 return ret_arith_lookup_val;
12207 if (op == TOK_CONDITIONAL) {
12208 numptr_m1->contidional_second_val = rez;
12210 rez = numptr_m1->val;
12211 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12213 else if (op == TOK_OR)
12214 rez = numptr_val || rez;
12215 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12217 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12219 else if (op == TOK_AND)
12220 rez = rez && numptr_val;
12221 else if (op == TOK_EQ)
12222 rez = (rez == numptr_val);
12223 else if (op == TOK_NE)
12224 rez = (rez != numptr_val);
12225 else if (op == TOK_GE)
12226 rez = (rez >= numptr_val);
12227 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12228 rez >>= numptr_val;
12229 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12230 rez <<= numptr_val;
12231 else if (op == TOK_GT)
12232 rez = (rez > numptr_val);
12233 else if (op == TOK_LT)
12234 rez = (rez < numptr_val);
12235 else if (op == TOK_LE)
12236 rez = (rez <= numptr_val);
12237 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12239 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12241 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12243 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12245 else if (op == TOK_CONDITIONAL_SEP) {
12246 if (numptr_m1 == numstack) {
12247 /* protect $((expr : expr)) without "expr ? " */
12250 numptr_m1->contidional_second_val_initialized = op;
12251 numptr_m1->contidional_second_val = numptr_val;
12252 } else if (op == TOK_CONDITIONAL) {
12254 numptr_val : numptr_m1->contidional_second_val;
12255 } else if (op == TOK_EXPONENT) {
12256 if (numptr_val < 0)
12257 return -3; /* exponent less than 0 */
12262 while (numptr_val--)
12266 } else if (numptr_val==0) /* zero divisor check */
12268 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12270 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12273 if (tok_have_assign(op)) {
12274 char buf[sizeof(arith_t_type)*3 + 2];
12276 if (numptr_m1->var == NULL) {
12280 /* save to shell variable */
12281 #if ENABLE_ASH_MATH_SUPPORT_64
12282 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12284 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12286 setvar(numptr_m1->var, buf, 0);
12287 /* after saving, make previous value for v++ or v-- */
12288 if (op == TOK_POST_INC)
12290 else if (op == TOK_POST_DEC)
12293 numptr_m1->val = rez;
12294 /* protect geting var value, is number now */
12295 numptr_m1->var = NULL;
12301 /* longest must be first */
12302 static const char op_tokens[] = {
12303 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12304 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12305 '<','<', 0, TOK_LSHIFT,
12306 '>','>', 0, TOK_RSHIFT,
12307 '|','|', 0, TOK_OR,
12308 '&','&', 0, TOK_AND,
12309 '!','=', 0, TOK_NE,
12310 '<','=', 0, TOK_LE,
12311 '>','=', 0, TOK_GE,
12312 '=','=', 0, TOK_EQ,
12313 '|','=', 0, TOK_OR_ASSIGN,
12314 '&','=', 0, TOK_AND_ASSIGN,
12315 '*','=', 0, TOK_MUL_ASSIGN,
12316 '/','=', 0, TOK_DIV_ASSIGN,
12317 '%','=', 0, TOK_REM_ASSIGN,
12318 '+','=', 0, TOK_PLUS_ASSIGN,
12319 '-','=', 0, TOK_MINUS_ASSIGN,
12320 '-','-', 0, TOK_POST_DEC,
12321 '^','=', 0, TOK_XOR_ASSIGN,
12322 '+','+', 0, TOK_POST_INC,
12323 '*','*', 0, TOK_EXPONENT,
12327 '=', 0, TOK_ASSIGN,
12339 '?', 0, TOK_CONDITIONAL,
12340 ':', 0, TOK_CONDITIONAL_SEP,
12341 ')', 0, TOK_RPAREN,
12342 '(', 0, TOK_LPAREN,
12346 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12349 arith(const char *expr, int *perrcode)
12351 char arithval; /* Current character under analysis */
12352 operator lasttok, op;
12355 const char *p = endexpression;
12358 size_t datasizes = strlen(expr) + 2;
12360 /* Stack of integers */
12361 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12362 * in any given correct or incorrect expression is left as an exercise to
12364 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12365 *numstackptr = numstack;
12366 /* Stack of operator tokens */
12367 operator *stack = alloca((datasizes) * sizeof(operator)),
12370 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12371 *perrcode = errcode = 0;
12375 if (arithval == 0) {
12376 if (p == endexpression) {
12377 /* Null expression. */
12381 /* This is only reached after all tokens have been extracted from the
12382 * input stream. If there are still tokens on the operator stack, they
12383 * are to be applied in order. At the end, there should be a final
12384 * result on the integer stack */
12386 if (expr != endexpression + 1) {
12387 /* If we haven't done so already, */
12388 /* append a closing right paren */
12389 expr = endexpression;
12390 /* and let the loop process it. */
12393 /* At this point, we're done with the expression. */
12394 if (numstackptr != numstack+1) {
12395 /* ... but if there isn't, it's bad */
12397 return (*perrcode = -1);
12399 if (numstack->var) {
12400 /* expression is $((var)) only, lookup now */
12401 errcode = arith_lookup_val(numstack);
12404 *perrcode = errcode;
12405 return numstack->val;
12408 /* Continue processing the expression. */
12409 if (arith_isspace(arithval)) {
12410 /* Skip whitespace */
12413 p = endofname(expr);
12415 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12417 numstackptr->var = alloca(var_name_size);
12418 safe_strncpy(numstackptr->var, expr, var_name_size);
12421 numstackptr->contidional_second_val_initialized = 0;
12426 if (isdigit(arithval)) {
12427 numstackptr->var = NULL;
12428 #if ENABLE_ASH_MATH_SUPPORT_64
12429 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12431 numstackptr->val = strtol(expr, (char **) &expr, 0);
12435 for (p = op_tokens; ; p++) {
12439 /* strange operator not found */
12442 for (o = expr; *p && *o == *p; p++)
12449 /* skip tail uncompared token */
12452 /* skip zero delim */
12457 /* post grammar: a++ reduce to num */
12458 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12461 /* Plus and minus are binary (not unary) _only_ if the last
12462 * token was as number, or a right paren (which pretends to be
12463 * a number, since it evaluates to one). Think about it.
12464 * It makes sense. */
12465 if (lasttok != TOK_NUM) {
12481 /* We don't want a unary operator to cause recursive descent on the
12482 * stack, because there can be many in a row and it could cause an
12483 * operator to be evaluated before its argument is pushed onto the
12484 * integer stack. */
12485 /* But for binary operators, "apply" everything on the operator
12486 * stack until we find an operator with a lesser priority than the
12487 * one we have just extracted. */
12488 /* Left paren is given the lowest priority so it will never be
12489 * "applied" in this way.
12490 * if associativity is right and priority eq, applied also skip
12493 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12494 /* not left paren or unary */
12495 if (lasttok != TOK_NUM) {
12496 /* binary op must be preceded by a num */
12499 while (stackptr != stack) {
12500 if (op == TOK_RPAREN) {
12501 /* The algorithm employed here is simple: while we don't
12502 * hit an open paren nor the bottom of the stack, pop
12503 * tokens and apply them */
12504 if (stackptr[-1] == TOK_LPAREN) {
12506 /* Any operator directly after a */
12508 /* close paren should consider itself binary */
12512 operator prev_prec = PREC(stackptr[-1]);
12514 convert_prec_is_assing(prec);
12515 convert_prec_is_assing(prev_prec);
12516 if (prev_prec < prec)
12518 /* check right assoc */
12519 if (prev_prec == prec && is_right_associativity(prec))
12522 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12523 if (errcode) goto ret;
12525 if (op == TOK_RPAREN) {
12530 /* Push this operator to the stack and remember it. */
12531 *stackptr++ = lasttok = op;
12536 #endif /* ASH_MATH_SUPPORT */
12539 /* ============ main() and helpers */
12542 * Called to exit the shell.
12544 static void exitshell(void) ATTRIBUTE_NORETURN;
12552 status = exitstatus;
12553 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12554 if (setjmp(loc.loc)) {
12555 if (exception == EXEXIT)
12556 /* dash bug: it just does _exit(exitstatus) here
12557 * but we have to do setjobctl(0) first!
12558 * (bug is still not fixed in dash-0.5.3 - if you run dash
12559 * under Midnight Commander, on exit from dash MC is backgrounded) */
12560 status = exitstatus;
12563 exception_handler = &loc;
12569 flush_stdout_stderr();
12579 /* from input.c: */
12580 basepf.nextc = basepf.buf = basebuf;
12583 signal(SIGCHLD, SIG_DFL);
12588 char ppid[sizeof(int)*3 + 1];
12590 struct stat st1, st2;
12593 for (envp = environ; envp && *envp; envp++) {
12594 if (strchr(*envp, '=')) {
12595 setvareq(*envp, VEXPORT|VTEXTFIXED);
12599 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12600 setvar("PPID", ppid, 0);
12602 p = lookupvar("PWD");
12604 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12605 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12612 * Process the shell command line arguments.
12615 procargs(int argc, char **argv)
12618 const char *xminusc;
12625 for (i = 0; i < NOPTS; i++)
12631 if (*xargv == NULL) {
12633 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12636 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12640 for (i = 0; i < NOPTS; i++)
12641 if (optlist[i] == 2)
12646 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12651 } else if (!sflag) {
12652 setinputfile(*xargv, 0);
12655 commandname = arg0;
12658 shellparam.p = xargv;
12659 #if ENABLE_ASH_GETOPTS
12660 shellparam.optind = 1;
12661 shellparam.optoff = -1;
12663 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12665 shellparam.nparam++;
12672 * Read /etc/profile or .profile.
12675 read_profile(const char *name)
12679 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12688 * This routine is called when an error or an interrupt occurs in an
12689 * interactive shell and control is returned to the main command loop.
12697 /* from input.c: */
12698 parselleft = parsenleft = 0; /* clear input buffer */
12700 /* from parser.c: */
12703 /* from redir.c: */
12708 static short profile_buf[16384];
12709 extern int etext();
12713 * Main routine. We initialize things, parse the arguments, execute
12714 * profiles if we're a login shell, and then call cmdloop to execute
12715 * commands. The setjmp call sets up the location to jump to when an
12716 * exception occurs. When an exception occurs the variable "state"
12717 * is used to figure out how far we had gotten.
12719 int ash_main(int argc, char **argv);
12720 int ash_main(int argc, char **argv)
12723 volatile int state;
12724 struct jmploc jmploc;
12725 struct stackmark smark;
12728 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12731 #if ENABLE_FEATURE_EDITING
12732 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12735 if (setjmp(jmploc.loc)) {
12745 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12749 outcslow('\n', stderr);
12751 popstackmark(&smark);
12752 FORCE_INT_ON; /* enable interrupts */
12761 exception_handler = &jmploc;
12764 trace_puts("Shell args: ");
12765 trace_puts_args(argv);
12767 rootpid = getpid();
12769 #if ENABLE_ASH_RANDOM_SUPPORT
12770 rseed = rootpid + time(NULL);
12773 setstackmark(&smark);
12774 procargs(argc, argv);
12775 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12777 const char *hp = lookupvar("HISTFILE");
12780 hp = lookupvar("HOME");
12782 char *defhp = concat_path_file(hp, ".ash_history");
12783 setvar("HISTFILE", defhp, 0);
12789 if (argv[0] && argv[0][0] == '-')
12793 read_profile("/etc/profile");
12796 read_profile(".profile");
12802 getuid() == geteuid() && getgid() == getegid() &&
12806 shinit = lookupvar("ENV");
12807 if (shinit != NULL && *shinit != '\0') {
12808 read_profile(shinit);
12814 evalstring(minusc, 0);
12816 if (sflag || minusc == NULL) {
12817 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12819 const char *hp = lookupvar("HISTFILE");
12822 line_input_state->hist_file = hp;
12825 state4: /* XXX ??? - why isn't this before the "if" statement */
12833 extern void _mcleanup(void);
12842 const char *applet_name = "debug stuff usage";
12843 int main(int argc, char **argv)
12845 return ash_main(argc, argv);
12851 * Copyright (c) 1989, 1991, 1993, 1994
12852 * The Regents of the University of California. All rights reserved.
12854 * This code is derived from software contributed to Berkeley by
12855 * Kenneth Almquist.
12857 * Redistribution and use in source and binary forms, with or without
12858 * modification, are permitted provided that the following conditions
12860 * 1. Redistributions of source code must retain the above copyright
12861 * notice, this list of conditions and the following disclaimer.
12862 * 2. Redistributions in binary form must reproduce the above copyright
12863 * notice, this list of conditions and the following disclaimer in the
12864 * documentation and/or other materials provided with the distribution.
12865 * 3. Neither the name of the University nor the names of its contributors
12866 * may be used to endorse or promote products derived from this software
12867 * without specific prior written permission.
12869 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12870 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12871 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12872 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12873 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12874 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12875 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12876 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12877 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12878 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF