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 /* pid of main shell */
139 /* shell level: 0 for the main shell, 1 for its children, and so on */
141 #define rootshell (!shlvl)
142 /* trap handler commands */
143 static char *trap[NSIG];
144 static smallint isloginsh;
145 /* current value of signal */
146 static char sigmode[NSIG - 1];
147 /* indicates specified signal received */
148 static char gotsig[NSIG - 1];
149 static char *arg0; /* value of $0 */
152 /* ============ Interrupts / exceptions */
155 * We enclose jmp_buf in a structure so that we can declare pointers to
156 * jump locations. The global variable handler contains the location to
157 * jump to when an exception occurs, and the global variable exception
158 * contains a code identifying the exception. To implement nested
159 * exception handlers, the user should save the value of handler on entry
160 * to an inner scope, set handler to point to a jmploc structure for the
161 * inner scope, and restore handler on exit from the scope.
166 static struct jmploc *exception_handler;
167 static int exception;
169 #define EXINT 0 /* SIGINT received */
170 #define EXERROR 1 /* a generic error */
171 #define EXSHELLPROC 2 /* execute a shell procedure */
172 #define EXEXEC 3 /* command execution failed */
173 #define EXEXIT 4 /* exit the shell */
174 #define EXSIG 5 /* trapped signal in wait(1) */
175 static volatile int suppressint;
176 static volatile sig_atomic_t intpending;
177 /* do we generate EXSIG events */
179 /* last pending signal */
180 static volatile sig_atomic_t pendingsig;
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
188 #define S_DFL 1 /* default signal handling (SIG_DFL) */
189 #define S_CATCH 2 /* signal is caught */
190 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
191 #define S_HARD_IGN 4 /* signal is ignored permenantly */
192 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
195 * These macros allow the user to suspend the handling of interrupt signals
196 * over a period of time. This is similar to SIGHOLD to or sigblock, but
197 * much more efficient and portable. (But hacking the kernel is so much
198 * more fun than worrying about efficiency and portability. :-))
207 * Called to raise an exception. Since C doesn't include exceptions, we
208 * just do a longjmp to the exception handler. The type of exception is
209 * stored in the global variable "exception".
211 static void raise_exception(int) ATTRIBUTE_NORETURN;
213 raise_exception(int e)
216 if (exception_handler == NULL)
221 longjmp(exception_handler->loc, 1);
225 * Called from trap.c when a SIGINT is received. (If the user specifies
226 * that SIGINT is to be trapped or ignored using the trap builtin, then
227 * this routine is not called.) Suppressint is nonzero when interrupts
228 * are held using the INT_OFF macro. (The test for iflag is just
229 * defensive programming.)
231 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
233 raise_interrupt(void)
239 /* Signal is not automatically re-enabled after it is raised,
242 sigprocmask(SIG_SETMASK, &mask, 0);
243 /* pendingsig = 0; - now done in onsig() */
246 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
247 if (!(rootshell && iflag)) {
248 signal(SIGINT, SIG_DFL);
257 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
261 if (--suppressint == 0 && intpending) {
265 #define INT_ON int_on()
273 #define FORCE_INT_ON force_int_on()
278 if (--suppressint == 0 && intpending) \
281 #define FORCE_INT_ON \
288 #endif /* ASH_OPTIMIZE_FOR_SIZE */
290 #define SAVE_INT(v) ((v) = suppressint)
292 #define RESTORE_INT(v) \
296 if (suppressint == 0 && intpending) \
305 raise_exception(EXSIG); \
307 /* EXSIG is turned off by evalbltin(). */
310 * Ignore a signal. Only one usage site - in forkchild()
315 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
316 signal(signo, SIG_IGN);
318 sigmode[signo - 1] = S_HARD_IGN;
322 * Signal handler. Only one usage site - in setsignal()
327 gotsig[signo - 1] = 1;
330 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
340 /* ============ Stdout/stderr output */
343 outstr(const char *p, FILE *file)
351 flush_stdout_stderr(void)
368 outcslow(int c, FILE *dest)
376 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
378 out1fmt(const char *fmt, ...)
385 r = vprintf(fmt, ap);
391 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
393 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
400 ret = vsnprintf(outbuf, length, fmt, ap);
407 out1str(const char *p)
413 out2str(const char *p)
420 /* ============ Parser structures */
422 /* control characters in argument strings */
423 #define CTLESC '\201' /* escape next character */
424 #define CTLVAR '\202' /* variable defn */
425 #define CTLENDVAR '\203'
426 #define CTLBACKQ '\204'
427 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
428 /* CTLBACKQ | CTLQUOTE == '\205' */
429 #define CTLARI '\206' /* arithmetic expression */
430 #define CTLENDARI '\207'
431 #define CTLQUOTEMARK '\210'
433 /* variable substitution byte (follows CTLVAR) */
434 #define VSTYPE 0x0f /* type of variable substitution */
435 #define VSNUL 0x10 /* colon--treat the empty string as unset */
436 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
438 /* values of VSTYPE field */
439 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
440 #define VSMINUS 0x2 /* ${var-text} */
441 #define VSPLUS 0x3 /* ${var+text} */
442 #define VSQUESTION 0x4 /* ${var?message} */
443 #define VSASSIGN 0x5 /* ${var=text} */
444 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
445 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
446 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
447 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
448 #define VSLENGTH 0xa /* ${#var} */
450 static const char dolatstr[] = { 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) {
852 switch (np->nfile.type) {
853 case NTO: s = ">>"+1; dftfd = 1; break;
854 case NCLOBBER: s = ">|"; dftfd = 1; break;
855 case NAPPEND: s = ">>"; dftfd = 1; break;
856 case NTOFD: s = ">&"; dftfd = 1; break;
857 case NFROM: s = "<"; break;
858 case NFROMFD: s = "<&"; break;
859 case NFROMTO: s = "<>"; break;
860 default: s = "*error*"; break;
862 if (np->nfile.fd != dftfd)
863 fprintf(fp, "%d", np->nfile.fd);
865 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
866 fprintf(fp, "%d", np->ndup.dupfd);
868 sharg(np->nfile.fname, fp);
875 shtree(union node *n, int ind, char *pfx, FILE *fp)
883 indent(ind, pfx, fp);
894 shtree(n->nbinary.ch1, ind, NULL, fp);
897 shtree(n->nbinary.ch2, ind, NULL, fp);
905 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
910 if (n->npipe.backgnd)
916 fprintf(fp, "<node type %d>", n->type);
924 showtree(union node *n)
926 trace_puts("showtree called\n");
927 shtree(n, 1, NULL, stdout);
930 #define TRACE(param) trace_printf param
931 #define TRACEV(param) trace_vprintf param
936 #define TRACEV(param)
941 /* ============ Parser data */
944 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
947 struct strlist *next;
956 struct strpush *prev; /* preceding string on stack */
960 struct alias *ap; /* if push was associated with an alias */
962 char *string; /* remember the string since it may change */
966 struct parsefile *prev; /* preceding file on stack */
967 int linno; /* current line */
968 int fd; /* file descriptor (or -1 if string) */
969 int nleft; /* number of chars left in this line */
970 int lleft; /* number of chars left in this buffer */
971 char *nextc; /* next char in buffer */
972 char *buf; /* input buffer */
973 struct strpush *strpush; /* for pushing strings at this level */
974 struct strpush basestrpush; /* so pushing one is fast */
977 static struct parsefile basepf; /* top level input file */
978 static struct parsefile *parsefile = &basepf; /* current input file */
979 static int startlinno; /* line # where last token started */
980 static char *commandname; /* currently executing command */
981 static struct strlist *cmdenviron; /* environment for builtin command */
982 static int exitstatus; /* exit status of last command */
985 /* ============ Message printing */
988 ash_vmsg(const char *msg, va_list ap)
990 fprintf(stderr, "%s: ", arg0);
992 if (strcmp(arg0, commandname))
993 fprintf(stderr, "%s: ", commandname);
994 if (!iflag || parsefile->fd)
995 fprintf(stderr, "line %d: ", startlinno);
997 vfprintf(stderr, msg, ap);
998 outcslow('\n', stderr);
1002 * Exverror is called to raise the error exception. If the second argument
1003 * is not NULL then error prints an error message using printf style
1004 * formatting. It then raises the error exception.
1006 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1008 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1012 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1014 TRACE(("\") pid=%d\n", getpid()));
1016 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1021 flush_stdout_stderr();
1022 raise_exception(cond);
1026 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1028 ash_msg_and_raise_error(const char *msg, ...)
1033 ash_vmsg_and_raise(EXERROR, msg, ap);
1038 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1040 ash_msg_and_raise(int cond, const char *msg, ...)
1045 ash_vmsg_and_raise(cond, msg, ap);
1051 * error/warning routines for external builtins
1054 ash_msg(const char *fmt, ...)
1064 * Return a string describing an error. The returned string may be a
1065 * pointer to a static buffer that will be overwritten on the next call.
1066 * Action describes the operation that got the error.
1069 errmsg(int e, const char *em)
1071 if (e == ENOENT || e == ENOTDIR) {
1078 /* ============ Memory allocation */
1081 * It appears that grabstackstr() will barf with such alignments
1082 * because stalloc() will return a string allocated in a new stackblock.
1084 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1086 /* Most machines require the value returned from malloc to be aligned
1087 * in some way. The following macro will get this right
1088 * on many machines. */
1089 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1090 /* Minimum size of a block */
1091 MINSIZE = SHELL_ALIGN(504),
1094 struct stack_block {
1095 struct stack_block *prev;
1096 char space[MINSIZE];
1100 struct stack_block *stackp;
1103 struct stackmark *marknext;
1106 static struct stack_block stackbase;
1107 static struct stack_block *stackp = &stackbase;
1108 static struct stackmark *markp;
1109 static char *stacknxt = stackbase.space;
1110 static size_t stacknleft = MINSIZE;
1111 static char *sstrend = stackbase.space + MINSIZE;
1112 static int herefd = -1;
1114 #define stackblock() ((void *)stacknxt)
1115 #define stackblocksize() stacknleft
1118 ckrealloc(void * p, size_t nbytes)
1120 p = realloc(p, nbytes);
1122 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1127 ckmalloc(size_t nbytes)
1129 return ckrealloc(NULL, nbytes);
1133 * Make a copy of a string in safe storage.
1136 ckstrdup(const char *s)
1138 char *p = strdup(s);
1140 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1145 * Parse trees for commands are allocated in lifo order, so we use a stack
1146 * to make this more efficient, and also to avoid all sorts of exception
1147 * handling code to handle interrupts in the middle of a parse.
1149 * The size 504 was chosen because the Ultrix malloc handles that size
1153 stalloc(size_t nbytes)
1158 aligned = SHELL_ALIGN(nbytes);
1159 if (aligned > stacknleft) {
1162 struct stack_block *sp;
1164 blocksize = aligned;
1165 if (blocksize < MINSIZE)
1166 blocksize = MINSIZE;
1167 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1168 if (len < blocksize)
1169 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1173 stacknxt = sp->space;
1174 stacknleft = blocksize;
1175 sstrend = stacknxt + blocksize;
1180 stacknxt += aligned;
1181 stacknleft -= aligned;
1189 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1190 write(2, "stunalloc\n", 10);
1194 stacknleft += stacknxt - (char *)p;
1199 * Like strdup but works with the ash stack.
1202 ststrdup(const char *p)
1204 size_t len = strlen(p) + 1;
1205 return memcpy(stalloc(len), p, len);
1209 setstackmark(struct stackmark *mark)
1211 mark->stackp = stackp;
1212 mark->stacknxt = stacknxt;
1213 mark->stacknleft = stacknleft;
1214 mark->marknext = markp;
1219 popstackmark(struct stackmark *mark)
1221 struct stack_block *sp;
1227 markp = mark->marknext;
1228 while (stackp != mark->stackp) {
1233 stacknxt = mark->stacknxt;
1234 stacknleft = mark->stacknleft;
1235 sstrend = mark->stacknxt + mark->stacknleft;
1240 * When the parser reads in a string, it wants to stick the string on the
1241 * stack and only adjust the stack pointer when it knows how big the
1242 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1243 * of space on top of the stack and stackblocklen returns the length of
1244 * this block. Growstackblock will grow this space by at least one byte,
1245 * possibly moving it (like realloc). Grabstackblock actually allocates the
1246 * part of the block that has been used.
1249 growstackblock(void)
1253 newlen = stacknleft * 2;
1254 if (newlen < stacknleft)
1255 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1259 if (stacknxt == stackp->space && stackp != &stackbase) {
1260 struct stack_block *oldstackp;
1261 struct stackmark *xmark;
1262 struct stack_block *sp;
1263 struct stack_block *prevstackp;
1269 prevstackp = sp->prev;
1270 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1271 sp = ckrealloc(sp, grosslen);
1272 sp->prev = prevstackp;
1274 stacknxt = sp->space;
1275 stacknleft = newlen;
1276 sstrend = sp->space + newlen;
1279 * Stack marks pointing to the start of the old block
1280 * must be relocated to point to the new block
1283 while (xmark != NULL && xmark->stackp == oldstackp) {
1284 xmark->stackp = stackp;
1285 xmark->stacknxt = stacknxt;
1286 xmark->stacknleft = stacknleft;
1287 xmark = xmark->marknext;
1291 char *oldspace = stacknxt;
1292 int oldlen = stacknleft;
1293 char *p = stalloc(newlen);
1295 /* free the space we just allocated */
1296 stacknxt = memcpy(p, oldspace, oldlen);
1297 stacknleft += newlen;
1302 grabstackblock(size_t len)
1304 len = SHELL_ALIGN(len);
1310 * The following routines are somewhat easier to use than the above.
1311 * The user declares a variable of type STACKSTR, which may be declared
1312 * to be a register. The macro STARTSTACKSTR initializes things. Then
1313 * the user uses the macro STPUTC to add characters to the string. In
1314 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1315 * grown as necessary. When the user is done, she can just leave the
1316 * string there and refer to it using stackblock(). Or she can allocate
1317 * the space for it using grabstackstr(). If it is necessary to allow
1318 * someone else to use the stack temporarily and then continue to grow
1319 * the string, the user should use grabstack to allocate the space, and
1320 * then call ungrabstr(p) to return to the previous mode of operation.
1322 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1323 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1324 * is space for at least one character.
1329 size_t len = stackblocksize();
1330 if (herefd >= 0 && len >= 1024) {
1331 full_write(herefd, stackblock(), len);
1332 return stackblock();
1335 return stackblock() + len;
1339 * Called from CHECKSTRSPACE.
1342 makestrspace(size_t newlen, char *p)
1344 size_t len = p - stacknxt;
1345 size_t size = stackblocksize();
1350 size = stackblocksize();
1352 if (nleft >= newlen)
1356 return stackblock() + len;
1360 stack_nputstr(const char *s, size_t n, char *p)
1362 p = makestrspace(n, p);
1363 p = memcpy(p, s, n) + n;
1368 stack_putstr(const char *s, char *p)
1370 return stack_nputstr(s, strlen(s), p);
1374 _STPUTC(int c, char *p)
1382 #define STARTSTACKSTR(p) ((p) = stackblock())
1383 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1384 #define CHECKSTRSPACE(n, p) \
1388 size_t m = sstrend - q; \
1390 (p) = makestrspace(l, q); \
1392 #define USTPUTC(c, p) (*p++ = (c))
1393 #define STACKSTRNUL(p) \
1395 if ((p) == sstrend) \
1396 p = growstackstr(); \
1399 #define STUNPUTC(p) (--p)
1400 #define STTOPC(p) (p[-1])
1401 #define STADJUST(amount, p) (p += (amount))
1403 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1404 #define ungrabstackstr(s, p) stunalloc((s))
1405 #define stackstrend() ((void *)sstrend)
1408 /* ============ String helpers */
1411 * prefix -- see if pfx is a prefix of string.
1414 prefix(const char *string, const char *pfx)
1417 if (*pfx++ != *string++)
1420 return (char *) string;
1424 * Check for a valid number. This should be elsewhere.
1427 is_number(const char *p)
1432 } while (*++p != '\0');
1437 * Convert a string of digits to an integer, printing an error message on
1441 number(const char *s)
1444 ash_msg_and_raise_error(illnum, s);
1449 * Produce a possibly single quoted string suitable as input to the shell.
1450 * The return string is allocated on the stack.
1453 single_quote(const char *s)
1463 len = strchrnul(s, '\'') - s;
1465 q = p = makestrspace(len + 3, p);
1468 q = memcpy(q, s, len) + len;
1474 len = strspn(s, "'");
1478 q = p = makestrspace(len + 3, p);
1481 q = memcpy(q, s, len) + len;
1490 return stackblock();
1494 /* ============ nextopt */
1496 static char **argptr; /* argument list for builtin commands */
1497 static char *optionarg; /* set by nextopt (like getopt) */
1498 static char *optptr; /* used by nextopt */
1501 * XXX - should get rid of. have all builtins use getopt(3). the
1502 * library getopt must have the BSD extension static variable "optreset"
1503 * otherwise it can't be used within the shell safely.
1505 * Standard option processing (a la getopt) for builtin routines. The
1506 * only argument that is passed to nextopt is the option string; the
1507 * other arguments are unnecessary. It return the character, or '\0' on
1511 nextopt(const char *optstring)
1518 if (p == NULL || *p == '\0') {
1520 if (p == NULL || *p != '-' || *++p == '\0')
1523 if (LONE_DASH(p)) /* check for "--" */
1527 for (q = optstring; *q != c; ) {
1529 ash_msg_and_raise_error("illegal option -%c", c);
1534 if (*p == '\0' && (p = *argptr++) == NULL)
1535 ash_msg_and_raise_error("no arg for -%c option", c);
1544 /* ============ Math support definitions */
1546 #if ENABLE_ASH_MATH_SUPPORT_64
1547 typedef int64_t arith_t;
1548 #define arith_t_type long long
1550 typedef long arith_t;
1551 #define arith_t_type long
1554 #if ENABLE_ASH_MATH_SUPPORT
1555 static arith_t dash_arith(const char *);
1556 static arith_t arith(const char *expr, int *perrcode);
1559 #if ENABLE_ASH_RANDOM_SUPPORT
1560 static unsigned long rseed;
1567 /* ============ Shell variables */
1570 #define VEXPORT 0x01 /* variable is exported */
1571 #define VREADONLY 0x02 /* variable cannot be modified */
1572 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1573 #define VTEXTFIXED 0x08 /* text is statically allocated */
1574 #define VSTACK 0x10 /* text is allocated on the stack */
1575 #define VUNSET 0x20 /* the variable is not set */
1576 #define VNOFUNC 0x40 /* don't call the callback function */
1577 #define VNOSET 0x80 /* do not set variable - just readonly test */
1578 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1580 # define VDYNAMIC 0x200 /* dynamic variable */
1586 static const char defifsvar[] = "IFS= \t\n";
1587 #define defifs (defifsvar + 4)
1589 static const char defifs[] = " \t\n";
1593 int nparam; /* # of positional parameters (without $0) */
1594 unsigned char malloc; /* if parameter list dynamically allocated */
1595 char **p; /* parameter list */
1596 #if ENABLE_ASH_GETOPTS
1597 int optind; /* next parameter to be processed by getopts */
1598 int optoff; /* used by getopts */
1602 static struct shparam shellparam; /* $@ current positional parameters */
1605 * Free the list of positional parameters.
1608 freeparam(volatile struct shparam *param)
1612 if (param->malloc) {
1613 for (ap = param->p; *ap; ap++)
1619 #if ENABLE_ASH_GETOPTS
1621 getoptsreset(const char *value)
1623 shellparam.optind = number(value);
1624 shellparam.optoff = -1;
1629 struct var *next; /* next entry in hash list */
1630 int flags; /* flags are defined above */
1631 const char *text; /* name=value */
1632 void (*func)(const char *); /* function to be called when */
1633 /* the variable gets set/unset */
1637 struct localvar *next; /* next local variable in list */
1638 struct var *vp; /* the variable that was made local */
1639 int flags; /* saved flags */
1640 const char *text; /* saved text */
1643 /* Forward decls for varinit[] */
1644 #if ENABLE_LOCALE_SUPPORT
1646 change_lc_all(const char *value)
1648 if (value && *value != '\0')
1649 setlocale(LC_ALL, value);
1652 change_lc_ctype(const char *value)
1654 if (value && *value != '\0')
1655 setlocale(LC_CTYPE, value);
1659 static void chkmail(void);
1660 static void changemail(const char *);
1662 static void changepath(const char *);
1663 #if ENABLE_ASH_RANDOM_SUPPORT
1664 static void change_random(const char *);
1667 static struct var varinit[] = {
1669 { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
1671 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
1674 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1675 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1677 { NULL, VSTRFIXED|VTEXTFIXED, bb_PATH_root_path, changepath },
1678 { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
1679 { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
1680 { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
1681 #if ENABLE_ASH_GETOPTS
1682 { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1684 #if ENABLE_ASH_RANDOM_SUPPORT
1685 { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1687 #if ENABLE_LOCALE_SUPPORT
1688 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1689 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1691 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1692 { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1696 #define vifs varinit[0]
1698 #define vmail (&vifs)[1]
1699 #define vmpath (&vmail)[1]
1703 #define vpath (&vmpath)[1]
1704 #define vps1 (&vpath)[1]
1705 #define vps2 (&vps1)[1]
1706 #define vps4 (&vps2)[1]
1707 #define voptind (&vps4)[1]
1708 #if ENABLE_ASH_GETOPTS
1709 #define vrandom (&voptind)[1]
1711 #define vrandom (&vps4)[1]
1715 * The following macros access the values of the above variables.
1716 * They have to skip over the name. They return the null string
1717 * for unset variables.
1719 #define ifsval() (vifs.text + 4)
1720 #define ifsset() ((vifs.flags & VUNSET) == 0)
1721 #define mailval() (vmail.text + 5)
1722 #define mpathval() (vmpath.text + 9)
1723 #define pathval() (vpath.text + 5)
1724 #define ps1val() (vps1.text + 4)
1725 #define ps2val() (vps2.text + 4)
1726 #define ps4val() (vps4.text + 4)
1727 #define optindval() (voptind.text + 7)
1729 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1732 * The parsefile structure pointed to by the global variable parsefile
1733 * contains information about the current file being read.
1736 struct redirtab *next;
1741 static struct redirtab *redirlist;
1742 static int nullredirs;
1743 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1747 static struct var *vartab[VTABSIZE];
1749 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1750 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1753 * Return of a legal variable name (a letter or underscore followed by zero or
1754 * more letters, underscores, and digits).
1757 endofname(const char *name)
1765 if (!is_in_name(*p))
1772 * Compares two strings up to the first = or '\0'. The first
1773 * string must be terminated by '='; the second may be terminated by
1774 * either '=' or '\0'.
1777 varcmp(const char *p, const char *q)
1781 while ((c = *p) == (d = *q)) {
1796 varequal(const char *a, const char *b)
1798 return !varcmp(a, b);
1802 * Find the appropriate entry in the hash table from the name.
1804 static struct var **
1805 hashvar(const char *p)
1809 hashval = ((unsigned char) *p) << 4;
1810 while (*p && *p != '=')
1811 hashval += (unsigned char) *p++;
1812 return &vartab[hashval % VTABSIZE];
1816 vpcmp(const void *a, const void *b)
1818 return varcmp(*(const char **)a, *(const char **)b);
1822 * This routine initializes the builtin variables.
1832 * PS1 depends on uid
1834 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1835 vps1.text = "PS1=\\w \\$ ";
1838 vps1.text = "PS1=# ";
1841 end = vp + ARRAY_SIZE(varinit);
1843 vpp = hashvar(vp->text);
1846 } while (++vp < end);
1849 static struct var **
1850 findvar(struct var **vpp, const char *name)
1852 for (; *vpp; vpp = &(*vpp)->next) {
1853 if (varequal((*vpp)->text, name)) {
1861 * Find the value of a variable. Returns NULL if not set.
1864 lookupvar(const char *name)
1868 v = *findvar(hashvar(name), name);
1872 * Dynamic variables are implemented roughly the same way they are
1873 * in bash. Namely, they're "special" so long as they aren't unset.
1874 * As soon as they're unset, they're no longer dynamic, and dynamic
1875 * lookup will no longer happen at that point. -- PFM.
1877 if ((v->flags & VDYNAMIC))
1880 if (!(v->flags & VUNSET))
1881 return strchrnul(v->text, '=') + 1;
1887 * Search the environment of a builtin command.
1890 bltinlookup(const char *name)
1894 for (sp = cmdenviron; sp; sp = sp->next) {
1895 if (varequal(sp->text, name))
1896 return strchrnul(sp->text, '=') + 1;
1898 return lookupvar(name);
1902 * Same as setvar except that the variable and value are passed in
1903 * the first argument as name=value. Since the first argument will
1904 * be actually stored in the table, it should not be a string that
1906 * Called with interrupts off.
1909 setvareq(char *s, int flags)
1911 struct var *vp, **vpp;
1914 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1915 vp = *findvar(vpp, s);
1917 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1920 if (flags & VNOSAVE)
1923 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1929 if (vp->func && (flags & VNOFUNC) == 0)
1930 (*vp->func)(strchrnul(s, '=') + 1);
1932 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1933 free((char*)vp->text);
1935 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1940 vp = ckmalloc(sizeof(*vp));
1945 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1952 * Set the value of a variable. The flags argument is ored with the
1953 * flags of the variable. If val is NULL, the variable is unset.
1956 setvar(const char *name, const char *val, int flags)
1963 q = endofname(name);
1964 p = strchrnul(q, '=');
1966 if (!namelen || p != q)
1967 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1972 vallen = strlen(val);
1975 nameeq = ckmalloc(namelen + vallen + 2);
1976 p = memcpy(nameeq, name, namelen) + namelen;
1979 p = memcpy(p, val, vallen) + vallen;
1982 setvareq(nameeq, flags | VNOSAVE);
1986 #if ENABLE_ASH_GETOPTS
1988 * Safe version of setvar, returns 1 on success 0 on failure.
1991 setvarsafe(const char *name, const char *val, int flags)
1994 volatile int saveint;
1995 struct jmploc *volatile savehandler = exception_handler;
1996 struct jmploc jmploc;
1999 if (setjmp(jmploc.loc))
2002 exception_handler = &jmploc;
2003 setvar(name, val, flags);
2006 exception_handler = savehandler;
2007 RESTORE_INT(saveint);
2013 * Unset the specified variable.
2016 unsetvar(const char *s)
2022 vpp = findvar(hashvar(s), s);
2026 int flags = vp->flags;
2029 if (flags & VREADONLY)
2032 vp->flags &= ~VDYNAMIC;
2036 if ((flags & VSTRFIXED) == 0) {
2038 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2039 free((char*)vp->text);
2045 vp->flags &= ~VEXPORT;
2055 * Process a linked list of variable assignments.
2058 listsetvar(struct strlist *list_set_var, int flags)
2060 struct strlist *lp = list_set_var;
2066 setvareq(lp->text, flags);
2073 * Generate a list of variables satisfying the given conditions.
2076 listvars(int on, int off, char ***end)
2087 for (vp = *vpp; vp; vp = vp->next) {
2088 if ((vp->flags & mask) == on) {
2089 if (ep == stackstrend())
2090 ep = growstackstr();
2091 *ep++ = (char *) vp->text;
2094 } while (++vpp < vartab + VTABSIZE);
2095 if (ep == stackstrend())
2096 ep = growstackstr();
2100 return grabstackstr(ep);
2104 /* ============ Path search helper
2106 * The variable path (passed by reference) should be set to the start
2107 * of the path before the first call; padvance will update
2108 * this value as it proceeds. Successive calls to padvance will return
2109 * the possible path expansions in sequence. If an option (indicated by
2110 * a percent sign) appears in the path entry then the global variable
2111 * pathopt will be set to point to it; otherwise pathopt will be set to
2114 static const char *pathopt; /* set by padvance */
2117 padvance(const char **path, const char *name)
2127 for (p = start; *p && *p != ':' && *p != '%'; p++);
2128 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2129 while (stackblocksize() < len)
2133 memcpy(q, start, p - start);
2141 while (*p && *p != ':') p++;
2147 return stalloc(len);
2151 /* ============ Prompt */
2153 static int doprompt; /* if set, prompt the user */
2154 static int needprompt; /* true if interactive and at start of line */
2156 #if ENABLE_FEATURE_EDITING
2157 static line_input_t *line_input_state;
2158 static const char *cmdedit_prompt;
2160 putprompt(const char *s)
2162 if (ENABLE_ASH_EXPAND_PRMT) {
2163 free((char*)cmdedit_prompt);
2164 cmdedit_prompt = ckstrdup(s);
2171 putprompt(const char *s)
2177 #if ENABLE_ASH_EXPAND_PRMT
2178 /* expandstr() needs parsing machinery, so it is far away ahead... */
2179 static const char *expandstr(const char *ps);
2181 #define expandstr(s) s
2185 setprompt(int whichprompt)
2188 #if ENABLE_ASH_EXPAND_PRMT
2189 struct stackmark smark;
2194 switch (whichprompt) {
2204 #if ENABLE_ASH_EXPAND_PRMT
2205 setstackmark(&smark);
2206 stalloc(stackblocksize());
2208 putprompt(expandstr(prompt));
2209 #if ENABLE_ASH_EXPAND_PRMT
2210 popstackmark(&smark);
2215 /* ============ The cd and pwd commands */
2217 #define CD_PHYSICAL 1
2220 static int docd(const char *, int);
2222 static char *curdir = nullstr; /* current working directory */
2223 static char *physdir = nullstr; /* physical working directory */
2232 while ((i = nextopt("LP"))) {
2234 flags ^= CD_PHYSICAL;
2243 * Update curdir (the name of the current directory) in response to a
2247 updatepwd(const char *dir)
2254 cdcomppath = ststrdup(dir);
2257 if (curdir == nullstr)
2259 new = stack_putstr(curdir, new);
2261 new = makestrspace(strlen(dir) + 2, new);
2262 lim = stackblock() + 1;
2266 if (new > lim && *lim == '/')
2271 if (dir[1] == '/' && dir[2] != '/') {
2277 p = strtok(cdcomppath, "/");
2281 if (p[1] == '.' && p[2] == '\0') {
2293 new = stack_putstr(p, new);
2301 return stackblock();
2305 * Find out what the current directory is. If we already know the current
2306 * directory, this routine returns immediately.
2311 char *dir = getcwd(0, 0);
2312 return dir ? dir : nullstr;
2316 setpwd(const char *val, int setold)
2320 oldcur = dir = curdir;
2323 setvar("OLDPWD", oldcur, VEXPORT);
2326 if (physdir != nullstr) {
2327 if (physdir != oldcur)
2331 if (oldcur == val || !val) {
2337 dir = ckstrdup(val);
2338 if (oldcur != dir && oldcur != nullstr) {
2343 setvar("PWD", dir, VEXPORT);
2346 static void hashcd(void);
2349 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2350 * know that the current directory has changed.
2353 docd(const char *dest, int flags)
2355 const char *dir = 0;
2358 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2361 if (!(flags & CD_PHYSICAL)) {
2362 dir = updatepwd(dest);
2377 cdcmd(int argc, char **argv)
2389 dest = bltinlookup(homestr);
2390 else if (LONE_DASH(dest)) {
2391 dest = bltinlookup("OLDPWD");
2413 path = bltinlookup("CDPATH");
2422 p = padvance(&path, dest);
2423 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2427 if (!docd(p, flags))
2432 ash_msg_and_raise_error("can't cd to %s", dest);
2435 if (flags & CD_PRINT)
2436 out1fmt(snlfmt, curdir);
2441 pwdcmd(int argc, char **argv)
2444 const char *dir = curdir;
2448 if (physdir == nullstr)
2452 out1fmt(snlfmt, dir);
2457 /* ============ ... */
2459 #define IBUFSIZ (BUFSIZ + 1)
2460 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2462 /* Syntax classes */
2463 #define CWORD 0 /* character is nothing special */
2464 #define CNL 1 /* newline character */
2465 #define CBACK 2 /* a backslash character */
2466 #define CSQUOTE 3 /* single quote */
2467 #define CDQUOTE 4 /* double quote */
2468 #define CENDQUOTE 5 /* a terminating quote */
2469 #define CBQUOTE 6 /* backwards single quote */
2470 #define CVAR 7 /* a dollar sign */
2471 #define CENDVAR 8 /* a '}' character */
2472 #define CLP 9 /* a left paren in arithmetic */
2473 #define CRP 10 /* a right paren in arithmetic */
2474 #define CENDFILE 11 /* end of file */
2475 #define CCTL 12 /* like CWORD, except it must be escaped */
2476 #define CSPCL 13 /* these terminate a word */
2477 #define CIGN 14 /* character should be ignored */
2479 #if ENABLE_ASH_ALIAS
2483 #define PEOA_OR_PEOF PEOA
2487 #define PEOA_OR_PEOF PEOF
2490 /* number syntax index */
2491 #define BASESYNTAX 0 /* not in quotes */
2492 #define DQSYNTAX 1 /* in double quotes */
2493 #define SQSYNTAX 2 /* in single quotes */
2494 #define ARISYNTAX 3 /* in arithmetic */
2496 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2497 #define USE_SIT_FUNCTION
2500 #if ENABLE_ASH_MATH_SUPPORT
2501 static const char S_I_T[][4] = {
2502 #if ENABLE_ASH_ALIAS
2503 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2505 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2506 { CNL, CNL, CNL, CNL }, /* 2, \n */
2507 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2508 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2509 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2510 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2511 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2512 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2513 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2514 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2515 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2516 #ifndef USE_SIT_FUNCTION
2517 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2518 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2519 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2523 static const char S_I_T[][3] = {
2524 #if ENABLE_ASH_ALIAS
2525 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2527 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2528 { CNL, CNL, CNL }, /* 2, \n */
2529 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2530 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2531 { CVAR, CVAR, CWORD }, /* 5, $ */
2532 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2533 { CSPCL, CWORD, CWORD }, /* 7, ( */
2534 { CSPCL, CWORD, CWORD }, /* 8, ) */
2535 { CBACK, CBACK, CCTL }, /* 9, \ */
2536 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2537 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2538 #ifndef USE_SIT_FUNCTION
2539 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2540 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2541 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2544 #endif /* ASH_MATH_SUPPORT */
2546 #ifdef USE_SIT_FUNCTION
2549 SIT(int c, int syntax)
2551 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2552 #if ENABLE_ASH_ALIAS
2553 static const char syntax_index_table[] = {
2554 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2555 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2556 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2560 static const char syntax_index_table[] = {
2561 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2562 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2563 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2570 if (c == PEOF) /* 2^8+2 */
2572 #if ENABLE_ASH_ALIAS
2573 if (c == PEOA) /* 2^8+1 */
2577 #define U_C(c) ((unsigned char)(c))
2579 if ((unsigned char)c >= (unsigned char)(CTLESC)
2580 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2584 s = strchr(spec_symbls, c);
2585 if (s == NULL || *s == '\0')
2587 indx = syntax_index_table[(s - spec_symbls)];
2589 return S_I_T[indx][syntax];
2592 #else /* !USE_SIT_FUNCTION */
2594 #if ENABLE_ASH_ALIAS
2595 #define CSPCL_CIGN_CIGN_CIGN 0
2596 #define CSPCL_CWORD_CWORD_CWORD 1
2597 #define CNL_CNL_CNL_CNL 2
2598 #define CWORD_CCTL_CCTL_CWORD 3
2599 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2600 #define CVAR_CVAR_CWORD_CVAR 5
2601 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2602 #define CSPCL_CWORD_CWORD_CLP 7
2603 #define CSPCL_CWORD_CWORD_CRP 8
2604 #define CBACK_CBACK_CCTL_CBACK 9
2605 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2606 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2607 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2608 #define CWORD_CWORD_CWORD_CWORD 13
2609 #define CCTL_CCTL_CCTL_CCTL 14
2611 #define CSPCL_CWORD_CWORD_CWORD 0
2612 #define CNL_CNL_CNL_CNL 1
2613 #define CWORD_CCTL_CCTL_CWORD 2
2614 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2615 #define CVAR_CVAR_CWORD_CVAR 4
2616 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2617 #define CSPCL_CWORD_CWORD_CLP 6
2618 #define CSPCL_CWORD_CWORD_CRP 7
2619 #define CBACK_CBACK_CCTL_CBACK 8
2620 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2621 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2622 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2623 #define CWORD_CWORD_CWORD_CWORD 12
2624 #define CCTL_CCTL_CCTL_CCTL 13
2627 static const char syntax_index_table[258] = {
2628 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2629 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2630 #if ENABLE_ASH_ALIAS
2631 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2633 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2634 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2635 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2636 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2637 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2638 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2639 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2640 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2641 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2642 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2643 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2644 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2645 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2646 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2647 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2648 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2649 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2650 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2651 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2652 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2653 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2654 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2655 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2656 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2657 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2658 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2659 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2660 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2661 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2662 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2663 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2664 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2665 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2666 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2667 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2668 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2669 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2670 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2671 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2672 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2673 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2674 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2675 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2676 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2677 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2678 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2679 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2680 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2681 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2682 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2683 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2684 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2685 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2686 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2687 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2688 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2689 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2690 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2691 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2692 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2693 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2694 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2695 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2696 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2697 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2698 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2699 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2700 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2701 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2702 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2703 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2704 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2705 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2706 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2707 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2708 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2709 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2710 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2711 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2712 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2713 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2714 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2717 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2718 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2719 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2720 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2721 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2722 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2771 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2772 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2794 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2795 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2796 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2798 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2800 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2801 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2802 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2803 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2804 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2806 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2807 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2808 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2809 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2821 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2822 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2824 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2825 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2853 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2854 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2857 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2858 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2861 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2883 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2886 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2887 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2888 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2891 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2893 #endif /* USE_SIT_FUNCTION */
2896 /* ============ Alias handling */
2898 #if ENABLE_ASH_ALIAS
2900 #define ALIASINUSE 1
2912 static struct alias *atab[ATABSIZE];
2914 static struct alias **
2915 __lookupalias(const char *name) {
2916 unsigned int hashval;
2923 ch = (unsigned char)*p;
2927 ch = (unsigned char)*++p;
2929 app = &atab[hashval % ATABSIZE];
2931 for (; *app; app = &(*app)->next) {
2932 if (strcmp(name, (*app)->name) == 0) {
2940 static struct alias *
2941 lookupalias(const char *name, int check)
2943 struct alias *ap = *__lookupalias(name);
2945 if (check && ap && (ap->flag & ALIASINUSE))
2950 static struct alias *
2951 freealias(struct alias *ap)
2955 if (ap->flag & ALIASINUSE) {
2956 ap->flag |= ALIASDEAD;
2968 setalias(const char *name, const char *val)
2970 struct alias *ap, **app;
2972 app = __lookupalias(name);
2976 if (!(ap->flag & ALIASINUSE)) {
2979 ap->val = ckstrdup(val);
2980 ap->flag &= ~ALIASDEAD;
2983 ap = ckmalloc(sizeof(struct alias));
2984 ap->name = ckstrdup(name);
2985 ap->val = ckstrdup(val);
2994 unalias(const char *name)
2998 app = __lookupalias(name);
3002 *app = freealias(*app);
3013 struct alias *ap, **app;
3017 for (i = 0; i < ATABSIZE; i++) {
3019 for (ap = *app; ap; ap = *app) {
3020 *app = freealias(*app);
3030 printalias(const struct alias *ap)
3032 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3036 * TODO - sort output
3039 aliascmd(int argc, char **argv)
3048 for (i = 0; i < ATABSIZE; i++)
3049 for (ap = atab[i]; ap; ap = ap->next) {
3054 while ((n = *++argv) != NULL) {
3055 v = strchr(n+1, '=');
3056 if (v == NULL) { /* n+1: funny ksh stuff */
3057 ap = *__lookupalias(n);
3059 fprintf(stderr, "%s: %s not found\n", "alias", n);
3073 unaliascmd(int argc, char **argv)
3077 while ((i = nextopt("a")) != '\0') {
3083 for (i = 0; *argptr; argptr++) {
3084 if (unalias(*argptr)) {
3085 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3093 #endif /* ASH_ALIAS */
3096 /* ============ jobs.c */
3098 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3101 #define FORK_NOJOB 2
3103 /* mode flags for showjob(s) */
3104 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3105 #define SHOW_PID 0x04 /* include process pid */
3106 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3109 * A job structure contains information about a job. A job is either a
3110 * single process or a set of processes contained in a pipeline. In the
3111 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3116 pid_t pid; /* process id */
3117 int status; /* last process status from wait() */
3118 char *cmd; /* text of command being run */
3122 struct procstat ps0; /* status of process */
3123 struct procstat *ps; /* status or processes when more than one */
3125 int stopstatus; /* status of a stopped job */
3128 nprocs: 16, /* number of processes */
3130 #define JOBRUNNING 0 /* at least one proc running */
3131 #define JOBSTOPPED 1 /* all procs are stopped */
3132 #define JOBDONE 2 /* all procs are completed */
3134 sigint: 1, /* job was killed by SIGINT */
3135 jobctl: 1, /* job running under job control */
3137 waited: 1, /* true if this entry has been waited for */
3138 used: 1, /* true if this entry is in used */
3139 changed: 1; /* true if status has changed */
3140 struct job *prev_job; /* previous job */
3143 static pid_t backgndpid; /* pid of last background process */
3144 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3146 static struct job *makejob(union node *, int);
3147 static int forkshell(struct job *, union node *, int);
3148 static int waitforjob(struct job *);
3151 enum { jobctl = 0 };
3152 #define setjobctl(on) do {} while (0)
3154 static smallint jobctl; /* true if doing job control */
3155 static void setjobctl(int);
3159 * Set the signal handler for the specified signal. The routine figures
3160 * out what it should be set to.
3163 setsignal(int signo)
3167 struct sigaction act;
3172 else if (*t != '\0')
3176 if (rootshell && action == S_DFL) {
3179 if (iflag || minusc || sflag == 0)
3202 t = &sigmode[signo - 1];
3206 * current setting unknown
3208 if (sigaction(signo, 0, &act) == -1) {
3210 * Pretend it worked; maybe we should give a warning
3211 * here, but other shells don't. We don't alter
3212 * sigmode, so that we retry every time.
3216 if (act.sa_handler == SIG_IGN) {
3218 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3220 tsig = S_IGN; /* don't hard ignore these */
3224 tsig = S_RESET; /* force to be set */
3227 if (tsig == S_HARD_IGN || tsig == action)
3231 act.sa_handler = onsig;
3234 act.sa_handler = SIG_IGN;
3237 act.sa_handler = SIG_DFL;
3241 sigfillset(&act.sa_mask);
3242 sigaction(signo, &act, 0);
3245 /* mode flags for set_curjob */
3246 #define CUR_DELETE 2
3247 #define CUR_RUNNING 1
3248 #define CUR_STOPPED 0
3250 /* mode flags for dowait */
3251 #define DOWAIT_NORMAL 0
3252 #define DOWAIT_BLOCK 1
3255 /* pgrp of shell on invocation */
3256 static int initialpgrp;
3257 static int ttyfd = -1;
3260 static struct job *jobtab;
3262 static unsigned njobs;
3264 static struct job *curjob;
3265 /* number of presumed living untracked jobs */
3269 set_curjob(struct job *jp, unsigned mode)
3272 struct job **jpp, **curp;
3274 /* first remove from list */
3275 jpp = curp = &curjob;
3280 jpp = &jp1->prev_job;
3282 *jpp = jp1->prev_job;
3284 /* Then re-insert in correct position */
3292 /* job being deleted */
3295 /* newly created job or backgrounded job,
3296 put after all stopped jobs. */
3300 if (!jp1 || jp1->state != JOBSTOPPED)
3303 jpp = &jp1->prev_job;
3309 /* newly stopped job - becomes curjob */
3310 jp->prev_job = *jpp;
3318 jobno(const struct job *jp)
3320 return jp - jobtab + 1;
3325 * Convert a job name to a job structure.
3328 getjob(const char *name, int getctl)
3332 const char *err_msg = "No such job: %s";
3336 char *(*match)(const char *, const char *);
3351 if (c == '+' || c == '%') {
3353 err_msg = "No current job";
3359 err_msg = "No previous job";
3370 jp = jobtab + num - 1;
3387 if (match(jp->ps[0].cmd, p)) {
3391 err_msg = "%s: ambiguous";
3398 err_msg = "job %s not created under job control";
3399 if (getctl && jp->jobctl == 0)
3404 ash_msg_and_raise_error(err_msg, name);
3408 * Mark a job structure as unused.
3411 freejob(struct job *jp)
3413 struct procstat *ps;
3417 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3418 if (ps->cmd != nullstr)
3421 if (jp->ps != &jp->ps0)
3424 set_curjob(jp, CUR_DELETE);
3430 xtcsetpgrp(int fd, pid_t pgrp)
3432 if (tcsetpgrp(fd, pgrp))
3433 ash_msg_and_raise_error("cannot set tty process group (%m)");
3437 * Turn job control on and off.
3439 * Note: This code assumes that the third arg to ioctl is a character
3440 * pointer, which is true on Berkeley systems but not System V. Since
3441 * System V doesn't have job control yet, this isn't a problem now.
3443 * Called with interrupts off.
3451 if (on == jobctl || rootshell == 0)
3455 ofd = fd = open(_PATH_TTY, O_RDWR);
3457 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3458 * That sometimes helps to acquire controlling tty.
3459 * Obviously, a workaround for bugs when someone
3460 * failed to provide a controlling tty to bash! :) */
3462 while (!isatty(fd) && --fd >= 0)
3465 fd = fcntl(fd, F_DUPFD, 10);
3469 fcntl(fd, F_SETFD, FD_CLOEXEC);
3470 do { /* while we are in the background */
3471 pgrp = tcgetpgrp(fd);
3474 ash_msg("can't access tty; job control turned off");
3478 if (pgrp == getpgrp())
3489 xtcsetpgrp(fd, pgrp);
3491 /* turning job control off */
3494 /* was xtcsetpgrp, but this can make exiting ash
3495 * with pty already deleted loop forever */
3496 tcsetpgrp(fd, pgrp);
3510 killcmd(int argc, char **argv)
3512 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3515 if (argv[i][0] == '%') {
3516 struct job *jp = getjob(argv[i], 0);
3517 unsigned pid = jp->ps[0].pid;
3518 /* Enough space for ' -NNN<nul>' */
3519 argv[i] = alloca(sizeof(int)*3 + 3);
3520 /* kill_main has matching code to expect
3521 * leading space. Needed to not confuse
3522 * negative pids with "kill -SIGNAL_NO" syntax */
3523 sprintf(argv[i], " -%u", pid);
3525 } while (argv[++i]);
3527 return kill_main(argc, argv);
3531 showpipe(struct job *jp, FILE *out)
3533 struct procstat *sp;
3534 struct procstat *spend;
3536 spend = jp->ps + jp->nprocs;
3537 for (sp = jp->ps + 1; sp < spend; sp++)
3538 fprintf(out, " | %s", sp->cmd);
3539 outcslow('\n', out);
3540 flush_stdout_stderr();
3545 restartjob(struct job *jp, int mode)
3547 struct procstat *ps;
3553 if (jp->state == JOBDONE)
3555 jp->state = JOBRUNNING;
3557 if (mode == FORK_FG)
3558 xtcsetpgrp(ttyfd, pgid);
3559 killpg(pgid, SIGCONT);
3563 if (WIFSTOPPED(ps->status)) {
3569 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3575 fg_bgcmd(int argc, char **argv)
3582 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3587 jp = getjob(*argv, 1);
3588 if (mode == FORK_BG) {
3589 set_curjob(jp, CUR_RUNNING);
3590 fprintf(out, "[%d] ", jobno(jp));
3592 outstr(jp->ps->cmd, out);
3594 retval = restartjob(jp, mode);
3595 } while (*argv && *++argv);
3601 sprint_status(char *s, int status, int sigonly)
3607 if (!WIFEXITED(status)) {
3609 if (WIFSTOPPED(status))
3610 st = WSTOPSIG(status);
3613 st = WTERMSIG(status);
3615 if (st == SIGINT || st == SIGPIPE)
3618 if (WIFSTOPPED(status))
3623 col = fmtstr(s, 32, strsignal(st));
3624 if (WCOREDUMP(status)) {
3625 col += fmtstr(s + col, 16, " (core dumped)");
3627 } else if (!sigonly) {
3628 st = WEXITSTATUS(status);
3630 col = fmtstr(s, 16, "Done(%d)", st);
3632 col = fmtstr(s, 16, "Done");
3639 * Do a wait system call. If job control is compiled in, we accept
3640 * stopped processes. If block is zero, we return a value of zero
3641 * rather than blocking.
3643 * System V doesn't have a non-blocking wait system call. It does
3644 * have a SIGCLD signal that is sent to a process when one of it's
3645 * children dies. The obvious way to use SIGCLD would be to install
3646 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3647 * was received, and have waitproc bump another counter when it got
3648 * the status of a process. Waitproc would then know that a wait
3649 * system call would not block if the two counters were different.
3650 * This approach doesn't work because if a process has children that
3651 * have not been waited for, System V will send it a SIGCLD when it
3652 * installs a signal handler for SIGCLD. What this means is that when
3653 * a child exits, the shell will be sent SIGCLD signals continuously
3654 * until is runs out of stack space, unless it does a wait call before
3655 * restoring the signal handler. The code below takes advantage of
3656 * this (mis)feature by installing a signal handler for SIGCLD and
3657 * then checking to see whether it was called. If there are any
3658 * children to be waited for, it will be.
3660 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3661 * waits at all. In this case, the user will not be informed when
3662 * a background process until the next time she runs a real program
3663 * (as opposed to running a builtin command or just typing return),
3664 * and the jobs command may give out of date information.
3667 waitproc(int block, int *status)
3677 return wait3(status, flags, (struct rusage *)NULL);
3681 * Wait for a process to terminate.
3684 dowait(int block, struct job *job)
3689 struct job *thisjob;
3692 TRACE(("dowait(%d) called\n", block));
3693 pid = waitproc(block, &status);
3694 TRACE(("wait returns pid %d, status=%d\n", pid, status));
3699 for (jp = curjob; jp; jp = jp->prev_job) {
3700 struct procstat *sp;
3701 struct procstat *spend;
3702 if (jp->state == JOBDONE)
3705 spend = jp->ps + jp->nprocs;
3708 if (sp->pid == pid) {
3709 TRACE(("Job %d: changing status of proc %d "
3710 "from 0x%x to 0x%x\n",
3711 jobno(jp), pid, sp->status, status));
3712 sp->status = status;
3715 if (sp->status == -1)
3718 if (state == JOBRUNNING)
3720 if (WIFSTOPPED(sp->status)) {
3721 jp->stopstatus = sp->status;
3725 } while (++sp < spend);
3730 if (!WIFSTOPPED(status))
3737 if (state != JOBRUNNING) {
3738 thisjob->changed = 1;
3740 if (thisjob->state != state) {
3741 TRACE(("Job %d: changing state from %d to %d\n",
3742 jobno(thisjob), thisjob->state, state));
3743 thisjob->state = state;
3745 if (state == JOBSTOPPED) {
3746 set_curjob(thisjob, CUR_STOPPED);
3755 if (thisjob && thisjob == job) {
3759 len = sprint_status(s, status, 1);
3771 showjob(FILE *out, struct job *jp, int mode)
3773 struct procstat *ps;
3774 struct procstat *psend;
3781 if (mode & SHOW_PGID) {
3782 /* just output process (group) id of pipeline */
3783 fprintf(out, "%d\n", ps->pid);
3787 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3792 else if (curjob && jp == curjob->prev_job)
3795 if (mode & SHOW_PID)
3796 col += fmtstr(s + col, 16, "%d ", ps->pid);
3798 psend = ps + jp->nprocs;
3800 if (jp->state == JOBRUNNING) {
3801 strcpy(s + col, "Running");
3802 col += sizeof("Running") - 1;
3804 int status = psend[-1].status;
3805 if (jp->state == JOBSTOPPED)
3806 status = jp->stopstatus;
3807 col += sprint_status(s + col, status, 0);
3813 /* for each process */
3814 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3816 fprintf(out, "%s%*c%s",
3817 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3819 if (!(mode & SHOW_PID)) {
3823 if (++ps == psend) {
3824 outcslow('\n', out);
3831 if (jp->state == JOBDONE) {
3832 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3838 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3839 * statuses have changed since the last call to showjobs.
3842 showjobs(FILE *out, int mode)
3846 TRACE(("showjobs(%x) called\n", mode));
3848 /* If not even one one job changed, there is nothing to do */
3849 while (dowait(DOWAIT_NORMAL, NULL) > 0)
3852 for (jp = curjob; jp; jp = jp->prev_job) {
3853 if (!(mode & SHOW_CHANGED) || jp->changed) {
3854 showjob(out, jp, mode);
3860 jobscmd(int argc, char **argv)
3865 while ((m = nextopt("lp"))) {
3875 showjob(stdout, getjob(*argv,0), mode);
3878 showjobs(stdout, mode);
3885 getstatus(struct job *job)
3890 status = job->ps[job->nprocs - 1].status;
3891 retval = WEXITSTATUS(status);
3892 if (!WIFEXITED(status)) {
3894 retval = WSTOPSIG(status);
3895 if (!WIFSTOPPED(status))
3898 /* XXX: limits number of signals */
3899 retval = WTERMSIG(status);
3901 if (retval == SIGINT)
3907 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3908 jobno(job), job->nprocs, status, retval));
3913 waitcmd(int argc, char **argv)
3926 /* wait for all jobs */
3931 /* no running procs */
3934 if (jp->state == JOBRUNNING)
3939 dowait(DOWAIT_BLOCK, 0);
3945 if (**argv != '%') {
3946 pid_t pid = number(*argv);
3950 if (job->ps[job->nprocs - 1].pid == pid)
3952 job = job->prev_job;
3958 job = getjob(*argv, 0);
3959 /* loop until process terminated or stopped */
3960 while (job->state == JOBRUNNING)
3961 dowait(DOWAIT_BLOCK, 0);
3963 retval = getstatus(job);
3977 struct job *jp, *jq;
3979 len = njobs * sizeof(*jp);
3981 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
3983 offset = (char *)jp - (char *)jq;
3985 /* Relocate pointers */
3988 jq = (struct job *)((char *)jq + l);
3992 #define joff(p) ((struct job *)((char *)(p) + l))
3993 #define jmove(p) (p) = (void *)((char *)(p) + offset)
3994 if (joff(jp)->ps == &jq->ps0)
3995 jmove(joff(jp)->ps);
3996 if (joff(jp)->prev_job)
3997 jmove(joff(jp)->prev_job);
4007 jp = (struct job *)((char *)jp + len);
4011 } while (--jq >= jp);
4016 * Return a new job structure.
4017 * Called with interrupts off.
4020 makejob(union node *node, int nprocs)
4025 for (i = njobs, jp = jobtab; ; jp++) {
4032 if (jp->state != JOBDONE || !jp->waited)
4041 memset(jp, 0, sizeof(*jp));
4043 /* jp->jobctl is a bitfield.
4044 * "jp->jobctl |= jobctl" likely to give awful code */
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);
4378 /* Lives far away from here, needed for forkchild */
4379 static void closescript(void);
4380 /* Called after fork(), in child */
4382 forkchild(struct job *jp, union node *n, int mode)
4386 TRACE(("Child shell %d\n", getpid()));
4393 /* do job control only in root shell */
4395 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4398 if (jp->nprocs == 0)
4401 pgrp = jp->ps[0].pid;
4402 /* This can fail because we are doing it in the parent also */
4403 (void)setpgid(0, pgrp);
4404 if (mode == FORK_FG)
4405 xtcsetpgrp(ttyfd, pgrp);
4410 if (mode == FORK_BG) {
4413 if (jp->nprocs == 0) {
4415 if (open(bb_dev_null, O_RDONLY) != 0)
4416 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4419 if (!oldlvl && iflag) {
4425 /* For "jobs | cat" to work like in bash, we must retain list of jobs
4426 * in child, but we do need to remove ourself */
4430 for (jp = curjob; jp; jp = jp->prev_job)
4436 /* Called after fork(), in parent */
4438 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4440 TRACE(("In parent shell: child = %d\n", pid));
4442 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
4447 if (mode != FORK_NOJOB && jp->jobctl) {
4450 if (jp->nprocs == 0)
4453 pgrp = jp->ps[0].pid;
4454 /* This can fail because we are doing it in the child also */
4458 if (mode == FORK_BG) {
4459 backgndpid = pid; /* set $! */
4460 set_curjob(jp, CUR_RUNNING);
4463 struct procstat *ps = &jp->ps[jp->nprocs++];
4469 ps->cmd = commandtext(n);
4475 forkshell(struct job *jp, union node *n, int mode)
4479 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4482 TRACE(("Fork failed, errno=%d", errno));
4485 ash_msg_and_raise_error("cannot fork");
4488 forkchild(jp, n, mode);
4490 forkparent(jp, n, mode, pid);
4495 * Wait for job to finish.
4497 * Under job control we have the problem that while a child process is
4498 * running interrupts generated by the user are sent to the child but not
4499 * to the shell. This means that an infinite loop started by an inter-
4500 * active user may be hard to kill. With job control turned off, an
4501 * interactive user may place an interactive program inside a loop. If
4502 * the interactive program catches interrupts, the user doesn't want
4503 * these interrupts to also abort the loop. The approach we take here
4504 * is to have the shell ignore interrupt signals while waiting for a
4505 * foreground process to terminate, and then send itself an interrupt
4506 * signal if the child process was terminated by an interrupt signal.
4507 * Unfortunately, some programs want to do a bit of cleanup and then
4508 * exit on interrupt; unless these processes terminate themselves by
4509 * sending a signal to themselves (instead of calling exit) they will
4510 * confuse this approach.
4512 * Called with interrupts off.
4515 waitforjob(struct job *jp)
4519 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4520 while (jp->state == JOBRUNNING) {
4521 dowait(DOWAIT_BLOCK, jp);
4526 xtcsetpgrp(ttyfd, rootpid);
4528 * This is truly gross.
4529 * If we're doing job control, then we did a TIOCSPGRP which
4530 * caused us (the shell) to no longer be in the controlling
4531 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4532 * intuit from the subprocess exit status whether a SIGINT
4533 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4538 if (jp->state == JOBDONE)
4545 * return 1 if there are stopped jobs, otherwise 0
4557 if (jp && jp->state == JOBSTOPPED) {
4558 out2str("You have stopped jobs.\n");
4567 /* ============ redir.c
4569 * Code for dealing with input/output redirection.
4572 #define EMPTY -2 /* marks an unused slot in redirtab */
4574 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4576 # define PIPESIZE PIPE_BUF
4580 * Open a file in noclobber mode.
4581 * The code was copied from bash.
4584 noclobberopen(const char *fname)
4587 struct stat finfo, finfo2;
4590 * If the file exists and is a regular file, return an error
4593 r = stat(fname, &finfo);
4594 if (r == 0 && S_ISREG(finfo.st_mode)) {
4600 * If the file was not present (r != 0), make sure we open it
4601 * exclusively so that if it is created before we open it, our open
4602 * will fail. Make sure that we do not truncate an existing file.
4603 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4604 * file was not a regular file, we leave O_EXCL off.
4607 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4608 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4610 /* If the open failed, return the file descriptor right away. */
4615 * OK, the open succeeded, but the file may have been changed from a
4616 * non-regular file to a regular file between the stat and the open.
4617 * We are assuming that the O_EXCL open handles the case where FILENAME
4618 * did not exist and is symlinked to an existing file between the stat
4623 * If we can open it and fstat the file descriptor, and neither check
4624 * revealed that it was a regular file, and the file has not been
4625 * replaced, return the file descriptor.
4627 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4628 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4631 /* The file has been replaced. badness. */
4638 * Handle here documents. Normally we fork off a process to write the
4639 * data to a pipe. If the document is short, we can stuff the data in
4640 * the pipe without forking.
4642 /* openhere needs this forward reference */
4643 static void expandhere(union node *arg, int fd);
4645 openhere(union node *redir)
4651 ash_msg_and_raise_error("pipe call failed");
4652 if (redir->type == NHERE) {
4653 len = strlen(redir->nhere.doc->narg.text);
4654 if (len <= PIPESIZE) {
4655 full_write(pip[1], redir->nhere.doc->narg.text, len);
4659 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4661 signal(SIGINT, SIG_IGN);
4662 signal(SIGQUIT, SIG_IGN);
4663 signal(SIGHUP, SIG_IGN);
4665 signal(SIGTSTP, SIG_IGN);
4667 signal(SIGPIPE, SIG_DFL);
4668 if (redir->type == NHERE)
4669 full_write(pip[1], redir->nhere.doc->narg.text, len);
4671 expandhere(redir->nhere.doc, pip[1]);
4680 openredirect(union node *redir)
4685 switch (redir->nfile.type) {
4687 fname = redir->nfile.expfname;
4688 f = open(fname, O_RDONLY);
4693 fname = redir->nfile.expfname;
4694 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4699 /* Take care of noclobber mode. */
4701 fname = redir->nfile.expfname;
4702 f = noclobberopen(fname);
4709 fname = redir->nfile.expfname;
4710 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4715 fname = redir->nfile.expfname;
4716 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4724 /* Fall through to eliminate warning. */
4731 f = openhere(redir);
4737 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4739 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4743 * Copy a file descriptor to be >= to. Returns -1
4744 * if the source file descriptor is closed, EMPTY if there are no unused
4745 * file descriptors left.
4748 copyfd(int from, int to)
4752 newfd = fcntl(from, F_DUPFD, to);
4754 if (errno == EMFILE)
4756 ash_msg_and_raise_error("%d: %m", from);
4762 dupredirect(union node *redir, int f)
4764 int fd = redir->nfile.fd;
4766 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4767 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4768 copyfd(redir->ndup.dupfd, fd);
4780 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4781 * old file descriptors are stashed away so that the redirection can be
4782 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4783 * standard output, and the standard error if it becomes a duplicate of
4784 * stdout, is saved in memory.
4786 /* flags passed to redirect */
4787 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4788 #define REDIR_SAVEFD2 03 /* set preverrout */
4790 redirect(union node *redir, int flags)
4793 struct redirtab *sv;
4804 if (flags & REDIR_PUSH) {
4806 q = ckmalloc(sizeof(struct redirtab));
4807 q->next = redirlist;
4809 q->nullredirs = nullredirs - 1;
4810 for (i = 0; i < 10; i++)
4811 q->renamed[i] = EMPTY;
4818 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4819 && n->ndup.dupfd == fd)
4820 continue; /* redirect from/to same file descriptor */
4822 newfd = openredirect(n);
4825 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
4826 i = fcntl(fd, F_DUPFD, 10);
4833 ash_msg_and_raise_error("%d: %m", fd);
4843 dupredirect(n, newfd);
4844 } while ((n = n->nfile.next));
4846 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
4847 preverrout_fd = sv->renamed[2];
4851 * Undo the effects of the last redirection.
4856 struct redirtab *rp;
4859 if (--nullredirs >= 0)
4863 for (i = 0; i < 10; i++) {
4864 if (rp->renamed[i] != EMPTY) {
4867 copyfd(rp->renamed[i], i);
4869 close(rp->renamed[i]);
4872 redirlist = rp->next;
4873 nullredirs = rp->nullredirs;
4879 * Undo all redirections. Called on error or interrupt.
4883 * Discard all saved file descriptors.
4886 clearredir(int drop)
4897 redirectsafe(union node *redir, int flags)
4900 volatile int saveint;
4901 struct jmploc *volatile savehandler = exception_handler;
4902 struct jmploc jmploc;
4905 err = setjmp(jmploc.loc) * 2;
4907 exception_handler = &jmploc;
4908 redirect(redir, flags);
4910 exception_handler = savehandler;
4911 if (err && exception != EXERROR)
4912 longjmp(exception_handler->loc, 1);
4913 RESTORE_INT(saveint);
4918 /* ============ Routines to expand arguments to commands
4920 * We have to deal with backquotes, shell variables, and file metacharacters.
4926 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
4927 #define EXP_TILDE 0x2 /* do normal tilde expansion */
4928 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
4929 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
4930 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
4931 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
4932 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
4933 #define EXP_WORD 0x80 /* expand word in parameter expansion */
4934 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
4938 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4939 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4940 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4941 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4942 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4945 * Structure specifying which parts of the string should be searched
4946 * for IFS characters.
4949 struct ifsregion *next; /* next region in list */
4950 int begoff; /* offset of start of region */
4951 int endoff; /* offset of end of region */
4952 int nulonly; /* search for nul bytes only */
4956 struct strlist *list;
4957 struct strlist **lastp;
4960 /* output of current string */
4961 static char *expdest;
4962 /* list of back quote expressions */
4963 static struct nodelist *argbackq;
4964 /* first struct in list of ifs regions */
4965 static struct ifsregion ifsfirst;
4966 /* last struct in list */
4967 static struct ifsregion *ifslastp;
4968 /* holds expanded arg list */
4969 static struct arglist exparg;
4979 expdest = makestrspace(32, expdest);
4980 #if ENABLE_ASH_MATH_SUPPORT_64
4981 len = fmtstr(expdest, 32, "%lld", (long long) num);
4983 len = fmtstr(expdest, 32, "%ld", num);
4985 STADJUST(len, expdest);
4990 esclen(const char *start, const char *p)
4994 while (p > start && *--p == CTLESC) {
5001 * Remove any CTLESC characters from a string.
5004 _rmescapes(char *str, int flag)
5006 static const char qchars[] = { CTLESC, CTLQUOTEMARK, '\0' };
5013 p = strpbrk(str, qchars);
5019 if (flag & RMESCAPE_ALLOC) {
5020 size_t len = p - str;
5021 size_t fulllen = len + strlen(p) + 1;
5023 if (flag & RMESCAPE_GROW) {
5024 r = makestrspace(fulllen, expdest);
5025 } else if (flag & RMESCAPE_HEAP) {
5026 r = ckmalloc(fulllen);
5028 r = stalloc(fulllen);
5032 q = memcpy(q, str, len) + len;
5035 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5036 globbing = flag & RMESCAPE_GLOB;
5037 notescaped = globbing;
5039 if (*p == CTLQUOTEMARK) {
5040 inquotes = ~inquotes;
5042 notescaped = globbing;
5046 /* naked back slash */
5052 if (notescaped && inquotes && *p != '/') {
5056 notescaped = globbing;
5061 if (flag & RMESCAPE_GROW) {
5063 STADJUST(q - r + 1, expdest);
5067 #define rmescapes(p) _rmescapes((p), 0)
5069 #define pmatch(a, b) !fnmatch((a), (b), 0)
5072 * Prepare a pattern for a expmeta (internal glob(3)) call.
5074 * Returns an stalloced string.
5077 preglob(const char *pattern, int quoted, int flag)
5079 flag |= RMESCAPE_GLOB;
5081 flag |= RMESCAPE_QUOTED;
5083 return _rmescapes((char *)pattern, flag);
5087 * Put a string on the stack.
5090 memtodest(const char *p, size_t len, int syntax, int quotes)
5094 q = makestrspace(len * 2, q);
5097 int c = signed_char2int(*p++);
5100 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5109 strtodest(const char *p, int syntax, int quotes)
5111 memtodest(p, strlen(p), syntax, quotes);
5115 * Record the fact that we have to scan this region of the
5116 * string for IFS characters.
5119 recordregion(int start, int end, int nulonly)
5121 struct ifsregion *ifsp;
5123 if (ifslastp == NULL) {
5127 ifsp = ckmalloc(sizeof(*ifsp));
5129 ifslastp->next = ifsp;
5133 ifslastp->begoff = start;
5134 ifslastp->endoff = end;
5135 ifslastp->nulonly = nulonly;
5139 removerecordregions(int endoff)
5141 if (ifslastp == NULL)
5144 if (ifsfirst.endoff > endoff) {
5145 while (ifsfirst.next != NULL) {
5146 struct ifsregion *ifsp;
5148 ifsp = ifsfirst.next->next;
5149 free(ifsfirst.next);
5150 ifsfirst.next = ifsp;
5153 if (ifsfirst.begoff > endoff)
5156 ifslastp = &ifsfirst;
5157 ifsfirst.endoff = endoff;
5162 ifslastp = &ifsfirst;
5163 while (ifslastp->next && ifslastp->next->begoff < endoff)
5164 ifslastp=ifslastp->next;
5165 while (ifslastp->next != NULL) {
5166 struct ifsregion *ifsp;
5168 ifsp = ifslastp->next->next;
5169 free(ifslastp->next);
5170 ifslastp->next = ifsp;
5173 if (ifslastp->endoff > endoff)
5174 ifslastp->endoff = endoff;
5178 exptilde(char *startp, char *p, int flag)
5184 int quotes = flag & (EXP_FULL | EXP_CASE);
5189 while ((c = *++p) != '\0') {
5196 if (flag & EXP_VARTILDE)
5206 if (*name == '\0') {
5207 home = lookupvar(homestr);
5209 pw = getpwnam(name);
5214 if (!home || !*home)
5217 startloc = expdest - (char *)stackblock();
5218 strtodest(home, SQSYNTAX, quotes);
5219 recordregion(startloc, expdest - (char *)stackblock(), 0);
5227 * Execute a command inside back quotes. If it's a builtin command, we
5228 * want to save its output in a block obtained from malloc. Otherwise
5229 * we fork off a subprocess and get the output of the command via a pipe.
5230 * Should be called with interrupts off.
5232 struct backcmd { /* result of evalbackcmd */
5233 int fd; /* file descriptor to read from */
5234 char *buf; /* buffer */
5235 int nleft; /* number of chars in buffer */
5236 struct job *jp; /* job structure for command */
5239 /* These forward decls are needed to use "eval" code for backticks handling: */
5240 static int back_exitstatus; /* exit status of backquoted command */
5241 #define EV_EXIT 01 /* exit after evaluating tree */
5242 static void evaltree(union node *, int);
5245 evalbackcmd(union node *n, struct backcmd *result)
5257 saveherefd = herefd;
5265 ash_msg_and_raise_error("pipe call failed");
5267 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5276 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5280 result->fd = pip[0];
5283 herefd = saveherefd;
5285 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5286 result->fd, result->buf, result->nleft, result->jp));
5290 * Expand stuff in backwards quotes.
5293 expbackq(union node *cmd, int quoted, int quotes)
5301 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5302 struct stackmark smark;
5305 setstackmark(&smark);
5307 startloc = dest - (char *)stackblock();
5309 evalbackcmd(cmd, &in);
5310 popstackmark(&smark);
5317 memtodest(p, i, syntax, quotes);
5321 i = safe_read(in.fd, buf, sizeof(buf));
5322 TRACE(("expbackq: read returns %d\n", i));
5332 back_exitstatus = waitforjob(in.jp);
5336 /* Eat all trailing newlines */
5338 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5343 recordregion(startloc, dest - (char *)stackblock(), 0);
5344 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5345 (dest - (char *)stackblock()) - startloc,
5346 (dest - (char *)stackblock()) - startloc,
5347 stackblock() + startloc));
5350 #if ENABLE_ASH_MATH_SUPPORT
5352 * Expand arithmetic expression. Backup to start of expression,
5353 * evaluate, place result in (backed up) result, adjust string position.
5366 * This routine is slightly over-complicated for
5367 * efficiency. Next we scan backwards looking for the
5368 * start of arithmetic.
5370 start = stackblock();
5377 while (*p != CTLARI) {
5381 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5386 esc = esclen(start, p);
5396 removerecordregions(begoff);
5405 len = cvtnum(dash_arith(p + 2));
5408 recordregion(begoff, begoff + len, 0);
5412 /* argstr needs it */
5413 static char *evalvar(char *p, int flag);
5416 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5417 * characters to allow for further processing. Otherwise treat
5418 * $@ like $* since no splitting will be performed.
5421 argstr(char *p, int flag)
5423 static const char spclchars[] = {
5431 CTLBACKQ | CTLQUOTE,
5432 #if ENABLE_ASH_MATH_SUPPORT
5437 const char *reject = spclchars;
5439 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5440 int breakall = flag & EXP_WORD;
5445 if (!(flag & EXP_VARTILDE)) {
5447 } else if (flag & EXP_VARTILDE2) {
5452 if (flag & EXP_TILDE) {
5458 if (*q == CTLESC && (flag & EXP_QWORD))
5461 p = exptilde(p, q, flag);
5464 startloc = expdest - (char *)stackblock();
5466 length += strcspn(p + length, reject);
5468 if (c && (!(c & 0x80)
5469 #if ENABLE_ASH_MATH_SUPPORT
5473 /* c == '=' || c == ':' || c == CTLENDARI */
5478 expdest = stack_nputstr(p, length, expdest);
5479 newloc = expdest - (char *)stackblock();
5480 if (breakall && !inquotes && newloc > startloc) {
5481 recordregion(startloc, newloc, 0);
5492 if (flag & EXP_VARTILDE2) {
5496 flag |= EXP_VARTILDE2;
5501 * sort of a hack - expand tildes in variable
5502 * assignments (after the first '=' and after ':'s).
5511 case CTLENDVAR: /* ??? */
5514 /* "$@" syntax adherence hack */
5517 !memcmp(p, dolatstr, 4) &&
5518 (p[4] == CTLQUOTEMARK || (
5519 p[4] == CTLENDVAR &&
5520 p[5] == CTLQUOTEMARK
5523 p = evalvar(p + 1, flag) + 1;
5526 inquotes = !inquotes;
5539 p = evalvar(p, flag);
5543 case CTLBACKQ|CTLQUOTE:
5544 expbackq(argbackq->n, c, quotes);
5545 argbackq = argbackq->next;
5547 #if ENABLE_ASH_MATH_SUPPORT
5560 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5571 const char *s = loc2;
5577 match = pmatch(str, s);
5581 if (quotes && *loc == CTLESC)
5590 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5597 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5600 const char *s = loc2;
5605 match = pmatch(str, s);
5612 esc = esclen(startp, loc);
5623 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5625 varunset(const char *end, const char *var, const char *umsg, int varflags)
5631 msg = "parameter not set";
5633 if (*end == CTLENDVAR) {
5634 if (varflags & VSNUL)
5639 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5643 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5647 int saveherefd = herefd;
5648 struct nodelist *saveargbackq = argbackq;
5650 char *rmesc, *rmescend;
5652 char *(*scan)(char *, char *, char *, char *, int , int);
5655 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5656 STPUTC('\0', expdest);
5657 herefd = saveherefd;
5658 argbackq = saveargbackq;
5659 startp = stackblock() + startloc;
5663 setvar(str, startp, 0);
5664 amount = startp - expdest;
5665 STADJUST(amount, expdest);
5669 varunset(p, str, startp, varflags);
5673 subtype -= VSTRIMRIGHT;
5675 if (subtype < 0 || subtype > 3)
5680 rmescend = stackblock() + strloc;
5682 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5683 if (rmesc != startp) {
5685 startp = stackblock() + startloc;
5689 str = stackblock() + strloc;
5690 preglob(str, varflags & VSQUOTE, 0);
5692 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5693 zero = subtype >> 1;
5694 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5695 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5697 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5700 memmove(startp, loc, str - loc);
5701 loc = startp + (str - loc) - 1;
5704 amount = loc - expdest;
5705 STADJUST(amount, expdest);
5711 * Add the value of a specialized variable to the stack string.
5714 varvalue(char *name, int varflags, int flags)
5724 int quoted = varflags & VSQUOTE;
5725 int subtype = varflags & VSTYPE;
5726 int quotes = flags & (EXP_FULL | EXP_CASE);
5728 if (quoted && (flags & EXP_FULL))
5729 sep = 1 << CHAR_BIT;
5731 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5740 num = shellparam.nparam;
5750 p = makestrspace(NOPTS, expdest);
5751 for (i = NOPTS - 1; i >= 0; i--) {
5753 USTPUTC(optletters(i), p);
5764 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5765 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5771 while ((p = *ap++)) {
5774 partlen = strlen(p);
5777 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5778 memtodest(p, partlen, syntax, quotes);
5784 if (subtype == VSPLUS || subtype == VSLENGTH) {
5806 if (num < 0 || num > shellparam.nparam)
5808 p = num ? shellparam.p[num - 1] : arg0;
5811 p = lookupvar(name);
5817 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5818 memtodest(p, len, syntax, quotes);
5822 if (subtype == VSPLUS || subtype == VSLENGTH)
5823 STADJUST(-len, expdest);
5828 * Expand a variable, and return a pointer to the next character in the
5832 evalvar(char *p, int flag)
5845 quotes = flag & (EXP_FULL | EXP_CASE);
5847 subtype = varflags & VSTYPE;
5848 quoted = varflags & VSQUOTE;
5850 easy = (!quoted || (*var == '@' && shellparam.nparam));
5851 startloc = expdest - (char *)stackblock();
5852 p = strchr(p, '=') + 1;
5855 varlen = varvalue(var, varflags, flag);
5856 if (varflags & VSNUL)
5859 if (subtype == VSPLUS) {
5860 varlen = -1 - varlen;
5864 if (subtype == VSMINUS) {
5868 p, flag | EXP_TILDE |
5869 (quoted ? EXP_QWORD : EXP_WORD)
5878 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5880 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5883 * Remove any recorded regions beyond
5886 removerecordregions(startloc);
5896 if (varlen < 0 && uflag)
5897 varunset(p, var, 0, 0);
5899 if (subtype == VSLENGTH) {
5900 cvtnum(varlen > 0 ? varlen : 0);
5904 if (subtype == VSNORMAL) {
5908 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5917 case VSTRIMRIGHTMAX:
5926 * Terminate the string and start recording the pattern
5929 STPUTC('\0', expdest);
5930 patloc = expdest - (char *)stackblock();
5931 if (subevalvar(p, NULL, patloc, subtype,
5932 startloc, varflags, quotes) == 0) {
5933 int amount = expdest - (
5934 (char *)stackblock() + patloc - 1
5936 STADJUST(-amount, expdest);
5938 /* Remove any recorded regions beyond start of variable */
5939 removerecordregions(startloc);
5944 if (subtype != VSNORMAL) { /* skip to end of alternative */
5950 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5952 argbackq = argbackq->next;
5953 } else if (c == CTLVAR) {
5954 if ((*p++ & VSTYPE) != VSNORMAL)
5956 } else if (c == CTLENDVAR) {
5966 * Break the argument string into pieces based upon IFS and add the
5967 * strings to the argument list. The regions of the string to be
5968 * searched for IFS characters have been stored by recordregion.
5971 ifsbreakup(char *string, struct arglist *arglist)
5973 struct ifsregion *ifsp;
5978 const char *ifs, *realifs;
5983 if (ifslastp != NULL) {
5986 realifs = ifsset() ? ifsval() : defifs;
5989 p = string + ifsp->begoff;
5990 nulonly = ifsp->nulonly;
5991 ifs = nulonly ? nullstr : realifs;
5993 while (p < string + ifsp->endoff) {
5997 if (!strchr(ifs, *p)) {
6002 ifsspc = (strchr(defifs, *p) != NULL);
6003 /* Ignore IFS whitespace at start */
6004 if (q == start && ifsspc) {
6010 sp = stalloc(sizeof(*sp));
6012 *arglist->lastp = sp;
6013 arglist->lastp = &sp->next;
6017 if (p >= string + ifsp->endoff) {
6023 if (strchr(ifs, *p) == NULL ) {
6026 } else if (strchr(defifs, *p) == NULL) {
6041 } while (ifsp != NULL);
6050 sp = stalloc(sizeof(*sp));
6052 *arglist->lastp = sp;
6053 arglist->lastp = &sp->next;
6059 struct ifsregion *p;
6064 struct ifsregion *ifsp;
6070 ifsfirst.next = NULL;
6075 * Add a file name to the list.
6078 addfname(const char *name)
6082 sp = stalloc(sizeof(*sp));
6083 sp->text = ststrdup(name);
6085 exparg.lastp = &sp->next;
6088 static char *expdir;
6091 * Do metacharacter (i.e. *, ?, [...]) expansion.
6094 expmeta(char *enddir, char *name)
6109 for (p = name; *p; p++) {
6110 if (*p == '*' || *p == '?')
6112 else if (*p == '[') {
6119 if (*q == '/' || *q == '\0')
6126 } else if (*p == '\\')
6128 else if (*p == '/') {
6135 if (metaflag == 0) { /* we've reached the end of the file name */
6136 if (enddir != expdir)
6144 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6155 } while (p < start);
6157 if (enddir == expdir) {
6159 } else if (enddir == expdir + 1 && *expdir == '/') {
6168 if (enddir != expdir)
6170 if (*endname == 0) {
6182 while (! intpending && (dp = readdir(dirp)) != NULL) {
6183 if (dp->d_name[0] == '.' && ! matchdot)
6185 if (pmatch(start, dp->d_name)) {
6187 strcpy(enddir, dp->d_name);
6190 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6193 expmeta(p, endname);
6202 static struct strlist *
6203 msort(struct strlist *list, int len)
6205 struct strlist *p, *q = NULL;
6206 struct strlist **lpp;
6214 for (n = half; --n >= 0; ) {
6218 q->next = NULL; /* terminate first half of list */
6219 q = msort(list, half); /* sort first half of list */
6220 p = msort(p, len - half); /* sort second half */
6223 #if ENABLE_LOCALE_SUPPORT
6224 if (strcoll(p->text, q->text) < 0)
6226 if (strcmp(p->text, q->text) < 0)
6250 * Sort the results of file name expansion. It calculates the number of
6251 * strings to sort and then calls msort (short for merge sort) to do the
6254 static struct strlist *
6255 expsort(struct strlist *str)
6261 for (sp = str; sp; sp = sp->next)
6263 return msort(str, len);
6267 expandmeta(struct strlist *str, int flag)
6269 static const char metachars[] = {
6272 /* TODO - EXP_REDIR */
6275 struct strlist **savelastp;
6281 if (!strpbrk(str->text, metachars))
6283 savelastp = exparg.lastp;
6286 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6288 int i = strlen(str->text);
6289 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6297 if (exparg.lastp == savelastp) {
6302 *exparg.lastp = str;
6303 rmescapes(str->text);
6304 exparg.lastp = &str->next;
6306 *exparg.lastp = NULL;
6307 *savelastp = sp = expsort(*savelastp);
6308 while (sp->next != NULL)
6310 exparg.lastp = &sp->next;
6317 * Perform variable substitution and command substitution on an argument,
6318 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6319 * perform splitting and file name expansion. When arglist is NULL, perform
6320 * here document expansion.
6323 expandarg(union node *arg, struct arglist *arglist, int flag)
6328 argbackq = arg->narg.backquote;
6329 STARTSTACKSTR(expdest);
6330 ifsfirst.next = NULL;
6332 argstr(arg->narg.text, flag);
6333 p = _STPUTC('\0', expdest);
6335 if (arglist == NULL) {
6336 return; /* here document expanded */
6338 p = grabstackstr(p);
6339 exparg.lastp = &exparg.list;
6343 if (flag & EXP_FULL) {
6344 ifsbreakup(p, &exparg);
6345 *exparg.lastp = NULL;
6346 exparg.lastp = &exparg.list;
6347 expandmeta(exparg.list, flag);
6349 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6351 sp = stalloc(sizeof(*sp));
6354 exparg.lastp = &sp->next;
6358 *exparg.lastp = NULL;
6360 *arglist->lastp = exparg.list;
6361 arglist->lastp = exparg.lastp;
6366 * Expand shell variables and backquotes inside a here document.
6369 expandhere(union node *arg, int fd)
6372 expandarg(arg, (struct arglist *)NULL, 0);
6373 full_write(fd, stackblock(), expdest - (char *)stackblock());
6377 * Returns true if the pattern matches the string.
6380 patmatch(char *pattern, const char *string)
6382 return pmatch(preglob(pattern, 0, 0), string);
6386 * See if a pattern matches in a case statement.
6389 casematch(union node *pattern, char *val)
6391 struct stackmark smark;
6394 setstackmark(&smark);
6395 argbackq = pattern->narg.backquote;
6396 STARTSTACKSTR(expdest);
6398 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6399 STACKSTRNUL(expdest);
6400 result = patmatch(stackblock(), val);
6401 popstackmark(&smark);
6406 /* ============ find_command */
6410 int (*builtin)(int, char **);
6411 /* unsigned flags; */
6413 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6414 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6415 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6421 const struct builtincmd *cmd;
6422 struct funcnode *func;
6425 /* values of cmdtype */
6426 #define CMDUNKNOWN -1 /* no entry in table for command */
6427 #define CMDNORMAL 0 /* command is an executable program */
6428 #define CMDFUNCTION 1 /* command is a shell function */
6429 #define CMDBUILTIN 2 /* command is a shell builtin */
6431 /* action to find_command() */
6432 #define DO_ERR 0x01 /* prints errors */
6433 #define DO_ABS 0x02 /* checks absolute paths */
6434 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6435 #define DO_ALTPATH 0x08 /* using alternate path */
6436 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6438 static void find_command(char *, struct cmdentry *, int, const char *);
6441 /* ============ Hashing commands */
6444 * When commands are first encountered, they are entered in a hash table.
6445 * This ensures that a full path search will not have to be done for them
6446 * on each invocation.
6448 * We should investigate converting to a linear search, even though that
6449 * would make the command name "hash" a misnomer.
6452 #define CMDTABLESIZE 31 /* should be prime */
6453 #define ARB 1 /* actual size determined at run time */
6456 struct tblentry *next; /* next entry in hash chain */
6457 union param param; /* definition of builtin function */
6458 short cmdtype; /* index identifying command */
6459 char rehash; /* if set, cd done since entry created */
6460 char cmdname[ARB]; /* name of command */
6463 static struct tblentry *cmdtable[CMDTABLESIZE];
6464 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6467 tryexec(char *cmd, char **argv, char **envp)
6471 #if ENABLE_FEATURE_SH_STANDALONE
6472 if (strchr(cmd, '/') == NULL) {
6473 const struct bb_applet *a;
6475 a = find_applet_by_name(cmd);
6479 run_current_applet_and_exit(argv);
6481 /* re-exec ourselves with the new arguments */
6482 execve(bb_busybox_exec_path, argv, envp);
6483 /* If they called chroot or otherwise made the binary no longer
6484 * executable, fall through */
6492 execve(cmd, argv, envp);
6493 } while (errno == EINTR);
6495 execve(cmd, argv, envp);
6499 } else if (errno == ENOEXEC) {
6503 for (ap = argv; *ap; ap++)
6505 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6507 ap[0] = cmd = (char *)DEFAULT_SHELL;
6510 while ((*ap++ = *argv++))
6518 * Exec a program. Never returns. If you change this routine, you may
6519 * have to change the find_command routine as well.
6521 #define environment() listvars(VEXPORT, VUNSET, 0)
6522 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6524 shellexec(char **argv, const char *path, int idx)
6532 envp = environment();
6533 if (strchr(argv[0], '/')
6534 #if ENABLE_FEATURE_SH_STANDALONE
6535 || find_applet_by_name(argv[0])
6538 tryexec(argv[0], argv, envp);
6542 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6543 if (--idx < 0 && pathopt == NULL) {
6544 tryexec(cmdname, argv, envp);
6545 if (errno != ENOENT && errno != ENOTDIR)
6552 /* Map to POSIX errors */
6564 exitstatus = exerrno;
6565 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6566 argv[0], e, suppressint ));
6567 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6572 printentry(struct tblentry *cmdp)
6578 idx = cmdp->param.index;
6581 name = padvance(&path, cmdp->cmdname);
6583 } while (--idx >= 0);
6584 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6588 * Clear out command entries. The argument specifies the first entry in
6589 * PATH which has changed.
6592 clearcmdentry(int firstchange)
6594 struct tblentry **tblp;
6595 struct tblentry **pp;
6596 struct tblentry *cmdp;
6599 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6601 while ((cmdp = *pp) != NULL) {
6602 if ((cmdp->cmdtype == CMDNORMAL &&
6603 cmdp->param.index >= firstchange)
6604 || (cmdp->cmdtype == CMDBUILTIN &&
6605 builtinloc >= firstchange)
6618 * Locate a command in the command hash table. If "add" is nonzero,
6619 * add the command to the table if it is not already present. The
6620 * variable "lastcmdentry" is set to point to the address of the link
6621 * pointing to the entry, so that delete_cmd_entry can delete the
6624 * Interrupts must be off if called with add != 0.
6626 static struct tblentry **lastcmdentry;
6628 static struct tblentry *
6629 cmdlookup(const char *name, int add)
6631 unsigned int hashval;
6633 struct tblentry *cmdp;
6634 struct tblentry **pp;
6637 hashval = (unsigned char)*p << 4;
6639 hashval += (unsigned char)*p++;
6641 pp = &cmdtable[hashval % CMDTABLESIZE];
6642 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6643 if (strcmp(cmdp->cmdname, name) == 0)
6647 if (add && cmdp == NULL) {
6648 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6649 + strlen(name) + 1);
6651 cmdp->cmdtype = CMDUNKNOWN;
6652 strcpy(cmdp->cmdname, name);
6659 * Delete the command entry returned on the last lookup.
6662 delete_cmd_entry(void)
6664 struct tblentry *cmdp;
6667 cmdp = *lastcmdentry;
6668 *lastcmdentry = cmdp->next;
6669 if (cmdp->cmdtype == CMDFUNCTION)
6670 freefunc(cmdp->param.func);
6676 * Add a new command entry, replacing any existing command entry for
6677 * the same name - except special builtins.
6680 addcmdentry(char *name, struct cmdentry *entry)
6682 struct tblentry *cmdp;
6684 cmdp = cmdlookup(name, 1);
6685 if (cmdp->cmdtype == CMDFUNCTION) {
6686 freefunc(cmdp->param.func);
6688 cmdp->cmdtype = entry->cmdtype;
6689 cmdp->param = entry->u;
6694 hashcmd(int argc, char **argv)
6696 struct tblentry **pp;
6697 struct tblentry *cmdp;
6699 struct cmdentry entry;
6702 while ((c = nextopt("r")) != '\0') {
6706 if (*argptr == NULL) {
6707 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6708 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6709 if (cmdp->cmdtype == CMDNORMAL)
6716 while ((name = *argptr) != NULL) {
6717 cmdp = cmdlookup(name, 0);
6719 && (cmdp->cmdtype == CMDNORMAL
6720 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
6722 find_command(name, &entry, DO_ERR, pathval());
6723 if (entry.cmdtype == CMDUNKNOWN)
6731 * Called when a cd is done. Marks all commands so the next time they
6732 * are executed they will be rehashed.
6737 struct tblentry **pp;
6738 struct tblentry *cmdp;
6740 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6741 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6742 if (cmdp->cmdtype == CMDNORMAL || (
6743 cmdp->cmdtype == CMDBUILTIN &&
6744 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
6753 * Fix command hash table when PATH changed.
6754 * Called before PATH is changed. The argument is the new value of PATH;
6755 * pathval() still returns the old value at this point.
6756 * Called with interrupts off.
6759 changepath(const char *newval)
6761 const char *old, *new;
6768 firstchange = 9999; /* assume no change */
6774 if ((*old == '\0' && *new == ':')
6775 || (*old == ':' && *new == '\0'))
6777 old = new; /* ignore subsequent differences */
6781 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6788 if (builtinloc < 0 && idx_bltin >= 0)
6789 builtinloc = idx_bltin; /* zap builtins */
6790 if (builtinloc >= 0 && idx_bltin < 0)
6792 clearcmdentry(firstchange);
6793 builtinloc = idx_bltin;
6808 #define TENDBQUOTE 12
6826 /* first char is indicating which tokens mark the end of a list */
6827 static const char *const tokname_array[] = {
6841 #define KWDOFFSET 13
6842 /* the following are keywords */
6864 static char buf[16];
6867 //if (tok < TSEMI) return tokname_array[tok] + 1;
6868 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6873 sprintf(buf + (tok >= TSEMI), "%s%c",
6874 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6878 /* Wrapper around strcmp for qsort/bsearch/... */
6880 pstrcmp(const void *a, const void *b)
6882 return strcmp((char*) a, (*(char**) b) + 1);
6885 static const char *const *
6886 findkwd(const char *s)
6888 return bsearch(s, tokname_array + KWDOFFSET,
6889 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6890 sizeof(tokname_array[0]), pstrcmp);
6894 * Locate and print what a word is...
6897 describe_command(char *command, int describe_command_verbose)
6899 struct cmdentry entry;
6900 struct tblentry *cmdp;
6901 #if ENABLE_ASH_ALIAS
6902 const struct alias *ap;
6904 const char *path = pathval();
6906 if (describe_command_verbose) {
6910 /* First look at the keywords */
6911 if (findkwd(command)) {
6912 out1str(describe_command_verbose ? " is a shell keyword" : command);
6916 #if ENABLE_ASH_ALIAS
6917 /* Then look at the aliases */
6918 ap = lookupalias(command, 0);
6920 if (!describe_command_verbose) {
6925 out1fmt(" is an alias for %s", ap->val);
6929 /* Then check if it is a tracked alias */
6930 cmdp = cmdlookup(command, 0);
6932 entry.cmdtype = cmdp->cmdtype;
6933 entry.u = cmdp->param;
6935 /* Finally use brute force */
6936 find_command(command, &entry, DO_ABS, path);
6939 switch (entry.cmdtype) {
6941 int j = entry.u.index;
6947 p = padvance(&path, command);
6951 if (describe_command_verbose) {
6953 (cmdp ? " a tracked alias for" : nullstr), p
6962 if (describe_command_verbose) {
6963 out1str(" is a shell function");
6970 if (describe_command_verbose) {
6971 out1fmt(" is a %sshell builtin",
6972 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
6973 "special " : nullstr
6981 if (describe_command_verbose) {
6982 out1str(": not found\n");
6987 outstr("\n", stdout);
6992 typecmd(int argc, char **argv)
6998 /* type -p ... ? (we don't bother checking for 'p') */
6999 if (argv[1] && argv[1][0] == '-') {
7004 err |= describe_command(argv[i++], verbose);
7009 #if ENABLE_ASH_CMDCMD
7011 commandcmd(int argc, char **argv)
7019 while ((c = nextopt("pvV")) != '\0')
7021 verify |= VERIFY_VERBOSE;
7023 verify |= VERIFY_BRIEF;
7029 return describe_command(*argptr, verify - VERIFY_BRIEF);
7036 /* ============ eval.c */
7038 static int funcblocksize; /* size of structures in function */
7039 static int funcstringsize; /* size of strings in node */
7040 static void *funcblock; /* block to allocate function from */
7041 static char *funcstring; /* block to allocate strings from */
7043 /* flags in argument to evaltree */
7044 #define EV_EXIT 01 /* exit after evaluating tree */
7045 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7046 #define EV_BACKCMD 04 /* command executing within back quotes */
7048 static const short nodesize[26] = {
7049 SHELL_ALIGN(sizeof(struct ncmd)),
7050 SHELL_ALIGN(sizeof(struct npipe)),
7051 SHELL_ALIGN(sizeof(struct nredir)),
7052 SHELL_ALIGN(sizeof(struct nredir)),
7053 SHELL_ALIGN(sizeof(struct nredir)),
7054 SHELL_ALIGN(sizeof(struct nbinary)),
7055 SHELL_ALIGN(sizeof(struct nbinary)),
7056 SHELL_ALIGN(sizeof(struct nbinary)),
7057 SHELL_ALIGN(sizeof(struct nif)),
7058 SHELL_ALIGN(sizeof(struct nbinary)),
7059 SHELL_ALIGN(sizeof(struct nbinary)),
7060 SHELL_ALIGN(sizeof(struct nfor)),
7061 SHELL_ALIGN(sizeof(struct ncase)),
7062 SHELL_ALIGN(sizeof(struct nclist)),
7063 SHELL_ALIGN(sizeof(struct narg)),
7064 SHELL_ALIGN(sizeof(struct narg)),
7065 SHELL_ALIGN(sizeof(struct nfile)),
7066 SHELL_ALIGN(sizeof(struct nfile)),
7067 SHELL_ALIGN(sizeof(struct nfile)),
7068 SHELL_ALIGN(sizeof(struct nfile)),
7069 SHELL_ALIGN(sizeof(struct nfile)),
7070 SHELL_ALIGN(sizeof(struct ndup)),
7071 SHELL_ALIGN(sizeof(struct ndup)),
7072 SHELL_ALIGN(sizeof(struct nhere)),
7073 SHELL_ALIGN(sizeof(struct nhere)),
7074 SHELL_ALIGN(sizeof(struct nnot)),
7077 static void calcsize(union node *n);
7080 sizenodelist(struct nodelist *lp)
7083 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7090 calcsize(union node *n)
7094 funcblocksize += nodesize[n->type];
7097 calcsize(n->ncmd.redirect);
7098 calcsize(n->ncmd.args);
7099 calcsize(n->ncmd.assign);
7102 sizenodelist(n->npipe.cmdlist);
7107 calcsize(n->nredir.redirect);
7108 calcsize(n->nredir.n);
7115 calcsize(n->nbinary.ch2);
7116 calcsize(n->nbinary.ch1);
7119 calcsize(n->nif.elsepart);
7120 calcsize(n->nif.ifpart);
7121 calcsize(n->nif.test);
7124 funcstringsize += strlen(n->nfor.var) + 1;
7125 calcsize(n->nfor.body);
7126 calcsize(n->nfor.args);
7129 calcsize(n->ncase.cases);
7130 calcsize(n->ncase.expr);
7133 calcsize(n->nclist.body);
7134 calcsize(n->nclist.pattern);
7135 calcsize(n->nclist.next);
7139 sizenodelist(n->narg.backquote);
7140 funcstringsize += strlen(n->narg.text) + 1;
7141 calcsize(n->narg.next);
7148 calcsize(n->nfile.fname);
7149 calcsize(n->nfile.next);
7153 calcsize(n->ndup.vname);
7154 calcsize(n->ndup.next);
7158 calcsize(n->nhere.doc);
7159 calcsize(n->nhere.next);
7162 calcsize(n->nnot.com);
7168 nodeckstrdup(char *s)
7170 char *rtn = funcstring;
7172 strcpy(funcstring, s);
7173 funcstring += strlen(s) + 1;
7177 static union node *copynode(union node *);
7179 static struct nodelist *
7180 copynodelist(struct nodelist *lp)
7182 struct nodelist *start;
7183 struct nodelist **lpp;
7188 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7189 (*lpp)->n = copynode(lp->n);
7191 lpp = &(*lpp)->next;
7198 copynode(union node *n)
7205 funcblock = (char *) funcblock + nodesize[n->type];
7209 new->ncmd.redirect = copynode(n->ncmd.redirect);
7210 new->ncmd.args = copynode(n->ncmd.args);
7211 new->ncmd.assign = copynode(n->ncmd.assign);
7214 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7215 new->npipe.backgnd = n->npipe.backgnd;
7220 new->nredir.redirect = copynode(n->nredir.redirect);
7221 new->nredir.n = copynode(n->nredir.n);
7228 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7229 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7232 new->nif.elsepart = copynode(n->nif.elsepart);
7233 new->nif.ifpart = copynode(n->nif.ifpart);
7234 new->nif.test = copynode(n->nif.test);
7237 new->nfor.var = nodeckstrdup(n->nfor.var);
7238 new->nfor.body = copynode(n->nfor.body);
7239 new->nfor.args = copynode(n->nfor.args);
7242 new->ncase.cases = copynode(n->ncase.cases);
7243 new->ncase.expr = copynode(n->ncase.expr);
7246 new->nclist.body = copynode(n->nclist.body);
7247 new->nclist.pattern = copynode(n->nclist.pattern);
7248 new->nclist.next = copynode(n->nclist.next);
7252 new->narg.backquote = copynodelist(n->narg.backquote);
7253 new->narg.text = nodeckstrdup(n->narg.text);
7254 new->narg.next = copynode(n->narg.next);
7261 new->nfile.fname = copynode(n->nfile.fname);
7262 new->nfile.fd = n->nfile.fd;
7263 new->nfile.next = copynode(n->nfile.next);
7267 new->ndup.vname = copynode(n->ndup.vname);
7268 new->ndup.dupfd = n->ndup.dupfd;
7269 new->ndup.fd = n->ndup.fd;
7270 new->ndup.next = copynode(n->ndup.next);
7274 new->nhere.doc = copynode(n->nhere.doc);
7275 new->nhere.fd = n->nhere.fd;
7276 new->nhere.next = copynode(n->nhere.next);
7279 new->nnot.com = copynode(n->nnot.com);
7282 new->type = n->type;
7287 * Make a copy of a parse tree.
7289 static struct funcnode *
7290 copyfunc(union node *n)
7295 funcblocksize = offsetof(struct funcnode, n);
7298 blocksize = funcblocksize;
7299 f = ckmalloc(blocksize + funcstringsize);
7300 funcblock = (char *) f + offsetof(struct funcnode, n);
7301 funcstring = (char *) f + blocksize;
7308 * Define a shell function.
7311 defun(char *name, union node *func)
7313 struct cmdentry entry;
7316 entry.cmdtype = CMDFUNCTION;
7317 entry.u.func = copyfunc(func);
7318 addcmdentry(name, &entry);
7322 static int evalskip; /* set if we are skipping commands */
7323 /* reasons for skipping commands (see comment on breakcmd routine) */
7324 #define SKIPBREAK (1 << 0)
7325 #define SKIPCONT (1 << 1)
7326 #define SKIPFUNC (1 << 2)
7327 #define SKIPFILE (1 << 3)
7328 #define SKIPEVAL (1 << 4)
7329 static int skipcount; /* number of levels to skip */
7330 static int funcnest; /* depth of function calls */
7332 /* forward decl way out to parsing code - dotrap needs it */
7333 static int evalstring(char *s, int mask);
7336 * Called to execute a trap. Perhaps we should avoid entering new trap
7337 * handlers while we are executing a trap handler.
7348 savestatus = exitstatus;
7352 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7360 skip = evalstring(p, SKIPEVAL);
7361 exitstatus = savestatus;
7369 /* forward declarations - evaluation is fairly recursive business... */
7370 static void evalloop(union node *, int);
7371 static void evalfor(union node *, int);
7372 static void evalcase(union node *, int);
7373 static void evalsubshell(union node *, int);
7374 static void expredir(union node *);
7375 static void evalpipe(union node *, int);
7376 static void evalcommand(union node *, int);
7377 static int evalbltin(const struct builtincmd *, int, char **);
7378 static void prehash(union node *);
7381 * Evaluate a parse tree. The value is left in the global variable
7385 evaltree(union node *n, int flags)
7388 void (*evalfn)(union node *, int);
7392 TRACE(("evaltree(NULL) called\n"));
7395 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7396 getpid(), n, n->type, flags));
7400 out1fmt("Node type = %d\n", n->type);
7405 evaltree(n->nnot.com, EV_TESTED);
7406 status = !exitstatus;
7409 expredir(n->nredir.redirect);
7410 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7412 evaltree(n->nredir.n, flags & EV_TESTED);
7413 status = exitstatus;
7418 evalfn = evalcommand;
7420 if (eflag && !(flags & EV_TESTED))
7432 evalfn = evalsubshell;
7444 #error NAND + 1 != NOR
7446 #if NOR + 1 != NSEMI
7447 #error NOR + 1 != NSEMI
7449 isor = n->type - NAND;
7452 (flags | ((isor >> 1) - 1)) & EV_TESTED
7454 if (!exitstatus == isor)
7466 evaltree(n->nif.test, EV_TESTED);
7469 if (exitstatus == 0) {
7472 } else if (n->nif.elsepart) {
7473 n = n->nif.elsepart;
7478 defun(n->narg.text, n->narg.next);
7482 exitstatus = status;
7486 if ((checkexit & exitstatus))
7487 evalskip |= SKIPEVAL;
7488 else if (pendingsig && dotrap())
7491 if (flags & EV_EXIT) {
7493 raise_exception(EXEXIT);
7497 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7500 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7502 static int loopnest; /* current loop nesting level */
7505 evalloop(union node *n, int flags)
7515 evaltree(n->nbinary.ch1, EV_TESTED);
7518 if (evalskip == SKIPCONT && --skipcount <= 0) {
7522 if (evalskip == SKIPBREAK && --skipcount <= 0)
7527 if (n->type != NWHILE)
7531 evaltree(n->nbinary.ch2, flags);
7532 status = exitstatus;
7537 exitstatus = status;
7541 evalfor(union node *n, int flags)
7543 struct arglist arglist;
7546 struct stackmark smark;
7548 setstackmark(&smark);
7549 arglist.lastp = &arglist.list;
7550 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7551 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7556 *arglist.lastp = NULL;
7561 for (sp = arglist.list; sp; sp = sp->next) {
7562 setvar(n->nfor.var, sp->text, 0);
7563 evaltree(n->nfor.body, flags);
7565 if (evalskip == SKIPCONT && --skipcount <= 0) {
7569 if (evalskip == SKIPBREAK && --skipcount <= 0)
7576 popstackmark(&smark);
7580 evalcase(union node *n, int flags)
7584 struct arglist arglist;
7585 struct stackmark smark;
7587 setstackmark(&smark);
7588 arglist.lastp = &arglist.list;
7589 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7591 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7592 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7593 if (casematch(patp, arglist.list->text)) {
7594 if (evalskip == 0) {
7595 evaltree(cp->nclist.body, flags);
7602 popstackmark(&smark);
7606 * Kick off a subshell to evaluate a tree.
7609 evalsubshell(union node *n, int flags)
7612 int backgnd = (n->type == NBACKGND);
7615 expredir(n->nredir.redirect);
7616 if (!backgnd && flags & EV_EXIT && !trap[0])
7620 if (forkshell(jp, n, backgnd) == 0) {
7624 flags &=~ EV_TESTED;
7626 redirect(n->nredir.redirect, 0);
7627 evaltreenr(n->nredir.n, flags);
7632 status = waitforjob(jp);
7633 exitstatus = status;
7638 * Compute the names of the files in a redirection list.
7640 static void fixredir(union node *, const char *, int);
7642 expredir(union node *n)
7646 for (redir = n; redir; redir = redir->nfile.next) {
7649 memset(&fn, 0, sizeof(fn));
7650 fn.lastp = &fn.list;
7651 switch (redir->type) {
7657 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7658 redir->nfile.expfname = fn.list->text;
7662 if (redir->ndup.vname) {
7663 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7664 if (fn.list == NULL)
7665 ash_msg_and_raise_error("redir error");
7666 fixredir(redir, fn.list->text, 1);
7674 * Evaluate a pipeline. All the processes in the pipeline are children
7675 * of the process creating the pipeline. (This differs from some versions
7676 * of the shell, which make the last process in a pipeline the parent
7680 evalpipe(union node *n, int flags)
7683 struct nodelist *lp;
7688 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7690 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7694 jp = makejob(n, pipelen);
7696 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7700 if (pipe(pip) < 0) {
7702 ash_msg_and_raise_error("pipe call failed");
7705 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7718 evaltreenr(lp->n, flags);
7726 if (n->npipe.backgnd == 0) {
7727 exitstatus = waitforjob(jp);
7728 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7734 * Controls whether the shell is interactive or not.
7737 setinteractive(int on)
7739 static int is_interactive;
7741 if (++on == is_interactive)
7743 is_interactive = on;
7747 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7748 if (is_interactive > 1) {
7749 /* Looks like they want an interactive shell */
7750 static smallint did_banner;
7755 "%s built-in shell (ash)\n"
7756 "Enter 'help' for a list of built-in commands."
7765 #if ENABLE_FEATURE_EDITING_VI
7766 #define setvimode(on) do { \
7767 if (on) line_input_state->flags |= VI_MODE; \
7768 else line_input_state->flags &= ~VI_MODE; \
7771 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7780 setinteractive(iflag);
7785 static struct localvar *localvars;
7788 * Called after a function returns.
7789 * Interrupts must be off.
7794 struct localvar *lvp;
7797 while ((lvp = localvars) != NULL) {
7798 localvars = lvp->next;
7800 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7801 if (vp == NULL) { /* $- saved */
7802 memcpy(optlist, lvp->text, sizeof(optlist));
7803 free((char*)lvp->text);
7805 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7809 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7810 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7811 free((char*)vp->text);
7812 vp->flags = lvp->flags;
7813 vp->text = lvp->text;
7820 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7822 volatile struct shparam saveparam;
7823 struct localvar *volatile savelocalvars;
7824 struct jmploc *volatile savehandler;
7825 struct jmploc jmploc;
7828 saveparam = shellparam;
7829 savelocalvars = localvars;
7830 e = setjmp(jmploc.loc);
7835 savehandler = exception_handler;
7836 exception_handler = &jmploc;
7838 shellparam.malloc = 0;
7842 shellparam.nparam = argc - 1;
7843 shellparam.p = argv + 1;
7844 #if ENABLE_ASH_GETOPTS
7845 shellparam.optind = 1;
7846 shellparam.optoff = -1;
7848 evaltree(&func->n, flags & EV_TESTED);
7854 localvars = savelocalvars;
7855 freeparam(&shellparam);
7856 shellparam = saveparam;
7857 exception_handler = savehandler;
7859 evalskip &= ~SKIPFUNC;
7863 #if ENABLE_ASH_CMDCMD
7865 parse_command_args(char **argv, const char **path)
7878 if (c == '-' && !*cp) {
7885 *path = bb_default_path;
7888 /* run 'typecmd' for other options */
7899 * Make a variable a local variable. When a variable is made local, it's
7900 * value and flags are saved in a localvar structure. The saved values
7901 * will be restored when the shell function returns. We handle the name
7902 * "-" as a special case.
7907 struct localvar *lvp;
7912 lvp = ckmalloc(sizeof(struct localvar));
7913 if (LONE_DASH(name)) {
7915 p = ckmalloc(sizeof(optlist));
7916 lvp->text = memcpy(p, optlist, sizeof(optlist));
7921 vpp = hashvar(name);
7922 vp = *findvar(vpp, name);
7923 eq = strchr(name, '=');
7926 setvareq(name, VSTRFIXED);
7928 setvar(name, NULL, VSTRFIXED);
7929 vp = *vpp; /* the new variable */
7930 lvp->flags = VUNSET;
7932 lvp->text = vp->text;
7933 lvp->flags = vp->flags;
7934 vp->flags |= VSTRFIXED|VTEXTFIXED;
7940 lvp->next = localvars;
7946 * The "local" command.
7949 localcmd(int argc, char **argv)
7954 while ((name = *argv++) != NULL) {
7961 falsecmd(int argc, char **argv)
7967 truecmd(int argc, char **argv)
7973 execcmd(int argc, char **argv)
7976 iflag = 0; /* exit on error */
7979 shellexec(argv + 1, pathval(), 0);
7985 * The return command.
7988 returncmd(int argc, char **argv)
7991 * If called outside a function, do what ksh does;
7992 * skip the rest of the file.
7994 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
7995 return argv[1] ? number(argv[1]) : exitstatus;
7998 /* Forward declarations for builtintab[] */
7999 static int breakcmd(int, char **);
8000 static int dotcmd(int, char **);
8001 static int evalcmd(int, char **);
8002 #if ENABLE_ASH_BUILTIN_ECHO
8003 static int echocmd(int, char **);
8005 #if ENABLE_ASH_BUILTIN_TEST
8006 static int testcmd(int, char **);
8008 static int exitcmd(int, char **);
8009 static int exportcmd(int, char **);
8010 #if ENABLE_ASH_GETOPTS
8011 static int getoptscmd(int, char **);
8013 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8014 static int helpcmd(int argc, char **argv);
8016 #if ENABLE_ASH_MATH_SUPPORT
8017 static int letcmd(int, char **);
8019 static int readcmd(int, char **);
8020 static int setcmd(int, char **);
8021 static int shiftcmd(int, char **);
8022 static int timescmd(int, char **);
8023 static int trapcmd(int, char **);
8024 static int umaskcmd(int, char **);
8025 static int unsetcmd(int, char **);
8026 static int ulimitcmd(int, char **);
8028 #define BUILTIN_NOSPEC "0"
8029 #define BUILTIN_SPECIAL "1"
8030 #define BUILTIN_REGULAR "2"
8031 #define BUILTIN_SPEC_REG "3"
8032 #define BUILTIN_ASSIGN "4"
8033 #define BUILTIN_SPEC_ASSG "5"
8034 #define BUILTIN_REG_ASSG "6"
8035 #define BUILTIN_SPEC_REG_ASSG "7"
8037 /* make sure to keep these in proper order since it is searched via bsearch() */
8038 static const struct builtincmd builtintab[] = {
8039 { BUILTIN_SPEC_REG ".", dotcmd },
8040 { BUILTIN_SPEC_REG ":", truecmd },
8041 #if ENABLE_ASH_BUILTIN_TEST
8042 { BUILTIN_REGULAR "[", testcmd },
8043 { BUILTIN_REGULAR "[[", testcmd },
8045 #if ENABLE_ASH_ALIAS
8046 { BUILTIN_REG_ASSG "alias", aliascmd },
8049 { BUILTIN_REGULAR "bg", fg_bgcmd },
8051 { BUILTIN_SPEC_REG "break", breakcmd },
8052 { BUILTIN_REGULAR "cd", cdcmd },
8053 { BUILTIN_NOSPEC "chdir", cdcmd },
8054 #if ENABLE_ASH_CMDCMD
8055 { BUILTIN_REGULAR "command", commandcmd },
8057 { BUILTIN_SPEC_REG "continue", breakcmd },
8058 #if ENABLE_ASH_BUILTIN_ECHO
8059 { BUILTIN_REGULAR "echo", echocmd },
8061 { BUILTIN_SPEC_REG "eval", evalcmd },
8062 { BUILTIN_SPEC_REG "exec", execcmd },
8063 { BUILTIN_SPEC_REG "exit", exitcmd },
8064 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8065 { BUILTIN_REGULAR "false", falsecmd },
8067 { BUILTIN_REGULAR "fg", fg_bgcmd },
8069 #if ENABLE_ASH_GETOPTS
8070 { BUILTIN_REGULAR "getopts", getoptscmd },
8072 { BUILTIN_NOSPEC "hash", hashcmd },
8073 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8074 { BUILTIN_NOSPEC "help", helpcmd },
8077 { BUILTIN_REGULAR "jobs", jobscmd },
8078 { BUILTIN_REGULAR "kill", killcmd },
8080 #if ENABLE_ASH_MATH_SUPPORT
8081 { BUILTIN_NOSPEC "let", letcmd },
8083 { BUILTIN_ASSIGN "local", localcmd },
8084 { BUILTIN_NOSPEC "pwd", pwdcmd },
8085 { BUILTIN_REGULAR "read", readcmd },
8086 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8087 { BUILTIN_SPEC_REG "return", returncmd },
8088 { BUILTIN_SPEC_REG "set", setcmd },
8089 { BUILTIN_SPEC_REG "shift", shiftcmd },
8090 { BUILTIN_SPEC_REG "source", dotcmd },
8091 #if ENABLE_ASH_BUILTIN_TEST
8092 { BUILTIN_REGULAR "test", testcmd },
8094 { BUILTIN_SPEC_REG "times", timescmd },
8095 { BUILTIN_SPEC_REG "trap", trapcmd },
8096 { BUILTIN_REGULAR "true", truecmd },
8097 { BUILTIN_NOSPEC "type", typecmd },
8098 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8099 { BUILTIN_REGULAR "umask", umaskcmd },
8100 #if ENABLE_ASH_ALIAS
8101 { BUILTIN_REGULAR "unalias", unaliascmd },
8103 { BUILTIN_SPEC_REG "unset", unsetcmd },
8104 { BUILTIN_REGULAR "wait", waitcmd },
8108 #define COMMANDCMD (builtintab + 5 + \
8109 2 * ENABLE_ASH_BUILTIN_TEST + \
8110 ENABLE_ASH_ALIAS + \
8111 ENABLE_ASH_JOB_CONTROL)
8112 #define EXECCMD (builtintab + 7 + \
8113 2 * ENABLE_ASH_BUILTIN_TEST + \
8114 ENABLE_ASH_ALIAS + \
8115 ENABLE_ASH_JOB_CONTROL + \
8116 ENABLE_ASH_CMDCMD + \
8117 ENABLE_ASH_BUILTIN_ECHO)
8120 * Search the table of builtin commands.
8122 static struct builtincmd *
8123 find_builtin(const char *name)
8125 struct builtincmd *bp;
8128 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8135 * Execute a simple command.
8137 static int back_exitstatus; /* exit status of backquoted command */
8139 isassignment(const char *p)
8141 const char *q = endofname(p);
8147 bltincmd(int argc, char **argv)
8149 /* Preserve exitstatus of a previous possible redirection
8150 * as POSIX mandates */
8151 return back_exitstatus;
8154 evalcommand(union node *cmd, int flags)
8156 static const struct builtincmd bltin = {
8159 struct stackmark smark;
8161 struct arglist arglist;
8162 struct arglist varlist;
8165 const struct strlist *sp;
8166 struct cmdentry cmdentry;
8174 struct builtincmd *bcmd;
8175 int pseudovarflag = 0;
8177 /* First expand the arguments. */
8178 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8179 setstackmark(&smark);
8180 back_exitstatus = 0;
8182 cmdentry.cmdtype = CMDBUILTIN;
8183 cmdentry.u.cmd = &bltin;
8184 varlist.lastp = &varlist.list;
8185 *varlist.lastp = NULL;
8186 arglist.lastp = &arglist.list;
8187 *arglist.lastp = NULL;
8190 if (cmd->ncmd.args) {
8191 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8192 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8195 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8196 struct strlist **spp;
8198 spp = arglist.lastp;
8199 if (pseudovarflag && isassignment(argp->narg.text))
8200 expandarg(argp, &arglist, EXP_VARTILDE);
8202 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8204 for (sp = *spp; sp; sp = sp->next)
8208 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8209 for (sp = arglist.list; sp; sp = sp->next) {
8210 TRACE(("evalcommand arg: %s\n", sp->text));
8211 *nargv++ = sp->text;
8216 if (iflag && funcnest == 0 && argc > 0)
8217 lastarg = nargv[-1];
8220 expredir(cmd->ncmd.redirect);
8221 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8224 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8225 struct strlist **spp;
8228 spp = varlist.lastp;
8229 expandarg(argp, &varlist, EXP_VARTILDE);
8232 * Modify the command lookup path, if a PATH= assignment
8236 if (varequal(p, path))
8240 /* Print the command if xflag is set. */
8243 const char *p = " %s";
8246 dprintf(preverrout_fd, p, expandstr(ps4val()));
8249 for (n = 0; n < 2; n++) {
8251 dprintf(preverrout_fd, p, sp->text);
8259 full_write(preverrout_fd, "\n", 1);
8265 /* Now locate the command. */
8267 const char *oldpath;
8268 int cmd_flag = DO_ERR;
8273 find_command(argv[0], &cmdentry, cmd_flag, path);
8274 if (cmdentry.cmdtype == CMDUNKNOWN) {
8280 /* implement bltin and command here */
8281 if (cmdentry.cmdtype != CMDBUILTIN)
8284 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8285 if (cmdentry.u.cmd == EXECCMD)
8287 #if ENABLE_ASH_CMDCMD
8288 if (cmdentry.u.cmd == COMMANDCMD) {
8290 nargv = parse_command_args(argv, &path);
8293 argc -= nargv - argv;
8295 cmd_flag |= DO_NOFUNC;
8303 /* We have a redirection error. */
8305 raise_exception(EXERROR);
8307 exitstatus = status;
8311 /* Execute the command. */
8312 switch (cmdentry.cmdtype) {
8314 /* Fork off a child process if necessary. */
8315 if (!(flags & EV_EXIT) || trap[0]) {
8317 jp = makejob(cmd, 1);
8318 if (forkshell(jp, cmd, FORK_FG) != 0) {
8319 exitstatus = waitforjob(jp);
8325 listsetvar(varlist.list, VEXPORT|VSTACK);
8326 shellexec(argv, path, cmdentry.u.index);
8330 cmdenviron = varlist.list;
8332 struct strlist *list = cmdenviron;
8334 if (spclbltin > 0 || argc == 0) {
8336 if (cmd_is_exec && argc > 1)
8339 listsetvar(list, i);
8341 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8356 exit_status = j + 128;
8357 exitstatus = exit_status;
8359 if (i == EXINT || spclbltin > 0) {
8361 longjmp(exception_handler->loc, 1);
8368 listsetvar(varlist.list, 0);
8369 if (evalfun(cmdentry.u.func, argc, argv, flags))
8375 popredir(cmd_is_exec);
8377 /* dsl: I think this is intended to be used to support
8378 * '_' in 'vi' command mode during line editing...
8379 * However I implemented that within libedit itself.
8381 setvar("_", lastarg, 0);
8382 popstackmark(&smark);
8386 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8388 char *volatile savecmdname;
8389 struct jmploc *volatile savehandler;
8390 struct jmploc jmploc;
8393 savecmdname = commandname;
8394 i = setjmp(jmploc.loc);
8397 savehandler = exception_handler;
8398 exception_handler = &jmploc;
8399 commandname = argv[0];
8401 optptr = NULL; /* initialize nextopt */
8402 exitstatus = (*cmd->builtin)(argc, argv);
8403 flush_stdout_stderr();
8405 exitstatus |= ferror(stdout);
8407 commandname = savecmdname;
8409 exception_handler = savehandler;
8415 goodname(const char *p)
8417 return !*endofname(p);
8422 * Search for a command. This is called before we fork so that the
8423 * location of the command will be available in the parent as well as
8424 * the child. The check for "goodname" is an overly conservative
8425 * check that the name will not be subject to expansion.
8428 prehash(union node *n)
8430 struct cmdentry entry;
8432 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8433 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8437 /* ============ Builtin commands
8439 * Builtin commands whose functions are closely tied to evaluation
8440 * are implemented here.
8444 * Handle break and continue commands. Break, continue, and return are
8445 * all handled by setting the evalskip flag. The evaluation routines
8446 * above all check this flag, and if it is set they start skipping
8447 * commands rather than executing them. The variable skipcount is
8448 * the number of loops to break/continue, or the number of function
8449 * levels to return. (The latter is always 1.) It should probably
8450 * be an error to break out of more loops than exist, but it isn't
8451 * in the standard shell so we don't make it one here.
8454 breakcmd(int argc, char **argv)
8456 int n = argc > 1 ? number(argv[1]) : 1;
8459 ash_msg_and_raise_error(illnum, argv[1]);
8463 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8470 /* ============ input.c
8472 * This implements the input routines used by the parser.
8475 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8478 INPUT_PUSH_FILE = 1,
8479 INPUT_NOFILE_OK = 2,
8483 * NEOF is returned by parsecmd when it encounters an end of file. It
8484 * must be distinct from NULL, so we use the address of a variable that
8485 * happens to be handy.
8487 static int plinno = 1; /* input line number */
8488 /* number of characters left in input buffer */
8489 static int parsenleft; /* copy of parsefile->nleft */
8490 static int parselleft; /* copy of parsefile->lleft */
8491 /* next character in input buffer */
8492 static char *parsenextc; /* copy of parsefile->nextc */
8494 static int checkkwd;
8495 /* values of checkkwd variable */
8496 #define CHKALIAS 0x1
8503 struct strpush *sp = parsefile->strpush;
8506 #if ENABLE_ASH_ALIAS
8508 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8509 checkkwd |= CHKALIAS;
8511 if (sp->string != sp->ap->val) {
8514 sp->ap->flag &= ~ALIASINUSE;
8515 if (sp->ap->flag & ALIASDEAD) {
8516 unalias(sp->ap->name);
8520 parsenextc = sp->prevstring;
8521 parsenleft = sp->prevnleft;
8522 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8523 parsefile->strpush = sp->prev;
8524 if (sp != &(parsefile->basestrpush))
8533 char *buf = parsefile->buf;
8537 #if ENABLE_FEATURE_EDITING
8538 if (!iflag || parsefile->fd)
8539 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8541 #if ENABLE_FEATURE_TAB_COMPLETION
8542 line_input_state->path_lookup = pathval();
8544 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8546 /* Ctrl+C pressed */
8555 if (nr < 0 && errno == 0) {
8556 /* Ctrl+D presend */
8561 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8565 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8566 int flags = fcntl(0, F_GETFL, 0);
8567 if (flags >= 0 && flags & O_NONBLOCK) {
8568 flags &=~ O_NONBLOCK;
8569 if (fcntl(0, F_SETFL, flags) >= 0) {
8570 out2str("sh: turning off NDELAY mode\n");
8580 * Refill the input buffer and return the next input character:
8582 * 1) If a string was pushed back on the input, pop it;
8583 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8584 * from a string so we can't refill the buffer, return EOF.
8585 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8586 * 4) Process input up to the next newline, deleting nul characters.
8595 while (parsefile->strpush) {
8596 #if ENABLE_ASH_ALIAS
8597 if (parsenleft == -1 && parsefile->strpush->ap &&
8598 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8603 if (--parsenleft >= 0)
8604 return signed_char2int(*parsenextc++);
8606 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8608 flush_stdout_stderr();
8615 parselleft = parsenleft = EOF_NLEFT;
8622 /* delete nul characters */
8630 memmove(q, q + 1, more);
8634 parsenleft = q - parsenextc - 1;
8640 parsenleft = q - parsenextc - 1;
8652 out2str(parsenextc);
8657 return signed_char2int(*parsenextc++);
8660 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8664 return pgetc_as_macro();
8667 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8668 #define pgetc_macro() pgetc()
8670 #define pgetc_macro() pgetc_as_macro()
8674 * Same as pgetc(), but ignores PEOA.
8676 #if ENABLE_ASH_ALIAS
8684 } while (c == PEOA);
8691 return pgetc_macro();
8696 * Read a line from the script.
8699 pfgets(char *line, int len)
8705 while (--nleft > 0) {
8721 * Undo the last call to pgetc. Only one character may be pushed back.
8722 * PEOF may be pushed back.
8732 * Push a string back onto the input at this current parsefile level.
8733 * We handle aliases this way.
8736 pushstring(char *s, void *ap)
8743 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8744 if (parsefile->strpush) {
8745 sp = ckmalloc(sizeof(struct strpush));
8746 sp->prev = parsefile->strpush;
8747 parsefile->strpush = sp;
8749 sp = parsefile->strpush = &(parsefile->basestrpush);
8750 sp->prevstring = parsenextc;
8751 sp->prevnleft = parsenleft;
8752 #if ENABLE_ASH_ALIAS
8753 sp->ap = (struct alias *)ap;
8755 ((struct alias *)ap)->flag |= ALIASINUSE;
8765 * To handle the "." command, a stack of input files is used. Pushfile
8766 * adds a new entry to the stack and popfile restores the previous level.
8771 struct parsefile *pf;
8773 parsefile->nleft = parsenleft;
8774 parsefile->lleft = parselleft;
8775 parsefile->nextc = parsenextc;
8776 parsefile->linno = plinno;
8777 pf = ckmalloc(sizeof(*pf));
8778 pf->prev = parsefile;
8781 pf->basestrpush.prev = NULL;
8788 struct parsefile *pf = parsefile;
8797 parsefile = pf->prev;
8799 parsenleft = parsefile->nleft;
8800 parselleft = parsefile->lleft;
8801 parsenextc = parsefile->nextc;
8802 plinno = parsefile->linno;
8807 * Return to top level.
8812 while (parsefile != &basepf)
8817 * Close the file(s) that the shell is reading commands from. Called
8818 * after a fork is done.
8824 if (parsefile->fd > 0) {
8825 close(parsefile->fd);
8831 * Like setinputfile, but takes an open file descriptor. Call this with
8835 setinputfd(int fd, int push)
8837 fcntl(fd, F_SETFD, FD_CLOEXEC);
8843 if (parsefile->buf == NULL)
8844 parsefile->buf = ckmalloc(IBUFSIZ);
8845 parselleft = parsenleft = 0;
8850 * Set the input to take input from a file. If push is set, push the
8851 * old input onto the stack first.
8854 setinputfile(const char *fname, int flags)
8860 fd = open(fname, O_RDONLY);
8862 if (flags & INPUT_NOFILE_OK)
8864 ash_msg_and_raise_error("can't open %s", fname);
8867 fd2 = copyfd(fd, 10);
8870 ash_msg_and_raise_error("out of file descriptors");
8873 setinputfd(fd, flags & INPUT_PUSH_FILE);
8880 * Like setinputfile, but takes input from a string.
8883 setinputstring(char *string)
8887 parsenextc = string;
8888 parsenleft = strlen(string);
8889 parsefile->buf = NULL;
8895 /* ============ mail.c
8897 * Routines to check for mail.
8902 #define MAXMBOXES 10
8904 /* times of mailboxes */
8905 static time_t mailtime[MAXMBOXES];
8906 /* Set if MAIL or MAILPATH is changed. */
8907 static int mail_var_path_changed;
8910 * Print appropriate message(s) if mail has arrived.
8911 * If mail_var_path_changed is set,
8912 * then the value of MAIL has mail_var_path_changed,
8913 * so we just update the values.
8922 struct stackmark smark;
8925 setstackmark(&smark);
8926 mpath = mpathset() ? mpathval() : mailval();
8927 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8928 p = padvance(&mpath, nullstr);
8933 for (q = p; *q; q++);
8938 q[-1] = '\0'; /* delete trailing '/' */
8939 if (stat(p, &statb) < 0) {
8943 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
8946 pathopt ? pathopt : "you have mail"
8949 *mtp = statb.st_mtime;
8951 mail_var_path_changed = 0;
8952 popstackmark(&smark);
8956 changemail(const char *val)
8958 mail_var_path_changed++;
8961 #endif /* ASH_MAIL */
8964 /* ============ ??? */
8967 * Set the shell parameters.
8970 setparam(char **argv)
8976 for (nparam = 0; argv[nparam]; nparam++);
8977 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
8979 *ap++ = ckstrdup(*argv++);
8982 freeparam(&shellparam);
8983 shellparam.malloc = 1;
8984 shellparam.nparam = nparam;
8985 shellparam.p = newparam;
8986 #if ENABLE_ASH_GETOPTS
8987 shellparam.optind = 1;
8988 shellparam.optoff = -1;
8993 * Process shell options. The global variable argptr contains a pointer
8994 * to the argument list; we advance it past the options.
8997 minus_o(char *name, int val)
9002 for (i = 0; i < NOPTS; i++) {
9003 if (strcmp(name, optnames(i)) == 0) {
9008 ash_msg_and_raise_error("illegal option -o %s", name);
9010 out1str("Current option settings\n");
9011 for (i = 0; i < NOPTS; i++)
9012 out1fmt("%-16s%s\n", optnames(i),
9013 optlist[i] ? "on" : "off");
9016 setoption(int flag, int val)
9020 for (i = 0; i < NOPTS; i++) {
9021 if (optletters(i) == flag) {
9026 ash_msg_and_raise_error("illegal option -%c", flag);
9030 options(int cmdline)
9038 while ((p = *argptr) != NULL) {
9040 if (c != '-' && c != '+')
9043 val = 0; /* val = 0 if c == '+' */
9046 if (p[0] == '\0' || LONE_DASH(p)) {
9048 /* "-" means turn off -x and -v */
9051 /* "--" means reset params */
9052 else if (*argptr == NULL)
9055 break; /* "-" or "--" terminates options */
9058 /* first char was + or - */
9059 while ((c = *p++) != '\0') {
9060 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9061 if (c == 'c' && cmdline) {
9062 minusc = p; /* command is after shell args */
9063 } else if (c == 'o') {
9064 minus_o(*argptr, val);
9067 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9069 /* bash does not accept +-login, we also won't */
9070 } else if (cmdline && val && (c == '-')) { /* long options */
9071 if (strcmp(p, "login") == 0)
9082 * The shift builtin command.
9085 shiftcmd(int argc, char **argv)
9092 n = number(argv[1]);
9093 if (n > shellparam.nparam)
9094 ash_msg_and_raise_error("can't shift that many");
9096 shellparam.nparam -= n;
9097 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9098 if (shellparam.malloc)
9102 while ((*ap2++ = *ap1++) != NULL);
9103 #if ENABLE_ASH_GETOPTS
9104 shellparam.optind = 1;
9105 shellparam.optoff = -1;
9112 * POSIX requires that 'set' (but not export or readonly) output the
9113 * variables in lexicographic order - by the locale's collating order (sigh).
9114 * Maybe we could keep them in an ordered balanced binary tree
9115 * instead of hashed lists.
9116 * For now just roll 'em through qsort for printing...
9119 showvars(const char *sep_prefix, int on, int off)
9124 ep = listvars(on, off, &epend);
9125 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9127 sep = *sep_prefix ? " " : sep_prefix;
9129 for (; ep < epend; ep++) {
9133 p = strchrnul(*ep, '=');
9136 q = single_quote(++p);
9137 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9143 * The set command builtin.
9146 setcmd(int argc, char **argv)
9149 return showvars(nullstr, 0, VUNSET);
9153 if (*argptr != NULL) {
9160 #if ENABLE_ASH_RANDOM_SUPPORT
9161 /* Roughly copied from bash.. */
9163 change_random(const char *value)
9165 if (value == NULL) {
9166 /* "get", generate */
9169 rseed = rseed * 1103515245 + 12345;
9170 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9171 /* set without recursion */
9172 setvar(vrandom.text, buf, VNOFUNC);
9173 vrandom.flags &= ~VNOFUNC;
9176 rseed = strtoul(value, (char **)NULL, 10);
9181 #if ENABLE_ASH_GETOPTS
9183 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9192 if (*param_optind < 1)
9194 optnext = optfirst + *param_optind - 1;
9196 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9199 p = optnext[-1] + *optoff;
9200 if (p == NULL || *p == '\0') {
9201 /* Current word is done, advance */
9203 if (p == NULL || *p != '-' || *++p == '\0') {
9210 if (LONE_DASH(p)) /* check for "--" */
9215 for (q = optstr; *q != c; ) {
9217 if (optstr[0] == ':') {
9220 err |= setvarsafe("OPTARG", s, 0);
9222 fprintf(stderr, "Illegal option -%c\n", c);
9233 if (*p == '\0' && (p = *optnext) == NULL) {
9234 if (optstr[0] == ':') {
9237 err |= setvarsafe("OPTARG", s, 0);
9240 fprintf(stderr, "No arg for -%c option\n", c);
9249 err |= setvarsafe("OPTARG", p, 0);
9252 err |= setvarsafe("OPTARG", nullstr, 0);
9254 *optoff = p ? p - *(optnext - 1) : -1;
9255 *param_optind = optnext - optfirst + 1;
9256 fmtstr(s, sizeof(s), "%d", *param_optind);
9257 err |= setvarsafe("OPTIND", s, VNOFUNC);
9260 err |= setvarsafe(optvar, s, 0);
9264 flush_stdout_stderr();
9265 raise_exception(EXERROR);
9271 * The getopts builtin. Shellparam.optnext points to the next argument
9272 * to be processed. Shellparam.optptr points to the next character to
9273 * be processed in the current argument. If shellparam.optnext is NULL,
9274 * then it's the first time getopts has been called.
9277 getoptscmd(int argc, char **argv)
9282 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9284 optbase = shellparam.p;
9285 if (shellparam.optind > shellparam.nparam + 1) {
9286 shellparam.optind = 1;
9287 shellparam.optoff = -1;
9291 if (shellparam.optind > argc - 2) {
9292 shellparam.optind = 1;
9293 shellparam.optoff = -1;
9297 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9298 &shellparam.optoff);
9300 #endif /* ASH_GETOPTS */
9303 /* ============ Shell parser */
9305 static int tokpushback; /* last token pushed back */
9306 #define NEOF ((union node *)&tokpushback)
9307 static int parsebackquote; /* nonzero if we are inside backquotes */
9308 static int lasttoken; /* last token read */
9309 static char *wordtext; /* text of last word returned by readtoken */
9310 static struct nodelist *backquotelist;
9311 static union node *redirnode;
9312 static struct heredoc *heredoc;
9313 static int quoteflag; /* set if (part of) last token was quoted */
9315 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9317 raise_error_syntax(const char *msg)
9319 ash_msg_and_raise_error("syntax error: %s", msg);
9324 * Called when an unexpected token is read during the parse. The argument
9325 * is the token that is expected, or -1 if more than one type of token can
9326 * occur at this point.
9328 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9330 raise_error_unexpected_syntax(int token)
9335 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9337 sprintf(msg + l, " (expecting %s)", tokname(token));
9338 raise_error_syntax(msg);
9342 #define EOFMARKLEN 79
9345 struct heredoc *next; /* next here document in list */
9346 union node *here; /* redirection node */
9347 char *eofmark; /* string indicating end of input */
9348 int striptabs; /* if set, strip leading tabs */
9351 static struct heredoc *heredoclist; /* list of here documents to read */
9353 /* parsing is heavily cross-recursive, need these forward decls */
9354 static union node *andor(void);
9355 static union node *pipeline(void);
9356 static union node *parse_command(void);
9357 static void parseheredoc(void);
9358 static char peektoken(void);
9359 static int readtoken(void);
9364 union node *n1, *n2, *n3;
9367 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9368 if (nlflag == 2 && peektoken())
9374 if (tok == TBACKGND) {
9375 if (n2->type == NPIPE) {
9376 n2->npipe.backgnd = 1;
9378 if (n2->type != NREDIR) {
9379 n3 = stalloc(sizeof(struct nredir));
9381 n3->nredir.redirect = NULL;
9384 n2->type = NBACKGND;
9390 n3 = stalloc(sizeof(struct nbinary));
9392 n3->nbinary.ch1 = n1;
9393 n3->nbinary.ch2 = n2;
9409 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9417 pungetc(); /* push back EOF on input */
9421 raise_error_unexpected_syntax(-1);
9431 union node *n1, *n2, *n3;
9439 } else if (t == TOR) {
9445 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9447 n3 = stalloc(sizeof(struct nbinary));
9449 n3->nbinary.ch1 = n1;
9450 n3->nbinary.ch2 = n2;
9458 union node *n1, *n2, *pipenode;
9459 struct nodelist *lp, *prev;
9463 TRACE(("pipeline: entered\n"));
9464 if (readtoken() == TNOT) {
9466 checkkwd = CHKKWD | CHKALIAS;
9469 n1 = parse_command();
9470 if (readtoken() == TPIPE) {
9471 pipenode = stalloc(sizeof(struct npipe));
9472 pipenode->type = NPIPE;
9473 pipenode->npipe.backgnd = 0;
9474 lp = stalloc(sizeof(struct nodelist));
9475 pipenode->npipe.cmdlist = lp;
9479 lp = stalloc(sizeof(struct nodelist));
9480 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9481 lp->n = parse_command();
9483 } while (readtoken() == TPIPE);
9489 n2 = stalloc(sizeof(struct nnot));
9502 n = stalloc(sizeof(struct narg));
9504 n->narg.next = NULL;
9505 n->narg.text = wordtext;
9506 n->narg.backquote = backquotelist;
9511 fixredir(union node *n, const char *text, int err)
9513 TRACE(("Fix redir %s %d\n", text, err));
9515 n->ndup.vname = NULL;
9517 if (isdigit(text[0]) && text[1] == '\0')
9518 n->ndup.dupfd = text[0] - '0';
9519 else if (LONE_DASH(text))
9523 raise_error_syntax("Bad fd number");
9524 n->ndup.vname = makename();
9529 * Returns true if the text contains nothing to expand (no dollar signs
9533 noexpand(char *text)
9539 while ((c = *p++) != '\0') {
9540 if (c == CTLQUOTEMARK)
9544 else if (SIT(c, BASESYNTAX) == CCTL)
9553 union node *n = redirnode;
9555 if (readtoken() != TWORD)
9556 raise_error_unexpected_syntax(-1);
9557 if (n->type == NHERE) {
9558 struct heredoc *here = heredoc;
9564 TRACE(("Here document %d\n", n->type));
9565 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9566 raise_error_syntax("Illegal eof marker for << redirection");
9567 rmescapes(wordtext);
9568 here->eofmark = wordtext;
9570 if (heredoclist == NULL)
9573 for (p = heredoclist; p->next; p = p->next);
9576 } else if (n->type == NTOFD || n->type == NFROMFD) {
9577 fixredir(n, wordtext, 0);
9579 n->nfile.fname = makename();
9586 union node *args, **app;
9587 union node *n = NULL;
9588 union node *vars, **vpp;
9589 union node **rpp, *redir;
9599 savecheckkwd = CHKALIAS;
9601 checkkwd = savecheckkwd;
9602 switch (readtoken()) {
9604 n = stalloc(sizeof(struct narg));
9606 n->narg.text = wordtext;
9607 n->narg.backquote = backquotelist;
9608 if (savecheckkwd && isassignment(wordtext)) {
9610 vpp = &n->narg.next;
9613 app = &n->narg.next;
9618 *rpp = n = redirnode;
9619 rpp = &n->nfile.next;
9620 parsefname(); /* read name of redirection file */
9623 if (args && app == &args->narg.next
9626 struct builtincmd *bcmd;
9629 /* We have a function */
9630 if (readtoken() != TRP)
9631 raise_error_unexpected_syntax(TRP);
9632 name = n->narg.text;
9634 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9636 raise_error_syntax("Bad function name");
9639 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9640 n->narg.next = parse_command();
9653 n = stalloc(sizeof(struct ncmd));
9655 n->ncmd.args = args;
9656 n->ncmd.assign = vars;
9657 n->ncmd.redirect = redir;
9664 union node *n1, *n2;
9665 union node *ap, **app;
9666 union node *cp, **cpp;
9667 union node *redir, **rpp;
9674 switch (readtoken()) {
9676 raise_error_unexpected_syntax(-1);
9679 n1 = stalloc(sizeof(struct nif));
9681 n1->nif.test = list(0);
9682 if (readtoken() != TTHEN)
9683 raise_error_unexpected_syntax(TTHEN);
9684 n1->nif.ifpart = list(0);
9686 while (readtoken() == TELIF) {
9687 n2->nif.elsepart = stalloc(sizeof(struct nif));
9688 n2 = n2->nif.elsepart;
9690 n2->nif.test = list(0);
9691 if (readtoken() != TTHEN)
9692 raise_error_unexpected_syntax(TTHEN);
9693 n2->nif.ifpart = list(0);
9695 if (lasttoken == TELSE)
9696 n2->nif.elsepart = list(0);
9698 n2->nif.elsepart = NULL;
9706 n1 = stalloc(sizeof(struct nbinary));
9707 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9708 n1->nbinary.ch1 = list(0);
9711 TRACE(("expecting DO got %s %s\n", tokname(got),
9712 got == TWORD ? wordtext : ""));
9713 raise_error_unexpected_syntax(TDO);
9715 n1->nbinary.ch2 = list(0);
9720 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9721 raise_error_syntax("Bad for loop variable");
9722 n1 = stalloc(sizeof(struct nfor));
9724 n1->nfor.var = wordtext;
9725 checkkwd = CHKKWD | CHKALIAS;
9726 if (readtoken() == TIN) {
9728 while (readtoken() == TWORD) {
9729 n2 = stalloc(sizeof(struct narg));
9731 n2->narg.text = wordtext;
9732 n2->narg.backquote = backquotelist;
9734 app = &n2->narg.next;
9738 if (lasttoken != TNL && lasttoken != TSEMI)
9739 raise_error_unexpected_syntax(-1);
9741 n2 = stalloc(sizeof(struct narg));
9743 n2->narg.text = (char *)dolatstr;
9744 n2->narg.backquote = NULL;
9745 n2->narg.next = NULL;
9748 * Newline or semicolon here is optional (but note
9749 * that the original Bourne shell only allowed NL).
9751 if (lasttoken != TNL && lasttoken != TSEMI)
9754 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9755 if (readtoken() != TDO)
9756 raise_error_unexpected_syntax(TDO);
9757 n1->nfor.body = list(0);
9761 n1 = stalloc(sizeof(struct ncase));
9763 if (readtoken() != TWORD)
9764 raise_error_unexpected_syntax(TWORD);
9765 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9767 n2->narg.text = wordtext;
9768 n2->narg.backquote = backquotelist;
9769 n2->narg.next = NULL;
9771 checkkwd = CHKKWD | CHKALIAS;
9772 } while (readtoken() == TNL);
9773 if (lasttoken != TIN)
9774 raise_error_unexpected_syntax(TIN);
9775 cpp = &n1->ncase.cases;
9777 checkkwd = CHKNL | CHKKWD;
9779 while (t != TESAC) {
9780 if (lasttoken == TLP)
9782 *cpp = cp = stalloc(sizeof(struct nclist));
9784 app = &cp->nclist.pattern;
9786 *app = ap = stalloc(sizeof(struct narg));
9788 ap->narg.text = wordtext;
9789 ap->narg.backquote = backquotelist;
9790 if (readtoken() != TPIPE)
9792 app = &ap->narg.next;
9795 ap->narg.next = NULL;
9796 if (lasttoken != TRP)
9797 raise_error_unexpected_syntax(TRP);
9798 cp->nclist.body = list(2);
9800 cpp = &cp->nclist.next;
9802 checkkwd = CHKNL | CHKKWD;
9806 raise_error_unexpected_syntax(TENDCASE);
9813 n1 = stalloc(sizeof(struct nredir));
9814 n1->type = NSUBSHELL;
9815 n1->nredir.n = list(0);
9816 n1->nredir.redirect = NULL;
9829 if (readtoken() != t)
9830 raise_error_unexpected_syntax(t);
9833 /* Now check for redirection which may follow command */
9834 checkkwd = CHKKWD | CHKALIAS;
9836 while (readtoken() == TREDIR) {
9837 *rpp = n2 = redirnode;
9838 rpp = &n2->nfile.next;
9844 if (n1->type != NSUBSHELL) {
9845 n2 = stalloc(sizeof(struct nredir));
9850 n1->nredir.redirect = redir;
9856 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9857 * is not NULL, read a here document. In the latter case, eofmark is the
9858 * word which marks the end of the document and striptabs is true if
9859 * leading tabs should be stripped from the document. The argument firstc
9860 * is the first character of the input token or document.
9862 * Because C does not have internal subroutines, I have simulated them
9863 * using goto's to implement the subroutine linkage. The following macros
9864 * will run code that appears at the end of readtoken1.
9867 static int parsebackquote; /* nonzero if we are inside backquotes */
9869 #define CHECKEND() {goto checkend; checkend_return:;}
9870 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9871 #define PARSESUB() {goto parsesub; parsesub_return:;}
9872 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9873 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9874 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9877 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9882 char line[EOFMARKLEN + 1];
9883 struct nodelist *bqlist = 0;
9886 int varnest = 0; /* levels of variables expansion */
9887 int arinest = 0; /* levels of arithmetic expansion */
9888 int parenlevel = 0; /* levels of parens in arithmetic */
9889 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9891 int prevsyntax = 0; /* syntax before arithmetic */
9893 /* Avoid longjmp clobbering */
9906 startlinno = plinno;
9908 if (syntax == DQSYNTAX)
9918 loop: { /* for each line, until end of word */
9919 CHECKEND(); /* set c to PEOF if at end of here document */
9920 for (;;) { /* until end of line or end of word */
9921 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9922 switch (SIT(c, syntax)) {
9923 case CNL: /* '\n' */
9924 if (syntax == BASESYNTAX)
9925 goto endword; /* exit outer loop */
9931 goto loop; /* continue outer loop */
9936 if (eofmark == NULL || dblquote)
9937 USTPUTC(CTLESC, out);
9940 case CBACK: /* backslash */
9943 USTPUTC(CTLESC, out);
9946 } else if (c == '\n') {
9951 c != '\\' && c != '`' &&
9956 USTPUTC(CTLESC, out);
9959 if (SIT(c, SQSYNTAX) == CCTL)
9960 USTPUTC(CTLESC, out);
9968 if (eofmark == NULL) {
9969 USTPUTC(CTLQUOTEMARK, out);
9977 if (eofmark != NULL && arinest == 0
9982 if (dqvarnest == 0) {
9983 syntax = BASESYNTAX;
9990 case CVAR: /* '$' */
9991 PARSESUB(); /* parse substitution */
9993 case CENDVAR: /* '}' */
9996 if (dqvarnest > 0) {
9999 USTPUTC(CTLENDVAR, out);
10004 #if ENABLE_ASH_MATH_SUPPORT
10005 case CLP: /* '(' in arithmetic */
10009 case CRP: /* ')' in arithmetic */
10010 if (parenlevel > 0) {
10014 if (pgetc() == ')') {
10015 if (--arinest == 0) {
10016 USTPUTC(CTLENDARI, out);
10017 syntax = prevsyntax;
10018 if (syntax == DQSYNTAX)
10026 * unbalanced parens
10027 * (don't 2nd guess - no error)
10035 case CBQUOTE: /* '`' */
10039 goto endword; /* exit outer loop */
10044 goto endword; /* exit outer loop */
10045 #if ENABLE_ASH_ALIAS
10055 #if ENABLE_ASH_MATH_SUPPORT
10056 if (syntax == ARISYNTAX)
10057 raise_error_syntax("Missing '))'");
10059 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10060 raise_error_syntax("Unterminated quoted string");
10061 if (varnest != 0) {
10062 startlinno = plinno;
10064 raise_error_syntax("Missing '}'");
10066 USTPUTC('\0', out);
10067 len = out - (char *)stackblock();
10068 out = stackblock();
10069 if (eofmark == NULL) {
10070 if ((c == '>' || c == '<')
10073 && (*out == '\0' || isdigit(*out))) {
10075 return lasttoken = TREDIR;
10080 quoteflag = quotef;
10081 backquotelist = bqlist;
10082 grabstackblock(len);
10086 /* end of readtoken routine */
10089 * Check to see whether we are at the end of the here document. When this
10090 * is called, c is set to the first character of the next input line. If
10091 * we are at the end of the here document, this routine sets the c to PEOF.
10095 #if ENABLE_ASH_ALIAS
10101 while (c == '\t') {
10105 if (c == *eofmark) {
10106 if (pfgets(line, sizeof(line)) != NULL) {
10110 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10111 if (*p == '\n' && *q == '\0') {
10114 needprompt = doprompt;
10116 pushstring(line, NULL);
10121 goto checkend_return;
10125 * Parse a redirection operator. The variable "out" points to a string
10126 * specifying the fd to be redirected. The variable "c" contains the
10127 * first character of the redirection operator.
10133 np = stalloc(sizeof(struct nfile));
10138 np->type = NAPPEND;
10140 np->type = NCLOBBER;
10147 } else { /* c == '<' */
10152 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10153 np = stalloc(sizeof(struct nhere));
10157 heredoc = stalloc(sizeof(struct heredoc));
10158 heredoc->here = np;
10161 heredoc->striptabs = 1;
10163 heredoc->striptabs = 0;
10169 np->type = NFROMFD;
10173 np->type = NFROMTO;
10183 np->nfile.fd = fd - '0';
10185 goto parseredir_return;
10189 * Parse a substitution. At this point, we have read the dollar sign
10190 * and nothing else.
10193 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10194 * (assuming ascii char codes, as the original implementation did) */
10195 #define is_special(c) \
10196 ((((unsigned int)c) - 33 < 32) \
10197 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10203 static const char types[] = "}-+?=";
10207 c <= PEOA_OR_PEOF ||
10208 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10212 } else if (c == '(') { /* $(command) or $((arith)) */
10213 if (pgetc() == '(') {
10214 #if ENABLE_ASH_MATH_SUPPORT
10217 raise_error_syntax("We unsupport $((arith))");
10224 USTPUTC(CTLVAR, out);
10225 typeloc = out - (char *)stackblock();
10226 USTPUTC(VSNORMAL, out);
10227 subtype = VSNORMAL;
10235 subtype = VSLENGTH;
10239 if (c > PEOA_OR_PEOF && is_name(c)) {
10243 } while (c > PEOA_OR_PEOF && is_in_name(c));
10244 } else if (isdigit(c)) {
10248 } while (isdigit(c));
10249 } else if (is_special(c)) {
10253 badsub: raise_error_syntax("Bad substitution");
10257 if (subtype == 0) {
10264 p = strchr(types, c);
10267 subtype = p - types + VSNORMAL;
10273 subtype = c == '#' ? VSTRIMLEFT :
10286 if (dblquote || arinest)
10288 *((char *)stackblock() + typeloc) = subtype | flags;
10289 if (subtype != VSNORMAL) {
10291 if (dblquote || arinest) {
10296 goto parsesub_return;
10300 * Called to parse command substitutions. Newstyle is set if the command
10301 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10302 * list of commands (passed by reference), and savelen is the number of
10303 * characters on the top of the stack which must be preserved.
10306 struct nodelist **nlpp;
10309 char *volatile str;
10310 struct jmploc jmploc;
10311 struct jmploc *volatile savehandler;
10313 int saveprompt = 0;
10315 (void) &saveprompt;
10318 savepbq = parsebackquote;
10319 if (setjmp(jmploc.loc)) {
10322 parsebackquote = 0;
10323 exception_handler = savehandler;
10324 longjmp(exception_handler->loc, 1);
10328 savelen = out - (char *)stackblock();
10330 str = ckmalloc(savelen);
10331 memcpy(str, stackblock(), savelen);
10333 savehandler = exception_handler;
10334 exception_handler = &jmploc;
10337 /* We must read until the closing backquote, giving special
10338 treatment to some slashes, and then push the string and
10339 reread it as input, interpreting it normally. */
10346 STARTSTACKSTR(pout);
10363 * If eating a newline, avoid putting
10364 * the newline into the new character
10365 * stream (via the STPUTC after the
10370 if (pc != '\\' && pc != '`' && pc != '$'
10371 && (!dblquote || pc != '"'))
10372 STPUTC('\\', pout);
10373 if (pc > PEOA_OR_PEOF) {
10379 #if ENABLE_ASH_ALIAS
10382 startlinno = plinno;
10383 raise_error_syntax("EOF in backquote substitution");
10387 needprompt = doprompt;
10396 STPUTC('\0', pout);
10397 psavelen = pout - (char *)stackblock();
10398 if (psavelen > 0) {
10399 pstr = grabstackstr(pout);
10400 setinputstring(pstr);
10405 nlpp = &(*nlpp)->next;
10406 *nlpp = stalloc(sizeof(**nlpp));
10407 (*nlpp)->next = NULL;
10408 parsebackquote = oldstyle;
10411 saveprompt = doprompt;
10418 doprompt = saveprompt;
10419 else if (readtoken() != TRP)
10420 raise_error_unexpected_syntax(TRP);
10425 * Start reading from old file again, ignoring any pushed back
10426 * tokens left from the backquote parsing
10431 while (stackblocksize() <= savelen)
10433 STARTSTACKSTR(out);
10435 memcpy(out, str, savelen);
10436 STADJUST(savelen, out);
10442 parsebackquote = savepbq;
10443 exception_handler = savehandler;
10444 if (arinest || dblquote)
10445 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10447 USTPUTC(CTLBACKQ, out);
10449 goto parsebackq_oldreturn;
10450 goto parsebackq_newreturn;
10453 #if ENABLE_ASH_MATH_SUPPORT
10455 * Parse an arithmetic expansion (indicate start of one and set state)
10458 if (++arinest == 1) {
10459 prevsyntax = syntax;
10460 syntax = ARISYNTAX;
10461 USTPUTC(CTLARI, out);
10468 * we collapse embedded arithmetic expansion to
10469 * parenthesis, which should be equivalent
10473 goto parsearith_return;
10477 } /* end of readtoken */
10480 * Read the next input token.
10481 * If the token is a word, we set backquotelist to the list of cmds in
10482 * backquotes. We set quoteflag to true if any part of the word was
10484 * If the token is TREDIR, then we set redirnode to a structure containing
10486 * In all cases, the variable startlinno is set to the number of the line
10487 * on which the token starts.
10489 * [Change comment: here documents and internal procedures]
10490 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10491 * word parsing code into a separate routine. In this case, readtoken
10492 * doesn't need to have any internal procedures, but parseword does.
10493 * We could also make parseoperator in essence the main routine, and
10494 * have parseword (readtoken1?) handle both words and redirection.]
10496 #define NEW_xxreadtoken
10497 #ifdef NEW_xxreadtoken
10498 /* singles must be first! */
10499 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10501 static const char xxreadtoken_tokens[] = {
10502 TNL, TLP, TRP, /* only single occurrence allowed */
10503 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10504 TEOF, /* corresponds to trailing nul */
10505 TAND, TOR, TENDCASE, /* if double occurrence */
10508 #define xxreadtoken_doubles \
10509 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10510 #define xxreadtoken_singles \
10511 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10525 startlinno = plinno;
10526 for (;;) { /* until token or start of word found */
10529 if ((c != ' ') && (c != '\t')
10530 #if ENABLE_ASH_ALIAS
10535 while ((c = pgetc()) != '\n' && c != PEOF);
10537 } else if (c == '\\') {
10538 if (pgetc() != '\n') {
10542 startlinno = ++plinno;
10547 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10552 needprompt = doprompt;
10555 p = strchr(xxreadtoken_chars, c);
10558 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10561 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10562 if (pgetc() == *p) { /* double occurrence? */
10563 p += xxreadtoken_doubles + 1;
10569 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10575 #define RETURN(token) return lasttoken = token
10588 startlinno = plinno;
10589 for (;;) { /* until token or start of word found */
10592 case ' ': case '\t':
10593 #if ENABLE_ASH_ALIAS
10598 while ((c = pgetc()) != '\n' && c != PEOF);
10602 if (pgetc() == '\n') {
10603 startlinno = ++plinno;
10612 needprompt = doprompt;
10617 if (pgetc() == '&')
10622 if (pgetc() == '|')
10627 if (pgetc() == ';')
10640 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10643 #endif /* NEW_xxreadtoken */
10650 int alreadyseen = tokpushback;
10653 #if ENABLE_ASH_ALIAS
10662 if (checkkwd & CHKNL) {
10669 if (t != TWORD || quoteflag) {
10674 * check for keywords
10676 if (checkkwd & CHKKWD) {
10677 const char *const *pp;
10679 pp = findkwd(wordtext);
10681 lasttoken = t = pp - tokname_array;
10682 TRACE(("keyword %s recognized\n", tokname(t)));
10687 if (checkkwd & CHKALIAS) {
10688 #if ENABLE_ASH_ALIAS
10690 ap = lookupalias(wordtext, 1);
10693 pushstring(ap->val, ap);
10703 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10705 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10717 return tokname_array[t][0];
10721 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10722 * valid parse tree indicating a blank line.)
10724 static union node *
10725 parsecmd(int interact)
10730 doprompt = interact;
10732 setprompt(doprompt);
10744 * Input any here documents.
10749 struct heredoc *here;
10752 here = heredoclist;
10759 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10760 here->eofmark, here->striptabs);
10761 n = stalloc(sizeof(struct narg));
10762 n->narg.type = NARG;
10763 n->narg.next = NULL;
10764 n->narg.text = wordtext;
10765 n->narg.backquote = backquotelist;
10766 here->here->nhere.doc = n;
10773 * called by editline -- any expansions to the prompt should be added here.
10775 #if ENABLE_ASH_EXPAND_PRMT
10776 static const char *
10777 expandstr(const char *ps)
10781 /* XXX Fix (char *) cast. */
10782 setinputstring((char *)ps);
10783 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10786 n.narg.type = NARG;
10787 n.narg.next = NULL;
10788 n.narg.text = wordtext;
10789 n.narg.backquote = backquotelist;
10791 expandarg(&n, NULL, 0);
10792 return stackblock();
10797 * Execute a command or commands contained in a string.
10800 evalstring(char *s, int mask)
10803 struct stackmark smark;
10807 setstackmark(&smark);
10810 while ((n = parsecmd(0)) != NEOF) {
10812 popstackmark(&smark);
10825 * The eval command.
10828 evalcmd(int argc, char **argv)
10837 STARTSTACKSTR(concat);
10840 concat = stack_putstr(p, concat);
10844 STPUTC(' ', concat);
10846 STPUTC('\0', concat);
10847 p = grabstackstr(concat);
10849 evalstring(p, ~SKIPEVAL);
10856 * Read and execute commands. "Top" is nonzero for the top level command
10857 * loop; it turns on prompting if the shell is interactive.
10863 struct stackmark smark;
10867 TRACE(("cmdloop(%d) called\n", top));
10871 setstackmark(&smark);
10874 showjobs(stderr, SHOW_CHANGED);
10877 if (iflag && top) {
10879 #if ENABLE_ASH_MAIL
10883 n = parsecmd(inter);
10884 /* showtree(n); DEBUG */
10886 if (!top || numeof >= 50)
10888 if (!stoppedjobs()) {
10891 out2str("\nUse \"exit\" to leave shell.\n");
10894 } else if (nflag == 0) {
10895 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
10900 popstackmark(&smark);
10905 return skip & SKIPEVAL;
10912 * Take commands from a file. To be compatible we should do a path
10913 * search for the file, which is necessary to find sub-commands.
10916 find_dot_file(char *name)
10919 const char *path = pathval();
10922 /* don't try this for absolute or relative paths */
10923 if (strchr(name, '/'))
10926 while ((fullname = padvance(&path, name)) != NULL) {
10927 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
10929 * Don't bother freeing here, since it will
10930 * be freed by the caller.
10934 stunalloc(fullname);
10937 /* not found in the PATH */
10938 ash_msg_and_raise_error("%s: not found", name);
10943 dotcmd(int argc, char **argv)
10945 struct strlist *sp;
10946 volatile struct shparam saveparam;
10949 for (sp = cmdenviron; sp; sp = sp->next)
10950 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
10952 if (argc >= 2) { /* That's what SVR2 does */
10955 fullname = find_dot_file(argv[1]);
10958 saveparam = shellparam;
10959 shellparam.malloc = 0;
10960 shellparam.nparam = argc - 2;
10961 shellparam.p = argv + 2;
10964 setinputfile(fullname, INPUT_PUSH_FILE);
10965 commandname = fullname;
10970 freeparam(&shellparam);
10971 shellparam = saveparam;
10973 status = exitstatus;
10979 exitcmd(int argc, char **argv)
10984 exitstatus = number(argv[1]);
10985 raise_exception(EXEXIT);
10989 #if ENABLE_ASH_BUILTIN_ECHO
10991 echocmd(int argc, char **argv)
10993 return bb_echo(argv);
10997 #if ENABLE_ASH_BUILTIN_TEST
10999 testcmd(int argc, char **argv)
11001 return test_main(argc, argv);
11006 * Read a file containing shell functions.
11009 readcmdfile(char *name)
11011 setinputfile(name, INPUT_PUSH_FILE);
11017 /* ============ find_command inplementation */
11020 * Resolve a command name. If you change this routine, you may have to
11021 * change the shellexec routine as well.
11024 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11026 struct tblentry *cmdp;
11033 struct builtincmd *bcmd;
11035 /* If name contains a slash, don't use PATH or hash table */
11036 if (strchr(name, '/') != NULL) {
11037 entry->u.index = -1;
11038 if (act & DO_ABS) {
11039 while (stat(name, &statb) < 0) {
11041 if (errno == EINTR)
11044 entry->cmdtype = CMDUNKNOWN;
11048 entry->cmdtype = CMDNORMAL;
11052 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11054 updatetbl = (path == pathval());
11057 if (strstr(path, "%builtin") != NULL)
11058 act |= DO_ALTBLTIN;
11061 /* If name is in the table, check answer will be ok */
11062 cmdp = cmdlookup(name, 0);
11063 if (cmdp != NULL) {
11066 switch (cmdp->cmdtype) {
11084 } else if (cmdp->rehash == 0)
11085 /* if not invalidated by cd, we're done */
11089 /* If %builtin not in path, check for builtin next */
11090 bcmd = find_builtin(name);
11092 if (IS_BUILTIN_REGULAR(bcmd))
11093 goto builtin_success;
11094 if (act & DO_ALTPATH) {
11095 if (!(act & DO_ALTBLTIN))
11096 goto builtin_success;
11097 } else if (builtinloc <= 0) {
11098 goto builtin_success;
11102 #if ENABLE_FEATURE_SH_STANDALONE
11103 if (find_applet_by_name(name)) {
11104 entry->cmdtype = CMDNORMAL;
11105 entry->u.index = -1;
11110 /* We have to search path. */
11111 prev = -1; /* where to start */
11112 if (cmdp && cmdp->rehash) { /* doing a rehash */
11113 if (cmdp->cmdtype == CMDBUILTIN)
11116 prev = cmdp->param.index;
11122 while ((fullname = padvance(&path, name)) != NULL) {
11123 stunalloc(fullname);
11124 /* NB: code below will still use fullname
11125 * despite it being "unallocated" */
11128 if (prefix(pathopt, "builtin")) {
11130 goto builtin_success;
11132 } else if (!(act & DO_NOFUNC)
11133 && prefix(pathopt, "func")) {
11134 /* handled below */
11136 /* ignore unimplemented options */
11140 /* if rehash, don't redo absolute path names */
11141 if (fullname[0] == '/' && idx <= prev) {
11144 TRACE(("searchexec \"%s\": no change\n", name));
11147 while (stat(fullname, &statb) < 0) {
11149 if (errno == EINTR)
11152 if (errno != ENOENT && errno != ENOTDIR)
11156 e = EACCES; /* if we fail, this will be the error */
11157 if (!S_ISREG(statb.st_mode))
11159 if (pathopt) { /* this is a %func directory */
11160 stalloc(strlen(fullname) + 1);
11161 /* NB: stalloc will return space pointed by fullname
11162 * (because we don't have any intervening allocations
11163 * between stunalloc above and this stalloc) */
11164 readcmdfile(fullname);
11165 cmdp = cmdlookup(name, 0);
11166 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11167 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11168 stunalloc(fullname);
11171 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11173 entry->cmdtype = CMDNORMAL;
11174 entry->u.index = idx;
11178 cmdp = cmdlookup(name, 1);
11179 cmdp->cmdtype = CMDNORMAL;
11180 cmdp->param.index = idx;
11185 /* We failed. If there was an entry for this command, delete it */
11186 if (cmdp && updatetbl)
11187 delete_cmd_entry();
11189 ash_msg("%s: %s", name, errmsg(e, "not found"));
11190 entry->cmdtype = CMDUNKNOWN;
11195 entry->cmdtype = CMDBUILTIN;
11196 entry->u.cmd = bcmd;
11200 cmdp = cmdlookup(name, 1);
11201 cmdp->cmdtype = CMDBUILTIN;
11202 cmdp->param.cmd = bcmd;
11206 entry->cmdtype = cmdp->cmdtype;
11207 entry->u = cmdp->param;
11211 /* ============ trap.c */
11214 * The trap builtin.
11217 trapcmd(int argc, char **argv)
11226 for (signo = 0; signo < NSIG; signo++) {
11227 if (trap[signo] != NULL) {
11230 sn = get_signame(signo);
11231 out1fmt("trap -- %s %s\n",
11232 single_quote(trap[signo]), sn);
11242 signo = get_signum(*ap);
11244 ash_msg_and_raise_error("%s: bad trap", *ap);
11247 if (LONE_DASH(action))
11250 action = ckstrdup(action);
11254 trap[signo] = action;
11264 /* ============ Builtins */
11266 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11268 * Lists available builtins
11271 helpcmd(int argc, char **argv)
11275 out1fmt("\nBuilt-in commands:\n-------------------\n");
11276 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11277 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11278 builtintab[i].name + 1);
11284 #if ENABLE_FEATURE_SH_STANDALONE
11285 for (i = 0; i < NUM_APPLETS; i++) {
11286 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11294 return EXIT_SUCCESS;
11296 #endif /* FEATURE_SH_EXTRA_QUIET */
11299 * The export and readonly commands.
11302 exportcmd(int argc, char **argv)
11308 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11310 if (nextopt("p") != 'p') {
11315 p = strchr(name, '=');
11319 vp = *findvar(hashvar(name), name);
11325 setvar(name, p, flag);
11326 } while ((name = *++aptr) != NULL);
11330 showvars(argv[0], flag, 0);
11335 * Delete a function if it exists.
11338 unsetfunc(const char *name)
11340 struct tblentry *cmdp;
11342 cmdp = cmdlookup(name, 0);
11343 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11344 delete_cmd_entry();
11348 * The unset builtin command. We unset the function before we unset the
11349 * variable to allow a function to be unset when there is a readonly variable
11350 * with the same name.
11353 unsetcmd(int argc, char **argv)
11360 while ((i = nextopt("vf")) != '\0') {
11364 for (ap = argptr; *ap; ap++) {
11380 #include <sys/times.h>
11382 static const unsigned char timescmd_str[] = {
11383 ' ', offsetof(struct tms, tms_utime),
11384 '\n', offsetof(struct tms, tms_stime),
11385 ' ', offsetof(struct tms, tms_cutime),
11386 '\n', offsetof(struct tms, tms_cstime),
11391 timescmd(int ac, char **av)
11393 long clk_tck, s, t;
11394 const unsigned char *p;
11397 clk_tck = sysconf(_SC_CLK_TCK);
11402 t = *(clock_t *)(((char *) &buf) + p[1]);
11404 out1fmt("%ldm%ld.%.3lds%c",
11406 ((t - s * clk_tck) * 1000) / clk_tck,
11408 } while (*(p += 2));
11413 #if ENABLE_ASH_MATH_SUPPORT
11415 dash_arith(const char *s)
11421 result = arith(s, &errcode);
11424 ash_msg_and_raise_error("exponent less than 0");
11426 ash_msg_and_raise_error("divide by zero");
11428 ash_msg_and_raise_error("expression recursion loop detected");
11429 raise_error_syntax(s);
11437 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11438 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11440 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11443 letcmd(int argc, char **argv)
11450 ash_msg_and_raise_error("expression expected");
11451 for (ap = argv + 1; *ap; ap++) {
11452 i = dash_arith(*ap);
11457 #endif /* ASH_MATH_SUPPORT */
11460 /* ============ miscbltin.c
11462 * Miscellaneous builtins.
11467 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11468 typedef enum __rlimit_resource rlim_t;
11472 * The read builtin. The -e option causes backslashes to escape the
11473 * following character.
11475 * This uses unbuffered input, which may be avoidable in some cases.
11478 readcmd(int argc, char **argv)
11490 #if ENABLE_ASH_READ_NCHARS
11494 struct termios tty, old_tty;
11496 #if ENABLE_ASH_READ_TIMEOUT
11500 ts.tv_sec = ts.tv_usec = 0;
11505 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11506 while ((i = nextopt("p:rt:n:s")) != '\0')
11507 #elif ENABLE_ASH_READ_NCHARS
11508 while ((i = nextopt("p:rn:s")) != '\0')
11509 #elif ENABLE_ASH_READ_TIMEOUT
11510 while ((i = nextopt("p:rt:")) != '\0')
11512 while ((i = nextopt("p:r")) != '\0')
11517 prompt = optionarg;
11519 #if ENABLE_ASH_READ_NCHARS
11521 nchars = strtol(optionarg, &p, 10);
11523 ash_msg_and_raise_error("invalid count");
11524 nch_flag = (nchars > 0);
11530 #if ENABLE_ASH_READ_TIMEOUT
11532 ts.tv_sec = strtol(optionarg, &p, 10);
11538 ts.tv_usec = strtol(p, &p2, 10);
11540 ash_msg_and_raise_error("invalid timeout");
11542 /* normalize to usec */
11544 ash_msg_and_raise_error("invalid timeout");
11545 while (scale++ < 6)
11549 ash_msg_and_raise_error("invalid timeout");
11551 if ( ! ts.tv_sec && ! ts.tv_usec)
11552 ash_msg_and_raise_error("invalid timeout");
11562 if (prompt && isatty(0)) {
11567 ash_msg_and_raise_error("arg count");
11568 ifs = bltinlookup("IFS");
11571 #if ENABLE_ASH_READ_NCHARS
11572 if (nch_flag || silent) {
11573 tcgetattr(0, &tty);
11576 tty.c_lflag &= ~ICANON;
11577 tty.c_cc[VMIN] = nchars;
11580 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11583 tcsetattr(0, TCSANOW, &tty);
11586 #if ENABLE_ASH_READ_TIMEOUT
11587 if (ts.tv_sec || ts.tv_usec) {
11591 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11593 #if ENABLE_ASH_READ_NCHARS
11595 tcsetattr(0, TCSANOW, &old_tty);
11605 #if ENABLE_ASH_READ_NCHARS
11606 while (!nch_flag || nchars--)
11611 if (read(0, &c, 1) != 1) {
11623 if (!rflag && c == '\\') {
11629 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11633 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11635 setvar(*ap, stackblock(), 0);
11644 #if ENABLE_ASH_READ_NCHARS
11645 if (nch_flag || silent)
11646 tcsetattr(0, TCSANOW, &old_tty);
11650 /* Remove trailing blanks */
11651 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11653 setvar(*ap, stackblock(), 0);
11654 while (*++ap != NULL)
11655 setvar(*ap, nullstr, 0);
11660 umaskcmd(int argc, char **argv)
11662 static const char permuser[3] = "ugo";
11663 static const char permmode[3] = "rwx";
11664 static const short int permmask[] = {
11665 S_IRUSR, S_IWUSR, S_IXUSR,
11666 S_IRGRP, S_IWGRP, S_IXGRP,
11667 S_IROTH, S_IWOTH, S_IXOTH
11673 int symbolic_mode = 0;
11675 while (nextopt("S") != '\0') {
11686 if (symbolic_mode) {
11690 for (i = 0; i < 3; i++) {
11693 *p++ = permuser[i];
11695 for (j = 0; j < 3; j++) {
11696 if ((mask & permmask[3 * i + j]) == 0) {
11697 *p++ = permmode[j];
11705 out1fmt("%.4o\n", mask);
11708 if (isdigit((unsigned char) *ap)) {
11711 if (*ap >= '8' || *ap < '0')
11712 ash_msg_and_raise_error(illnum, argv[1]);
11713 mask = (mask << 3) + (*ap - '0');
11714 } while (*++ap != '\0');
11717 mask = ~mask & 0777;
11718 if (!bb_parse_mode(ap, &mask)) {
11719 ash_msg_and_raise_error("illegal mode: %s", ap);
11721 umask(~mask & 0777);
11730 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11731 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11732 * ash by J.T. Conklin.
11740 int factor; /* multiply by to get rlim_{cur,max} values */
11744 static const struct limits limits[] = {
11746 { "time(seconds)", RLIMIT_CPU, 1, 't' },
11748 #ifdef RLIMIT_FSIZE
11749 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
11752 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
11754 #ifdef RLIMIT_STACK
11755 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
11758 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
11761 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
11763 #ifdef RLIMIT_MEMLOCK
11764 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
11766 #ifdef RLIMIT_NPROC
11767 { "process", RLIMIT_NPROC, 1, 'p' },
11769 #ifdef RLIMIT_NOFILE
11770 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
11773 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
11775 #ifdef RLIMIT_LOCKS
11776 { "locks", RLIMIT_LOCKS, 1, 'w' },
11778 { NULL, 0, 0, '\0' }
11781 enum limtype { SOFT = 0x1, HARD = 0x2 };
11784 printlim(enum limtype how, const struct rlimit *limit,
11785 const struct limits *l)
11789 val = limit->rlim_max;
11791 val = limit->rlim_cur;
11793 if (val == RLIM_INFINITY)
11794 out1fmt("unlimited\n");
11797 out1fmt("%lld\n", (long long) val);
11802 ulimitcmd(int argc, char **argv)
11806 enum limtype how = SOFT | HARD;
11807 const struct limits *l;
11810 struct rlimit limit;
11813 while ((optc = nextopt("HSa"
11817 #ifdef RLIMIT_FSIZE
11823 #ifdef RLIMIT_STACK
11832 #ifdef RLIMIT_MEMLOCK
11835 #ifdef RLIMIT_NPROC
11838 #ifdef RLIMIT_NOFILE
11844 #ifdef RLIMIT_LOCKS
11862 for (l = limits; l->option != what; l++)
11865 set = *argptr ? 1 : 0;
11869 if (all || argptr[1])
11870 ash_msg_and_raise_error("too many arguments");
11871 if (strncmp(p, "unlimited\n", 9) == 0)
11872 val = RLIM_INFINITY;
11876 while ((c = *p++) >= '0' && c <= '9') {
11877 val = (val * 10) + (long)(c - '0');
11878 if (val < (rlim_t) 0)
11882 ash_msg_and_raise_error("bad number");
11887 for (l = limits; l->name; l++) {
11888 getrlimit(l->cmd, &limit);
11889 out1fmt("%-20s ", l->name);
11890 printlim(how, &limit, l);
11895 getrlimit(l->cmd, &limit);
11898 limit.rlim_max = val;
11900 limit.rlim_cur = val;
11901 if (setrlimit(l->cmd, &limit) < 0)
11902 ash_msg_and_raise_error("error setting limit (%m)");
11904 printlim(how, &limit, l);
11910 /* ============ Math support */
11912 #if ENABLE_ASH_MATH_SUPPORT
11914 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
11916 Permission is hereby granted, free of charge, to any person obtaining
11917 a copy of this software and associated documentation files (the
11918 "Software"), to deal in the Software without restriction, including
11919 without limitation the rights to use, copy, modify, merge, publish,
11920 distribute, sublicense, and/or sell copies of the Software, and to
11921 permit persons to whom the Software is furnished to do so, subject to
11922 the following conditions:
11924 The above copyright notice and this permission notice shall be
11925 included in all copies or substantial portions of the Software.
11927 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11928 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11929 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
11930 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
11931 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11932 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11933 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11936 /* This is my infix parser/evaluator. It is optimized for size, intended
11937 * as a replacement for yacc-based parsers. However, it may well be faster
11938 * than a comparable parser written in yacc. The supported operators are
11939 * listed in #defines below. Parens, order of operations, and error handling
11940 * are supported. This code is thread safe. The exact expression format should
11941 * be that which POSIX specifies for shells. */
11943 /* The code uses a simple two-stack algorithm. See
11944 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
11945 * for a detailed explanation of the infix-to-postfix algorithm on which
11946 * this is based (this code differs in that it applies operators immediately
11947 * to the stack instead of adding them to a queue to end up with an
11950 /* To use the routine, call it with an expression string and error return
11954 * Aug 24, 2001 Manuel Novoa III
11956 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
11958 * 1) In arith_apply():
11959 * a) Cached values of *numptr and &(numptr[-1]).
11960 * b) Removed redundant test for zero denominator.
11963 * a) Eliminated redundant code for processing operator tokens by moving
11964 * to a table-based implementation. Also folded handling of parens
11966 * b) Combined all 3 loops which called arith_apply to reduce generated
11967 * code size at the cost of speed.
11969 * 3) The following expressions were treated as valid by the original code:
11970 * 1() , 0! , 1 ( *3 ) .
11971 * These bugs have been fixed by internally enclosing the expression in
11972 * parens and then checking that all binary ops and right parens are
11973 * preceded by a valid expression (NUM_TOKEN).
11975 * Note: It may be desirable to replace Aaron's test for whitespace with
11976 * ctype's isspace() if it is used by another busybox applet or if additional
11977 * whitespace chars should be considered. Look below the "#include"s for a
11978 * precompiler test.
11982 * Aug 26, 2001 Manuel Novoa III
11984 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
11986 * Merge in Aaron's comments previously posted to the busybox list,
11987 * modified slightly to take account of my changes to the code.
11992 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11994 * - allow access to variable,
11995 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
11996 * - realize assign syntax (VAR=expr, +=, *= etc)
11997 * - realize exponentiation (** operator)
11998 * - realize comma separated - expr, expr
11999 * - realise ++expr --expr expr++ expr--
12000 * - realise expr ? expr : expr (but, second expr calculate always)
12001 * - allow hexadecimal and octal numbers
12002 * - was restored loses XOR operator
12003 * - remove one goto label, added three ;-)
12004 * - protect $((num num)) as true zero expr (Manuel`s error)
12005 * - always use special isspace(), see comment from bash ;-)
12008 #define arith_isspace(arithval) \
12009 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12011 typedef unsigned char operator;
12013 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12014 * precedence, and 3 high bits are an ID unique across operators of that
12015 * precedence. The ID portion is so that multiple operators can have the
12016 * same precedence, ensuring that the leftmost one is evaluated first.
12017 * Consider * and /. */
12019 #define tok_decl(prec,id) (((id)<<5)|(prec))
12020 #define PREC(op) ((op) & 0x1F)
12022 #define TOK_LPAREN tok_decl(0,0)
12024 #define TOK_COMMA tok_decl(1,0)
12026 #define TOK_ASSIGN tok_decl(2,0)
12027 #define TOK_AND_ASSIGN tok_decl(2,1)
12028 #define TOK_OR_ASSIGN tok_decl(2,2)
12029 #define TOK_XOR_ASSIGN tok_decl(2,3)
12030 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12031 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12032 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12033 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12035 #define TOK_MUL_ASSIGN tok_decl(3,0)
12036 #define TOK_DIV_ASSIGN tok_decl(3,1)
12037 #define TOK_REM_ASSIGN tok_decl(3,2)
12039 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12040 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12042 /* conditional is right associativity too */
12043 #define TOK_CONDITIONAL tok_decl(4,0)
12044 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12046 #define TOK_OR tok_decl(5,0)
12048 #define TOK_AND tok_decl(6,0)
12050 #define TOK_BOR tok_decl(7,0)
12052 #define TOK_BXOR tok_decl(8,0)
12054 #define TOK_BAND tok_decl(9,0)
12056 #define TOK_EQ tok_decl(10,0)
12057 #define TOK_NE tok_decl(10,1)
12059 #define TOK_LT tok_decl(11,0)
12060 #define TOK_GT tok_decl(11,1)
12061 #define TOK_GE tok_decl(11,2)
12062 #define TOK_LE tok_decl(11,3)
12064 #define TOK_LSHIFT tok_decl(12,0)
12065 #define TOK_RSHIFT tok_decl(12,1)
12067 #define TOK_ADD tok_decl(13,0)
12068 #define TOK_SUB tok_decl(13,1)
12070 #define TOK_MUL tok_decl(14,0)
12071 #define TOK_DIV tok_decl(14,1)
12072 #define TOK_REM tok_decl(14,2)
12074 /* exponent is right associativity */
12075 #define TOK_EXPONENT tok_decl(15,1)
12077 /* For now unary operators. */
12078 #define UNARYPREC 16
12079 #define TOK_BNOT tok_decl(UNARYPREC,0)
12080 #define TOK_NOT tok_decl(UNARYPREC,1)
12082 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12083 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12085 #define PREC_PRE (UNARYPREC+2)
12087 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12088 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12090 #define PREC_POST (UNARYPREC+3)
12092 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12093 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12095 #define SPEC_PREC (UNARYPREC+4)
12097 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12098 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12100 #define NUMPTR (*numstackptr)
12103 tok_have_assign(operator op)
12105 operator prec = PREC(op);
12107 convert_prec_is_assing(prec);
12108 return (prec == PREC(TOK_ASSIGN) ||
12109 prec == PREC_PRE || prec == PREC_POST);
12113 is_right_associativity(operator prec)
12115 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12116 || prec == PREC(TOK_CONDITIONAL));
12119 typedef struct ARITCH_VAR_NUM {
12121 arith_t contidional_second_val;
12122 char contidional_second_val_initialized;
12123 char *var; /* if NULL then is regular number,
12124 else is variable name */
12127 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12129 struct CHK_VAR_RECURSIVE_LOOPED *next;
12130 } chk_var_recursive_looped_t;
12132 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12135 arith_lookup_val(v_n_t *t)
12138 const char * p = lookupvar(t->var);
12143 /* recursive try as expression */
12144 chk_var_recursive_looped_t *cur;
12145 chk_var_recursive_looped_t cur_save;
12147 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12148 if (strcmp(cur->var, t->var) == 0) {
12149 /* expression recursion loop detected */
12153 /* save current lookuped var name */
12154 cur = prev_chk_var_recursive;
12155 cur_save.var = t->var;
12156 cur_save.next = cur;
12157 prev_chk_var_recursive = &cur_save;
12159 t->val = arith (p, &errcode);
12160 /* restore previous ptr after recursiving */
12161 prev_chk_var_recursive = cur;
12164 /* allow undefined var as 0 */
12170 /* "applying" a token means performing it on the top elements on the integer
12171 * stack. For a unary operator it will only change the top element, but a
12172 * binary operator will pop two arguments and push a result */
12174 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12177 arith_t numptr_val, rez;
12178 int ret_arith_lookup_val;
12180 /* There is no operator that can work without arguments */
12181 if (NUMPTR == numstack) goto err;
12182 numptr_m1 = NUMPTR - 1;
12184 /* check operand is var with noninteger value */
12185 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12186 if (ret_arith_lookup_val)
12187 return ret_arith_lookup_val;
12189 rez = numptr_m1->val;
12190 if (op == TOK_UMINUS)
12192 else if (op == TOK_NOT)
12194 else if (op == TOK_BNOT)
12196 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12198 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12200 else if (op != TOK_UPLUS) {
12201 /* Binary operators */
12203 /* check and binary operators need two arguments */
12204 if (numptr_m1 == numstack) goto err;
12206 /* ... and they pop one */
12209 if (op == TOK_CONDITIONAL) {
12210 if (! numptr_m1->contidional_second_val_initialized) {
12211 /* protect $((expr1 ? expr2)) without ": expr" */
12214 rez = numptr_m1->contidional_second_val;
12215 } else if (numptr_m1->contidional_second_val_initialized) {
12216 /* protect $((expr1 : expr2)) without "expr ? " */
12219 numptr_m1 = NUMPTR - 1;
12220 if (op != TOK_ASSIGN) {
12221 /* check operand is var with noninteger value for not '=' */
12222 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12223 if (ret_arith_lookup_val)
12224 return ret_arith_lookup_val;
12226 if (op == TOK_CONDITIONAL) {
12227 numptr_m1->contidional_second_val = rez;
12229 rez = numptr_m1->val;
12230 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12232 else if (op == TOK_OR)
12233 rez = numptr_val || rez;
12234 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12236 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12238 else if (op == TOK_AND)
12239 rez = rez && numptr_val;
12240 else if (op == TOK_EQ)
12241 rez = (rez == numptr_val);
12242 else if (op == TOK_NE)
12243 rez = (rez != numptr_val);
12244 else if (op == TOK_GE)
12245 rez = (rez >= numptr_val);
12246 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12247 rez >>= numptr_val;
12248 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12249 rez <<= numptr_val;
12250 else if (op == TOK_GT)
12251 rez = (rez > numptr_val);
12252 else if (op == TOK_LT)
12253 rez = (rez < numptr_val);
12254 else if (op == TOK_LE)
12255 rez = (rez <= numptr_val);
12256 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12258 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12260 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12262 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12264 else if (op == TOK_CONDITIONAL_SEP) {
12265 if (numptr_m1 == numstack) {
12266 /* protect $((expr : expr)) without "expr ? " */
12269 numptr_m1->contidional_second_val_initialized = op;
12270 numptr_m1->contidional_second_val = numptr_val;
12271 } else if (op == TOK_CONDITIONAL) {
12273 numptr_val : numptr_m1->contidional_second_val;
12274 } else if (op == TOK_EXPONENT) {
12275 if (numptr_val < 0)
12276 return -3; /* exponent less than 0 */
12281 while (numptr_val--)
12285 } else if (numptr_val==0) /* zero divisor check */
12287 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12289 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12292 if (tok_have_assign(op)) {
12293 char buf[sizeof(arith_t_type)*3 + 2];
12295 if (numptr_m1->var == NULL) {
12299 /* save to shell variable */
12300 #if ENABLE_ASH_MATH_SUPPORT_64
12301 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12303 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12305 setvar(numptr_m1->var, buf, 0);
12306 /* after saving, make previous value for v++ or v-- */
12307 if (op == TOK_POST_INC)
12309 else if (op == TOK_POST_DEC)
12312 numptr_m1->val = rez;
12313 /* protect geting var value, is number now */
12314 numptr_m1->var = NULL;
12320 /* longest must be first */
12321 static const char op_tokens[] = {
12322 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12323 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12324 '<','<', 0, TOK_LSHIFT,
12325 '>','>', 0, TOK_RSHIFT,
12326 '|','|', 0, TOK_OR,
12327 '&','&', 0, TOK_AND,
12328 '!','=', 0, TOK_NE,
12329 '<','=', 0, TOK_LE,
12330 '>','=', 0, TOK_GE,
12331 '=','=', 0, TOK_EQ,
12332 '|','=', 0, TOK_OR_ASSIGN,
12333 '&','=', 0, TOK_AND_ASSIGN,
12334 '*','=', 0, TOK_MUL_ASSIGN,
12335 '/','=', 0, TOK_DIV_ASSIGN,
12336 '%','=', 0, TOK_REM_ASSIGN,
12337 '+','=', 0, TOK_PLUS_ASSIGN,
12338 '-','=', 0, TOK_MINUS_ASSIGN,
12339 '-','-', 0, TOK_POST_DEC,
12340 '^','=', 0, TOK_XOR_ASSIGN,
12341 '+','+', 0, TOK_POST_INC,
12342 '*','*', 0, TOK_EXPONENT,
12346 '=', 0, TOK_ASSIGN,
12358 '?', 0, TOK_CONDITIONAL,
12359 ':', 0, TOK_CONDITIONAL_SEP,
12360 ')', 0, TOK_RPAREN,
12361 '(', 0, TOK_LPAREN,
12365 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12368 arith(const char *expr, int *perrcode)
12370 char arithval; /* Current character under analysis */
12371 operator lasttok, op;
12374 const char *p = endexpression;
12377 size_t datasizes = strlen(expr) + 2;
12379 /* Stack of integers */
12380 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12381 * in any given correct or incorrect expression is left as an exercise to
12383 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12384 *numstackptr = numstack;
12385 /* Stack of operator tokens */
12386 operator *stack = alloca((datasizes) * sizeof(operator)),
12389 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12390 *perrcode = errcode = 0;
12394 if (arithval == 0) {
12395 if (p == endexpression) {
12396 /* Null expression. */
12400 /* This is only reached after all tokens have been extracted from the
12401 * input stream. If there are still tokens on the operator stack, they
12402 * are to be applied in order. At the end, there should be a final
12403 * result on the integer stack */
12405 if (expr != endexpression + 1) {
12406 /* If we haven't done so already, */
12407 /* append a closing right paren */
12408 expr = endexpression;
12409 /* and let the loop process it. */
12412 /* At this point, we're done with the expression. */
12413 if (numstackptr != numstack+1) {
12414 /* ... but if there isn't, it's bad */
12416 return (*perrcode = -1);
12418 if (numstack->var) {
12419 /* expression is $((var)) only, lookup now */
12420 errcode = arith_lookup_val(numstack);
12423 *perrcode = errcode;
12424 return numstack->val;
12427 /* Continue processing the expression. */
12428 if (arith_isspace(arithval)) {
12429 /* Skip whitespace */
12432 p = endofname(expr);
12434 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12436 numstackptr->var = alloca(var_name_size);
12437 safe_strncpy(numstackptr->var, expr, var_name_size);
12440 numstackptr->contidional_second_val_initialized = 0;
12445 if (isdigit(arithval)) {
12446 numstackptr->var = NULL;
12447 #if ENABLE_ASH_MATH_SUPPORT_64
12448 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12450 numstackptr->val = strtol(expr, (char **) &expr, 0);
12454 for (p = op_tokens; ; p++) {
12458 /* strange operator not found */
12461 for (o = expr; *p && *o == *p; p++)
12468 /* skip tail uncompared token */
12471 /* skip zero delim */
12476 /* post grammar: a++ reduce to num */
12477 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12480 /* Plus and minus are binary (not unary) _only_ if the last
12481 * token was as number, or a right paren (which pretends to be
12482 * a number, since it evaluates to one). Think about it.
12483 * It makes sense. */
12484 if (lasttok != TOK_NUM) {
12500 /* We don't want a unary operator to cause recursive descent on the
12501 * stack, because there can be many in a row and it could cause an
12502 * operator to be evaluated before its argument is pushed onto the
12503 * integer stack. */
12504 /* But for binary operators, "apply" everything on the operator
12505 * stack until we find an operator with a lesser priority than the
12506 * one we have just extracted. */
12507 /* Left paren is given the lowest priority so it will never be
12508 * "applied" in this way.
12509 * if associativity is right and priority eq, applied also skip
12512 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12513 /* not left paren or unary */
12514 if (lasttok != TOK_NUM) {
12515 /* binary op must be preceded by a num */
12518 while (stackptr != stack) {
12519 if (op == TOK_RPAREN) {
12520 /* The algorithm employed here is simple: while we don't
12521 * hit an open paren nor the bottom of the stack, pop
12522 * tokens and apply them */
12523 if (stackptr[-1] == TOK_LPAREN) {
12525 /* Any operator directly after a */
12527 /* close paren should consider itself binary */
12531 operator prev_prec = PREC(stackptr[-1]);
12533 convert_prec_is_assing(prec);
12534 convert_prec_is_assing(prev_prec);
12535 if (prev_prec < prec)
12537 /* check right assoc */
12538 if (prev_prec == prec && is_right_associativity(prec))
12541 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12542 if (errcode) goto ret;
12544 if (op == TOK_RPAREN) {
12549 /* Push this operator to the stack and remember it. */
12550 *stackptr++ = lasttok = op;
12555 #endif /* ASH_MATH_SUPPORT */
12558 /* ============ main() and helpers */
12561 * Called to exit the shell.
12563 static void exitshell(void) ATTRIBUTE_NORETURN;
12571 status = exitstatus;
12572 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12573 if (setjmp(loc.loc)) {
12574 if (exception == EXEXIT)
12575 /* dash bug: it just does _exit(exitstatus) here
12576 * but we have to do setjobctl(0) first!
12577 * (bug is still not fixed in dash-0.5.3 - if you run dash
12578 * under Midnight Commander, on exit from dash MC is backgrounded) */
12579 status = exitstatus;
12582 exception_handler = &loc;
12588 flush_stdout_stderr();
12598 /* from input.c: */
12599 basepf.nextc = basepf.buf = basebuf;
12602 signal(SIGCHLD, SIG_DFL);
12607 char ppid[sizeof(int)*3 + 1];
12609 struct stat st1, st2;
12612 for (envp = environ; envp && *envp; envp++) {
12613 if (strchr(*envp, '=')) {
12614 setvareq(*envp, VEXPORT|VTEXTFIXED);
12618 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12619 setvar("PPID", ppid, 0);
12621 p = lookupvar("PWD");
12623 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12624 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12631 * Process the shell command line arguments.
12634 procargs(int argc, char **argv)
12637 const char *xminusc;
12644 for (i = 0; i < NOPTS; i++)
12650 if (*xargv == NULL) {
12652 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12655 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12659 for (i = 0; i < NOPTS; i++)
12660 if (optlist[i] == 2)
12665 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12670 } else if (!sflag) {
12671 setinputfile(*xargv, 0);
12674 commandname = arg0;
12677 shellparam.p = xargv;
12678 #if ENABLE_ASH_GETOPTS
12679 shellparam.optind = 1;
12680 shellparam.optoff = -1;
12682 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
12684 shellparam.nparam++;
12691 * Read /etc/profile or .profile.
12694 read_profile(const char *name)
12698 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12707 * This routine is called when an error or an interrupt occurs in an
12708 * interactive shell and control is returned to the main command loop.
12716 /* from input.c: */
12717 parselleft = parsenleft = 0; /* clear input buffer */
12719 /* from parser.c: */
12722 /* from redir.c: */
12727 static short profile_buf[16384];
12728 extern int etext();
12732 * Main routine. We initialize things, parse the arguments, execute
12733 * profiles if we're a login shell, and then call cmdloop to execute
12734 * commands. The setjmp call sets up the location to jump to when an
12735 * exception occurs. When an exception occurs the variable "state"
12736 * is used to figure out how far we had gotten.
12738 int ash_main(int argc, char **argv);
12739 int ash_main(int argc, char **argv)
12742 volatile int state;
12743 struct jmploc jmploc;
12744 struct stackmark smark;
12747 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12750 #if ENABLE_FEATURE_EDITING
12751 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12754 if (setjmp(jmploc.loc)) {
12764 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12768 outcslow('\n', stderr);
12770 popstackmark(&smark);
12771 FORCE_INT_ON; /* enable interrupts */
12780 exception_handler = &jmploc;
12783 trace_puts("Shell args: ");
12784 trace_puts_args(argv);
12786 rootpid = getpid();
12788 #if ENABLE_ASH_RANDOM_SUPPORT
12789 rseed = rootpid + time(NULL);
12792 setstackmark(&smark);
12793 procargs(argc, argv);
12794 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12796 const char *hp = lookupvar("HISTFILE");
12799 hp = lookupvar("HOME");
12801 char *defhp = concat_path_file(hp, ".ash_history");
12802 setvar("HISTFILE", defhp, 0);
12808 if (argv[0] && argv[0][0] == '-')
12812 read_profile("/etc/profile");
12815 read_profile(".profile");
12821 getuid() == geteuid() && getgid() == getegid() &&
12825 shinit = lookupvar("ENV");
12826 if (shinit != NULL && *shinit != '\0') {
12827 read_profile(shinit);
12833 evalstring(minusc, 0);
12835 if (sflag || minusc == NULL) {
12836 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12838 const char *hp = lookupvar("HISTFILE");
12841 line_input_state->hist_file = hp;
12844 state4: /* XXX ??? - why isn't this before the "if" statement */
12852 extern void _mcleanup(void);
12861 const char *applet_name = "debug stuff usage";
12862 int main(int argc, char **argv)
12864 return ash_main(argc, argv);
12870 * Copyright (c) 1989, 1991, 1993, 1994
12871 * The Regents of the University of California. All rights reserved.
12873 * This code is derived from software contributed to Berkeley by
12874 * Kenneth Almquist.
12876 * Redistribution and use in source and binary forms, with or without
12877 * modification, are permitted provided that the following conditions
12879 * 1. Redistributions of source code must retain the above copyright
12880 * notice, this list of conditions and the following disclaimer.
12881 * 2. Redistributions in binary form must reproduce the above copyright
12882 * notice, this list of conditions and the following disclaimer in the
12883 * documentation and/or other materials provided with the distribution.
12884 * 3. Neither the name of the University nor the names of its contributors
12885 * may be used to endorse or promote products derived from this software
12886 * without specific prior written permission.
12888 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12889 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12890 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12891 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12892 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12893 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12894 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12895 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12896 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12897 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF