1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
12 * This code is derived from software contributed to Berkeley by
15 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
17 * Original BSD copyright notice is retained at the end of this file.
21 * rewrite arith.y to micro stack based cryptic algorithm by
22 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
24 * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
27 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
28 * used in busybox and size optimizations,
29 * rewrote arith (see notes to this), added locale support,
30 * rewrote dynamic variables.
35 * The follow should be set to reflect the type of system you have:
36 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
37 * define SYSV if you are running under System V.
38 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
39 * define DEBUG=2 to compile in and turn on debugging.
41 * When debugging is on, debugging info will be written to ./trace and
42 * a quit signal will generate a core dump.
47 #if ENABLE_ASH_JOB_CONTROL
60 #if JOBS || ENABLE_ASH_READ_NCHARS
64 #if defined(__uClinux__)
65 #error "Do not even bother, ash will not run on uClinux"
69 /* ============ Shell options */
71 static const char *const optletters_optnames[] = {
92 #define optletters(n) optletters_optnames[(n)][0]
93 #define optnames(n) (&optletters_optnames[(n)][1])
95 #define NOPTS (sizeof(optletters_optnames)/sizeof(optletters_optnames[0]))
97 static char optlist[NOPTS];
99 #define eflag optlist[0]
100 #define fflag optlist[1]
101 #define Iflag optlist[2]
102 #define iflag optlist[3]
103 #define mflag optlist[4]
104 #define nflag optlist[5]
105 #define sflag optlist[6]
106 #define xflag optlist[7]
107 #define vflag optlist[8]
108 #define Cflag optlist[9]
109 #define aflag optlist[10]
110 #define bflag optlist[11]
111 #define uflag optlist[12]
112 #define viflag optlist[13]
114 #define nolog optlist[14]
115 #define debug optlist[15]
119 /* ============ Misc data */
123 static int *dash_errno;
125 #define errno (*dash_errno)
128 static char nullstr[1]; /* zero length string */
129 static const char homestr[] = "HOME";
130 static const char snlfmt[] = "%s\n";
131 static const char illnum[] = "Illegal number: %s";
133 static int isloginsh;
134 /* pid of main shell */
136 /* shell level: 0 for the main shell, 1 for its children, and so on */
138 #define rootshell (!shlvl)
139 /* trap handler commands */
140 static char *trap[NSIG];
141 /* current value of signal */
142 static char sigmode[NSIG - 1];
143 /* indicates specified signal received */
144 static char gotsig[NSIG - 1];
145 static char *arg0; /* value of $0 */
148 /* ============ Interrupts / exceptions
150 * We enclose jmp_buf in a structure so that we can declare pointers to
151 * jump locations. The global variable handler contains the location to
152 * jump to when an exception occurs, and the global variable exception
153 * contains a code identifying the exception. To implement nested
154 * exception handlers, the user should save the value of handler on entry
155 * to an inner scope, set handler to point to a jmploc structure for the
156 * inner scope, and restore handler on exit from the scope.
161 static struct jmploc *exception_handler;
162 static int exception;
164 #define EXINT 0 /* SIGINT received */
165 #define EXERROR 1 /* a generic error */
166 #define EXSHELLPROC 2 /* execute a shell procedure */
167 #define EXEXEC 3 /* command execution failed */
168 #define EXEXIT 4 /* exit the shell */
169 #define EXSIG 5 /* trapped signal in wait(1) */
170 static volatile int suppressint;
171 static volatile sig_atomic_t intpending;
172 /* do we generate EXSIG events */
174 /* last pending signal */
175 static volatile sig_atomic_t pendingsigs;
178 * Sigmode records the current value of the signal handlers for the various
179 * modes. A value of zero means that the current handler is not known.
180 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
183 #define S_DFL 1 /* default signal handling (SIG_DFL) */
184 #define S_CATCH 2 /* signal is caught */
185 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
186 #define S_HARD_IGN 4 /* signal is ignored permenantly */
187 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
190 * These macros allow the user to suspend the handling of interrupt signals
191 * over a period of time. This is similar to SIGHOLD to or sigblock, but
192 * much more efficient and portable. (But hacking the kernel is so much
193 * more fun than worrying about efficiency and portability. :-))
195 #define xbarrier() ({ __asm__ __volatile__ ("": : :"memory"); })
204 * Called to raise an exception. Since C doesn't include exceptions, we
205 * just do a longjmp to the exception handler. The type of exception is
206 * stored in the global variable "exception".
208 static void raise_exception(int) ATTRIBUTE_NORETURN;
210 raise_exception(int e)
213 if (exception_handler == NULL)
218 longjmp(exception_handler->loc, 1);
222 * Called from trap.c when a SIGINT is received. (If the user specifies
223 * that SIGINT is to be trapped or ignored using the trap builtin, then
224 * this routine is not called.) Suppressint is nonzero when interrupts
225 * are held using the INT_OFF macro. (The test for iflag is just
226 * defensive programming.)
228 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
230 raise_interrupt(void)
236 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
237 if (!(rootshell && iflag)) {
238 signal(SIGINT, SIG_DFL);
247 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
251 if (--suppressint == 0 && intpending) {
255 #define INT_ON int_on()
263 #define FORCE_INT_ON force_int_on()
268 if (--suppressint == 0 && intpending) raise_interrupt(); \
271 #define FORCE_INT_ON \
275 if (intpending) raise_interrupt(); \
278 #endif /* ASH_OPTIMIZE_FOR_SIZE */
280 #define SAVE_INT(v) ((v) = suppressint)
282 #define RESTORE_INT(v) \
286 if (suppressint == 0 && intpending) raise_interrupt(); \
295 raise_exception(EXSIG); \
298 /* EXSIG is turned off by evalbltin(). */
301 * Ignore a signal. Only one usage site - in forkchild()
306 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
307 signal(signo, SIG_IGN);
309 sigmode[signo - 1] = S_HARD_IGN;
313 * Signal handler. Only one usage site - in setsignal()
318 gotsig[signo - 1] = 1;
321 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
329 /* ============ stdout/stderr output */
332 outstr(const char *p, FILE *file)
340 flush_stdout_stderr(void)
357 outcslow(int c, FILE *dest)
365 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
367 out1fmt(const char *fmt, ...)
374 r = vprintf(fmt, ap);
380 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
382 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
389 ret = vsnprintf(outbuf, length, fmt, ap);
396 out1str(const char *p)
402 out2str(const char *p)
409 /* ============ Parsing structures */
443 union node *redirect;
449 struct nodelist *cmdlist;
455 union node *redirect;
468 union node *elsepart;
495 struct nodelist *backquote;
530 struct nredir nredir;
531 struct nbinary nbinary;
535 struct nclist nclist;
544 struct nodelist *next;
554 /* ============ Debugging output */
558 static FILE *tracefile;
561 trace_printf(const char *fmt, ...)
568 vfprintf(tracefile, fmt, va);
573 trace_vprintf(const char *fmt, va_list va)
577 vfprintf(tracefile, fmt, va);
581 trace_puts(const char *s)
589 trace_puts_quoted(char *s)
596 putc('"', tracefile);
597 for (p = s; *p; p++) {
599 case '\n': c = 'n'; goto backslash;
600 case '\t': c = 't'; goto backslash;
601 case '\r': c = 'r'; goto backslash;
602 case '"': c = '"'; goto backslash;
603 case '\\': c = '\\'; goto backslash;
604 case CTLESC: c = 'e'; goto backslash;
605 case CTLVAR: c = 'v'; goto backslash;
606 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
607 case CTLBACKQ: c = 'q'; goto backslash;
608 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
610 putc('\\', tracefile);
614 if (*p >= ' ' && *p <= '~')
617 putc('\\', tracefile);
618 putc(*p >> 6 & 03, tracefile);
619 putc(*p >> 3 & 07, tracefile);
620 putc(*p & 07, tracefile);
625 putc('"', tracefile);
629 trace_puts_args(char **ap)
636 trace_puts_quoted(*ap);
638 putc('\n', tracefile);
641 putc(' ', tracefile);
656 /* leave open because libedit might be using it */
659 strcpy(s, "./trace");
661 if (!freopen(s, "a", tracefile)) {
662 fprintf(stderr, "Can't re-open %s\n", s);
667 tracefile = fopen(s, "a");
668 if (tracefile == NULL) {
669 fprintf(stderr, "Can't open %s\n", s);
675 flags = fcntl(fileno(tracefile), F_GETFL, 0);
677 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
679 setlinebuf(tracefile);
680 fputs("\nTracing started.\n", tracefile);
684 indent(int amount, char *pfx, FILE *fp)
688 for (i = 0; i < amount; i++) {
689 if (pfx && i == amount - 1)
695 /* little circular references here... */
696 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
699 sharg(union node *arg, FILE *fp)
702 struct nodelist *bqlist;
705 if (arg->type != NARG) {
706 out1fmt("<node type %d>\n", arg->type);
709 bqlist = arg->narg.backquote;
710 for (p = arg->narg.text; *p; p++) {
719 if (subtype == VSLENGTH)
728 switch (subtype & VSTYPE) {
761 out1fmt("<subtype %d>", subtype);
768 case CTLBACKQ|CTLQUOTE:
771 shtree(bqlist->n, -1, NULL, fp);
782 shcmd(union node *cmd, FILE *fp)
790 for (np = cmd->ncmd.args; np; np = np->narg.next) {
796 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
799 switch (np->nfile.type) {
800 case NTO: s = ">"; dftfd = 1; break;
801 case NCLOBBER: s = ">|"; dftfd = 1; break;
802 case NAPPEND: s = ">>"; dftfd = 1; break;
803 case NTOFD: s = ">&"; dftfd = 1; break;
804 case NFROM: s = "<"; dftfd = 0; break;
805 case NFROMFD: s = "<&"; dftfd = 0; break;
806 case NFROMTO: s = "<>"; dftfd = 0; break;
807 default: s = "*error*"; dftfd = 0; break;
809 if (np->nfile.fd != dftfd)
810 fprintf(fp, "%d", np->nfile.fd);
812 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
813 fprintf(fp, "%d", np->ndup.dupfd);
815 sharg(np->nfile.fname, fp);
822 shtree(union node *n, int ind, char *pfx, FILE *fp)
830 indent(ind, pfx, fp);
841 shtree(n->nbinary.ch1, ind, NULL, fp);
844 shtree(n->nbinary.ch2, ind, NULL, fp);
852 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
857 if (n->npipe.backgnd)
863 fprintf(fp, "<node type %d>", n->type);
871 showtree(union node *n)
873 trace_puts("showtree called\n");
874 shtree(n, 1, NULL, stdout);
877 #define TRACE(param) trace_printf param
878 #define TRACEV(param) trace_vprintf param
883 #define TRACEV(param)
888 /* ============ Parser data
890 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
894 struct strlist *next;
902 static int aliascmd(int, char **);
903 static int unaliascmd(int, char **);
904 static void printalias(const struct alias *);
908 struct strpush *prev; /* preceding string on stack */
912 struct alias *ap; /* if push was associated with an alias */
914 char *string; /* remember the string since it may change */
918 struct parsefile *prev; /* preceding file on stack */
919 int linno; /* current line */
920 int fd; /* file descriptor (or -1 if string) */
921 int nleft; /* number of chars left in this line */
922 int lleft; /* number of chars left in this buffer */
923 char *nextc; /* next char in buffer */
924 char *buf; /* input buffer */
925 struct strpush *strpush; /* for pushing strings at this level */
926 struct strpush basestrpush; /* so pushing one is fast */
929 static struct parsefile basepf; /* top level input file */
930 static struct parsefile *parsefile = &basepf; /* current input file */
931 static int startlinno; /* line # where last token started */
932 static char *commandname; /* currently executing command */
933 static struct strlist *cmdenviron; /* environment for builtin command */
934 static int exitstatus; /* exit status of last command */
935 static int back_exitstatus; /* exit status of backquoted command */
938 /* ============ Message printing */
941 ash_vmsg(const char *msg, va_list ap)
943 fprintf(stderr, "%s: ", arg0);
945 const char *fmt = (!iflag || parsefile->fd) ?
947 fprintf(stderr, fmt, commandname, startlinno);
949 vfprintf(stderr, msg, ap);
950 outcslow('\n', stderr);
954 * Exverror is called to raise the error exception. If the second argument
955 * is not NULL then error prints an error message using printf style
956 * formatting. It then raises the error exception.
958 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
960 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
964 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
966 TRACE(("\") pid=%d\n", getpid()));
968 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
973 flush_stdout_stderr();
974 raise_exception(cond);
978 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
980 ash_msg_and_raise_error(const char *msg, ...)
985 ash_vmsg_and_raise(EXERROR, msg, ap);
990 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
992 ash_msg_and_raise(int cond, const char *msg, ...)
997 ash_vmsg_and_raise(cond, msg, ap);
1003 * error/warning routines for external builtins
1006 ash_msg(const char *fmt, ...)
1016 * Return a string describing an error. The returned string may be a
1017 * pointer to a static buffer that will be overwritten on the next call.
1018 * Action describes the operation that got the error.
1021 errmsg(int e, const char *em)
1023 if (e == ENOENT || e == ENOTDIR) {
1030 /* ============ Memory allocation */
1033 * It appears that grabstackstr() will barf with such alignments
1034 * because stalloc() will return a string allocated in a new stackblock.
1036 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1038 /* Most machines require the value returned from malloc to be aligned
1039 * in some way. The following macro will get this right
1040 * on many machines. */
1041 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1042 /* Minimum size of a block */
1043 MINSIZE = SHELL_ALIGN(504),
1046 struct stack_block {
1047 struct stack_block *prev;
1048 char space[MINSIZE];
1052 struct stack_block *stackp;
1055 struct stackmark *marknext;
1058 static struct stack_block stackbase;
1059 static struct stack_block *stackp = &stackbase;
1060 static struct stackmark *markp;
1061 static char *stacknxt = stackbase.space;
1062 static size_t stacknleft = MINSIZE;
1063 static char *sstrend = stackbase.space + MINSIZE;
1064 static int herefd = -1;
1066 #define stackblock() ((void *)stacknxt)
1067 #define stackblocksize() stacknleft
1070 ckrealloc(void * p, size_t nbytes)
1072 p = realloc(p, nbytes);
1074 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1079 ckmalloc(size_t nbytes)
1081 return ckrealloc(NULL, nbytes);
1085 * Make a copy of a string in safe storage.
1088 ckstrdup(const char *s)
1090 char *p = strdup(s);
1092 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1097 * Parse trees for commands are allocated in lifo order, so we use a stack
1098 * to make this more efficient, and also to avoid all sorts of exception
1099 * handling code to handle interrupts in the middle of a parse.
1101 * The size 504 was chosen because the Ultrix malloc handles that size
1105 stalloc(size_t nbytes)
1110 aligned = SHELL_ALIGN(nbytes);
1111 if (aligned > stacknleft) {
1114 struct stack_block *sp;
1116 blocksize = aligned;
1117 if (blocksize < MINSIZE)
1118 blocksize = MINSIZE;
1119 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1120 if (len < blocksize)
1121 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1125 stacknxt = sp->space;
1126 stacknleft = blocksize;
1127 sstrend = stacknxt + blocksize;
1132 stacknxt += aligned;
1133 stacknleft -= aligned;
1141 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
1142 write(2, "stunalloc\n", 10);
1146 stacknleft += stacknxt - (char *)p;
1151 * Like strdup but works with the ash stack.
1154 ststrdup(const char *p)
1156 size_t len = strlen(p) + 1;
1157 return memcpy(stalloc(len), p, len);
1161 setstackmark(struct stackmark *mark)
1163 mark->stackp = stackp;
1164 mark->stacknxt = stacknxt;
1165 mark->stacknleft = stacknleft;
1166 mark->marknext = markp;
1171 popstackmark(struct stackmark *mark)
1173 struct stack_block *sp;
1176 markp = mark->marknext;
1177 while (stackp != mark->stackp) {
1182 stacknxt = mark->stacknxt;
1183 stacknleft = mark->stacknleft;
1184 sstrend = mark->stacknxt + mark->stacknleft;
1189 * When the parser reads in a string, it wants to stick the string on the
1190 * stack and only adjust the stack pointer when it knows how big the
1191 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1192 * of space on top of the stack and stackblocklen returns the length of
1193 * this block. Growstackblock will grow this space by at least one byte,
1194 * possibly moving it (like realloc). Grabstackblock actually allocates the
1195 * part of the block that has been used.
1198 growstackblock(void)
1202 newlen = stacknleft * 2;
1203 if (newlen < stacknleft)
1204 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1208 if (stacknxt == stackp->space && stackp != &stackbase) {
1209 struct stack_block *oldstackp;
1210 struct stackmark *xmark;
1211 struct stack_block *sp;
1212 struct stack_block *prevstackp;
1218 prevstackp = sp->prev;
1219 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1220 sp = ckrealloc(sp, grosslen);
1221 sp->prev = prevstackp;
1223 stacknxt = sp->space;
1224 stacknleft = newlen;
1225 sstrend = sp->space + newlen;
1228 * Stack marks pointing to the start of the old block
1229 * must be relocated to point to the new block
1232 while (xmark != NULL && xmark->stackp == oldstackp) {
1233 xmark->stackp = stackp;
1234 xmark->stacknxt = stacknxt;
1235 xmark->stacknleft = stacknleft;
1236 xmark = xmark->marknext;
1240 char *oldspace = stacknxt;
1241 int oldlen = stacknleft;
1242 char *p = stalloc(newlen);
1244 /* free the space we just allocated */
1245 stacknxt = memcpy(p, oldspace, oldlen);
1246 stacknleft += newlen;
1251 grabstackblock(size_t len)
1253 len = SHELL_ALIGN(len);
1259 * The following routines are somewhat easier to use than the above.
1260 * The user declares a variable of type STACKSTR, which may be declared
1261 * to be a register. The macro STARTSTACKSTR initializes things. Then
1262 * the user uses the macro STPUTC to add characters to the string. In
1263 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1264 * grown as necessary. When the user is done, she can just leave the
1265 * string there and refer to it using stackblock(). Or she can allocate
1266 * the space for it using grabstackstr(). If it is necessary to allow
1267 * someone else to use the stack temporarily and then continue to grow
1268 * the string, the user should use grabstack to allocate the space, and
1269 * then call ungrabstr(p) to return to the previous mode of operation.
1271 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1272 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1273 * is space for at least one character.
1278 size_t len = stackblocksize();
1279 if (herefd >= 0 && len >= 1024) {
1280 full_write(herefd, stackblock(), len);
1281 return stackblock();
1284 return stackblock() + len;
1288 * Called from CHECKSTRSPACE.
1291 makestrspace(size_t newlen, char *p)
1293 size_t len = p - stacknxt;
1294 size_t size = stackblocksize();
1299 size = stackblocksize();
1301 if (nleft >= newlen)
1305 return stackblock() + len;
1309 stack_nputstr(const char *s, size_t n, char *p)
1311 p = makestrspace(n, p);
1312 p = memcpy(p, s, n) + n;
1317 stack_putstr(const char *s, char *p)
1319 return stack_nputstr(s, strlen(s), p);
1323 _STPUTC(int c, char *p)
1331 #define STARTSTACKSTR(p) ((p) = stackblock())
1332 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1333 #define CHECKSTRSPACE(n, p) \
1337 size_t m = sstrend - q; \
1339 (p) = makestrspace(l, q); \
1342 #define USTPUTC(c, p) (*p++ = (c))
1343 #define STACKSTRNUL(p) ((p) == sstrend ? (p = growstackstr(), *p = '\0') : (*p = '\0'))
1344 #define STUNPUTC(p) (--p)
1345 #define STTOPC(p) p[-1]
1346 #define STADJUST(amount, p) (p += (amount))
1348 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1349 #define ungrabstackstr(s, p) stunalloc((s))
1350 #define stackstrend() ((void *)sstrend)
1353 /* ============ String helpers */
1356 * prefix -- see if pfx is a prefix of string.
1359 prefix(const char *string, const char *pfx)
1362 if (*pfx++ != *string++)
1365 return (char *) string;
1369 * Check for a valid number. This should be elsewhere.
1372 is_number(const char *p)
1377 } while (*++p != '\0');
1382 * Convert a string of digits to an integer, printing an error message on
1386 number(const char *s)
1389 ash_msg_and_raise_error(illnum, s);
1394 * Produce a possibly single quoted string suitable as input to the shell.
1395 * The return string is allocated on the stack.
1398 single_quote(const char *s)
1408 len = strchrnul(s, '\'') - s;
1410 q = p = makestrspace(len + 3, p);
1413 q = memcpy(q, s, len) + len;
1419 len = strspn(s, "'");
1423 q = p = makestrspace(len + 3, p);
1426 q = memcpy(q, s, len) + len;
1435 return stackblock();
1439 /* ============ ... */
1441 static char **argptr; /* argument list for builtin commands */
1442 static char *optionarg; /* set by nextopt (like getopt) */
1443 static char *optptr; /* used by nextopt */
1446 * XXX - should get rid of. have all builtins use getopt(3). the
1447 * library getopt must have the BSD extension static variable "optreset"
1448 * otherwise it can't be used within the shell safely.
1450 * Standard option processing (a la getopt) for builtin routines. The
1451 * only argument that is passed to nextopt is the option string; the
1452 * other arguments are unnecessary. It return the character, or '\0' on
1456 nextopt(const char *optstring)
1463 if (p == NULL || *p == '\0') {
1465 if (p == NULL || *p != '-' || *++p == '\0')
1468 if (LONE_DASH(p)) /* check for "--" */
1472 for (q = optstring; *q != c; ) {
1474 ash_msg_and_raise_error("Illegal option -%c", c);
1479 if (*p == '\0' && (p = *argptr++) == NULL)
1480 ash_msg_and_raise_error("No arg for -%c option", c);
1489 /* ============ Variables */
1492 #define VEXPORT 0x01 /* variable is exported */
1493 #define VREADONLY 0x02 /* variable cannot be modified */
1494 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1495 #define VTEXTFIXED 0x08 /* text is statically allocated */
1496 #define VSTACK 0x10 /* text is allocated on the stack */
1497 #define VUNSET 0x20 /* the variable is not set */
1498 #define VNOFUNC 0x40 /* don't call the callback function */
1499 #define VNOSET 0x80 /* do not set variable - just readonly test */
1500 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1502 # define VDYNAMIC 0x200 /* dynamic variable */
1507 #if ENABLE_LOCALE_SUPPORT
1508 static void change_lc_all(const char *value);
1509 static void change_lc_ctype(const char *value);
1512 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
1514 static const char defifsvar[] = "IFS= \t\n";
1515 #define defifs (defifsvar + 4)
1517 static const char defifs[] = " \t\n";
1521 struct var *next; /* next entry in hash list */
1522 int flags; /* flags are defined above */
1523 const char *text; /* name=value */
1524 void (*func)(const char *); /* function to be called when */
1525 /* the variable gets set/unset */
1529 struct localvar *next; /* next local variable in list */
1530 struct var *vp; /* the variable that was made local */
1531 int flags; /* saved flags */
1532 const char *text; /* saved text */
1535 /* Forward decls for varinit[] */
1537 static void chkmail(void);
1538 static void changemail(const char *);
1540 static void changepath(const char *);
1541 #if ENABLE_ASH_GETOPTS
1542 static void getoptsreset(const char *);
1544 #if ENABLE_ASH_RANDOM_SUPPORT
1545 static void change_random(const char *);
1548 static struct var varinit[] = {
1550 { 0, VSTRFIXED|VTEXTFIXED, defifsvar, 0 },
1552 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", 0 },
1556 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1557 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1560 { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
1561 { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
1562 { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
1563 { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
1564 #if ENABLE_ASH_GETOPTS
1565 { 0, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1567 #if ENABLE_ASH_RANDOM_SUPPORT
1568 {0, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1570 #if ENABLE_LOCALE_SUPPORT
1571 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
1572 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
1574 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1575 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
1579 #define vifs varinit[0]
1581 #define vmail (&vifs)[1]
1582 #define vmpath (&vmail)[1]
1586 #define vpath (&vmpath)[1]
1587 #define vps1 (&vpath)[1]
1588 #define vps2 (&vps1)[1]
1589 #define vps4 (&vps2)[1]
1590 #define voptind (&vps4)[1]
1591 #if ENABLE_ASH_GETOPTS
1592 #define vrandom (&voptind)[1]
1594 #define vrandom (&vps4)[1]
1596 #define defpath (defpathvar + 5)
1599 * The following macros access the values of the above variables.
1600 * They have to skip over the name. They return the null string
1601 * for unset variables.
1603 #define ifsval() (vifs.text + 4)
1604 #define ifsset() ((vifs.flags & VUNSET) == 0)
1605 #define mailval() (vmail.text + 5)
1606 #define mpathval() (vmpath.text + 9)
1607 #define pathval() (vpath.text + 5)
1608 #define ps1val() (vps1.text + 4)
1609 #define ps2val() (vps2.text + 4)
1610 #define ps4val() (vps4.text + 4)
1611 #define optindval() (voptind.text + 7)
1613 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1615 static struct var **hashvar(const char *);
1617 static int loopnest; /* current loop nesting level */
1620 * The parsefile structure pointed to by the global variable parsefile
1621 * contains information about the current file being read.
1624 struct redirtab *next;
1629 static struct redirtab *redirlist;
1630 static int nullredirs;
1632 extern char **environ;
1634 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1637 int nparam; /* # of positional parameters (without $0) */
1638 unsigned char malloc; /* if parameter list dynamically allocated */
1639 char **p; /* parameter list */
1640 #if ENABLE_ASH_GETOPTS
1641 int optind; /* next parameter to be processed by getopts */
1642 int optoff; /* used by getopts */
1646 static struct shparam shellparam; /* $@ current positional parameters */
1650 static struct var *vartab[VTABSIZE];
1652 #if ENABLE_ASH_GETOPTS
1654 getoptsreset(const char *value)
1656 shellparam.optind = number(value);
1657 shellparam.optoff = -1;
1661 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1662 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1665 * Return of a legal variable name (a letter or underscore followed by zero or
1666 * more letters, underscores, and digits).
1669 endofname(const char *name)
1677 if (!is_in_name(*p))
1684 * Compares two strings up to the first = or '\0'. The first
1685 * string must be terminated by '='; the second may be terminated by
1686 * either '=' or '\0'.
1689 varcmp(const char *p, const char *q)
1693 while ((c = *p) == (d = *q)) {
1708 varequal(const char *a, const char *b)
1710 return !varcmp(a, b);
1714 * Find the appropriate entry in the hash table from the name.
1716 static struct var **
1717 hashvar(const char *p)
1721 hashval = ((unsigned char) *p) << 4;
1722 while (*p && *p != '=')
1723 hashval += (unsigned char) *p++;
1724 return &vartab[hashval % VTABSIZE];
1728 vpcmp(const void *a, const void *b)
1730 return varcmp(*(const char **)a, *(const char **)b);
1734 * This routine initializes the builtin variables.
1744 * PS1 depends on uid
1746 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1747 vps1.text = "PS1=\\w \\$ ";
1750 vps1.text = "PS1=# ";
1753 end = vp + sizeof(varinit) / sizeof(varinit[0]);
1755 vpp = hashvar(vp->text);
1758 } while (++vp < end);
1761 static struct var **
1762 findvar(struct var **vpp, const char *name)
1764 for (; *vpp; vpp = &(*vpp)->next) {
1765 if (varequal((*vpp)->text, name)) {
1773 * Find the value of a variable. Returns NULL if not set.
1776 lookupvar(const char *name)
1780 v = *findvar(hashvar(name), name);
1784 * Dynamic variables are implemented roughly the same way they are
1785 * in bash. Namely, they're "special" so long as they aren't unset.
1786 * As soon as they're unset, they're no longer dynamic, and dynamic
1787 * lookup will no longer happen at that point. -- PFM.
1789 if ((v->flags & VDYNAMIC))
1792 if (!(v->flags & VUNSET))
1793 return strchrnul(v->text, '=') + 1;
1799 * Search the environment of a builtin command.
1802 bltinlookup(const char *name)
1806 for (sp = cmdenviron; sp; sp = sp->next) {
1807 if (varequal(sp->text, name))
1808 return strchrnul(sp->text, '=') + 1;
1810 return lookupvar(name);
1814 * Same as setvar except that the variable and value are passed in
1815 * the first argument as name=value. Since the first argument will
1816 * be actually stored in the table, it should not be a string that
1818 * Called with interrupts off.
1821 setvareq(char *s, int flags)
1823 struct var *vp, **vpp;
1826 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1827 vp = *findvar(vpp, s);
1829 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
1832 if (flags & VNOSAVE)
1835 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
1841 if (vp->func && (flags & VNOFUNC) == 0)
1842 (*vp->func)(strchrnul(s, '=') + 1);
1844 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1845 free((char*)vp->text);
1847 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
1852 vp = ckmalloc(sizeof(*vp));
1857 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
1864 * Set the value of a variable. The flags argument is ored with the
1865 * flags of the variable. If val is NULL, the variable is unset.
1868 setvar(const char *name, const char *val, int flags)
1875 q = endofname(name);
1876 p = strchrnul(q, '=');
1878 if (!namelen || p != q)
1879 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
1884 vallen = strlen(val);
1887 nameeq = ckmalloc(namelen + vallen + 2);
1888 p = memcpy(nameeq, name, namelen) + namelen;
1891 p = memcpy(p, val, vallen) + vallen;
1894 setvareq(nameeq, flags | VNOSAVE);
1898 #if ENABLE_ASH_GETOPTS
1900 * Safe version of setvar, returns 1 on success 0 on failure.
1903 setvarsafe(const char *name, const char *val, int flags)
1906 volatile int saveint;
1907 struct jmploc *volatile savehandler = exception_handler;
1908 struct jmploc jmploc;
1911 if (setjmp(jmploc.loc))
1914 exception_handler = &jmploc;
1915 setvar(name, val, flags);
1918 exception_handler = savehandler;
1919 RESTORE_INT(saveint);
1925 * Unset the specified variable.
1928 unsetvar(const char *s)
1934 vpp = findvar(hashvar(s), s);
1938 int flags = vp->flags;
1941 if (flags & VREADONLY)
1944 vp->flags &= ~VDYNAMIC;
1948 if ((flags & VSTRFIXED) == 0) {
1950 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
1951 free((char*)vp->text);
1957 vp->flags &= ~VEXPORT;
1967 * Process a linked list of variable assignments.
1970 listsetvar(struct strlist *list_set_var, int flags)
1972 struct strlist *lp = list_set_var;
1978 setvareq(lp->text, flags);
1985 * Generate a list of variables satisfying the given conditions.
1988 listvars(int on, int off, char ***end)
1999 for (vp = *vpp; vp; vp = vp->next) {
2000 if ((vp->flags & mask) == on) {
2001 if (ep == stackstrend())
2002 ep = growstackstr();
2003 *ep++ = (char *) vp->text;
2006 } while (++vpp < vartab + VTABSIZE);
2007 if (ep == stackstrend())
2008 ep = growstackstr();
2012 return grabstackstr(ep);
2016 /* ============ Path search helper
2018 * The variable path (passed by reference) should be set to the start
2019 * of the path before the first call; padvance will update
2020 * this value as it proceeds. Successive calls to padvance will return
2021 * the possible path expansions in sequence. If an option (indicated by
2022 * a percent sign) appears in the path entry then the global variable
2023 * pathopt will be set to point to it; otherwise pathopt will be set to
2026 static const char *pathopt; /* set by padvance */
2029 padvance(const char **path, const char *name)
2039 for (p = start; *p && *p != ':' && *p != '%'; p++);
2040 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2041 while (stackblocksize() < len)
2045 memcpy(q, start, p - start);
2053 while (*p && *p != ':') p++;
2059 return stalloc(len);
2063 /* ============ Prompt */
2065 static int doprompt; /* if set, prompt the user */
2066 static int needprompt; /* true if interactive and at start of line */
2068 #if ENABLE_FEATURE_EDITING
2069 static line_input_t *line_input_state;
2070 static const char *cmdedit_prompt;
2072 putprompt(const char *s)
2074 if (ENABLE_ASH_EXPAND_PRMT) {
2075 free((char*)cmdedit_prompt);
2076 cmdedit_prompt = xstrdup(s);
2083 putprompt(const char *s)
2089 #if ENABLE_ASH_EXPAND_PRMT
2090 /* expandstr() needs parsing machinery, so it is far away ahead... */
2091 static const char *expandstr(const char *ps);
2093 #define expandstr(s) s
2097 setprompt(int whichprompt)
2100 #if ENABLE_ASH_EXPAND_PRMT
2101 struct stackmark smark;
2106 switch (whichprompt) {
2116 #if ENABLE_ASH_EXPAND_PRMT
2117 setstackmark(&smark);
2118 stalloc(stackblocksize());
2120 putprompt(expandstr(prompt));
2121 #if ENABLE_ASH_EXPAND_PRMT
2122 popstackmark(&smark);
2127 /* ============ The cd and pwd commands */
2129 #define CD_PHYSICAL 1
2132 static int docd(const char *, int);
2134 static char *curdir = nullstr; /* current working directory */
2135 static char *physdir = nullstr; /* physical working directory */
2144 while ((i = nextopt("LP"))) {
2146 flags ^= CD_PHYSICAL;
2155 * Update curdir (the name of the current directory) in response to a
2159 updatepwd(const char *dir)
2166 cdcomppath = ststrdup(dir);
2169 if (curdir == nullstr)
2171 new = stack_putstr(curdir, new);
2173 new = makestrspace(strlen(dir) + 2, new);
2174 lim = stackblock() + 1;
2178 if (new > lim && *lim == '/')
2183 if (dir[1] == '/' && dir[2] != '/') {
2189 p = strtok(cdcomppath, "/");
2193 if (p[1] == '.' && p[2] == '\0') {
2200 } else if (p[1] == '\0')
2204 new = stack_putstr(p, new);
2212 return stackblock();
2216 * Find out what the current directory is. If we already know the current
2217 * directory, this routine returns immediately.
2222 char *dir = getcwd(0, 0);
2223 return dir ? dir : nullstr;
2227 setpwd(const char *val, int setold)
2231 oldcur = dir = curdir;
2234 setvar("OLDPWD", oldcur, VEXPORT);
2237 if (physdir != nullstr) {
2238 if (physdir != oldcur)
2242 if (oldcur == val || !val) {
2248 dir = ckstrdup(val);
2249 if (oldcur != dir && oldcur != nullstr) {
2254 setvar("PWD", dir, VEXPORT);
2257 static void hashcd(void);
2260 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2261 * know that the current directory has changed.
2264 docd(const char *dest, int flags)
2266 const char *dir = 0;
2269 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2272 if (!(flags & CD_PHYSICAL)) {
2273 dir = updatepwd(dest);
2288 cdcmd(int argc, char **argv)
2300 dest = bltinlookup(homestr);
2301 else if (LONE_DASH(dest)) {
2302 dest = bltinlookup("OLDPWD");
2324 path = bltinlookup("CDPATH");
2333 p = padvance(&path, dest);
2334 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2338 if (!docd(p, flags))
2343 ash_msg_and_raise_error("can't cd to %s", dest);
2346 if (flags & CD_PRINT)
2347 out1fmt(snlfmt, curdir);
2352 pwdcmd(int argc, char **argv)
2355 const char *dir = curdir;
2359 if (physdir == nullstr)
2363 out1fmt(snlfmt, dir);
2368 /* ============ Unsorted yet */
2374 struct strlist *list;
2375 struct strlist **lastp;
2381 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
2382 #define EXP_TILDE 0x2 /* do normal tilde expansion */
2383 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
2384 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
2385 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
2386 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
2387 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
2388 #define EXP_WORD 0x80 /* expand word in parameter expansion */
2389 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
2392 static void expandarg(union node *, struct arglist *, int);
2393 #define rmescapes(p) _rmescapes((p), 0)
2394 static char *_rmescapes(char *, int);
2395 static int casematch(union node *, char *);
2397 #if ENABLE_ASH_MATH_SUPPORT
2398 static void expari(int);
2405 struct backcmd { /* result of evalbackcmd */
2406 int fd; /* file descriptor to read from */
2407 char *buf; /* buffer */
2408 int nleft; /* number of chars in buffer */
2409 struct job *jp; /* job structure for command */
2413 static void freefunc(struct funcnode *);
2416 /* control characters in argument strings */
2417 #define CTL_FIRST '\201' /* first 'special' character */
2418 #define CTLESC '\201' /* escape next character */
2419 #define CTLVAR '\202' /* variable defn */
2420 #define CTLENDVAR '\203'
2421 #define CTLBACKQ '\204'
2422 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
2423 /* CTLBACKQ | CTLQUOTE == '\205' */
2424 #define CTLARI '\206' /* arithmetic expression */
2425 #define CTLENDARI '\207'
2426 #define CTLQUOTEMARK '\210'
2427 #define CTL_LAST '\210' /* last 'special' character */
2429 /* variable substitution byte (follows CTLVAR) */
2430 #define VSTYPE 0x0f /* type of variable substitution */
2431 #define VSNUL 0x10 /* colon--treat the empty string as unset */
2432 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
2434 /* values of VSTYPE field */
2435 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
2436 #define VSMINUS 0x2 /* ${var-text} */
2437 #define VSPLUS 0x3 /* ${var+text} */
2438 #define VSQUESTION 0x4 /* ${var?message} */
2439 #define VSASSIGN 0x5 /* ${var=text} */
2440 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
2441 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
2442 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
2443 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
2444 #define VSLENGTH 0xa /* ${#var} */
2446 /* values of checkkwd variable */
2447 #define CHKALIAS 0x1
2451 #define IBUFSIZ (BUFSIZ + 1)
2454 * NEOF is returned by parsecmd when it encounters an end of file. It
2455 * must be distinct from NULL, so we use the address of a variable that
2456 * happens to be handy.
2458 static int plinno = 1; /* input line number */
2460 /* number of characters left in input buffer */
2461 static int parsenleft; /* copy of parsefile->nleft */
2462 static int parselleft; /* copy of parsefile->lleft */
2464 /* next character in input buffer */
2465 static char *parsenextc; /* copy of parsefile->nextc */
2467 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2470 static int tokpushback; /* last token pushed back */
2471 #define NEOF ((union node *)&tokpushback)
2472 static int parsebackquote; /* nonzero if we are inside backquotes */
2473 static int lasttoken; /* last token read */
2474 static char *wordtext; /* text of last word returned by readtoken */
2475 static int checkkwd;
2476 static struct nodelist *backquotelist;
2477 static union node *redirnode;
2478 static struct heredoc *heredoc;
2479 static int quoteflag; /* set if (part of) last token was quoted */
2481 static void fixredir(union node *, const char *, int);
2482 static char *endofname(const char *);
2486 static const char spcstr[] = " ";
2487 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
2489 #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2490 #define __builtin_expect(x, expected_value) (x)
2493 #define xlikely(x) __builtin_expect((x),1)
2508 #define TENDBQUOTE 12
2526 /* first char is indicating which tokens mark the end of a list */
2527 static const char *const tokname_array[] = {
2541 #define KWDOFFSET 13
2542 /* the following are keywords */
2564 static char buf[16];
2568 sprintf(buf + (tok >= TSEMI), "%s%c",
2569 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
2573 /* Wrapper around strcmp for qsort/bsearch/... */
2575 pstrcmp(const void *a, const void *b)
2577 return strcmp((const char *) a, (*(const char *const *) b) + 1);
2580 static const char *const *
2581 findkwd(const char *s)
2583 return bsearch(s, tokname_array + KWDOFFSET,
2584 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
2585 sizeof(const char *), pstrcmp);
2588 /* Syntax classes */
2589 #define CWORD 0 /* character is nothing special */
2590 #define CNL 1 /* newline character */
2591 #define CBACK 2 /* a backslash character */
2592 #define CSQUOTE 3 /* single quote */
2593 #define CDQUOTE 4 /* double quote */
2594 #define CENDQUOTE 5 /* a terminating quote */
2595 #define CBQUOTE 6 /* backwards single quote */
2596 #define CVAR 7 /* a dollar sign */
2597 #define CENDVAR 8 /* a '}' character */
2598 #define CLP 9 /* a left paren in arithmetic */
2599 #define CRP 10 /* a right paren in arithmetic */
2600 #define CENDFILE 11 /* end of file */
2601 #define CCTL 12 /* like CWORD, except it must be escaped */
2602 #define CSPCL 13 /* these terminate a word */
2603 #define CIGN 14 /* character should be ignored */
2605 #if ENABLE_ASH_ALIAS
2609 #define PEOA_OR_PEOF PEOA
2613 #define PEOA_OR_PEOF PEOF
2616 /* C99 say: "char" declaration may be signed or unsigned default */
2617 #define SC2INT(chr2may_be_negative_int) (int)((signed char)chr2may_be_negative_int)
2620 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
2621 * (assuming ascii char codes, as the original implementation did)
2623 #define is_special(c) \
2624 ( (((unsigned int)c) - 33 < 32) \
2625 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
2627 #define digit_val(c) ((c) - '0')
2630 * This file was generated by the mksyntax program.
2633 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2634 #define USE_SIT_FUNCTION
2637 /* number syntax index */
2638 #define BASESYNTAX 0 /* not in quotes */
2639 #define DQSYNTAX 1 /* in double quotes */
2640 #define SQSYNTAX 2 /* in single quotes */
2641 #define ARISYNTAX 3 /* in arithmetic */
2643 #if ENABLE_ASH_MATH_SUPPORT
2644 static const char S_I_T[][4] = {
2645 #if ENABLE_ASH_ALIAS
2646 {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
2648 {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
2649 {CNL, CNL, CNL, CNL}, /* 2, \n */
2650 {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
2651 {CDQUOTE, CENDQUOTE, CWORD, CWORD}, /* 4, '"' */
2652 {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
2653 {CSQUOTE, CWORD, CENDQUOTE, CWORD}, /* 6, "'" */
2654 {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
2655 {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
2656 {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
2657 {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
2658 {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
2659 #ifndef USE_SIT_FUNCTION
2660 {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
2661 {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
2662 {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
2666 static const char S_I_T[][3] = {
2667 #if ENABLE_ASH_ALIAS
2668 {CSPCL, CIGN, CIGN}, /* 0, PEOA */
2670 {CSPCL, CWORD, CWORD}, /* 1, ' ' */
2671 {CNL, CNL, CNL}, /* 2, \n */
2672 {CWORD, CCTL, CCTL}, /* 3, !*-/:=?[]~ */
2673 {CDQUOTE, CENDQUOTE, CWORD}, /* 4, '"' */
2674 {CVAR, CVAR, CWORD}, /* 5, $ */
2675 {CSQUOTE, CWORD, CENDQUOTE}, /* 6, "'" */
2676 {CSPCL, CWORD, CWORD}, /* 7, ( */
2677 {CSPCL, CWORD, CWORD}, /* 8, ) */
2678 {CBACK, CBACK, CCTL}, /* 9, \ */
2679 {CBQUOTE, CBQUOTE, CWORD}, /* 10, ` */
2680 {CENDVAR, CENDVAR, CWORD}, /* 11, } */
2681 #ifndef USE_SIT_FUNCTION
2682 {CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
2683 {CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
2684 {CCTL, CCTL, CCTL} /* 14, CTLESC ... */
2687 #endif /* ASH_MATH_SUPPORT */
2689 #ifdef USE_SIT_FUNCTION
2691 #define U_C(c) ((unsigned char)(c))
2694 SIT(int c, int syntax)
2696 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2697 #if ENABLE_ASH_ALIAS
2698 static const char syntax_index_table[] = {
2699 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2700 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2701 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2705 static const char syntax_index_table[] = {
2706 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2707 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2708 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2715 if (c == PEOF) /* 2^8+2 */
2717 #if ENABLE_ASH_ALIAS
2718 if (c == PEOA) /* 2^8+1 */
2722 if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
2725 s = strchr(spec_symbls, c);
2726 if (s == NULL || *s == '\0')
2728 indx = syntax_index_table[(s - spec_symbls)];
2730 return S_I_T[indx][syntax];
2733 #else /* USE_SIT_FUNCTION */
2735 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
2737 #if ENABLE_ASH_ALIAS
2738 #define CSPCL_CIGN_CIGN_CIGN 0
2739 #define CSPCL_CWORD_CWORD_CWORD 1
2740 #define CNL_CNL_CNL_CNL 2
2741 #define CWORD_CCTL_CCTL_CWORD 3
2742 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2743 #define CVAR_CVAR_CWORD_CVAR 5
2744 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2745 #define CSPCL_CWORD_CWORD_CLP 7
2746 #define CSPCL_CWORD_CWORD_CRP 8
2747 #define CBACK_CBACK_CCTL_CBACK 9
2748 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2749 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2750 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2751 #define CWORD_CWORD_CWORD_CWORD 13
2752 #define CCTL_CCTL_CCTL_CCTL 14
2754 #define CSPCL_CWORD_CWORD_CWORD 0
2755 #define CNL_CNL_CNL_CNL 1
2756 #define CWORD_CCTL_CCTL_CWORD 2
2757 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2758 #define CVAR_CVAR_CWORD_CVAR 4
2759 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2760 #define CSPCL_CWORD_CWORD_CLP 6
2761 #define CSPCL_CWORD_CWORD_CRP 7
2762 #define CBACK_CBACK_CCTL_CBACK 8
2763 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2764 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2765 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2766 #define CWORD_CWORD_CWORD_CWORD 12
2767 #define CCTL_CCTL_CCTL_CCTL 13
2770 static const char syntax_index_table[258] = {
2771 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2772 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2773 #if ENABLE_ASH_ALIAS
2774 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2776 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2778 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2779 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2780 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2781 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2782 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2783 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2784 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2785 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2914 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2915 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2937 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2939 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2941 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2943 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2944 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2945 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2946 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2949 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2951 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2952 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2964 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2965 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2966 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2967 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2968 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2996 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2997 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2998 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3001 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3029 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3030 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3031 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3034 #endif /* USE_SIT_FUNCTION */
3041 static int funcblocksize; /* size of structures in function */
3042 static int funcstringsize; /* size of strings in node */
3043 static void *funcblock; /* block to allocate function from */
3044 static char *funcstring; /* block to allocate strings from */
3046 static const short nodesize[26] = {
3047 SHELL_ALIGN(sizeof(struct ncmd)),
3048 SHELL_ALIGN(sizeof(struct npipe)),
3049 SHELL_ALIGN(sizeof(struct nredir)),
3050 SHELL_ALIGN(sizeof(struct nredir)),
3051 SHELL_ALIGN(sizeof(struct nredir)),
3052 SHELL_ALIGN(sizeof(struct nbinary)),
3053 SHELL_ALIGN(sizeof(struct nbinary)),
3054 SHELL_ALIGN(sizeof(struct nbinary)),
3055 SHELL_ALIGN(sizeof(struct nif)),
3056 SHELL_ALIGN(sizeof(struct nbinary)),
3057 SHELL_ALIGN(sizeof(struct nbinary)),
3058 SHELL_ALIGN(sizeof(struct nfor)),
3059 SHELL_ALIGN(sizeof(struct ncase)),
3060 SHELL_ALIGN(sizeof(struct nclist)),
3061 SHELL_ALIGN(sizeof(struct narg)),
3062 SHELL_ALIGN(sizeof(struct narg)),
3063 SHELL_ALIGN(sizeof(struct nfile)),
3064 SHELL_ALIGN(sizeof(struct nfile)),
3065 SHELL_ALIGN(sizeof(struct nfile)),
3066 SHELL_ALIGN(sizeof(struct nfile)),
3067 SHELL_ALIGN(sizeof(struct nfile)),
3068 SHELL_ALIGN(sizeof(struct ndup)),
3069 SHELL_ALIGN(sizeof(struct ndup)),
3070 SHELL_ALIGN(sizeof(struct nhere)),
3071 SHELL_ALIGN(sizeof(struct nhere)),
3072 SHELL_ALIGN(sizeof(struct nnot)),
3076 static void calcsize(union node *);
3077 static void sizenodelist(struct nodelist *);
3078 static union node *copynode(union node *);
3079 static struct nodelist *copynodelist(struct nodelist *);
3080 static char *nodeckstrdup(char *);
3083 static int evalskip; /* set if we are skipping commands */
3084 static int skipcount; /* number of levels to skip */
3085 static int funcnest; /* depth of function calls */
3087 /* reasons for skipping commands (see comment on breakcmd routine) */
3088 #define SKIPBREAK (1 << 0)
3089 #define SKIPCONT (1 << 1)
3090 #define SKIPFUNC (1 << 2)
3091 #define SKIPFILE (1 << 3)
3092 #define SKIPEVAL (1 << 4)
3095 * This file was generated by the mkbuiltins program.
3099 static int fg_bgcmd(int, char **);
3101 static int breakcmd(int, char **);
3102 static int cdcmd(int, char **);
3103 #if ENABLE_ASH_CMDCMD
3104 static int commandcmd(int, char **);
3106 static int dotcmd(int, char **);
3107 static int evalcmd(int, char **);
3108 #if ENABLE_ASH_BUILTIN_ECHO
3109 static int echocmd(int, char **);
3111 #if ENABLE_ASH_BUILTIN_TEST
3112 static int testcmd(int, char **);
3114 static int execcmd(int, char **);
3115 static int exitcmd(int, char **);
3116 static int exportcmd(int, char **);
3117 static int falsecmd(int, char **);
3118 #if ENABLE_ASH_GETOPTS
3119 static int getoptscmd(int, char **);
3121 static int hashcmd(int, char **);
3122 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3123 static int helpcmd(int argc, char **argv);
3126 static int jobscmd(int, char **);
3128 #if ENABLE_ASH_MATH_SUPPORT
3129 static int letcmd(int, char **);
3131 static int localcmd(int, char **);
3132 static int pwdcmd(int, char **);
3133 static int readcmd(int, char **);
3134 static int returncmd(int, char **);
3135 static int setcmd(int, char **);
3136 static int shiftcmd(int, char **);
3137 static int timescmd(int, char **);
3138 static int trapcmd(int, char **);
3139 static int truecmd(int, char **);
3140 static int typecmd(int, char **);
3141 static int umaskcmd(int, char **);
3142 static int unsetcmd(int, char **);
3143 static int waitcmd(int, char **);
3144 static int ulimitcmd(int, char **);
3146 static int killcmd(int, char **);
3151 /* values of cmdtype */
3152 #define CMDUNKNOWN -1 /* no entry in table for command */
3153 #define CMDNORMAL 0 /* command is an executable program */
3154 #define CMDFUNCTION 1 /* command is a shell function */
3155 #define CMDBUILTIN 2 /* command is a shell builtin */
3159 int (*builtin)(int, char **);
3160 /* unsigned flags; */
3164 #define COMMANDCMD (builtincmd + 5 + \
3165 2 * ENABLE_ASH_BUILTIN_TEST + \
3166 ENABLE_ASH_ALIAS + \
3167 ENABLE_ASH_JOB_CONTROL)
3168 #define EXECCMD (builtincmd + 7 + \
3169 2 * ENABLE_ASH_BUILTIN_TEST + \
3170 ENABLE_ASH_ALIAS + \
3171 ENABLE_ASH_JOB_CONTROL + \
3172 ENABLE_ASH_CMDCMD + \
3173 ENABLE_ASH_BUILTIN_ECHO)
3175 #define BUILTIN_NOSPEC "0"
3176 #define BUILTIN_SPECIAL "1"
3177 #define BUILTIN_REGULAR "2"
3178 #define BUILTIN_SPEC_REG "3"
3179 #define BUILTIN_ASSIGN "4"
3180 #define BUILTIN_SPEC_ASSG "5"
3181 #define BUILTIN_REG_ASSG "6"
3182 #define BUILTIN_SPEC_REG_ASSG "7"
3184 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
3185 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
3186 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
3188 /* make sure to keep these in proper order since it is searched via bsearch() */
3189 static const struct builtincmd builtincmd[] = {
3190 { BUILTIN_SPEC_REG ".", dotcmd },
3191 { BUILTIN_SPEC_REG ":", truecmd },
3192 #if ENABLE_ASH_BUILTIN_TEST
3193 { BUILTIN_REGULAR "[", testcmd },
3194 { BUILTIN_REGULAR "[[", testcmd },
3196 #if ENABLE_ASH_ALIAS
3197 { BUILTIN_REG_ASSG "alias", aliascmd },
3200 { BUILTIN_REGULAR "bg", fg_bgcmd },
3202 { BUILTIN_SPEC_REG "break", breakcmd },
3203 { BUILTIN_REGULAR "cd", cdcmd },
3204 { BUILTIN_NOSPEC "chdir", cdcmd },
3205 #if ENABLE_ASH_CMDCMD
3206 { BUILTIN_REGULAR "command", commandcmd },
3208 { BUILTIN_SPEC_REG "continue", breakcmd },
3209 #if ENABLE_ASH_BUILTIN_ECHO
3210 { BUILTIN_REGULAR "echo", echocmd },
3212 { BUILTIN_SPEC_REG "eval", evalcmd },
3213 { BUILTIN_SPEC_REG "exec", execcmd },
3214 { BUILTIN_SPEC_REG "exit", exitcmd },
3215 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
3216 { BUILTIN_REGULAR "false", falsecmd },
3218 { BUILTIN_REGULAR "fg", fg_bgcmd },
3220 #if ENABLE_ASH_GETOPTS
3221 { BUILTIN_REGULAR "getopts", getoptscmd },
3223 { BUILTIN_NOSPEC "hash", hashcmd },
3224 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3225 { BUILTIN_NOSPEC "help", helpcmd },
3228 { BUILTIN_REGULAR "jobs", jobscmd },
3229 { BUILTIN_REGULAR "kill", killcmd },
3231 #if ENABLE_ASH_MATH_SUPPORT
3232 { BUILTIN_NOSPEC "let", letcmd },
3234 { BUILTIN_ASSIGN "local", localcmd },
3235 { BUILTIN_NOSPEC "pwd", pwdcmd },
3236 { BUILTIN_REGULAR "read", readcmd },
3237 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
3238 { BUILTIN_SPEC_REG "return", returncmd },
3239 { BUILTIN_SPEC_REG "set", setcmd },
3240 { BUILTIN_SPEC_REG "shift", shiftcmd },
3241 { BUILTIN_SPEC_REG "source", dotcmd },
3242 #if ENABLE_ASH_BUILTIN_TEST
3243 { BUILTIN_REGULAR "test", testcmd },
3245 { BUILTIN_SPEC_REG "times", timescmd },
3246 { BUILTIN_SPEC_REG "trap", trapcmd },
3247 { BUILTIN_REGULAR "true", truecmd },
3248 { BUILTIN_NOSPEC "type", typecmd },
3249 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
3250 { BUILTIN_REGULAR "umask", umaskcmd },
3251 #if ENABLE_ASH_ALIAS
3252 { BUILTIN_REGULAR "unalias", unaliascmd },
3254 { BUILTIN_SPEC_REG "unset", unsetcmd },
3255 { BUILTIN_REGULAR "wait", waitcmd },
3258 #define NUMBUILTINS (sizeof(builtincmd) / sizeof(builtincmd[0]))
3265 const struct builtincmd *cmd;
3266 struct funcnode *func;
3271 /* action to find_command() */
3272 #define DO_ERR 0x01 /* prints errors */
3273 #define DO_ABS 0x02 /* checks absolute paths */
3274 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
3275 #define DO_ALTPATH 0x08 /* using alternate path */
3276 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
3278 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
3279 static char *padvance(const char **, const char *);
3280 static void find_command(char *, struct cmdentry *, int, const char *);
3281 static struct builtincmd *find_builtin(const char *);
3282 static void defun(char *, union node *);
3283 static void unsetfunc(const char *);
3285 #if ENABLE_ASH_MATH_SUPPORT_64
3286 typedef int64_t arith_t;
3287 #define arith_t_type long long
3289 typedef long arith_t;
3290 #define arith_t_type long
3293 #if ENABLE_ASH_MATH_SUPPORT
3294 static arith_t dash_arith(const char *);
3295 static arith_t arith(const char *expr, int *perrcode);
3298 #if ENABLE_ASH_RANDOM_SUPPORT
3299 static unsigned long rseed;
3300 # ifndef DYNAMIC_VAR
3301 # define DYNAMIC_VAR
3305 /* PEOF (the end of file marker) */
3308 INPUT_PUSH_FILE = 1,
3309 INPUT_NOFILE_OK = 2,
3313 * The input line number. Input.c just defines this variable, and saves
3314 * and restores it when files are pushed and popped. The user of this
3315 * package must set its value.
3317 static void pungetc(void);
3318 static void pushstring(char *, void *);
3319 static void popstring(void);
3320 static void setinputfd(int, int);
3321 static void setinputstring(char *);
3322 static void popfile(void);
3323 static void popallfiles(void);
3324 static void closescript(void);
3329 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3332 #define FORK_NOJOB 2
3334 /* mode flags for showjob(s) */
3335 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3336 #define SHOW_PID 0x04 /* include process pid */
3337 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3341 * A job structure contains information about a job. A job is either a
3342 * single process or a set of processes contained in a pipeline. In the
3343 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3348 pid_t pid; /* process id */
3349 int status; /* last process status from wait() */
3350 char *cmd; /* text of command being run */
3354 struct procstat ps0; /* status of process */
3355 struct procstat *ps; /* status or processes when more than one */
3357 int stopstatus; /* status of a stopped job */
3360 nprocs: 16, /* number of processes */
3362 #define JOBRUNNING 0 /* at least one proc running */
3363 #define JOBSTOPPED 1 /* all procs are stopped */
3364 #define JOBDONE 2 /* all procs are completed */
3366 sigint: 1, /* job was killed by SIGINT */
3367 jobctl: 1, /* job running under job control */
3369 waited: 1, /* true if this entry has been waited for */
3370 used: 1, /* true if this entry is in used */
3371 changed: 1; /* true if status has changed */
3372 struct job *prev_job; /* previous job */
3375 static pid_t backgndpid; /* pid of last background process */
3376 static int job_warning; /* user was warned about stopped jobs */
3378 static int jobctl; /* true if doing job control */
3381 static struct job *makejob(union node *, int);
3382 static int forkshell(struct job *, union node *, int);
3383 static int waitforjob(struct job *);
3386 #define setjobctl(on) /* do nothing */
3388 static void setjobctl(int);
3389 static void showjobs(FILE *, int);
3395 static void readcmdfile(char *);
3400 static char *minusc; /* argument to -c option */
3403 static void optschanged(void);
3404 static void setparam(char **);
3405 static void freeparam(volatile struct shparam *);
3406 static int shiftcmd(int, char **);
3407 static int setcmd(int, char **);
3408 static int nextopt(const char *);
3412 /* flags passed to redirect */
3413 #define REDIR_PUSH 01 /* save previous values of file descriptors */
3414 #define REDIR_SAVEFD2 03 /* set preverrout */
3416 static void redirect(union node *, int);
3417 static void popredir(int);
3418 static void clearredir(int);
3419 static int copyfd(int, int);
3420 static int redirectsafe(union node *, int);
3424 static void clear_traps(void);
3425 static void setsignal(int);
3426 static int dotrap(void);
3427 static void setinteractive(int);
3428 static void exitshell(void) ATTRIBUTE_NORETURN;
3431 static int is_safe_applet(char *name)
3433 /* It isn't a bug to have non-existent applet here... */
3434 /* ...just a waste of space... */
3435 static const char safe_applets[][8] = {
3439 USE_CHMOD (, "chmod" )
3440 USE_CHOWN (, "chown" )
3444 USE_ECHO (, "echo" )
3445 USE_FIND (, "find" )
3446 USE_HEXDUMP(, "hexdump")
3449 USE_MKDIR (, "mkdir" )
3451 USE_SORT (, "sort" )
3452 USE_TEST (, "test" )
3453 USE_TOUCH (, "touch" )
3454 USE_XARGS (, "xargs" )
3456 int n = sizeof(safe_applets) / sizeof(safe_applets[0]);
3458 for (i = 0; i < n; i++)
3459 if (strcmp(safe_applets[i], name) == 0)
3466 #if ENABLE_ASH_ALIAS
3474 static struct alias *atab[ATABSIZE];
3476 static struct alias **
3477 __lookupalias(const char *name) {
3478 unsigned int hashval;
3485 ch = (unsigned char)*p;
3489 ch = (unsigned char)*++p;
3491 app = &atab[hashval % ATABSIZE];
3493 for (; *app; app = &(*app)->next) {
3494 if (strcmp(name, (*app)->name) == 0) {
3502 static struct alias *
3503 lookupalias(const char *name, int check)
3505 struct alias *ap = *__lookupalias(name);
3507 if (check && ap && (ap->flag & ALIASINUSE))
3512 static struct alias *
3513 freealias(struct alias *ap)
3517 if (ap->flag & ALIASINUSE) {
3518 ap->flag |= ALIASDEAD;
3530 setalias(const char *name, const char *val)
3532 struct alias *ap, **app;
3534 app = __lookupalias(name);
3538 if (!(ap->flag & ALIASINUSE)) {
3541 ap->val = ckstrdup(val);
3542 ap->flag &= ~ALIASDEAD;
3545 ap = ckmalloc(sizeof(struct alias));
3546 ap->name = ckstrdup(name);
3547 ap->val = ckstrdup(val);
3556 unalias(const char *name)
3560 app = __lookupalias(name);
3564 *app = freealias(*app);
3575 struct alias *ap, **app;
3579 for (i = 0; i < ATABSIZE; i++) {
3581 for (ap = *app; ap; ap = *app) {
3582 *app = freealias(*app);
3592 * TODO - sort output
3595 aliascmd(int argc, char **argv)
3604 for (i = 0; i < ATABSIZE; i++)
3605 for (ap = atab[i]; ap; ap = ap->next) {
3610 while ((n = *++argv) != NULL) {
3611 v = strchr(n+1, '=');
3612 if (v == NULL) { /* n+1: funny ksh stuff */
3613 ap = *__lookupalias(n);
3615 fprintf(stderr, "%s: %s not found\n", "alias", n);
3629 unaliascmd(int argc, char **argv)
3633 while ((i = nextopt("a")) != '\0') {
3639 for (i = 0; *argptr; argptr++) {
3640 if (unalias(*argptr)) {
3641 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3650 printalias(const struct alias *ap)
3652 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3654 #endif /* ASH_ALIAS */
3659 * Evaluate a command.
3662 /* flags in argument to evaltree */
3663 #define EV_EXIT 01 /* exit after evaluating tree */
3664 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
3665 #define EV_BACKCMD 04 /* command executing within back quotes */
3667 static void evalloop(union node *, int);
3668 static void evalfor(union node *, int);
3669 static void evalcase(union node *, int);
3670 static void evalsubshell(union node *, int);
3671 static void expredir(union node *);
3672 static void evalpipe(union node *, int);
3673 static void evalcommand(union node *, int);
3674 static int evalbltin(const struct builtincmd *, int, char **);
3675 static int evalfun(struct funcnode *, int, char **, int);
3676 static void prehash(union node *);
3677 static int bltincmd(int, char **);
3679 static const struct builtincmd bltin = {
3685 * Evaluate a parse tree. The value is left in the global variable
3689 evaltree(union node *n, int flags)
3692 void (*evalfn)(union node *, int);
3696 TRACE(("evaltree(NULL) called\n"));
3699 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
3700 getpid(), n, n->type, flags));
3704 out1fmt("Node type = %d\n", n->type);
3709 evaltree(n->nnot.com, EV_TESTED);
3710 status = !exitstatus;
3713 expredir(n->nredir.redirect);
3714 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
3716 evaltree(n->nredir.n, flags & EV_TESTED);
3717 status = exitstatus;
3722 evalfn = evalcommand;
3724 if (eflag && !(flags & EV_TESTED))
3736 evalfn = evalsubshell;
3748 #error NAND + 1 != NOR
3750 #if NOR + 1 != NSEMI
3751 #error NOR + 1 != NSEMI
3753 isor = n->type - NAND;
3756 (flags | ((isor >> 1) - 1)) & EV_TESTED
3758 if (!exitstatus == isor)
3770 evaltree(n->nif.test, EV_TESTED);
3773 if (exitstatus == 0) {
3776 } else if (n->nif.elsepart) {
3777 n = n->nif.elsepart;
3782 defun(n->narg.text, n->narg.next);
3786 exitstatus = status;
3790 if ((checkexit & exitstatus))
3791 evalskip |= SKIPEVAL;
3792 else if (pendingsigs && dotrap())
3795 if (flags & EV_EXIT) {
3797 raise_exception(EXEXIT);
3802 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
3805 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
3809 evalloop(union node *n, int flags)
3819 evaltree(n->nbinary.ch1, EV_TESTED);
3822 if (evalskip == SKIPCONT && --skipcount <= 0) {
3826 if (evalskip == SKIPBREAK && --skipcount <= 0)
3831 if (n->type != NWHILE)
3835 evaltree(n->nbinary.ch2, flags);
3836 status = exitstatus;
3841 exitstatus = status;
3846 evalfor(union node *n, int flags)
3848 struct arglist arglist;
3851 struct stackmark smark;
3853 setstackmark(&smark);
3854 arglist.lastp = &arglist.list;
3855 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
3856 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
3861 *arglist.lastp = NULL;
3866 for (sp = arglist.list; sp; sp = sp->next) {
3867 setvar(n->nfor.var, sp->text, 0);
3868 evaltree(n->nfor.body, flags);
3870 if (evalskip == SKIPCONT && --skipcount <= 0) {
3874 if (evalskip == SKIPBREAK && --skipcount <= 0)
3881 popstackmark(&smark);
3886 evalcase(union node *n, int flags)
3890 struct arglist arglist;
3891 struct stackmark smark;
3893 setstackmark(&smark);
3894 arglist.lastp = &arglist.list;
3895 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
3897 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
3898 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
3899 if (casematch(patp, arglist.list->text)) {
3900 if (evalskip == 0) {
3901 evaltree(cp->nclist.body, flags);
3908 popstackmark(&smark);
3913 * Kick off a subshell to evaluate a tree.
3916 evalsubshell(union node *n, int flags)
3919 int backgnd = (n->type == NBACKGND);
3922 expredir(n->nredir.redirect);
3923 if (!backgnd && flags & EV_EXIT && !trap[0])
3927 if (forkshell(jp, n, backgnd) == 0) {
3931 flags &=~ EV_TESTED;
3933 redirect(n->nredir.redirect, 0);
3934 evaltreenr(n->nredir.n, flags);
3939 status = waitforjob(jp);
3940 exitstatus = status;
3946 * Compute the names of the files in a redirection list.
3949 expredir(union node *n)
3953 for (redir = n; redir; redir = redir->nfile.next) {
3956 memset(&fn, 0, sizeof(fn));
3957 fn.lastp = &fn.list;
3958 switch (redir->type) {
3964 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
3965 redir->nfile.expfname = fn.list->text;
3969 if (redir->ndup.vname) {
3970 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
3971 if (fn.list == NULL)
3972 ash_msg_and_raise_error("redir error");
3973 fixredir(redir, fn.list->text, 1);
3982 * Evaluate a pipeline. All the processes in the pipeline are children
3983 * of the process creating the pipeline. (This differs from some versions
3984 * of the shell, which make the last process in a pipeline the parent
3988 evalpipe(union node *n, int flags)
3991 struct nodelist *lp;
3996 TRACE(("evalpipe(0x%lx) called\n", (long)n));
3998 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
4002 jp = makejob(n, pipelen);
4004 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
4008 if (pipe(pip) < 0) {
4010 ash_msg_and_raise_error("Pipe call failed");
4013 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
4026 evaltreenr(lp->n, flags);
4034 if (n->npipe.backgnd == 0) {
4035 exitstatus = waitforjob(jp);
4036 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
4043 * Execute a command inside back quotes. If it's a builtin command, we
4044 * want to save its output in a block obtained from malloc. Otherwise
4045 * we fork off a subprocess and get the output of the command via a pipe.
4046 * Should be called with interrupts off.
4049 evalbackcmd(union node *n, struct backcmd *result)
4061 saveherefd = herefd;
4069 ash_msg_and_raise_error("Pipe call failed");
4071 if (forkshell(jp, n, FORK_NOJOB) == 0) {
4080 evaltreenr(n, EV_EXIT);
4084 result->fd = pip[0];
4087 herefd = saveherefd;
4089 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
4090 result->fd, result->buf, result->nleft, result->jp));
4093 #if ENABLE_ASH_CMDCMD
4095 parse_command_args(char **argv, const char **path)
4108 if (c == '-' && !*cp) {
4118 /* run 'typecmd' for other options */
4128 static int isassignment(const char *p)
4130 const char *q = endofname(p);
4137 * Execute a simple command.
4140 evalcommand(union node *cmd, int flags)
4142 struct stackmark smark;
4144 struct arglist arglist;
4145 struct arglist varlist;
4148 const struct strlist *sp;
4149 struct cmdentry cmdentry;
4157 struct builtincmd *bcmd;
4158 int pseudovarflag = 0;
4160 /* First expand the arguments. */
4161 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
4162 setstackmark(&smark);
4163 back_exitstatus = 0;
4165 cmdentry.cmdtype = CMDBUILTIN;
4166 cmdentry.u.cmd = &bltin;
4167 varlist.lastp = &varlist.list;
4168 *varlist.lastp = NULL;
4169 arglist.lastp = &arglist.list;
4170 *arglist.lastp = NULL;
4173 if (cmd->ncmd.args) {
4174 bcmd = find_builtin(cmd->ncmd.args->narg.text);
4175 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
4178 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
4179 struct strlist **spp;
4181 spp = arglist.lastp;
4182 if (pseudovarflag && isassignment(argp->narg.text))
4183 expandarg(argp, &arglist, EXP_VARTILDE);
4185 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
4187 for (sp = *spp; sp; sp = sp->next)
4191 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
4192 for (sp = arglist.list; sp; sp = sp->next) {
4193 TRACE(("evalcommand arg: %s\n", sp->text));
4194 *nargv++ = sp->text;
4199 if (iflag && funcnest == 0 && argc > 0)
4200 lastarg = nargv[-1];
4203 expredir(cmd->ncmd.redirect);
4204 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
4207 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
4208 struct strlist **spp;
4211 spp = varlist.lastp;
4212 expandarg(argp, &varlist, EXP_VARTILDE);
4215 * Modify the command lookup path, if a PATH= assignment
4219 if (varequal(p, path))
4223 /* Print the command if xflag is set. */
4226 const char *p = " %s";
4229 dprintf(preverrout_fd, p, expandstr(ps4val()));
4232 for (n = 0; n < 2; n++) {
4234 dprintf(preverrout_fd, p, sp->text);
4242 full_write(preverrout_fd, "\n", 1);
4248 /* Now locate the command. */
4250 const char *oldpath;
4251 int cmd_flag = DO_ERR;
4256 find_command(argv[0], &cmdentry, cmd_flag, path);
4257 if (cmdentry.cmdtype == CMDUNKNOWN) {
4263 /* implement bltin and command here */
4264 if (cmdentry.cmdtype != CMDBUILTIN)
4267 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
4268 if (cmdentry.u.cmd == EXECCMD)
4270 #if ENABLE_ASH_CMDCMD
4271 if (cmdentry.u.cmd == COMMANDCMD) {
4274 nargv = parse_command_args(argv, &path);
4277 argc -= nargv - argv;
4279 cmd_flag |= DO_NOFUNC;
4287 /* We have a redirection error. */
4289 raise_exception(EXERROR);
4291 exitstatus = status;
4295 /* Execute the command. */
4296 switch (cmdentry.cmdtype) {
4298 /* Fork off a child process if necessary. */
4299 if (!(flags & EV_EXIT) || trap[0]) {
4301 jp = makejob(cmd, 1);
4302 if (forkshell(jp, cmd, FORK_FG) != 0) {
4303 exitstatus = waitforjob(jp);
4309 listsetvar(varlist.list, VEXPORT|VSTACK);
4310 shellexec(argv, path, cmdentry.u.index);
4314 cmdenviron = varlist.list;
4316 struct strlist *list = cmdenviron;
4318 if (spclbltin > 0 || argc == 0) {
4320 if (cmd_is_exec && argc > 1)
4323 listsetvar(list, i);
4325 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
4340 exit_status = j + 128;
4341 exitstatus = exit_status;
4343 if (i == EXINT || spclbltin > 0) {
4345 longjmp(exception_handler->loc, 1);
4352 listsetvar(varlist.list, 0);
4353 if (evalfun(cmdentry.u.func, argc, argv, flags))
4359 popredir(cmd_is_exec);
4361 /* dsl: I think this is intended to be used to support
4362 * '_' in 'vi' command mode during line editing...
4363 * However I implemented that within libedit itself.
4365 setvar("_", lastarg, 0);
4366 popstackmark(&smark);
4370 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
4372 char *volatile savecmdname;
4373 struct jmploc *volatile savehandler;
4374 struct jmploc jmploc;
4377 savecmdname = commandname;
4378 i = setjmp(jmploc.loc);
4381 savehandler = exception_handler;
4382 exception_handler = &jmploc;
4383 commandname = argv[0];
4385 optptr = NULL; /* initialize nextopt */
4386 exitstatus = (*cmd->builtin)(argc, argv);
4387 flush_stdout_stderr();
4389 exitstatus |= ferror(stdout);
4391 commandname = savecmdname;
4393 exception_handler = savehandler;
4398 static struct localvar *localvars;
4401 * Called after a function returns.
4402 * Interrupts must be off.
4407 struct localvar *lvp;
4410 while ((lvp = localvars) != NULL) {
4411 localvars = lvp->next;
4413 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
4414 if (vp == NULL) { /* $- saved */
4415 memcpy(optlist, lvp->text, sizeof(optlist));
4416 free((char*)lvp->text);
4418 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
4422 (*vp->func)(strchrnul(lvp->text, '=') + 1);
4423 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
4424 free((char*)vp->text);
4425 vp->flags = lvp->flags;
4426 vp->text = lvp->text;
4433 evalfun(struct funcnode *func, int argc, char **argv, int flags)
4435 volatile struct shparam saveparam;
4436 struct localvar *volatile savelocalvars;
4437 struct jmploc *volatile savehandler;
4438 struct jmploc jmploc;
4441 saveparam = shellparam;
4442 savelocalvars = localvars;
4443 e = setjmp(jmploc.loc);
4448 savehandler = exception_handler;
4449 exception_handler = &jmploc;
4451 shellparam.malloc = 0;
4455 shellparam.nparam = argc - 1;
4456 shellparam.p = argv + 1;
4457 #if ENABLE_ASH_GETOPTS
4458 shellparam.optind = 1;
4459 shellparam.optoff = -1;
4461 evaltree(&func->n, flags & EV_TESTED);
4467 localvars = savelocalvars;
4468 freeparam(&shellparam);
4469 shellparam = saveparam;
4470 exception_handler = savehandler;
4472 evalskip &= ~SKIPFUNC;
4478 goodname(const char *p)
4480 return !*endofname(p);
4485 * Search for a command. This is called before we fork so that the
4486 * location of the command will be available in the parent as well as
4487 * the child. The check for "goodname" is an overly conservative
4488 * check that the name will not be subject to expansion.
4491 prehash(union node *n)
4493 struct cmdentry entry;
4495 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
4496 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
4502 * Builtin commands. Builtin commands whose functions are closely
4503 * tied to evaluation are implemented here.
4510 bltincmd(int argc, char **argv)
4513 * Preserve exitstatus of a previous possible redirection
4516 return back_exitstatus;
4521 * Handle break and continue commands. Break, continue, and return are
4522 * all handled by setting the evalskip flag. The evaluation routines
4523 * above all check this flag, and if it is set they start skipping
4524 * commands rather than executing them. The variable skipcount is
4525 * the number of loops to break/continue, or the number of function
4526 * levels to return. (The latter is always 1.) It should probably
4527 * be an error to break out of more loops than exist, but it isn't
4528 * in the standard shell so we don't make it one here.
4532 breakcmd(int argc, char **argv)
4534 int n = argc > 1 ? number(argv[1]) : 1;
4537 ash_msg_and_raise_error(illnum, argv[1]);
4541 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
4549 * The return command.
4552 returncmd(int argc, char **argv)
4555 * If called outside a function, do what ksh does;
4556 * skip the rest of the file.
4558 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
4559 return argv[1] ? number(argv[1]) : exitstatus;
4564 falsecmd(int argc, char **argv)
4571 truecmd(int argc, char **argv)
4578 execcmd(int argc, char **argv)
4581 iflag = 0; /* exit on error */
4584 shellexec(argv + 1, pathval(), 0);
4593 * When commands are first encountered, they are entered in a hash table.
4594 * This ensures that a full path search will not have to be done for them
4595 * on each invocation.
4597 * We should investigate converting to a linear search, even though that
4598 * would make the command name "hash" a misnomer.
4601 #define CMDTABLESIZE 31 /* should be prime */
4602 #define ARB 1 /* actual size determined at run time */
4606 struct tblentry *next; /* next entry in hash chain */
4607 union param param; /* definition of builtin function */
4608 short cmdtype; /* index identifying command */
4609 char rehash; /* if set, cd done since entry created */
4610 char cmdname[ARB]; /* name of command */
4614 static struct tblentry *cmdtable[CMDTABLESIZE];
4615 static int builtinloc = -1; /* index in path of %builtin, or -1 */
4618 static void tryexec(char *, char **, char **);
4619 static void clearcmdentry(int);
4620 static struct tblentry *cmdlookup(const char *, int);
4621 static void delete_cmd_entry(void);
4625 * Exec a program. Never returns. If you change this routine, you may
4626 * have to change the find_command routine as well.
4628 #define environment() listvars(VEXPORT, VUNSET, 0)
4629 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
4631 shellexec(char **argv, const char *path, int idx)
4639 envp = environment();
4640 if (strchr(argv[0], '/') || is_safe_applet(argv[0])
4641 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
4642 || find_applet_by_name(argv[0])
4645 tryexec(argv[0], argv, envp);
4649 while ((cmdname = padvance(&path, argv[0])) != NULL) {
4650 if (--idx < 0 && pathopt == NULL) {
4651 tryexec(cmdname, argv, envp);
4652 if (errno != ENOENT && errno != ENOTDIR)
4659 /* Map to POSIX errors */
4671 exitstatus = exerrno;
4672 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
4673 argv[0], e, suppressint ));
4674 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
4680 tryexec(char *cmd, char **argv, char **envp)
4683 struct BB_applet *a;
4687 if (strchr(cmd, '/') == NULL
4688 && (a = find_applet_by_name(cmd)) != NULL
4689 && is_safe_applet(cmd)
4692 while (*c != NULL) {
4696 exit(a->main(argc, argv));
4698 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
4699 if (find_applet_by_name(cmd) != NULL) {
4700 /* re-exec ourselves with the new arguments */
4701 execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
4702 /* If they called chroot or otherwise made the binary no longer
4703 * executable, fall through */
4710 execve(cmd, argv, envp);
4711 } while (errno == EINTR);
4713 execve(cmd, argv, envp);
4717 } else if (errno == ENOEXEC) {
4721 for (ap = argv; *ap; ap++)
4723 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
4725 *ap = cmd = (char *)DEFAULT_SHELL;
4728 while ((*ap++ = *argv++))
4736 /*** Command hashing code ***/
4739 printentry(struct tblentry *cmdp)
4745 idx = cmdp->param.index;
4748 name = padvance(&path, cmdp->cmdname);
4750 } while (--idx >= 0);
4751 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
4756 hashcmd(int argc, char **argv)
4758 struct tblentry **pp;
4759 struct tblentry *cmdp;
4761 struct cmdentry entry;
4764 while ((c = nextopt("r")) != '\0') {
4768 if (*argptr == NULL) {
4769 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
4770 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
4771 if (cmdp->cmdtype == CMDNORMAL)
4778 while ((name = *argptr) != NULL) {
4779 cmdp = cmdlookup(name, 0);
4781 && (cmdp->cmdtype == CMDNORMAL
4782 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
4784 find_command(name, &entry, DO_ERR, pathval());
4785 if (entry.cmdtype == CMDUNKNOWN)
4794 * Resolve a command name. If you change this routine, you may have to
4795 * change the shellexec routine as well.
4798 find_command(char *name, struct cmdentry *entry, int act, const char *path)
4800 struct tblentry *cmdp;
4807 struct builtincmd *bcmd;
4809 /* If name contains a slash, don't use PATH or hash table */
4810 if (strchr(name, '/') != NULL) {
4811 entry->u.index = -1;
4813 while (stat(name, &statb) < 0) {
4818 entry->cmdtype = CMDUNKNOWN;
4822 entry->cmdtype = CMDNORMAL;
4826 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
4827 if (find_applet_by_name(name)) {
4828 entry->cmdtype = CMDNORMAL;
4829 entry->u.index = -1;
4834 if (is_safe_applet(name)) {
4835 entry->cmdtype = CMDNORMAL;
4836 entry->u.index = -1;
4840 updatetbl = (path == pathval());
4843 if (strstr(path, "%builtin") != NULL)
4847 /* If name is in the table, check answer will be ok */
4848 cmdp = cmdlookup(name, 0);
4852 switch (cmdp->cmdtype) {
4870 } else if (cmdp->rehash == 0)
4871 /* if not invalidated by cd, we're done */
4875 /* If %builtin not in path, check for builtin next */
4876 bcmd = find_builtin(name);
4877 if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
4878 act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
4880 goto builtin_success;
4882 /* We have to search path. */
4883 prev = -1; /* where to start */
4884 if (cmdp && cmdp->rehash) { /* doing a rehash */
4885 if (cmdp->cmdtype == CMDBUILTIN)
4888 prev = cmdp->param.index;
4894 while ((fullname = padvance(&path, name)) != NULL) {
4895 stunalloc(fullname);
4898 if (prefix(pathopt, "builtin")) {
4900 goto builtin_success;
4902 } else if (!(act & DO_NOFUNC) &&
4903 prefix(pathopt, "func")) {
4906 /* ignore unimplemented options */
4910 /* if rehash, don't redo absolute path names */
4911 if (fullname[0] == '/' && idx <= prev) {
4914 TRACE(("searchexec \"%s\": no change\n", name));
4917 while (stat(fullname, &statb) < 0) {
4922 if (errno != ENOENT && errno != ENOTDIR)
4926 e = EACCES; /* if we fail, this will be the error */
4927 if (!S_ISREG(statb.st_mode))
4929 if (pathopt) { /* this is a %func directory */
4930 stalloc(strlen(fullname) + 1);
4931 readcmdfile(fullname);
4932 cmdp = cmdlookup(name, 0);
4933 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
4934 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
4935 stunalloc(fullname);
4938 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
4940 entry->cmdtype = CMDNORMAL;
4941 entry->u.index = idx;
4945 cmdp = cmdlookup(name, 1);
4946 cmdp->cmdtype = CMDNORMAL;
4947 cmdp->param.index = idx;
4952 /* We failed. If there was an entry for this command, delete it */
4953 if (cmdp && updatetbl)
4956 ash_msg("%s: %s", name, errmsg(e, "not found"));
4957 entry->cmdtype = CMDUNKNOWN;
4962 entry->cmdtype = CMDBUILTIN;
4963 entry->u.cmd = bcmd;
4967 cmdp = cmdlookup(name, 1);
4968 cmdp->cmdtype = CMDBUILTIN;
4969 cmdp->param.cmd = bcmd;
4973 entry->cmdtype = cmdp->cmdtype;
4974 entry->u = cmdp->param;
4979 * Search the table of builtin commands.
4981 static struct builtincmd *
4982 find_builtin(const char *name)
4984 struct builtincmd *bp;
4987 name, builtincmd, NUMBUILTINS, sizeof(struct builtincmd),
4995 * Called when a cd is done. Marks all commands so the next time they
4996 * are executed they will be rehashed.
5001 struct tblentry **pp;
5002 struct tblentry *cmdp;
5004 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
5005 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
5006 if (cmdp->cmdtype == CMDNORMAL || (
5007 cmdp->cmdtype == CMDBUILTIN &&
5008 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
5018 * Fix command hash table when PATH changed.
5019 * Called before PATH is changed. The argument is the new value of PATH;
5020 * pathval() still returns the old value at this point.
5021 * Called with interrupts off.
5024 changepath(const char *newval)
5026 const char *old, *new;
5033 firstchange = 9999; /* assume no change */
5039 if ((*old == '\0' && *new == ':')
5040 || (*old == ':' && *new == '\0'))
5042 old = new; /* ignore subsequent differences */
5046 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
5053 if (builtinloc < 0 && idx_bltin >= 0)
5054 builtinloc = idx_bltin; /* zap builtins */
5055 if (builtinloc >= 0 && idx_bltin < 0)
5057 clearcmdentry(firstchange);
5058 builtinloc = idx_bltin;
5063 * Clear out command entries. The argument specifies the first entry in
5064 * PATH which has changed.
5067 clearcmdentry(int firstchange)
5069 struct tblentry **tblp;
5070 struct tblentry **pp;
5071 struct tblentry *cmdp;
5074 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
5076 while ((cmdp = *pp) != NULL) {
5077 if ((cmdp->cmdtype == CMDNORMAL &&
5078 cmdp->param.index >= firstchange)
5079 || (cmdp->cmdtype == CMDBUILTIN &&
5080 builtinloc >= firstchange)
5094 * Locate a command in the command hash table. If "add" is nonzero,
5095 * add the command to the table if it is not already present. The
5096 * variable "lastcmdentry" is set to point to the address of the link
5097 * pointing to the entry, so that delete_cmd_entry can delete the
5100 * Interrupts must be off if called with add != 0.
5102 static struct tblentry **lastcmdentry;
5104 static struct tblentry *
5105 cmdlookup(const char *name, int add)
5107 unsigned int hashval;
5109 struct tblentry *cmdp;
5110 struct tblentry **pp;
5113 hashval = (unsigned char)*p << 4;
5115 hashval += (unsigned char)*p++;
5117 pp = &cmdtable[hashval % CMDTABLESIZE];
5118 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
5119 if (strcmp(cmdp->cmdname, name) == 0)
5123 if (add && cmdp == NULL) {
5124 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
5125 + strlen(name) + 1);
5127 cmdp->cmdtype = CMDUNKNOWN;
5128 strcpy(cmdp->cmdname, name);
5136 * Delete the command entry returned on the last lookup.
5139 delete_cmd_entry(void)
5141 struct tblentry *cmdp;
5144 cmdp = *lastcmdentry;
5145 *lastcmdentry = cmdp->next;
5146 if (cmdp->cmdtype == CMDFUNCTION)
5147 freefunc(cmdp->param.func);
5154 * Add a new command entry, replacing any existing command entry for
5155 * the same name - except special builtins.
5157 static void addcmdentry(char *name, struct cmdentry *entry)
5159 struct tblentry *cmdp;
5161 cmdp = cmdlookup(name, 1);
5162 if (cmdp->cmdtype == CMDFUNCTION) {
5163 freefunc(cmdp->param.func);
5165 cmdp->cmdtype = entry->cmdtype;
5166 cmdp->param = entry->u;
5172 * Make a copy of a parse tree.
5174 static struct funcnode * copyfunc(union node *n)
5179 funcblocksize = offsetof(struct funcnode, n);
5182 blocksize = funcblocksize;
5183 f = ckmalloc(blocksize + funcstringsize);
5184 funcblock = (char *) f + offsetof(struct funcnode, n);
5185 funcstring = (char *) f + blocksize;
5193 * Define a shell function.
5196 defun(char *name, union node *func)
5198 struct cmdentry entry;
5201 entry.cmdtype = CMDFUNCTION;
5202 entry.u.func = copyfunc(func);
5203 addcmdentry(name, &entry);
5209 * Delete a function if it exists.
5212 unsetfunc(const char *name)
5214 struct tblentry *cmdp;
5216 cmdp = cmdlookup(name, 0);
5217 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
5222 * Locate and print what a word is...
5224 #if ENABLE_ASH_CMDCMD
5226 describe_command(char *command, int describe_command_verbose)
5228 #define describe_command_verbose 1
5230 describe_command(char *command)
5233 struct cmdentry entry;
5234 struct tblentry *cmdp;
5235 #if ENABLE_ASH_ALIAS
5236 const struct alias *ap;
5238 const char *path = pathval();
5240 if (describe_command_verbose) {
5244 /* First look at the keywords */
5245 if (findkwd(command)) {
5246 out1str(describe_command_verbose ? " is a shell keyword" : command);
5250 #if ENABLE_ASH_ALIAS
5251 /* Then look at the aliases */
5252 ap = lookupalias(command, 0);
5254 if (describe_command_verbose) {
5255 out1fmt(" is an alias for %s", ap->val);
5264 /* Then check if it is a tracked alias */
5265 cmdp = cmdlookup(command, 0);
5267 entry.cmdtype = cmdp->cmdtype;
5268 entry.u = cmdp->param;
5270 /* Finally use brute force */
5271 find_command(command, &entry, DO_ABS, path);
5274 switch (entry.cmdtype) {
5276 int j = entry.u.index;
5282 p = padvance(&path, command);
5286 if (describe_command_verbose) {
5288 (cmdp ? " a tracked alias for" : nullstr), p
5297 if (describe_command_verbose) {
5298 out1str(" is a shell function");
5305 if (describe_command_verbose) {
5306 out1fmt(" is a %sshell builtin",
5307 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
5308 "special " : nullstr
5316 if (describe_command_verbose) {
5317 out1str(": not found\n");
5322 outstr("\n", stdout);
5327 typecmd(int argc, char **argv)
5332 for (i = 1; i < argc; i++) {
5333 #if ENABLE_ASH_CMDCMD
5334 err |= describe_command(argv[i], 1);
5336 err |= describe_command(argv[i]);
5342 #if ENABLE_ASH_CMDCMD
5344 commandcmd(int argc, char **argv)
5352 while ((c = nextopt("pvV")) != '\0')
5354 verify |= VERIFY_VERBOSE;
5356 verify |= VERIFY_BRIEF;
5362 return describe_command(*argptr, verify - VERIFY_BRIEF);
5371 * Routines to expand arguments to commands. We have to deal with
5372 * backquotes, shell variables, and file metacharacters.
5378 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5379 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5380 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5381 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5382 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5385 * Structure specifying which parts of the string should be searched
5386 * for IFS characters.
5390 struct ifsregion *next; /* next region in list */
5391 int begoff; /* offset of start of region */
5392 int endoff; /* offset of end of region */
5393 int nulonly; /* search for nul bytes only */
5396 /* output of current string */
5397 static char *expdest;
5398 /* list of back quote expressions */
5399 static struct nodelist *argbackq;
5400 /* first struct in list of ifs regions */
5401 static struct ifsregion ifsfirst;
5402 /* last struct in list */
5403 static struct ifsregion *ifslastp;
5404 /* holds expanded arg list */
5405 static struct arglist exparg;
5407 static void argstr(char *, int);
5408 static char *exptilde(char *, char *, int);
5409 static void expbackq(union node *, int, int);
5410 static const char *subevalvar(char *, char *, int, int, int, int, int);
5411 static char *evalvar(char *, int);
5412 static void strtodest(const char *, int, int);
5413 static void memtodest(const char *p, size_t len, int syntax, int quotes);
5414 static ssize_t varvalue(char *, int, int);
5415 static void recordregion(int, int, int);
5416 static void removerecordregions(int);
5417 static void ifsbreakup(char *, struct arglist *);
5418 static void ifsfree(void);
5419 static void expandmeta(struct strlist *, int);
5420 static int patmatch(char *, const char *);
5422 static int cvtnum(arith_t);
5423 static size_t esclen(const char *, const char *);
5424 static char *scanleft(char *, char *, char *, char *, int, int);
5425 static char *scanright(char *, char *, char *, char *, int, int);
5426 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5429 #define pmatch(a, b) !fnmatch((a), (b), 0)
5431 * Prepare a pattern for a expmeta (internal glob(3)) call.
5433 * Returns an stalloced string.
5436 static char * preglob(const char *pattern, int quoted, int flag)
5438 flag |= RMESCAPE_GLOB;
5440 flag |= RMESCAPE_QUOTED;
5442 return _rmescapes((char *)pattern, flag);
5447 esclen(const char *start, const char *p)
5451 while (p > start && *--p == CTLESC) {
5459 * Expand shell variables and backquotes inside a here document.
5462 static void expandhere(union node *arg, int fd)
5465 expandarg(arg, (struct arglist *)NULL, 0);
5466 full_write(fd, stackblock(), expdest - (char *)stackblock());
5471 * Perform variable substitution and command substitution on an argument,
5472 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
5473 * perform splitting and file name expansion. When arglist is NULL, perform
5474 * here document expansion.
5477 expandarg(union node *arg, struct arglist *arglist, int flag)
5482 argbackq = arg->narg.backquote;
5483 STARTSTACKSTR(expdest);
5484 ifsfirst.next = NULL;
5486 argstr(arg->narg.text, flag);
5487 p = _STPUTC('\0', expdest);
5489 if (arglist == NULL) {
5490 return; /* here document expanded */
5492 p = grabstackstr(p);
5493 exparg.lastp = &exparg.list;
5497 if (flag & EXP_FULL) {
5498 ifsbreakup(p, &exparg);
5499 *exparg.lastp = NULL;
5500 exparg.lastp = &exparg.list;
5501 expandmeta(exparg.list, flag);
5503 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
5505 sp = stalloc(sizeof(*sp));
5508 exparg.lastp = &sp->next;
5512 *exparg.lastp = NULL;
5514 *arglist->lastp = exparg.list;
5515 arglist->lastp = exparg.lastp;
5521 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5522 * characters to allow for further processing. Otherwise treat
5523 * $@ like $* since no splitting will be performed.
5526 argstr(char *p, int flag)
5528 static const char spclchars[] = {
5536 CTLBACKQ | CTLQUOTE,
5537 #if ENABLE_ASH_MATH_SUPPORT
5542 const char *reject = spclchars;
5544 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5545 int breakall = flag & EXP_WORD;
5550 if (!(flag & EXP_VARTILDE)) {
5552 } else if (flag & EXP_VARTILDE2) {
5557 if (flag & EXP_TILDE) {
5563 if (*q == CTLESC && (flag & EXP_QWORD))
5566 p = exptilde(p, q, flag);
5569 startloc = expdest - (char *)stackblock();
5571 length += strcspn(p + length, reject);
5573 if (c && (!(c & 0x80)
5574 #if ENABLE_ASH_MATH_SUPPORT
5578 /* c == '=' || c == ':' || c == CTLENDARI */
5583 expdest = stack_nputstr(p, length, expdest);
5584 newloc = expdest - (char *)stackblock();
5585 if (breakall && !inquotes && newloc > startloc) {
5586 recordregion(startloc, newloc, 0);
5597 if (flag & EXP_VARTILDE2) {
5601 flag |= EXP_VARTILDE2;
5606 * sort of a hack - expand tildes in variable
5607 * assignments (after the first '=' and after ':'s).
5616 case CTLENDVAR: /* ??? */
5619 /* "$@" syntax adherence hack */
5622 !memcmp(p, dolatstr, 4) &&
5623 (p[4] == CTLQUOTEMARK || (
5624 p[4] == CTLENDVAR &&
5625 p[5] == CTLQUOTEMARK
5628 p = evalvar(p + 1, flag) + 1;
5631 inquotes = !inquotes;
5644 p = evalvar(p, flag);
5648 case CTLBACKQ|CTLQUOTE:
5649 expbackq(argbackq->n, c, quotes);
5650 argbackq = argbackq->next;
5652 #if ENABLE_ASH_MATH_SUPPORT
5665 exptilde(char *startp, char *p, int flag)
5671 int quotes = flag & (EXP_FULL | EXP_CASE);
5676 while ((c = *++p) != '\0') {
5683 if (flag & EXP_VARTILDE)
5693 if (*name == '\0') {
5694 home = lookupvar(homestr);
5696 pw = getpwnam(name);
5701 if (!home || !*home)
5704 startloc = expdest - (char *)stackblock();
5705 strtodest(home, SQSYNTAX, quotes);
5706 recordregion(startloc, expdest - (char *)stackblock(), 0);
5715 removerecordregions(int endoff)
5717 if (ifslastp == NULL)
5720 if (ifsfirst.endoff > endoff) {
5721 while (ifsfirst.next != NULL) {
5722 struct ifsregion *ifsp;
5724 ifsp = ifsfirst.next->next;
5725 free(ifsfirst.next);
5726 ifsfirst.next = ifsp;
5729 if (ifsfirst.begoff > endoff)
5732 ifslastp = &ifsfirst;
5733 ifsfirst.endoff = endoff;
5738 ifslastp = &ifsfirst;
5739 while (ifslastp->next && ifslastp->next->begoff < endoff)
5740 ifslastp=ifslastp->next;
5741 while (ifslastp->next != NULL) {
5742 struct ifsregion *ifsp;
5744 ifsp = ifslastp->next->next;
5745 free(ifslastp->next);
5746 ifslastp->next = ifsp;
5749 if (ifslastp->endoff > endoff)
5750 ifslastp->endoff = endoff;
5754 #if ENABLE_ASH_MATH_SUPPORT
5756 * Expand arithmetic expression. Backup to start of expression,
5757 * evaluate, place result in (backed up) result, adjust string position.
5770 * This routine is slightly over-complicated for
5771 * efficiency. Next we scan backwards looking for the
5772 * start of arithmetic.
5774 start = stackblock();
5781 while (*p != CTLARI) {
5785 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5790 esc = esclen(start, p);
5800 removerecordregions(begoff);
5809 len = cvtnum(dash_arith(p + 2));
5812 recordregion(begoff, begoff + len, 0);
5818 * Expand stuff in backwards quotes.
5821 expbackq(union node *cmd, int quoted, int quotes)
5829 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5830 struct stackmark smark;
5833 setstackmark(&smark);
5835 startloc = dest - (char *)stackblock();
5837 evalbackcmd(cmd, (struct backcmd *) &in);
5838 popstackmark(&smark);
5845 memtodest(p, i, syntax, quotes);
5849 i = safe_read(in.fd, buf, sizeof(buf));
5850 TRACE(("expbackq: read returns %d\n", i));
5860 back_exitstatus = waitforjob(in.jp);
5864 /* Eat all trailing newlines */
5866 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5871 recordregion(startloc, dest - (char *)stackblock(), 0);
5872 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5873 (dest - (char *)stackblock()) - startloc,
5874 (dest - (char *)stackblock()) - startloc,
5875 stackblock() + startloc));
5880 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5891 const char *s = loc2;
5897 match = pmatch(str, s);
5901 if (quotes && *loc == CTLESC)
5911 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5918 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5921 const char *s = loc2;
5926 match = pmatch(str, s);
5933 esc = esclen(startp, loc);
5945 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5949 int saveherefd = herefd;
5950 struct nodelist *saveargbackq = argbackq;
5952 char *rmesc, *rmescend;
5954 char *(*scan)(char *, char *, char *, char *, int , int);
5957 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5958 STPUTC('\0', expdest);
5959 herefd = saveherefd;
5960 argbackq = saveargbackq;
5961 startp = stackblock() + startloc;
5965 setvar(str, startp, 0);
5966 amount = startp - expdest;
5967 STADJUST(amount, expdest);
5971 varunset(p, str, startp, varflags);
5975 subtype -= VSTRIMRIGHT;
5977 if (subtype < 0 || subtype > 3)
5982 rmescend = stackblock() + strloc;
5984 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5985 if (rmesc != startp) {
5987 startp = stackblock() + startloc;
5991 str = stackblock() + strloc;
5992 preglob(str, varflags & VSQUOTE, 0);
5994 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5995 zero = subtype >> 1;
5996 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5997 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5999 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6002 memmove(startp, loc, str - loc);
6003 loc = startp + (str - loc) - 1;
6006 amount = loc - expdest;
6007 STADJUST(amount, expdest);
6014 * Expand a variable, and return a pointer to the next character in the
6018 evalvar(char *p, int flag)
6031 quotes = flag & (EXP_FULL | EXP_CASE);
6033 subtype = varflags & VSTYPE;
6034 quoted = varflags & VSQUOTE;
6036 easy = (!quoted || (*var == '@' && shellparam.nparam));
6037 startloc = expdest - (char *)stackblock();
6038 p = strchr(p, '=') + 1;
6041 varlen = varvalue(var, varflags, flag);
6042 if (varflags & VSNUL)
6045 if (subtype == VSPLUS) {
6046 varlen = -1 - varlen;
6050 if (subtype == VSMINUS) {
6054 p, flag | EXP_TILDE |
6055 (quoted ? EXP_QWORD : EXP_WORD)
6064 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6066 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
6069 * Remove any recorded regions beyond
6072 removerecordregions(startloc);
6082 if (varlen < 0 && uflag)
6083 varunset(p, var, 0, 0);
6085 if (subtype == VSLENGTH) {
6086 cvtnum(varlen > 0 ? varlen : 0);
6090 if (subtype == VSNORMAL) {
6094 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6103 case VSTRIMRIGHTMAX:
6112 * Terminate the string and start recording the pattern
6115 STPUTC('\0', expdest);
6116 patloc = expdest - (char *)stackblock();
6117 if (subevalvar(p, NULL, patloc, subtype,
6118 startloc, varflags, quotes) == 0) {
6119 int amount = expdest - (
6120 (char *)stackblock() + patloc - 1
6122 STADJUST(-amount, expdest);
6124 /* Remove any recorded regions beyond start of variable */
6125 removerecordregions(startloc);
6130 if (subtype != VSNORMAL) { /* skip to end of alternative */
6136 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6138 argbackq = argbackq->next;
6139 } else if (c == CTLVAR) {
6140 if ((*p++ & VSTYPE) != VSNORMAL)
6142 } else if (c == CTLENDVAR) {
6153 * Put a string on the stack.
6156 memtodest(const char *p, size_t len, int syntax, int quotes)
6160 q = makestrspace(len * 2, q);
6163 int c = SC2INT(*p++);
6166 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
6176 strtodest(const char *p, int syntax, int quotes)
6178 memtodest(p, strlen(p), syntax, quotes);
6183 * Add the value of a specialized variable to the stack string.
6186 varvalue(char *name, int varflags, int flags)
6196 int quoted = varflags & VSQUOTE;
6197 int subtype = varflags & VSTYPE;
6198 int quotes = flags & (EXP_FULL | EXP_CASE);
6200 if (quoted && (flags & EXP_FULL))
6201 sep = 1 << CHAR_BIT;
6203 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6212 num = shellparam.nparam;
6222 p = makestrspace(NOPTS, expdest);
6223 for (i = NOPTS - 1; i >= 0; i--) {
6225 USTPUTC(optletters(i), p);
6236 sep = ifsset() ? SC2INT(ifsval()[0]) : ' ';
6237 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6243 while ((p = *ap++)) {
6246 partlen = strlen(p);
6249 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6250 memtodest(p, partlen, syntax, quotes);
6256 if (subtype == VSPLUS || subtype == VSLENGTH) {
6278 if (num < 0 || num > shellparam.nparam)
6280 p = num ? shellparam.p[num - 1] : arg0;
6283 p = lookupvar(name);
6289 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6290 memtodest(p, len, syntax, quotes);
6294 if (subtype == VSPLUS || subtype == VSLENGTH)
6295 STADJUST(-len, expdest);
6301 * Record the fact that we have to scan this region of the
6302 * string for IFS characters.
6305 recordregion(int start, int end, int nulonly)
6307 struct ifsregion *ifsp;
6309 if (ifslastp == NULL) {
6313 ifsp = ckmalloc(sizeof(*ifsp));
6315 ifslastp->next = ifsp;
6319 ifslastp->begoff = start;
6320 ifslastp->endoff = end;
6321 ifslastp->nulonly = nulonly;
6326 * Break the argument string into pieces based upon IFS and add the
6327 * strings to the argument list. The regions of the string to be
6328 * searched for IFS characters have been stored by recordregion.
6331 ifsbreakup(char *string, struct arglist *arglist)
6333 struct ifsregion *ifsp;
6338 const char *ifs, *realifs;
6343 if (ifslastp != NULL) {
6346 realifs = ifsset() ? ifsval() : defifs;
6349 p = string + ifsp->begoff;
6350 nulonly = ifsp->nulonly;
6351 ifs = nulonly ? nullstr : realifs;
6353 while (p < string + ifsp->endoff) {
6357 if (!strchr(ifs, *p)) {
6362 ifsspc = (strchr(defifs, *p) != NULL);
6363 /* Ignore IFS whitespace at start */
6364 if (q == start && ifsspc) {
6370 sp = stalloc(sizeof(*sp));
6372 *arglist->lastp = sp;
6373 arglist->lastp = &sp->next;
6377 if (p >= string + ifsp->endoff) {
6383 if (strchr(ifs, *p) == NULL ) {
6386 } else if (strchr(defifs, *p) == NULL) {
6401 } while (ifsp != NULL);
6410 sp = stalloc(sizeof(*sp));
6412 *arglist->lastp = sp;
6413 arglist->lastp = &sp->next;
6419 struct ifsregion *p;
6424 struct ifsregion *ifsp;
6430 ifsfirst.next = NULL;
6434 static void expmeta(char *, char *);
6435 static struct strlist *expsort(struct strlist *);
6436 static struct strlist *msort(struct strlist *, int);
6438 static char *expdir;
6442 expandmeta(struct strlist *str, int flag)
6444 static const char metachars[] = {
6447 /* TODO - EXP_REDIR */
6450 struct strlist **savelastp;
6456 if (!strpbrk(str->text, metachars))
6458 savelastp = exparg.lastp;
6461 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6463 int i = strlen(str->text);
6464 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6472 if (exparg.lastp == savelastp) {
6477 *exparg.lastp = str;
6478 rmescapes(str->text);
6479 exparg.lastp = &str->next;
6481 *exparg.lastp = NULL;
6482 *savelastp = sp = expsort(*savelastp);
6483 while (sp->next != NULL)
6485 exparg.lastp = &sp->next;
6493 * Add a file name to the list.
6496 addfname(const char *name)
6500 sp = stalloc(sizeof(*sp));
6501 sp->text = ststrdup(name);
6503 exparg.lastp = &sp->next;
6508 * Do metacharacter (i.e. *, ?, [...]) expansion.
6511 expmeta(char *enddir, char *name)
6526 for (p = name; *p; p++) {
6527 if (*p == '*' || *p == '?')
6529 else if (*p == '[') {
6536 if (*q == '/' || *q == '\0')
6543 } else if (*p == '\\')
6545 else if (*p == '/') {
6552 if (metaflag == 0) { /* we've reached the end of the file name */
6553 if (enddir != expdir)
6561 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6572 } while (p < start);
6574 if (enddir == expdir) {
6576 } else if (enddir == expdir + 1 && *expdir == '/') {
6585 if (enddir != expdir)
6587 if (*endname == 0) {
6599 while (! intpending && (dp = readdir(dirp)) != NULL) {
6600 if (dp->d_name[0] == '.' && ! matchdot)
6602 if (pmatch(start, dp->d_name)) {
6604 strcpy(enddir, dp->d_name);
6607 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6610 expmeta(p, endname);
6621 * Sort the results of file name expansion. It calculates the number of
6622 * strings to sort and then calls msort (short for merge sort) to do the
6625 static struct strlist *
6626 expsort(struct strlist *str)
6632 for (sp = str; sp; sp = sp->next)
6634 return msort(str, len);
6638 static struct strlist *
6639 msort(struct strlist *list, int len)
6641 struct strlist *p, *q = NULL;
6642 struct strlist **lpp;
6650 for (n = half; --n >= 0; ) {
6654 q->next = NULL; /* terminate first half of list */
6655 q = msort(list, half); /* sort first half of list */
6656 p = msort(p, len - half); /* sort second half */
6659 #if ENABLE_LOCALE_SUPPORT
6660 if (strcoll(p->text, q->text) < 0)
6662 if (strcmp(p->text, q->text) < 0)
6687 * Returns true if the pattern matches the string.
6689 static int patmatch(char *pattern, const char *string)
6691 return pmatch(preglob(pattern, 0, 0), string);
6696 * Remove any CTLESC characters from a string.
6699 _rmescapes(char *str, int flag)
6702 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
6707 p = strpbrk(str, qchars);
6713 if (flag & RMESCAPE_ALLOC) {
6714 size_t len = p - str;
6715 size_t fulllen = len + strlen(p) + 1;
6717 if (flag & RMESCAPE_GROW) {
6718 r = makestrspace(fulllen, expdest);
6719 } else if (flag & RMESCAPE_HEAP) {
6720 r = ckmalloc(fulllen);
6722 r = stalloc(fulllen);
6726 q = memcpy(q, str, len) + len;
6729 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
6730 globbing = flag & RMESCAPE_GLOB;
6731 notescaped = globbing;
6733 if (*p == CTLQUOTEMARK) {
6734 inquotes = ~inquotes;
6736 notescaped = globbing;
6740 /* naked back slash */
6746 if (notescaped && inquotes && *p != '/') {
6750 notescaped = globbing;
6755 if (flag & RMESCAPE_GROW) {
6757 STADJUST(q - r + 1, expdest);
6764 * See if a pattern matches in a case statement.
6767 casematch(union node *pattern, char *val)
6769 struct stackmark smark;
6772 setstackmark(&smark);
6773 argbackq = pattern->narg.backquote;
6774 STARTSTACKSTR(expdest);
6776 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6777 STACKSTRNUL(expdest);
6778 result = patmatch(stackblock(), val);
6779 popstackmark(&smark);
6792 expdest = makestrspace(32, expdest);
6793 #if ENABLE_ASH_MATH_SUPPORT_64
6794 len = fmtstr(expdest, 32, "%lld", (long long) num);
6796 len = fmtstr(expdest, 32, "%ld", num);
6798 STADJUST(len, expdest);
6802 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
6804 varunset(const char *end, const char *var, const char *umsg, int varflags)
6810 msg = "parameter not set";
6812 if (*end == CTLENDVAR) {
6813 if (varflags & VSNUL)
6818 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6825 * This implements the input routines used by the parser.
6828 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
6830 static void pushfile(void);
6833 * Read a character from the script, returning PEOF on end of file.
6834 * Nul characters in the input are silently discarded.
6836 static int preadbuffer(void);
6837 #define pgetc_as_macro() (--parsenleft >= 0? SC2INT(*parsenextc++) : preadbuffer())
6839 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
6840 #define pgetc_macro() pgetc()
6844 return pgetc_as_macro();
6847 #define pgetc_macro() pgetc_as_macro()
6851 return pgetc_macro();
6856 * Same as pgetc(), but ignores PEOA.
6858 #if ENABLE_ASH_ALIAS
6866 } while (c == PEOA);
6873 return pgetc_macro();
6878 * Read a line from the script.
6881 pfgets(char *line, int len)
6887 while (--nleft > 0) {
6902 #if ENABLE_FEATURE_EDITING_VI
6903 #define setvimode(on) do { \
6904 if (on) line_input_state->flags |= VI_MODE; \
6905 else line_input_state->flags &= ~VI_MODE; \
6908 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
6915 char *buf = parsefile->buf;
6919 #if ENABLE_FEATURE_EDITING
6920 if (!iflag || parsefile->fd)
6921 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6923 #if ENABLE_FEATURE_TAB_COMPLETION
6924 line_input_state->path_lookup = pathval();
6926 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
6928 /* Ctrl+C pressed */
6937 if (nr < 0 && errno == 0) {
6938 /* Ctrl+D presend */
6943 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6947 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6948 int flags = fcntl(0, F_GETFL, 0);
6949 if (flags >= 0 && flags & O_NONBLOCK) {
6950 flags &=~ O_NONBLOCK;
6951 if (fcntl(0, F_SETFL, flags) >= 0) {
6952 out2str("sh: turning off NDELAY mode\n");
6962 * Refill the input buffer and return the next input character:
6964 * 1) If a string was pushed back on the input, pop it;
6965 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6966 * from a string so we can't refill the buffer, return EOF.
6967 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6968 * 4) Process input up to the next newline, deleting nul characters.
6977 while (parsefile->strpush) {
6978 #if ENABLE_ASH_ALIAS
6979 if (parsenleft == -1 && parsefile->strpush->ap &&
6980 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6985 if (--parsenleft >= 0)
6986 return SC2INT(*parsenextc++);
6988 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6990 flush_stdout_stderr();
6997 parselleft = parsenleft = EOF_NLEFT;
7004 /* delete nul characters */
7012 memmove(q, q + 1, more);
7016 parsenleft = q - parsenextc - 1;
7022 parsenleft = q - parsenextc - 1;
7034 out2str(parsenextc);
7039 return SC2INT(*parsenextc++);
7043 * Undo the last call to pgetc. Only one character may be pushed back.
7044 * PEOF may be pushed back.
7054 * Push a string back onto the input at this current parsefile level.
7055 * We handle aliases this way.
7058 pushstring(char *s, void *ap)
7065 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
7066 if (parsefile->strpush) {
7067 sp = ckmalloc(sizeof(struct strpush));
7068 sp->prev = parsefile->strpush;
7069 parsefile->strpush = sp;
7071 sp = parsefile->strpush = &(parsefile->basestrpush);
7072 sp->prevstring = parsenextc;
7073 sp->prevnleft = parsenleft;
7074 #if ENABLE_ASH_ALIAS
7075 sp->ap = (struct alias *)ap;
7077 ((struct alias *)ap)->flag |= ALIASINUSE;
7089 struct strpush *sp = parsefile->strpush;
7092 #if ENABLE_ASH_ALIAS
7094 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
7095 checkkwd |= CHKALIAS;
7097 if (sp->string != sp->ap->val) {
7100 sp->ap->flag &= ~ALIASINUSE;
7101 if (sp->ap->flag & ALIASDEAD) {
7102 unalias(sp->ap->name);
7106 parsenextc = sp->prevstring;
7107 parsenleft = sp->prevnleft;
7108 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
7109 parsefile->strpush = sp->prev;
7110 if (sp != &(parsefile->basestrpush))
7117 * Set the input to take input from a file. If push is set, push the
7118 * old input onto the stack first.
7121 setinputfile(const char *fname, int flags)
7127 fd = open(fname, O_RDONLY);
7129 if (flags & INPUT_NOFILE_OK)
7131 ash_msg_and_raise_error("Can't open %s", fname);
7134 fd2 = copyfd(fd, 10);
7137 ash_msg_and_raise_error("Out of file descriptors");
7140 setinputfd(fd, flags & INPUT_PUSH_FILE);
7148 * Like setinputfile, but takes an open file descriptor. Call this with
7152 setinputfd(int fd, int push)
7154 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
7160 if (parsefile->buf == NULL)
7161 parsefile->buf = ckmalloc(IBUFSIZ);
7162 parselleft = parsenleft = 0;
7168 * Like setinputfile, but takes input from a string.
7171 setinputstring(char *string)
7175 parsenextc = string;
7176 parsenleft = strlen(string);
7177 parsefile->buf = NULL;
7184 * To handle the "." command, a stack of input files is used. Pushfile
7185 * adds a new entry to the stack and popfile restores the previous level.
7190 struct parsefile *pf;
7192 parsefile->nleft = parsenleft;
7193 parsefile->lleft = parselleft;
7194 parsefile->nextc = parsenextc;
7195 parsefile->linno = plinno;
7196 pf = ckmalloc(sizeof(*pf));
7197 pf->prev = parsefile;
7200 pf->basestrpush.prev = NULL;
7208 struct parsefile *pf = parsefile;
7217 parsefile = pf->prev;
7219 parsenleft = parsefile->nleft;
7220 parselleft = parsefile->lleft;
7221 parsenextc = parsefile->nextc;
7222 plinno = parsefile->linno;
7228 * Return to top level.
7233 while (parsefile != &basepf)
7239 * Close the file(s) that the shell is reading commands from. Called
7240 * after a fork is done.
7246 if (parsefile->fd > 0) {
7247 close(parsefile->fd);
7254 /* mode flags for set_curjob */
7255 #define CUR_DELETE 2
7256 #define CUR_RUNNING 1
7257 #define CUR_STOPPED 0
7259 /* mode flags for dowait */
7260 #define DOWAIT_NORMAL 0
7261 #define DOWAIT_BLOCK 1
7264 /* pgrp of shell on invocation */
7265 static int initialpgrp;
7266 static int ttyfd = -1;
7269 static struct job *jobtab;
7271 static unsigned njobs;
7273 static struct job *curjob;
7274 /* number of presumed living untracked jobs */
7278 set_curjob(struct job *jp, unsigned mode)
7281 struct job **jpp, **curp;
7283 /* first remove from list */
7284 jpp = curp = &curjob;
7289 jpp = &jp1->prev_job;
7291 *jpp = jp1->prev_job;
7293 /* Then re-insert in correct position */
7301 /* job being deleted */
7304 /* newly created job or backgrounded job,
7305 put after all stopped jobs. */
7309 if (!jp1 || jp1->state != JOBSTOPPED)
7312 jpp = &jp1->prev_job;
7318 /* newly stopped job - becomes curjob */
7319 jp->prev_job = *jpp;
7327 jobno(const struct job *jp)
7329 return jp - jobtab + 1;
7334 * Convert a job name to a job structure.
7337 getjob(const char *name, int getctl)
7341 const char *err_msg = "No such job: %s";
7345 char *(*match)(const char *, const char *);
7360 if (c == '+' || c == '%') {
7362 err_msg = "No current job";
7368 err_msg = "No previous job";
7379 jp = jobtab + num - 1;
7396 if (match(jp->ps[0].cmd, p)) {
7400 err_msg = "%s: ambiguous";
7407 err_msg = "job %s not created under job control";
7408 if (getctl && jp->jobctl == 0)
7413 ash_msg_and_raise_error(err_msg, name);
7417 * Mark a job structure as unused.
7420 freejob(struct job *jp)
7422 struct procstat *ps;
7426 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
7427 if (ps->cmd != nullstr)
7430 if (jp->ps != &jp->ps0)
7433 set_curjob(jp, CUR_DELETE);
7439 xtcsetpgrp(int fd, pid_t pgrp)
7441 if (tcsetpgrp(fd, pgrp))
7442 ash_msg_and_raise_error("Cannot set tty process group (%m)");
7446 * Turn job control on and off.
7448 * Note: This code assumes that the third arg to ioctl is a character
7449 * pointer, which is true on Berkeley systems but not System V. Since
7450 * System V doesn't have job control yet, this isn't a problem now.
7452 * Called with interrupts off.
7460 if (on == jobctl || rootshell == 0)
7464 ofd = fd = open(_PATH_TTY, O_RDWR);
7466 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
7467 * That sometimes helps to acquire controlling tty.
7468 * Obviously, a workaround for bugs when someone
7469 * failed to provide a controlling tty to bash! :) */
7471 while (!isatty(fd) && --fd >= 0)
7474 fd = fcntl(fd, F_DUPFD, 10);
7478 fcntl(fd, F_SETFD, FD_CLOEXEC);
7479 do { /* while we are in the background */
7480 pgrp = tcgetpgrp(fd);
7483 ash_msg("can't access tty; job control turned off");
7487 if (pgrp == getpgrp())
7498 xtcsetpgrp(fd, pgrp);
7500 /* turning job control off */
7503 xtcsetpgrp(fd, pgrp);
7517 killcmd(int argc, char **argv)
7527 ash_msg_and_raise_error(
7528 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
7529 "kill -l [exitstatus]"
7533 if (**++argv == '-') {
7534 signo = get_signum(*argv + 1);
7538 while ((c = nextopt("ls:")) != '\0') {
7548 signo = get_signum(optionarg);
7550 ash_msg_and_raise_error(
7551 "invalid signal number or name: %s",
7563 if (!list && signo < 0)
7566 if ((signo < 0 || !*argv) ^ list) {
7574 for (i = 1; i < NSIG; i++) {
7575 name = get_signame(i);
7577 out1fmt(snlfmt, name);
7581 name = get_signame(signo);
7582 if (!isdigit(*name))
7583 ash_msg_and_raise_error("invalid signal number or exit status: %s", *argptr);
7584 out1fmt(snlfmt, name);
7590 if (**argv == '%') {
7591 jp = getjob(*argv, 0);
7592 pid = -jp->ps[0].pid;
7594 pid = **argv == '-' ?
7595 -number(*argv + 1) : number(*argv);
7597 if (kill(pid, signo) != 0) {
7598 ash_msg("(%d) - %m", pid);
7607 showpipe(struct job *jp, FILE *out)
7609 struct procstat *sp;
7610 struct procstat *spend;
7612 spend = jp->ps + jp->nprocs;
7613 for (sp = jp->ps + 1; sp < spend; sp++)
7614 fprintf(out, " | %s", sp->cmd);
7615 outcslow('\n', out);
7616 flush_stdout_stderr();
7621 restartjob(struct job *jp, int mode)
7623 struct procstat *ps;
7629 if (jp->state == JOBDONE)
7631 jp->state = JOBRUNNING;
7633 if (mode == FORK_FG)
7634 xtcsetpgrp(ttyfd, pgid);
7635 killpg(pgid, SIGCONT);
7639 if (WIFSTOPPED(ps->status)) {
7642 } while (ps++, --i);
7644 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
7650 fg_bgcmd(int argc, char **argv)
7657 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
7662 jp = getjob(*argv, 1);
7663 if (mode == FORK_BG) {
7664 set_curjob(jp, CUR_RUNNING);
7665 fprintf(out, "[%d] ", jobno(jp));
7667 outstr(jp->ps->cmd, out);
7669 retval = restartjob(jp, mode);
7670 } while (*argv && *++argv);
7676 sprint_status(char *s, int status, int sigonly)
7682 if (!WIFEXITED(status)) {
7684 if (WIFSTOPPED(status))
7685 st = WSTOPSIG(status);
7688 st = WTERMSIG(status);
7690 if (st == SIGINT || st == SIGPIPE)
7693 if (WIFSTOPPED(status))
7698 col = fmtstr(s, 32, strsignal(st));
7699 if (WCOREDUMP(status)) {
7700 col += fmtstr(s + col, 16, " (core dumped)");
7702 } else if (!sigonly) {
7703 st = WEXITSTATUS(status);
7705 col = fmtstr(s, 16, "Done(%d)", st);
7707 col = fmtstr(s, 16, "Done");
7714 * Do a wait system call. If job control is compiled in, we accept
7715 * stopped processes. If block is zero, we return a value of zero
7716 * rather than blocking.
7718 * System V doesn't have a non-blocking wait system call. It does
7719 * have a SIGCLD signal that is sent to a process when one of it's
7720 * children dies. The obvious way to use SIGCLD would be to install
7721 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
7722 * was received, and have waitproc bump another counter when it got
7723 * the status of a process. Waitproc would then know that a wait
7724 * system call would not block if the two counters were different.
7725 * This approach doesn't work because if a process has children that
7726 * have not been waited for, System V will send it a SIGCLD when it
7727 * installs a signal handler for SIGCLD. What this means is that when
7728 * a child exits, the shell will be sent SIGCLD signals continuously
7729 * until is runs out of stack space, unless it does a wait call before
7730 * restoring the signal handler. The code below takes advantage of
7731 * this (mis)feature by installing a signal handler for SIGCLD and
7732 * then checking to see whether it was called. If there are any
7733 * children to be waited for, it will be.
7735 * If neither SYSV nor BSD is defined, we don't implement nonblocking
7736 * waits at all. In this case, the user will not be informed when
7737 * a background process until the next time she runs a real program
7738 * (as opposed to running a builtin command or just typing return),
7739 * and the jobs command may give out of date information.
7742 waitproc(int block, int *status)
7752 return wait3(status, flags, (struct rusage *)NULL);
7756 * Wait for a process to terminate.
7759 dowait(int block, struct job *job)
7764 struct job *thisjob;
7767 TRACE(("dowait(%d) called\n", block));
7768 pid = waitproc(block, &status);
7769 TRACE(("wait returns pid %d, status=%d\n", pid, status));
7774 for (jp = curjob; jp; jp = jp->prev_job) {
7775 struct procstat *sp;
7776 struct procstat *spend;
7777 if (jp->state == JOBDONE)
7780 spend = jp->ps + jp->nprocs;
7783 if (sp->pid == pid) {
7784 TRACE(("Job %d: changing status of proc %d "
7785 "from 0x%x to 0x%x\n",
7786 jobno(jp), pid, sp->status, status));
7787 sp->status = status;
7790 if (sp->status == -1)
7793 if (state == JOBRUNNING)
7795 if (WIFSTOPPED(sp->status)) {
7796 jp->stopstatus = sp->status;
7800 } while (++sp < spend);
7805 if (!WIFSTOPPED(status))
7812 if (state != JOBRUNNING) {
7813 thisjob->changed = 1;
7815 if (thisjob->state != state) {
7816 TRACE(("Job %d: changing state from %d to %d\n",
7817 jobno(thisjob), thisjob->state, state));
7818 thisjob->state = state;
7820 if (state == JOBSTOPPED) {
7821 set_curjob(thisjob, CUR_STOPPED);
7830 if (thisjob && thisjob == job) {
7834 len = sprint_status(s, status, 1);
7846 showjob(FILE *out, struct job *jp, int mode)
7848 struct procstat *ps;
7849 struct procstat *psend;
7856 if (mode & SHOW_PGID) {
7857 /* just output process (group) id of pipeline */
7858 fprintf(out, "%d\n", ps->pid);
7862 col = fmtstr(s, 16, "[%d] ", jobno(jp));
7867 else if (curjob && jp == curjob->prev_job)
7870 if (mode & SHOW_PID)
7871 col += fmtstr(s + col, 16, "%d ", ps->pid);
7873 psend = ps + jp->nprocs;
7875 if (jp->state == JOBRUNNING) {
7876 strcpy(s + col, "Running");
7877 col += sizeof("Running") - 1;
7879 int status = psend[-1].status;
7880 if (jp->state == JOBSTOPPED)
7881 status = jp->stopstatus;
7882 col += sprint_status(s + col, status, 0);
7888 /* for each process */
7889 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
7891 fprintf(out, "%s%*c%s",
7892 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
7894 if (!(mode & SHOW_PID)) {
7898 if (++ps == psend) {
7899 outcslow('\n', out);
7906 if (jp->state == JOBDONE) {
7907 TRACE(("showjob: freeing job %d\n", jobno(jp)));
7913 jobscmd(int argc, char **argv)
7919 while ((m = nextopt("lp"))) {
7930 showjob(out, getjob(*argv,0), mode);
7933 showjobs(out, mode);
7939 * Print a list of jobs. If "change" is nonzero, only print jobs whose
7940 * statuses have changed since the last call to showjobs.
7943 showjobs(FILE *out, int mode)
7947 TRACE(("showjobs(%x) called\n", mode));
7949 /* If not even one one job changed, there is nothing to do */
7950 while (dowait(DOWAIT_NORMAL, NULL) > 0)
7953 for (jp = curjob; jp; jp = jp->prev_job) {
7954 if (!(mode & SHOW_CHANGED) || jp->changed)
7955 showjob(out, jp, mode);
7961 getstatus(struct job *job)
7966 status = job->ps[job->nprocs - 1].status;
7967 retval = WEXITSTATUS(status);
7968 if (!WIFEXITED(status)) {
7970 retval = WSTOPSIG(status);
7971 if (!WIFSTOPPED(status))
7974 /* XXX: limits number of signals */
7975 retval = WTERMSIG(status);
7977 if (retval == SIGINT)
7983 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
7984 jobno(job), job->nprocs, status, retval));
7989 waitcmd(int argc, char **argv)
8002 /* wait for all jobs */
8007 /* no running procs */
8010 if (jp->state == JOBRUNNING)
8015 dowait(DOWAIT_BLOCK, 0);
8021 if (**argv != '%') {
8022 pid_t pid = number(*argv);
8026 if (job->ps[job->nprocs - 1].pid == pid)
8028 job = job->prev_job;
8034 job = getjob(*argv, 0);
8035 /* loop until process terminated or stopped */
8036 while (job->state == JOBRUNNING)
8037 dowait(DOWAIT_BLOCK, 0);
8039 retval = getstatus(job);
8053 struct job *jp, *jq;
8055 len = njobs * sizeof(*jp);
8057 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
8059 offset = (char *)jp - (char *)jq;
8061 /* Relocate pointers */
8064 jq = (struct job *)((char *)jq + l);
8068 #define joff(p) ((struct job *)((char *)(p) + l))
8069 #define jmove(p) (p) = (void *)((char *)(p) + offset)
8070 if (xlikely(joff(jp)->ps == &jq->ps0))
8071 jmove(joff(jp)->ps);
8072 if (joff(jp)->prev_job)
8073 jmove(joff(jp)->prev_job);
8083 jp = (struct job *)((char *)jp + len);
8087 } while (--jq >= jp);
8092 * Return a new job structure.
8093 * Called with interrupts off.
8096 makejob(union node *node, int nprocs)
8101 for (i = njobs, jp = jobtab; ; jp++) {
8108 if (jp->state != JOBDONE || !jp->waited)
8117 memset(jp, 0, sizeof(*jp));
8122 jp->prev_job = curjob;
8127 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
8129 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
8136 * Return a string identifying a command (to be printed by the
8139 static char *cmdnextc;
8142 cmdputs(const char *s)
8144 const char *p, *str;
8145 char c, cc[2] = " ";
8149 static const char vstype[VSTYPE + 1][4] = {
8150 "", "}", "-", "+", "?", "=",
8151 "%", "%%", "#", "##"
8154 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
8156 while ((c = *p++) != 0) {
8164 if ((subtype & VSTYPE) == VSLENGTH)
8168 if (!(subtype & VSQUOTE) == !(quoted & 1))
8174 str = "\"}" + !(quoted & 1);
8181 case CTLBACKQ+CTLQUOTE:
8184 #if ENABLE_ASH_MATH_SUPPORT
8199 if ((subtype & VSTYPE) != VSNORMAL)
8201 str = vstype[subtype & VSTYPE];
8202 if (subtype & VSNUL)
8211 /* These can only happen inside quotes */
8224 while ((c = *str++)) {
8229 USTPUTC('"', nextc);
8235 /* cmdtxt() and cmdlist() call each other */
8236 static void cmdtxt(union node *n);
8239 cmdlist(union node *np, int sep)
8241 for (; np; np = np->narg.next) {
8245 if (sep && np->narg.next)
8251 cmdtxt(union node *n)
8254 struct nodelist *lp;
8266 lp = n->npipe.cmdlist;
8284 cmdtxt(n->nbinary.ch1);
8300 cmdtxt(n->nif.test);
8303 if (n->nif.elsepart) {
8306 n = n->nif.elsepart;
8322 cmdtxt(n->nbinary.ch1);
8332 cmdputs(n->nfor.var);
8334 cmdlist(n->nfor.args, 1);
8339 cmdputs(n->narg.text);
8343 cmdlist(n->ncmd.args, 1);
8344 cmdlist(n->ncmd.redirect, 0);
8357 cmdputs(n->ncase.expr->narg.text);
8359 for (np = n->ncase.cases; np; np = np->nclist.next) {
8360 cmdtxt(np->nclist.pattern);
8362 cmdtxt(np->nclist.body);
8388 s[0] = n->nfile.fd + '0';
8392 if (n->type == NTOFD || n->type == NFROMFD) {
8393 s[0] = n->ndup.dupfd + '0';
8403 commandtext(union node *n)
8407 STARTSTACKSTR(cmdnextc);
8409 name = stackblock();
8410 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
8411 name, cmdnextc, cmdnextc));
8412 return ckstrdup(name);
8417 * Fork off a subshell. If we are doing job control, give the subshell its
8418 * own process group. Jp is a job structure that the job is to be added to.
8419 * N is the command that will be evaluated by the child. Both jp and n may
8420 * be NULL. The mode parameter can be one of the following:
8421 * FORK_FG - Fork off a foreground process.
8422 * FORK_BG - Fork off a background process.
8423 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
8424 * process group even if job control is on.
8426 * When job control is turned off, background processes have their standard
8427 * input redirected to /dev/null (except for the second and later processes
8430 * Called with interrupts off.
8433 forkchild(struct job *jp, union node *n, int mode)
8437 TRACE(("Child shell %d\n", getpid()));
8444 /* do job control only in root shell */
8446 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
8449 if (jp->nprocs == 0)
8452 pgrp = jp->ps[0].pid;
8453 /* This can fail because we are doing it in the parent also */
8454 (void)setpgid(0, pgrp);
8455 if (mode == FORK_FG)
8456 xtcsetpgrp(ttyfd, pgrp);
8461 if (mode == FORK_BG) {
8464 if (jp->nprocs == 0) {
8466 if (open(bb_dev_null, O_RDONLY) != 0)
8467 ash_msg_and_raise_error("Can't open %s", bb_dev_null);
8470 if (!oldlvl && iflag) {
8475 for (jp = curjob; jp; jp = jp->prev_job)
8481 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
8483 TRACE(("In parent shell: child = %d\n", pid));
8485 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
8490 if (mode != FORK_NOJOB && jp->jobctl) {
8493 if (jp->nprocs == 0)
8496 pgrp = jp->ps[0].pid;
8497 /* This can fail because we are doing it in the child also */
8501 if (mode == FORK_BG) {
8502 backgndpid = pid; /* set $! */
8503 set_curjob(jp, CUR_RUNNING);
8506 struct procstat *ps = &jp->ps[jp->nprocs++];
8512 ps->cmd = commandtext(n);
8518 forkshell(struct job *jp, union node *n, int mode)
8522 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
8525 TRACE(("Fork failed, errno=%d", errno));
8528 ash_msg_and_raise_error("Cannot fork");
8531 forkchild(jp, n, mode);
8533 forkparent(jp, n, mode, pid);
8538 * Wait for job to finish.
8540 * Under job control we have the problem that while a child process is
8541 * running interrupts generated by the user are sent to the child but not
8542 * to the shell. This means that an infinite loop started by an inter-
8543 * active user may be hard to kill. With job control turned off, an
8544 * interactive user may place an interactive program inside a loop. If
8545 * the interactive program catches interrupts, the user doesn't want
8546 * these interrupts to also abort the loop. The approach we take here
8547 * is to have the shell ignore interrupt signals while waiting for a
8548 * foreground process to terminate, and then send itself an interrupt
8549 * signal if the child process was terminated by an interrupt signal.
8550 * Unfortunately, some programs want to do a bit of cleanup and then
8551 * exit on interrupt; unless these processes terminate themselves by
8552 * sending a signal to themselves (instead of calling exit) they will
8553 * confuse this approach.
8555 * Called with interrupts off.
8558 waitforjob(struct job *jp)
8562 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
8563 while (jp->state == JOBRUNNING) {
8564 dowait(DOWAIT_BLOCK, jp);
8569 xtcsetpgrp(ttyfd, rootpid);
8571 * This is truly gross.
8572 * If we're doing job control, then we did a TIOCSPGRP which
8573 * caused us (the shell) to no longer be in the controlling
8574 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
8575 * intuit from the subprocess exit status whether a SIGINT
8576 * occurred, and if so interrupt ourselves. Yuck. - mycroft
8581 if (jp->state == JOBDONE)
8588 * return 1 if there are stopped jobs, otherwise 0
8600 if (jp && jp->state == JOBSTOPPED) {
8601 out2str("You have stopped jobs.\n");
8614 * Routines to check for mail. (Perhaps make part of main.c?)
8617 #define MAXMBOXES 10
8619 /* times of mailboxes */
8620 static time_t mailtime[MAXMBOXES];
8621 /* Set if MAIL or MAILPATH is changed. */
8622 static int mail_var_path_changed;
8626 * Print appropriate message(s) if mail has arrived.
8627 * If mail_var_path_changed is set,
8628 * then the value of MAIL has mail_var_path_changed,
8629 * so we just update the values.
8638 struct stackmark smark;
8641 setstackmark(&smark);
8642 mpath = mpathset() ? mpathval() : mailval();
8643 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
8644 p = padvance(&mpath, nullstr);
8649 for (q = p; *q; q++);
8654 q[-1] = '\0'; /* delete trailing '/' */
8655 if (stat(p, &statb) < 0) {
8659 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
8662 pathopt ? pathopt : "you have mail"
8665 *mtp = statb.st_mtime;
8667 mail_var_path_changed = 0;
8668 popstackmark(&smark);
8673 changemail(const char *val)
8675 mail_var_path_changed++;
8678 #endif /* ASH_MAIL */
8681 * Take commands from a file. To be compatible we should do a path
8682 * search for the file, which is necessary to find sub-commands.
8685 find_dot_file(char *name)
8688 const char *path = pathval();
8691 /* don't try this for absolute or relative paths */
8692 if (strchr(name, '/'))
8695 while ((fullname = padvance(&path, name)) != NULL) {
8696 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
8698 * Don't bother freeing here, since it will
8699 * be freed by the caller.
8703 stunalloc(fullname);
8706 /* not found in the PATH */
8707 ash_msg_and_raise_error("%s: not found", name);
8712 calcsize(union node *n)
8716 funcblocksize += nodesize[n->type];
8719 calcsize(n->ncmd.redirect);
8720 calcsize(n->ncmd.args);
8721 calcsize(n->ncmd.assign);
8724 sizenodelist(n->npipe.cmdlist);
8729 calcsize(n->nredir.redirect);
8730 calcsize(n->nredir.n);
8737 calcsize(n->nbinary.ch2);
8738 calcsize(n->nbinary.ch1);
8741 calcsize(n->nif.elsepart);
8742 calcsize(n->nif.ifpart);
8743 calcsize(n->nif.test);
8746 funcstringsize += strlen(n->nfor.var) + 1;
8747 calcsize(n->nfor.body);
8748 calcsize(n->nfor.args);
8751 calcsize(n->ncase.cases);
8752 calcsize(n->ncase.expr);
8755 calcsize(n->nclist.body);
8756 calcsize(n->nclist.pattern);
8757 calcsize(n->nclist.next);
8761 sizenodelist(n->narg.backquote);
8762 funcstringsize += strlen(n->narg.text) + 1;
8763 calcsize(n->narg.next);
8770 calcsize(n->nfile.fname);
8771 calcsize(n->nfile.next);
8775 calcsize(n->ndup.vname);
8776 calcsize(n->ndup.next);
8780 calcsize(n->nhere.doc);
8781 calcsize(n->nhere.next);
8784 calcsize(n->nnot.com);
8791 sizenodelist(struct nodelist *lp)
8794 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8802 copynode(union node *n)
8809 funcblock = (char *) funcblock + nodesize[n->type];
8813 new->ncmd.redirect = copynode(n->ncmd.redirect);
8814 new->ncmd.args = copynode(n->ncmd.args);
8815 new->ncmd.assign = copynode(n->ncmd.assign);
8818 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8819 new->npipe.backgnd = n->npipe.backgnd;
8824 new->nredir.redirect = copynode(n->nredir.redirect);
8825 new->nredir.n = copynode(n->nredir.n);
8832 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8833 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8836 new->nif.elsepart = copynode(n->nif.elsepart);
8837 new->nif.ifpart = copynode(n->nif.ifpart);
8838 new->nif.test = copynode(n->nif.test);
8841 new->nfor.var = nodeckstrdup(n->nfor.var);
8842 new->nfor.body = copynode(n->nfor.body);
8843 new->nfor.args = copynode(n->nfor.args);
8846 new->ncase.cases = copynode(n->ncase.cases);
8847 new->ncase.expr = copynode(n->ncase.expr);
8850 new->nclist.body = copynode(n->nclist.body);
8851 new->nclist.pattern = copynode(n->nclist.pattern);
8852 new->nclist.next = copynode(n->nclist.next);
8856 new->narg.backquote = copynodelist(n->narg.backquote);
8857 new->narg.text = nodeckstrdup(n->narg.text);
8858 new->narg.next = copynode(n->narg.next);
8865 new->nfile.fname = copynode(n->nfile.fname);
8866 new->nfile.fd = n->nfile.fd;
8867 new->nfile.next = copynode(n->nfile.next);
8871 new->ndup.vname = copynode(n->ndup.vname);
8872 new->ndup.dupfd = n->ndup.dupfd;
8873 new->ndup.fd = n->ndup.fd;
8874 new->ndup.next = copynode(n->ndup.next);
8878 new->nhere.doc = copynode(n->nhere.doc);
8879 new->nhere.fd = n->nhere.fd;
8880 new->nhere.next = copynode(n->nhere.next);
8883 new->nnot.com = copynode(n->nnot.com);
8886 new->type = n->type;
8891 static struct nodelist *
8892 copynodelist(struct nodelist *lp)
8894 struct nodelist *start;
8895 struct nodelist **lpp;
8900 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8901 (*lpp)->n = copynode(lp->n);
8903 lpp = &(*lpp)->next;
8911 nodeckstrdup(char *s)
8913 char *rtn = funcstring;
8915 strcpy(funcstring, s);
8916 funcstring += strlen(s) + 1;
8922 * Free a parse tree.
8925 freefunc(struct funcnode *f)
8927 if (f && --f->count < 0)
8938 setinteractive(iflag);
8944 minus_o(char *name, int val)
8949 for (i = 0; i < NOPTS; i++) {
8950 if (strcmp(name, optnames(i)) == 0) {
8955 ash_msg_and_raise_error("Illegal option -o %s", name);
8957 out1str("Current option settings\n");
8958 for (i = 0; i < NOPTS; i++)
8959 out1fmt("%-16s%s\n", optnames(i),
8960 optlist[i] ? "on" : "off");
8965 setoption(int flag, int val)
8969 for (i = 0; i < NOPTS; i++) {
8970 if (optletters(i) == flag) {
8975 ash_msg_and_raise_error("Illegal option -%c", flag);
8981 * Process shell options. The global variable argptr contains a pointer
8982 * to the argument list; we advance it past the options.
8985 options(int cmdline)
8993 while ((p = *argptr) != NULL) {
8998 if (p[0] == '\0' || LONE_DASH(p)) {
9000 /* "-" means turn off -x and -v */
9003 /* "--" means reset params */
9004 else if (*argptr == NULL)
9007 break; /* "-" or "--" terminates options */
9009 } else if (c == '+') {
9015 while ((c = *p++) != '\0') {
9016 if (c == 'c' && cmdline) {
9017 minusc = p; /* command is after shell args*/
9018 } else if (c == 'o') {
9019 minus_o(*argptr, val);
9022 } else if (cmdline && (c == '-')) { // long options
9023 if (strcmp(p, "login") == 0)
9035 * Set the shell parameters.
9038 setparam(char **argv)
9044 for (nparam = 0; argv[nparam]; nparam++);
9045 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9047 *ap++ = ckstrdup(*argv++);
9050 freeparam(&shellparam);
9051 shellparam.malloc = 1;
9052 shellparam.nparam = nparam;
9053 shellparam.p = newparam;
9054 #if ENABLE_ASH_GETOPTS
9055 shellparam.optind = 1;
9056 shellparam.optoff = -1;
9062 * Free the list of positional parameters.
9065 freeparam(volatile struct shparam *param)
9069 if (param->malloc) {
9070 for (ap = param->p; *ap; ap++)
9078 * The shift builtin command.
9081 shiftcmd(int argc, char **argv)
9088 n = number(argv[1]);
9089 if (n > shellparam.nparam)
9090 ash_msg_and_raise_error("can't shift that many");
9092 shellparam.nparam -= n;
9093 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9094 if (shellparam.malloc)
9098 while ((*ap2++ = *ap1++) != NULL);
9099 #if ENABLE_ASH_GETOPTS
9100 shellparam.optind = 1;
9101 shellparam.optoff = -1;
9109 * POSIX requires that 'set' (but not export or readonly) output the
9110 * variables in lexicographic order - by the locale's collating order (sigh).
9111 * Maybe we could keep them in an ordered balanced binary tree
9112 * instead of hashed lists.
9113 * For now just roll 'em through qsort for printing...
9116 showvars(const char *sep_prefix, int on, int off)
9121 ep = listvars(on, off, &epend);
9122 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9124 sep = *sep_prefix ? spcstr : sep_prefix;
9126 for (; ep < epend; ep++) {
9130 p = strchrnul(*ep, '=');
9133 q = single_quote(++p);
9134 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9140 * The set command builtin.
9143 setcmd(int argc, char **argv)
9146 return showvars(nullstr, 0, VUNSET);
9150 if (*argptr != NULL) {
9158 #if ENABLE_LOCALE_SUPPORT
9160 change_lc_all(const char *value)
9162 if (value && *value != '\0')
9163 setlocale(LC_ALL, value);
9167 change_lc_ctype(const char *value)
9169 if (value && *value != '\0')
9170 setlocale(LC_CTYPE, value);
9174 #if ENABLE_ASH_RANDOM_SUPPORT
9175 /* Roughly copied from bash.. */
9177 change_random(const char *value)
9179 if (value == NULL) {
9180 /* "get", generate */
9183 rseed = rseed * 1103515245 + 12345;
9184 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9185 /* set without recursion */
9186 setvar(vrandom.text, buf, VNOFUNC);
9187 vrandom.flags &= ~VNOFUNC;
9190 rseed = strtoul(value, (char **)NULL, 10);
9196 #if ENABLE_ASH_GETOPTS
9198 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9207 if (*param_optind < 1)
9209 optnext = optfirst + *param_optind - 1;
9211 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9214 p = optnext[-1] + *optoff;
9215 if (p == NULL || *p == '\0') {
9216 /* Current word is done, advance */
9218 if (p == NULL || *p != '-' || *++p == '\0') {
9225 if (LONE_DASH(p)) /* check for "--" */
9230 for (q = optstr; *q != c; ) {
9232 if (optstr[0] == ':') {
9235 err |= setvarsafe("OPTARG", s, 0);
9237 fprintf(stderr, "Illegal option -%c\n", c);
9248 if (*p == '\0' && (p = *optnext) == NULL) {
9249 if (optstr[0] == ':') {
9252 err |= setvarsafe("OPTARG", s, 0);
9255 fprintf(stderr, "No arg for -%c option\n", c);
9264 err |= setvarsafe("OPTARG", p, 0);
9267 err |= setvarsafe("OPTARG", nullstr, 0);
9269 *optoff = p ? p - *(optnext - 1) : -1;
9270 *param_optind = optnext - optfirst + 1;
9271 fmtstr(s, sizeof(s), "%d", *param_optind);
9272 err |= setvarsafe("OPTIND", s, VNOFUNC);
9275 err |= setvarsafe(optvar, s, 0);
9279 flush_stdout_stderr();
9280 raise_exception(EXERROR);
9287 * The getopts builtin. Shellparam.optnext points to the next argument
9288 * to be processed. Shellparam.optptr points to the next character to
9289 * be processed in the current argument. If shellparam.optnext is NULL,
9290 * then it's the first time getopts has been called.
9293 getoptscmd(int argc, char **argv)
9298 ash_msg_and_raise_error("Usage: getopts optstring var [arg]");
9300 optbase = shellparam.p;
9301 if (shellparam.optind > shellparam.nparam + 1) {
9302 shellparam.optind = 1;
9303 shellparam.optoff = -1;
9307 if (shellparam.optind > argc - 2) {
9308 shellparam.optind = 1;
9309 shellparam.optoff = -1;
9313 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9314 &shellparam.optoff);
9316 #endif /* ASH_GETOPTS */
9319 /* ============ Shell parser */
9321 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9323 raise_error_syntax(const char *msg)
9325 ash_msg_and_raise_error("Syntax error: %s", msg);
9330 * Called when an unexpected token is read during the parse. The argument
9331 * is the token that is expected, or -1 if more than one type of token can
9332 * occur at this point.
9334 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9336 raise_error_unexpected_syntax(int token)
9341 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9343 sprintf(msg + l, " (expecting %s)", tokname(token));
9344 raise_error_syntax(msg);
9348 #define EOFMARKLEN 79
9351 struct heredoc *next; /* next here document in list */
9352 union node *here; /* redirection node */
9353 char *eofmark; /* string indicating end of input */
9354 int striptabs; /* if set, strip leading tabs */
9357 static struct heredoc *heredoclist; /* list of here documents to read */
9359 /* parsing is heavily cross-recursive, need these forward decls */
9360 static union node *andor(void);
9361 static union node *pipeline(void);
9362 static union node *parse_command(void);
9363 static void parseheredoc(void);
9364 static char peektoken(void);
9365 static int readtoken(void);
9370 union node *n1, *n2, *n3;
9373 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9374 if (nlflag == 2 && peektoken())
9380 if (tok == TBACKGND) {
9381 if (n2->type == NPIPE) {
9382 n2->npipe.backgnd = 1;
9384 if (n2->type != NREDIR) {
9385 n3 = stalloc(sizeof(struct nredir));
9387 n3->nredir.redirect = NULL;
9390 n2->type = NBACKGND;
9396 n3 = stalloc(sizeof(struct nbinary));
9398 n3->nbinary.ch1 = n1;
9399 n3->nbinary.ch2 = n2;
9415 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9423 pungetc(); /* push back EOF on input */
9427 raise_error_unexpected_syntax(-1);
9437 union node *n1, *n2, *n3;
9445 } else if (t == TOR) {
9451 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9453 n3 = stalloc(sizeof(struct nbinary));
9455 n3->nbinary.ch1 = n1;
9456 n3->nbinary.ch2 = n2;
9464 union node *n1, *n2, *pipenode;
9465 struct nodelist *lp, *prev;
9469 TRACE(("pipeline: entered\n"));
9470 if (readtoken() == TNOT) {
9472 checkkwd = CHKKWD | CHKALIAS;
9475 n1 = parse_command();
9476 if (readtoken() == TPIPE) {
9477 pipenode = stalloc(sizeof(struct npipe));
9478 pipenode->type = NPIPE;
9479 pipenode->npipe.backgnd = 0;
9480 lp = stalloc(sizeof(struct nodelist));
9481 pipenode->npipe.cmdlist = lp;
9485 lp = stalloc(sizeof(struct nodelist));
9486 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9487 lp->n = parse_command();
9489 } while (readtoken() == TPIPE);
9495 n2 = stalloc(sizeof(struct nnot));
9508 n = stalloc(sizeof(struct narg));
9510 n->narg.next = NULL;
9511 n->narg.text = wordtext;
9512 n->narg.backquote = backquotelist;
9517 fixredir(union node *n, const char *text, int err)
9519 TRACE(("Fix redir %s %d\n", text, err));
9521 n->ndup.vname = NULL;
9523 if (isdigit(text[0]) && text[1] == '\0')
9524 n->ndup.dupfd = digit_val(text[0]);
9525 else if (LONE_DASH(text))
9529 raise_error_syntax("Bad fd number");
9530 n->ndup.vname = makename();
9535 * Returns true if the text contains nothing to expand (no dollar signs
9539 noexpand(char *text)
9545 while ((c = *p++) != '\0') {
9546 if (c == CTLQUOTEMARK)
9550 else if (SIT(c, BASESYNTAX) == CCTL)
9559 union node *n = redirnode;
9561 if (readtoken() != TWORD)
9562 raise_error_unexpected_syntax(-1);
9563 if (n->type == NHERE) {
9564 struct heredoc *here = heredoc;
9570 TRACE(("Here document %d\n", n->type));
9571 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9572 raise_error_syntax("Illegal eof marker for << redirection");
9573 rmescapes(wordtext);
9574 here->eofmark = wordtext;
9576 if (heredoclist == NULL)
9579 for (p = heredoclist; p->next; p = p->next);
9582 } else if (n->type == NTOFD || n->type == NFROMFD) {
9583 fixredir(n, wordtext, 0);
9585 n->nfile.fname = makename();
9592 union node *args, **app;
9593 union node *n = NULL;
9594 union node *vars, **vpp;
9595 union node **rpp, *redir;
9605 savecheckkwd = CHKALIAS;
9607 checkkwd = savecheckkwd;
9608 switch (readtoken()) {
9610 n = stalloc(sizeof(struct narg));
9612 n->narg.text = wordtext;
9613 n->narg.backquote = backquotelist;
9614 if (savecheckkwd && isassignment(wordtext)) {
9616 vpp = &n->narg.next;
9619 app = &n->narg.next;
9624 *rpp = n = redirnode;
9625 rpp = &n->nfile.next;
9626 parsefname(); /* read name of redirection file */
9629 if (args && app == &args->narg.next
9632 struct builtincmd *bcmd;
9635 /* We have a function */
9636 if (readtoken() != TRP)
9637 raise_error_unexpected_syntax(TRP);
9638 name = n->narg.text;
9640 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9642 raise_error_syntax("Bad function name");
9645 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9646 n->narg.next = parse_command();
9659 n = stalloc(sizeof(struct ncmd));
9661 n->ncmd.args = args;
9662 n->ncmd.assign = vars;
9663 n->ncmd.redirect = redir;
9670 union node *n1, *n2;
9671 union node *ap, **app;
9672 union node *cp, **cpp;
9673 union node *redir, **rpp;
9680 switch (readtoken()) {
9682 raise_error_unexpected_syntax(-1);
9685 n1 = stalloc(sizeof(struct nif));
9687 n1->nif.test = list(0);
9688 if (readtoken() != TTHEN)
9689 raise_error_unexpected_syntax(TTHEN);
9690 n1->nif.ifpart = list(0);
9692 while (readtoken() == TELIF) {
9693 n2->nif.elsepart = stalloc(sizeof(struct nif));
9694 n2 = n2->nif.elsepart;
9696 n2->nif.test = list(0);
9697 if (readtoken() != TTHEN)
9698 raise_error_unexpected_syntax(TTHEN);
9699 n2->nif.ifpart = list(0);
9701 if (lasttoken == TELSE)
9702 n2->nif.elsepart = list(0);
9704 n2->nif.elsepart = NULL;
9712 n1 = stalloc(sizeof(struct nbinary));
9713 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9714 n1->nbinary.ch1 = list(0);
9717 TRACE(("expecting DO got %s %s\n", tokname(got),
9718 got == TWORD ? wordtext : ""));
9719 raise_error_unexpected_syntax(TDO);
9721 n1->nbinary.ch2 = list(0);
9726 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9727 raise_error_syntax("Bad for loop variable");
9728 n1 = stalloc(sizeof(struct nfor));
9730 n1->nfor.var = wordtext;
9731 checkkwd = CHKKWD | CHKALIAS;
9732 if (readtoken() == TIN) {
9734 while (readtoken() == TWORD) {
9735 n2 = stalloc(sizeof(struct narg));
9737 n2->narg.text = wordtext;
9738 n2->narg.backquote = backquotelist;
9740 app = &n2->narg.next;
9744 if (lasttoken != TNL && lasttoken != TSEMI)
9745 raise_error_unexpected_syntax(-1);
9747 n2 = stalloc(sizeof(struct narg));
9749 n2->narg.text = (char *)dolatstr;
9750 n2->narg.backquote = NULL;
9751 n2->narg.next = NULL;
9754 * Newline or semicolon here is optional (but note
9755 * that the original Bourne shell only allowed NL).
9757 if (lasttoken != TNL && lasttoken != TSEMI)
9760 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9761 if (readtoken() != TDO)
9762 raise_error_unexpected_syntax(TDO);
9763 n1->nfor.body = list(0);
9767 n1 = stalloc(sizeof(struct ncase));
9769 if (readtoken() != TWORD)
9770 raise_error_unexpected_syntax(TWORD);
9771 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9773 n2->narg.text = wordtext;
9774 n2->narg.backquote = backquotelist;
9775 n2->narg.next = NULL;
9777 checkkwd = CHKKWD | CHKALIAS;
9778 } while (readtoken() == TNL);
9779 if (lasttoken != TIN)
9780 raise_error_unexpected_syntax(TIN);
9781 cpp = &n1->ncase.cases;
9783 checkkwd = CHKNL | CHKKWD;
9785 while (t != TESAC) {
9786 if (lasttoken == TLP)
9788 *cpp = cp = stalloc(sizeof(struct nclist));
9790 app = &cp->nclist.pattern;
9792 *app = ap = stalloc(sizeof(struct narg));
9794 ap->narg.text = wordtext;
9795 ap->narg.backquote = backquotelist;
9796 if (readtoken() != TPIPE)
9798 app = &ap->narg.next;
9801 ap->narg.next = NULL;
9802 if (lasttoken != TRP)
9803 raise_error_unexpected_syntax(TRP);
9804 cp->nclist.body = list(2);
9806 cpp = &cp->nclist.next;
9808 checkkwd = CHKNL | CHKKWD;
9812 raise_error_unexpected_syntax(TENDCASE);
9819 n1 = stalloc(sizeof(struct nredir));
9820 n1->type = NSUBSHELL;
9821 n1->nredir.n = list(0);
9822 n1->nredir.redirect = NULL;
9835 if (readtoken() != t)
9836 raise_error_unexpected_syntax(t);
9839 /* Now check for redirection which may follow command */
9840 checkkwd = CHKKWD | CHKALIAS;
9842 while (readtoken() == TREDIR) {
9843 *rpp = n2 = redirnode;
9844 rpp = &n2->nfile.next;
9850 if (n1->type != NSUBSHELL) {
9851 n2 = stalloc(sizeof(struct nredir));
9856 n1->nredir.redirect = redir;
9862 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9863 * is not NULL, read a here document. In the latter case, eofmark is the
9864 * word which marks the end of the document and striptabs is true if
9865 * leading tabs should be stripped from the document. The argument firstc
9866 * is the first character of the input token or document.
9868 * Because C does not have internal subroutines, I have simulated them
9869 * using goto's to implement the subroutine linkage. The following macros
9870 * will run code that appears at the end of readtoken1.
9873 #define CHECKEND() {goto checkend; checkend_return:;}
9874 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9875 #define PARSESUB() {goto parsesub; parsesub_return:;}
9876 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9877 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9878 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9881 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9886 char line[EOFMARKLEN + 1];
9887 struct nodelist *bqlist = 0;
9890 int varnest = 0; /* levels of variables expansion */
9891 int arinest = 0; /* levels of arithmetic expansion */
9892 int parenlevel = 0; /* levels of parens in arithmetic */
9893 int dqvarnest = 0; /* levels of variables expansion within double quotes */
9895 int prevsyntax = 0; /* syntax before arithmetic */
9897 /* Avoid longjmp clobbering */
9910 startlinno = plinno;
9912 if (syntax == DQSYNTAX)
9922 loop: { /* for each line, until end of word */
9923 CHECKEND(); /* set c to PEOF if at end of here document */
9924 for (;;) { /* until end of line or end of word */
9925 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
9926 switch (SIT(c, syntax)) {
9927 case CNL: /* '\n' */
9928 if (syntax == BASESYNTAX)
9929 goto endword; /* exit outer loop */
9935 goto loop; /* continue outer loop */
9940 if (eofmark == NULL || dblquote)
9941 USTPUTC(CTLESC, out);
9944 case CBACK: /* backslash */
9947 USTPUTC(CTLESC, out);
9950 } else if (c == '\n') {
9955 c != '\\' && c != '`' &&
9960 USTPUTC(CTLESC, out);
9963 if (SIT(c, SQSYNTAX) == CCTL)
9964 USTPUTC(CTLESC, out);
9972 if (eofmark == NULL) {
9973 USTPUTC(CTLQUOTEMARK, out);
9981 if (eofmark != NULL && arinest == 0
9986 if (dqvarnest == 0) {
9987 syntax = BASESYNTAX;
9994 case CVAR: /* '$' */
9995 PARSESUB(); /* parse substitution */
9997 case CENDVAR: /* '}' */
10000 if (dqvarnest > 0) {
10003 USTPUTC(CTLENDVAR, out);
10008 #if ENABLE_ASH_MATH_SUPPORT
10009 case CLP: /* '(' in arithmetic */
10013 case CRP: /* ')' in arithmetic */
10014 if (parenlevel > 0) {
10018 if (pgetc() == ')') {
10019 if (--arinest == 0) {
10020 USTPUTC(CTLENDARI, out);
10021 syntax = prevsyntax;
10022 if (syntax == DQSYNTAX)
10030 * unbalanced parens
10031 * (don't 2nd guess - no error)
10039 case CBQUOTE: /* '`' */
10043 goto endword; /* exit outer loop */
10048 goto endword; /* exit outer loop */
10049 #if ENABLE_ASH_ALIAS
10059 #if ENABLE_ASH_MATH_SUPPORT
10060 if (syntax == ARISYNTAX)
10061 raise_error_syntax("Missing '))'");
10063 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10064 raise_error_syntax("Unterminated quoted string");
10065 if (varnest != 0) {
10066 startlinno = plinno;
10068 raise_error_syntax("Missing '}'");
10070 USTPUTC('\0', out);
10071 len = out - (char *)stackblock();
10072 out = stackblock();
10073 if (eofmark == NULL) {
10074 if ((c == '>' || c == '<')
10077 && (*out == '\0' || isdigit(*out))) {
10079 return lasttoken = TREDIR;
10084 quoteflag = quotef;
10085 backquotelist = bqlist;
10086 grabstackblock(len);
10090 /* end of readtoken routine */
10094 * Check to see whether we are at the end of the here document. When this
10095 * is called, c is set to the first character of the next input line. If
10096 * we are at the end of the here document, this routine sets the c to PEOF.
10100 #if ENABLE_ASH_ALIAS
10106 while (c == '\t') {
10110 if (c == *eofmark) {
10111 if (pfgets(line, sizeof(line)) != NULL) {
10115 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10116 if (*p == '\n' && *q == '\0') {
10119 needprompt = doprompt;
10121 pushstring(line, NULL);
10126 goto checkend_return;
10131 * Parse a redirection operator. The variable "out" points to a string
10132 * specifying the fd to be redirected. The variable "c" contains the
10133 * first character of the redirection operator.
10139 np = stalloc(sizeof(struct nfile));
10144 np->type = NAPPEND;
10146 np->type = NCLOBBER;
10153 } else { /* c == '<' */
10158 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10159 np = stalloc(sizeof(struct nhere));
10163 heredoc = stalloc(sizeof(struct heredoc));
10164 heredoc->here = np;
10167 heredoc->striptabs = 1;
10169 heredoc->striptabs = 0;
10175 np->type = NFROMFD;
10179 np->type = NFROMTO;
10189 np->nfile.fd = digit_val(fd);
10191 goto parseredir_return;
10196 * Parse a substitution. At this point, we have read the dollar sign
10197 * and nothing else.
10204 static const char types[] = "}-+?=";
10208 c <= PEOA_OR_PEOF ||
10209 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10213 } else if (c == '(') { /* $(command) or $((arith)) */
10214 if (pgetc() == '(') {
10215 #if ENABLE_ASH_MATH_SUPPORT
10218 raise_error_syntax("We unsupport $((arith))");
10225 USTPUTC(CTLVAR, out);
10226 typeloc = out - (char *)stackblock();
10227 USTPUTC(VSNORMAL, out);
10228 subtype = VSNORMAL;
10236 subtype = VSLENGTH;
10240 if (c > PEOA_OR_PEOF && is_name(c)) {
10244 } while (c > PEOA_OR_PEOF && is_in_name(c));
10245 } else if (isdigit(c)) {
10249 } while (isdigit(c));
10250 } else if (is_special(c)) {
10254 badsub: raise_error_syntax("Bad substitution");
10258 if (subtype == 0) {
10265 p = strchr(types, c);
10268 subtype = p - types + VSNORMAL;
10274 subtype = c == '#' ? VSTRIMLEFT :
10287 if (dblquote || arinest)
10289 *((char *)stackblock() + typeloc) = subtype | flags;
10290 if (subtype != VSNORMAL) {
10292 if (dblquote || arinest) {
10297 goto parsesub_return;
10302 * Called to parse command substitutions. Newstyle is set if the command
10303 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10304 * list of commands (passed by reference), and savelen is the number of
10305 * characters on the top of the stack which must be preserved.
10308 struct nodelist **nlpp;
10311 char *volatile str;
10312 struct jmploc jmploc;
10313 struct jmploc *volatile savehandler;
10315 int saveprompt = 0;
10317 (void) &saveprompt;
10320 savepbq = parsebackquote;
10321 if (setjmp(jmploc.loc)) {
10324 parsebackquote = 0;
10325 exception_handler = savehandler;
10326 longjmp(exception_handler->loc, 1);
10330 savelen = out - (char *)stackblock();
10332 str = ckmalloc(savelen);
10333 memcpy(str, stackblock(), savelen);
10335 savehandler = exception_handler;
10336 exception_handler = &jmploc;
10339 /* We must read until the closing backquote, giving special
10340 treatment to some slashes, and then push the string and
10341 reread it as input, interpreting it normally. */
10348 STARTSTACKSTR(pout);
10365 * If eating a newline, avoid putting
10366 * the newline into the new character
10367 * stream (via the STPUTC after the
10372 if (pc != '\\' && pc != '`' && pc != '$'
10373 && (!dblquote || pc != '"'))
10374 STPUTC('\\', pout);
10375 if (pc > PEOA_OR_PEOF) {
10381 #if ENABLE_ASH_ALIAS
10384 startlinno = plinno;
10385 raise_error_syntax("EOF in backquote substitution");
10389 needprompt = doprompt;
10398 STPUTC('\0', pout);
10399 psavelen = pout - (char *)stackblock();
10400 if (psavelen > 0) {
10401 pstr = grabstackstr(pout);
10402 setinputstring(pstr);
10407 nlpp = &(*nlpp)->next;
10408 *nlpp = stalloc(sizeof(**nlpp));
10409 (*nlpp)->next = NULL;
10410 parsebackquote = oldstyle;
10413 saveprompt = doprompt;
10420 doprompt = saveprompt;
10421 else if (readtoken() != TRP)
10422 raise_error_unexpected_syntax(TRP);
10427 * Start reading from old file again, ignoring any pushed back
10428 * tokens left from the backquote parsing
10433 while (stackblocksize() <= savelen)
10435 STARTSTACKSTR(out);
10437 memcpy(out, str, savelen);
10438 STADJUST(savelen, out);
10444 parsebackquote = savepbq;
10445 exception_handler = savehandler;
10446 if (arinest || dblquote)
10447 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10449 USTPUTC(CTLBACKQ, out);
10451 goto parsebackq_oldreturn;
10452 goto parsebackq_newreturn;
10455 #if ENABLE_ASH_MATH_SUPPORT
10457 * Parse an arithmetic expansion (indicate start of one and set state)
10460 if (++arinest == 1) {
10461 prevsyntax = syntax;
10462 syntax = ARISYNTAX;
10463 USTPUTC(CTLARI, out);
10470 * we collapse embedded arithmetic expansion to
10471 * parenthesis, which should be equivalent
10475 goto parsearith_return;
10479 } /* end of readtoken */
10482 * Read the next input token.
10483 * If the token is a word, we set backquotelist to the list of cmds in
10484 * backquotes. We set quoteflag to true if any part of the word was
10486 * If the token is TREDIR, then we set redirnode to a structure containing
10488 * In all cases, the variable startlinno is set to the number of the line
10489 * on which the token starts.
10491 * [Change comment: here documents and internal procedures]
10492 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10493 * word parsing code into a separate routine. In this case, readtoken
10494 * doesn't need to have any internal procedures, but parseword does.
10495 * We could also make parseoperator in essence the main routine, and
10496 * have parseword (readtoken1?) handle both words and redirection.]
10498 #define NEW_xxreadtoken
10499 #ifdef NEW_xxreadtoken
10500 /* singles must be first! */
10501 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
10503 static const char xxreadtoken_tokens[] = {
10504 TNL, TLP, TRP, /* only single occurrence allowed */
10505 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10506 TEOF, /* corresponds to trailing nul */
10507 TAND, TOR, TENDCASE, /* if double occurrence */
10510 #define xxreadtoken_doubles \
10511 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10512 #define xxreadtoken_singles \
10513 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10527 startlinno = plinno;
10528 for (;;) { /* until token or start of word found */
10531 if ((c != ' ') && (c != '\t')
10532 #if ENABLE_ASH_ALIAS
10537 while ((c = pgetc()) != '\n' && c != PEOF);
10539 } else if (c == '\\') {
10540 if (pgetc() != '\n') {
10544 startlinno = ++plinno;
10549 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10554 needprompt = doprompt;
10557 p = strchr(xxreadtoken_chars, c);
10560 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10563 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10564 if (pgetc() == *p) { /* double occurrence? */
10565 p += xxreadtoken_doubles + 1;
10571 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10577 #define RETURN(token) return lasttoken = token
10590 startlinno = plinno;
10591 for (;;) { /* until token or start of word found */
10594 case ' ': case '\t':
10595 #if ENABLE_ASH_ALIAS
10600 while ((c = pgetc()) != '\n' && c != PEOF);
10604 if (pgetc() == '\n') {
10605 startlinno = ++plinno;
10614 needprompt = doprompt;
10619 if (pgetc() == '&')
10624 if (pgetc() == '|')
10629 if (pgetc() == ';')
10642 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10645 #endif /* NEW_xxreadtoken */
10652 int alreadyseen = tokpushback;
10655 #if ENABLE_ASH_ALIAS
10664 if (checkkwd & CHKNL) {
10671 if (t != TWORD || quoteflag) {
10676 * check for keywords
10678 if (checkkwd & CHKKWD) {
10679 const char *const *pp;
10681 pp = findkwd(wordtext);
10683 lasttoken = t = pp - tokname_array;
10684 TRACE(("keyword %s recognized\n", tokname(t)));
10689 if (checkkwd & CHKALIAS) {
10690 #if ENABLE_ASH_ALIAS
10692 ap = lookupalias(wordtext, 1);
10695 pushstring(ap->val, ap);
10705 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10707 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10719 return tokname_array[t][0];
10723 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10724 * valid parse tree indicating a blank line.)
10726 static union node *
10727 parsecmd(int interact)
10732 doprompt = interact;
10734 setprompt(doprompt);
10746 * Input any here documents.
10751 struct heredoc *here;
10754 here = heredoclist;
10761 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10762 here->eofmark, here->striptabs);
10763 n = stalloc(sizeof(struct narg));
10764 n->narg.type = NARG;
10765 n->narg.next = NULL;
10766 n->narg.text = wordtext;
10767 n->narg.backquote = backquotelist;
10768 here->here->nhere.doc = n;
10775 * called by editline -- any expansions to the prompt
10776 * should be added here.
10778 #if ENABLE_ASH_EXPAND_PRMT
10779 static const char *
10780 expandstr(const char *ps)
10784 /* XXX Fix (char *) cast. */
10785 setinputstring((char *)ps);
10786 readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
10789 n.narg.type = NARG;
10790 n.narg.next = NULL;
10791 n.narg.text = wordtext;
10792 n.narg.backquote = backquotelist;
10794 expandarg(&n, NULL, 0);
10795 return stackblock();
10801 * Execute a command or commands contained in a string.
10804 evalstring(char *s, int mask)
10807 struct stackmark smark;
10811 setstackmark(&smark);
10814 while ((n = parsecmd(0)) != NEOF) {
10816 popstackmark(&smark);
10829 * The eval command.
10832 evalcmd(int argc, char **argv)
10841 STARTSTACKSTR(concat);
10844 concat = stack_putstr(p, concat);
10848 STPUTC(' ', concat);
10850 STPUTC('\0', concat);
10851 p = grabstackstr(concat);
10853 evalstring(p, ~SKIPEVAL);
10860 * Read and execute commands. "Top" is nonzero for the top level command
10861 * loop; it turns on prompting if the shell is interactive.
10867 struct stackmark smark;
10871 TRACE(("cmdloop(%d) called\n", top));
10875 setstackmark(&smark);
10878 showjobs(stderr, SHOW_CHANGED);
10881 if (iflag && top) {
10883 #if ENABLE_ASH_MAIL
10887 n = parsecmd(inter);
10888 /* showtree(n); DEBUG */
10890 if (!top || numeof >= 50)
10892 if (!stoppedjobs()) {
10895 out2str("\nUse \"exit\" to leave shell.\n");
10898 } else if (nflag == 0) {
10899 job_warning = (job_warning == 2) ? 1 : 0;
10903 popstackmark(&smark);
10908 return skip & SKIPEVAL;
10915 dotcmd(int argc, char **argv)
10917 struct strlist *sp;
10918 volatile struct shparam saveparam;
10921 for (sp = cmdenviron; sp; sp = sp->next)
10922 setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
10924 if (argc >= 2) { /* That's what SVR2 does */
10927 fullname = find_dot_file(argv[1]);
10930 saveparam = shellparam;
10931 shellparam.malloc = 0;
10932 shellparam.nparam = argc - 2;
10933 shellparam.p = argv + 2;
10936 setinputfile(fullname, INPUT_PUSH_FILE);
10937 commandname = fullname;
10942 freeparam(&shellparam);
10943 shellparam = saveparam;
10945 status = exitstatus;
10951 exitcmd(int argc, char **argv)
10956 exitstatus = number(argv[1]);
10957 raise_exception(EXEXIT);
10961 #if ENABLE_ASH_BUILTIN_ECHO
10963 echocmd(int argc, char **argv)
10965 return bb_echo(argv);
10969 #if ENABLE_ASH_BUILTIN_TEST
10971 testcmd(int argc, char **argv)
10973 return bb_test(argc, argv);
10978 * Read a file containing shell functions.
10981 readcmdfile(char *name)
10983 setinputfile(name, INPUT_PUSH_FILE);
10992 * Code for dealing with input/output redirection.
10995 #define EMPTY -2 /* marks an unused slot in redirtab */
10997 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10999 # define PIPESIZE PIPE_BUF
11003 * Open a file in noclobber mode.
11004 * The code was copied from bash.
11007 noclobberopen(const char *fname)
11010 struct stat finfo, finfo2;
11013 * If the file exists and is a regular file, return an error
11016 r = stat(fname, &finfo);
11017 if (r == 0 && S_ISREG(finfo.st_mode)) {
11023 * If the file was not present (r != 0), make sure we open it
11024 * exclusively so that if it is created before we open it, our open
11025 * will fail. Make sure that we do not truncate an existing file.
11026 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11027 * file was not a regular file, we leave O_EXCL off.
11030 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11031 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11033 /* If the open failed, return the file descriptor right away. */
11038 * OK, the open succeeded, but the file may have been changed from a
11039 * non-regular file to a regular file between the stat and the open.
11040 * We are assuming that the O_EXCL open handles the case where FILENAME
11041 * did not exist and is symlinked to an existing file between the stat
11046 * If we can open it and fstat the file descriptor, and neither check
11047 * revealed that it was a regular file, and the file has not been
11048 * replaced, return the file descriptor.
11050 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
11051 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11054 /* The file has been replaced. badness. */
11062 * Handle here documents. Normally we fork off a process to write the
11063 * data to a pipe. If the document is short, we can stuff the data in
11064 * the pipe without forking.
11067 openhere(union node *redir)
11073 ash_msg_and_raise_error("Pipe call failed");
11074 if (redir->type == NHERE) {
11075 len = strlen(redir->nhere.doc->narg.text);
11076 if (len <= PIPESIZE) {
11077 full_write(pip[1], redir->nhere.doc->narg.text, len);
11081 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11083 signal(SIGINT, SIG_IGN);
11084 signal(SIGQUIT, SIG_IGN);
11085 signal(SIGHUP, SIG_IGN);
11087 signal(SIGTSTP, SIG_IGN);
11089 signal(SIGPIPE, SIG_DFL);
11090 if (redir->type == NHERE)
11091 full_write(pip[1], redir->nhere.doc->narg.text, len);
11093 expandhere(redir->nhere.doc, pip[1]);
11102 openredirect(union node *redir)
11107 switch (redir->nfile.type) {
11109 fname = redir->nfile.expfname;
11110 f = open(fname, O_RDONLY);
11115 fname = redir->nfile.expfname;
11116 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
11121 /* Take care of noclobber mode. */
11123 fname = redir->nfile.expfname;
11124 f = noclobberopen(fname);
11131 fname = redir->nfile.expfname;
11132 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
11137 fname = redir->nfile.expfname;
11138 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
11146 /* Fall through to eliminate warning. */
11153 f = openhere(redir);
11159 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "Directory nonexistent"));
11161 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "No such file"));
11165 dupredirect(union node *redir, int f)
11167 int fd = redir->nfile.fd;
11169 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11170 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11171 copyfd(redir->ndup.dupfd, fd);
11184 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11185 * old file descriptors are stashed away so that the redirection can be
11186 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11187 * standard output, and the standard error if it becomes a duplicate of
11188 * stdout, is saved in memory.
11191 redirect(union node *redir, int flags)
11194 struct redirtab *sv;
11205 if (flags & REDIR_PUSH) {
11206 struct redirtab *q;
11207 q = ckmalloc(sizeof(struct redirtab));
11208 q->next = redirlist;
11210 q->nullredirs = nullredirs - 1;
11211 for (i = 0; i < 10; i++)
11212 q->renamed[i] = EMPTY;
11219 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
11220 && n->ndup.dupfd == fd)
11221 continue; /* redirect from/to same file descriptor */
11223 newfd = openredirect(n);
11226 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
11227 i = fcntl(fd, F_DUPFD, 10);
11234 ash_msg_and_raise_error("%d: %m", fd);
11244 dupredirect(n, newfd);
11245 } while ((n = n->nfile.next));
11247 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
11248 preverrout_fd = sv->renamed[2];
11253 * Undo the effects of the last redirection.
11258 struct redirtab *rp;
11261 if (--nullredirs >= 0)
11265 for (i = 0; i < 10; i++) {
11266 if (rp->renamed[i] != EMPTY) {
11269 copyfd(rp->renamed[i], i);
11271 close(rp->renamed[i]);
11274 redirlist = rp->next;
11275 nullredirs = rp->nullredirs;
11281 * Undo all redirections. Called on error or interrupt.
11285 * Discard all saved file descriptors.
11288 clearredir(int drop)
11300 * Copy a file descriptor to be >= to. Returns -1
11301 * if the source file descriptor is closed, EMPTY if there are no unused
11302 * file descriptors left.
11305 copyfd(int from, int to)
11309 newfd = fcntl(from, F_DUPFD, to);
11311 if (errno == EMFILE)
11313 ash_msg_and_raise_error("%d: %m", from);
11319 redirectsafe(union node *redir, int flags)
11322 volatile int saveint;
11323 struct jmploc *volatile savehandler = exception_handler;
11324 struct jmploc jmploc;
11327 err = setjmp(jmploc.loc) * 2;
11329 exception_handler = &jmploc;
11330 redirect(redir, flags);
11332 exception_handler = savehandler;
11333 if (err && exception != EXERROR)
11334 longjmp(exception_handler->loc, 1);
11335 RESTORE_INT(saveint);
11343 * The trap builtin.
11346 trapcmd(int argc, char **argv)
11355 for (signo = 0; signo < NSIG; signo++) {
11356 if (trap[signo] != NULL) {
11359 sn = get_signame(signo);
11360 out1fmt("trap -- %s %s\n",
11361 single_quote(trap[signo]), sn);
11371 signo = get_signum(*ap);
11373 ash_msg_and_raise_error("%s: bad trap", *ap);
11376 if (LONE_DASH(action))
11379 action = ckstrdup(action);
11383 trap[signo] = action;
11394 * Clear traps on a fork.
11401 for (tp = trap; tp < &trap[NSIG]; tp++) {
11402 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
11406 if (tp != &trap[0])
11407 setsignal(tp - trap);
11415 * Set the signal handler for the specified signal. The routine figures
11416 * out what it should be set to.
11419 setsignal(int signo)
11423 struct sigaction act;
11428 else if (*t != '\0')
11432 if (rootshell && action == S_DFL) {
11435 if (iflag || minusc || sflag == 0)
11458 t = &sigmode[signo - 1];
11462 * current setting unknown
11464 if (sigaction(signo, 0, &act) == -1) {
11466 * Pretend it worked; maybe we should give a warning
11467 * here, but other shells don't. We don't alter
11468 * sigmode, so that we retry every time.
11472 if (act.sa_handler == SIG_IGN) {
11474 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
11476 tsig = S_IGN; /* don't hard ignore these */
11480 tsig = S_RESET; /* force to be set */
11483 if (tsig == S_HARD_IGN || tsig == action)
11487 act.sa_handler = onsig;
11490 act.sa_handler = SIG_IGN;
11493 act.sa_handler = SIG_DFL;
11497 sigfillset(&act.sa_mask);
11498 sigaction(signo, &act, 0);
11503 * Called to execute a trap. Perhaps we should avoid entering new trap
11504 * handlers while we are executing a trap handler.
11515 savestatus = exitstatus;
11519 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
11527 skip = evalstring(p, SKIPEVAL);
11528 exitstatus = savestatus;
11537 * Controls whether the shell is interactive or not.
11540 setinteractive(int on)
11542 static int is_interactive;
11544 if (++on == is_interactive)
11546 is_interactive = on;
11548 setsignal(SIGQUIT);
11549 setsignal(SIGTERM);
11550 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11551 if (is_interactive > 1) {
11552 /* Looks like they want an interactive shell */
11553 static smallint do_banner;
11558 "%s Built-in shell (ash)\n"
11559 "Enter 'help' for a list of built-in commands."
11568 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11570 * Lists available builtins
11573 helpcmd(int argc, char **argv)
11577 out1fmt("\nBuilt-in commands:\n-------------------\n");
11578 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11579 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11580 builtincmd[i].name + 1);
11586 #if ENABLE_FEATURE_SH_STANDALONE_SHELL
11587 for (i = 0; i < NUM_APPLETS; i++) {
11588 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11596 return EXIT_SUCCESS;
11598 #endif /* FEATURE_SH_EXTRA_QUIET */
11601 * Called to exit the shell.
11610 status = exitstatus;
11611 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
11612 if (setjmp(loc.loc)) {
11613 if (exception == EXEXIT)
11614 /* dash bug: it just does _exit(exitstatus) here
11615 * but we have to do setjobctl(0) first!
11616 * (bug is still not fixed in dash-0.5.3 - if you run dash
11617 * under Midnight Commander, on exit from dash MC is backgrounded) */
11618 status = exitstatus;
11621 exception_handler = &loc;
11627 flush_stdout_stderr();
11636 * The export and readonly commands.
11639 exportcmd(int argc, char **argv)
11645 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11647 if (nextopt("p") != 'p') {
11652 p = strchr(name, '=');
11656 vp = *findvar(hashvar(name), name);
11662 setvar(name, p, flag);
11663 } while ((name = *++aptr) != NULL);
11667 showvars(argv[0], flag, 0);
11673 * Make a variable a local variable. When a variable is made local, it's
11674 * value and flags are saved in a localvar structure. The saved values
11675 * will be restored when the shell function returns. We handle the name
11676 * "-" as a special case.
11679 mklocal(char *name)
11681 struct localvar *lvp;
11686 lvp = ckmalloc(sizeof(struct localvar));
11687 if (LONE_DASH(name)) {
11689 p = ckmalloc(sizeof(optlist));
11690 lvp->text = memcpy(p, optlist, sizeof(optlist));
11695 vpp = hashvar(name);
11696 vp = *findvar(vpp, name);
11697 eq = strchr(name, '=');
11700 setvareq(name, VSTRFIXED);
11702 setvar(name, NULL, VSTRFIXED);
11703 vp = *vpp; /* the new variable */
11704 lvp->flags = VUNSET;
11706 lvp->text = vp->text;
11707 lvp->flags = vp->flags;
11708 vp->flags |= VSTRFIXED|VTEXTFIXED;
11714 lvp->next = localvars;
11721 * The "local" command.
11724 localcmd(int argc, char **argv)
11729 while ((name = *argv++) != NULL) {
11737 * The unset builtin command. We unset the function before we unset the
11738 * variable to allow a function to be unset when there is a readonly variable
11739 * with the same name.
11742 unsetcmd(int argc, char **argv)
11749 while ((i = nextopt("vf")) != '\0') {
11753 for (ap = argptr; *ap; ap++) {
11769 #include <sys/times.h>
11771 static const unsigned char timescmd_str[] = {
11772 ' ', offsetof(struct tms, tms_utime),
11773 '\n', offsetof(struct tms, tms_stime),
11774 ' ', offsetof(struct tms, tms_cutime),
11775 '\n', offsetof(struct tms, tms_cstime),
11780 timescmd(int ac, char **av)
11782 long clk_tck, s, t;
11783 const unsigned char *p;
11786 clk_tck = sysconf(_SC_CLK_TCK);
11791 t = *(clock_t *)(((char *) &buf) + p[1]);
11793 out1fmt("%ldm%ld.%.3lds%c",
11795 ((t - s * clk_tck) * 1000) / clk_tck,
11797 } while (*(p += 2));
11802 #if ENABLE_ASH_MATH_SUPPORT
11804 dash_arith(const char *s)
11810 result = arith(s, &errcode);
11813 ash_msg_and_raise_error("exponent less than 0");
11815 ash_msg_and_raise_error("divide by zero");
11817 ash_msg_and_raise_error("expression recursion loop detected");
11818 raise_error_syntax(s);
11827 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11828 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11830 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11833 letcmd(int argc, char **argv)
11840 ash_msg_and_raise_error("expression expected");
11841 for (ap = argv + 1; *ap; ap++) {
11842 i = dash_arith(*ap);
11847 #endif /* ASH_MATH_SUPPORT */
11852 * Miscellaneous builtins.
11857 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11858 typedef enum __rlimit_resource rlim_t;
11863 * The read builtin. The -e option causes backslashes to escape the
11864 * following character.
11866 * This uses unbuffered input, which may be avoidable in some cases.
11869 readcmd(int argc, char **argv)
11881 #if ENABLE_ASH_READ_NCHARS
11885 struct termios tty, old_tty;
11887 #if ENABLE_ASH_READ_TIMEOUT
11891 ts.tv_sec = ts.tv_usec = 0;
11896 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11897 while ((i = nextopt("p:rt:n:s")) != '\0')
11898 #elif ENABLE_ASH_READ_NCHARS
11899 while ((i = nextopt("p:rn:s")) != '\0')
11900 #elif ENABLE_ASH_READ_TIMEOUT
11901 while ((i = nextopt("p:rt:")) != '\0')
11903 while ((i = nextopt("p:r")) != '\0')
11908 prompt = optionarg;
11910 #if ENABLE_ASH_READ_NCHARS
11912 nchars = strtol(optionarg, &p, 10);
11914 ash_msg_and_raise_error("invalid count");
11915 nch_flag = (nchars > 0);
11921 #if ENABLE_ASH_READ_TIMEOUT
11923 ts.tv_sec = strtol(optionarg, &p, 10);
11929 ts.tv_usec = strtol(p, &p2, 10);
11931 ash_msg_and_raise_error("invalid timeout");
11933 /* normalize to usec */
11935 ash_msg_and_raise_error("invalid timeout");
11936 while (scale++ < 6)
11940 ash_msg_and_raise_error("invalid timeout");
11942 if ( ! ts.tv_sec && ! ts.tv_usec)
11943 ash_msg_and_raise_error("invalid timeout");
11953 if (prompt && isatty(0)) {
11958 ash_msg_and_raise_error("arg count");
11959 ifs = bltinlookup("IFS");
11962 #if ENABLE_ASH_READ_NCHARS
11963 if (nch_flag || silent) {
11964 tcgetattr(0, &tty);
11967 tty.c_lflag &= ~ICANON;
11968 tty.c_cc[VMIN] = nchars;
11971 tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
11974 tcsetattr(0, TCSANOW, &tty);
11977 #if ENABLE_ASH_READ_TIMEOUT
11978 if (ts.tv_sec || ts.tv_usec) {
11982 i = select(FD_SETSIZE, &set, NULL, NULL, &ts);
11984 #if ENABLE_ASH_READ_NCHARS
11986 tcsetattr(0, TCSANOW, &old_tty);
11996 #if ENABLE_ASH_READ_NCHARS
11997 while (!nch_flag || nchars--)
12002 if (read(0, &c, 1) != 1) {
12014 if (!rflag && c == '\\') {
12020 if (startword && *ifs == ' ' && strchr(ifs, c)) {
12024 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
12026 setvar(*ap, stackblock(), 0);
12035 #if ENABLE_ASH_READ_NCHARS
12036 if (nch_flag || silent)
12037 tcsetattr(0, TCSANOW, &old_tty);
12041 /* Remove trailing blanks */
12042 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
12044 setvar(*ap, stackblock(), 0);
12045 while (*++ap != NULL)
12046 setvar(*ap, nullstr, 0);
12052 umaskcmd(int argc, char **argv)
12054 static const char permuser[3] = "ugo";
12055 static const char permmode[3] = "rwx";
12056 static const short int permmask[] = {
12057 S_IRUSR, S_IWUSR, S_IXUSR,
12058 S_IRGRP, S_IWGRP, S_IXGRP,
12059 S_IROTH, S_IWOTH, S_IXOTH
12065 int symbolic_mode = 0;
12067 while (nextopt("S") != '\0') {
12078 if (symbolic_mode) {
12082 for (i = 0; i < 3; i++) {
12085 *p++ = permuser[i];
12087 for (j = 0; j < 3; j++) {
12088 if ((mask & permmask[3 * i + j]) == 0) {
12089 *p++ = permmode[j];
12097 out1fmt("%.4o\n", mask);
12100 if (isdigit((unsigned char) *ap)) {
12103 if (*ap >= '8' || *ap < '0')
12104 ash_msg_and_raise_error(illnum, argv[1]);
12105 mask = (mask << 3) + (*ap - '0');
12106 } while (*++ap != '\0');
12109 mask = ~mask & 0777;
12110 if (!bb_parse_mode(ap, &mask)) {
12111 ash_msg_and_raise_error("Illegal mode: %s", ap);
12113 umask(~mask & 0777);
12122 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12123 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12124 * ash by J.T. Conklin.
12132 int factor; /* multiply by to get rlim_{cur,max} values */
12136 static const struct limits limits[] = {
12138 { "time(seconds)", RLIMIT_CPU, 1, 't' },
12140 #ifdef RLIMIT_FSIZE
12141 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
12144 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
12146 #ifdef RLIMIT_STACK
12147 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
12150 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
12153 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
12155 #ifdef RLIMIT_MEMLOCK
12156 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
12158 #ifdef RLIMIT_NPROC
12159 { "process", RLIMIT_NPROC, 1, 'p' },
12161 #ifdef RLIMIT_NOFILE
12162 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
12165 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
12167 #ifdef RLIMIT_LOCKS
12168 { "locks", RLIMIT_LOCKS, 1, 'w' },
12170 { NULL, 0, 0, '\0' }
12173 enum limtype { SOFT = 0x1, HARD = 0x2 };
12176 printlim(enum limtype how, const struct rlimit *limit,
12177 const struct limits *l)
12181 val = limit->rlim_max;
12183 val = limit->rlim_cur;
12185 if (val == RLIM_INFINITY)
12186 out1fmt("unlimited\n");
12189 out1fmt("%lld\n", (long long) val);
12194 ulimitcmd(int argc, char **argv)
12198 enum limtype how = SOFT | HARD;
12199 const struct limits *l;
12202 struct rlimit limit;
12205 while ((optc = nextopt("HSa"
12209 #ifdef RLIMIT_FSIZE
12215 #ifdef RLIMIT_STACK
12224 #ifdef RLIMIT_MEMLOCK
12227 #ifdef RLIMIT_NPROC
12230 #ifdef RLIMIT_NOFILE
12236 #ifdef RLIMIT_LOCKS
12254 for (l = limits; l->option != what; l++)
12257 set = *argptr ? 1 : 0;
12261 if (all || argptr[1])
12262 ash_msg_and_raise_error("too many arguments");
12263 if (strncmp(p, "unlimited\n", 9) == 0)
12264 val = RLIM_INFINITY;
12268 while ((c = *p++) >= '0' && c <= '9') {
12269 val = (val * 10) + (long)(c - '0');
12270 if (val < (rlim_t) 0)
12274 ash_msg_and_raise_error("bad number");
12279 for (l = limits; l->name; l++) {
12280 getrlimit(l->cmd, &limit);
12281 out1fmt("%-20s ", l->name);
12282 printlim(how, &limit, l);
12287 getrlimit(l->cmd, &limit);
12290 limit.rlim_max = val;
12292 limit.rlim_cur = val;
12293 if (setrlimit(l->cmd, &limit) < 0)
12294 ash_msg_and_raise_error("error setting limit (%m)");
12296 printlim(how, &limit, l);
12302 #if ENABLE_ASH_MATH_SUPPORT
12304 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12306 Permission is hereby granted, free of charge, to any person obtaining
12307 a copy of this software and associated documentation files (the
12308 "Software"), to deal in the Software without restriction, including
12309 without limitation the rights to use, copy, modify, merge, publish,
12310 distribute, sublicense, and/or sell copies of the Software, and to
12311 permit persons to whom the Software is furnished to do so, subject to
12312 the following conditions:
12314 The above copyright notice and this permission notice shall be
12315 included in all copies or substantial portions of the Software.
12317 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12318 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12319 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12320 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12321 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12322 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12323 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12326 /* This is my infix parser/evaluator. It is optimized for size, intended
12327 * as a replacement for yacc-based parsers. However, it may well be faster
12328 * than a comparable parser written in yacc. The supported operators are
12329 * listed in #defines below. Parens, order of operations, and error handling
12330 * are supported. This code is thread safe. The exact expression format should
12331 * be that which POSIX specifies for shells. */
12333 /* The code uses a simple two-stack algorithm. See
12334 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12335 * for a detailed explanation of the infix-to-postfix algorithm on which
12336 * this is based (this code differs in that it applies operators immediately
12337 * to the stack instead of adding them to a queue to end up with an
12340 /* To use the routine, call it with an expression string and error return
12344 * Aug 24, 2001 Manuel Novoa III
12346 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12348 * 1) In arith_apply():
12349 * a) Cached values of *numptr and &(numptr[-1]).
12350 * b) Removed redundant test for zero denominator.
12353 * a) Eliminated redundant code for processing operator tokens by moving
12354 * to a table-based implementation. Also folded handling of parens
12356 * b) Combined all 3 loops which called arith_apply to reduce generated
12357 * code size at the cost of speed.
12359 * 3) The following expressions were treated as valid by the original code:
12360 * 1() , 0! , 1 ( *3 ) .
12361 * These bugs have been fixed by internally enclosing the expression in
12362 * parens and then checking that all binary ops and right parens are
12363 * preceded by a valid expression (NUM_TOKEN).
12365 * Note: It may be desirable to replace Aaron's test for whitespace with
12366 * ctype's isspace() if it is used by another busybox applet or if additional
12367 * whitespace chars should be considered. Look below the "#include"s for a
12368 * precompiler test.
12372 * Aug 26, 2001 Manuel Novoa III
12374 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12376 * Merge in Aaron's comments previously posted to the busybox list,
12377 * modified slightly to take account of my changes to the code.
12382 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12384 * - allow access to variable,
12385 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12386 * - realize assign syntax (VAR=expr, +=, *= etc)
12387 * - realize exponentiation (** operator)
12388 * - realize comma separated - expr, expr
12389 * - realise ++expr --expr expr++ expr--
12390 * - realise expr ? expr : expr (but, second expr calculate always)
12391 * - allow hexadecimal and octal numbers
12392 * - was restored loses XOR operator
12393 * - remove one goto label, added three ;-)
12394 * - protect $((num num)) as true zero expr (Manuel`s error)
12395 * - always use special isspace(), see comment from bash ;-)
12398 #define arith_isspace(arithval) \
12399 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12401 typedef unsigned char operator;
12403 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12404 * precedence, and 3 high bits are an ID unique across operators of that
12405 * precedence. The ID portion is so that multiple operators can have the
12406 * same precedence, ensuring that the leftmost one is evaluated first.
12407 * Consider * and /. */
12409 #define tok_decl(prec,id) (((id)<<5)|(prec))
12410 #define PREC(op) ((op) & 0x1F)
12412 #define TOK_LPAREN tok_decl(0,0)
12414 #define TOK_COMMA tok_decl(1,0)
12416 #define TOK_ASSIGN tok_decl(2,0)
12417 #define TOK_AND_ASSIGN tok_decl(2,1)
12418 #define TOK_OR_ASSIGN tok_decl(2,2)
12419 #define TOK_XOR_ASSIGN tok_decl(2,3)
12420 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12421 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12422 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12423 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12425 #define TOK_MUL_ASSIGN tok_decl(3,0)
12426 #define TOK_DIV_ASSIGN tok_decl(3,1)
12427 #define TOK_REM_ASSIGN tok_decl(3,2)
12429 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12430 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12432 /* conditional is right associativity too */
12433 #define TOK_CONDITIONAL tok_decl(4,0)
12434 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12436 #define TOK_OR tok_decl(5,0)
12438 #define TOK_AND tok_decl(6,0)
12440 #define TOK_BOR tok_decl(7,0)
12442 #define TOK_BXOR tok_decl(8,0)
12444 #define TOK_BAND tok_decl(9,0)
12446 #define TOK_EQ tok_decl(10,0)
12447 #define TOK_NE tok_decl(10,1)
12449 #define TOK_LT tok_decl(11,0)
12450 #define TOK_GT tok_decl(11,1)
12451 #define TOK_GE tok_decl(11,2)
12452 #define TOK_LE tok_decl(11,3)
12454 #define TOK_LSHIFT tok_decl(12,0)
12455 #define TOK_RSHIFT tok_decl(12,1)
12457 #define TOK_ADD tok_decl(13,0)
12458 #define TOK_SUB tok_decl(13,1)
12460 #define TOK_MUL tok_decl(14,0)
12461 #define TOK_DIV tok_decl(14,1)
12462 #define TOK_REM tok_decl(14,2)
12464 /* exponent is right associativity */
12465 #define TOK_EXPONENT tok_decl(15,1)
12467 /* For now unary operators. */
12468 #define UNARYPREC 16
12469 #define TOK_BNOT tok_decl(UNARYPREC,0)
12470 #define TOK_NOT tok_decl(UNARYPREC,1)
12472 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12473 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12475 #define PREC_PRE (UNARYPREC+2)
12477 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12478 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12480 #define PREC_POST (UNARYPREC+3)
12482 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12483 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12485 #define SPEC_PREC (UNARYPREC+4)
12487 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12488 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12490 #define NUMPTR (*numstackptr)
12493 tok_have_assign(operator op)
12495 operator prec = PREC(op);
12497 convert_prec_is_assing(prec);
12498 return (prec == PREC(TOK_ASSIGN) ||
12499 prec == PREC_PRE || prec == PREC_POST);
12503 is_right_associativity(operator prec)
12505 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12506 || prec == PREC(TOK_CONDITIONAL));
12509 typedef struct ARITCH_VAR_NUM {
12511 arith_t contidional_second_val;
12512 char contidional_second_val_initialized;
12513 char *var; /* if NULL then is regular number,
12514 else is variable name */
12517 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12519 struct CHK_VAR_RECURSIVE_LOOPED *next;
12520 } chk_var_recursive_looped_t;
12522 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12525 arith_lookup_val(v_n_t *t)
12528 const char * p = lookupvar(t->var);
12533 /* recursive try as expression */
12534 chk_var_recursive_looped_t *cur;
12535 chk_var_recursive_looped_t cur_save;
12537 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12538 if (strcmp(cur->var, t->var) == 0) {
12539 /* expression recursion loop detected */
12543 /* save current lookuped var name */
12544 cur = prev_chk_var_recursive;
12545 cur_save.var = t->var;
12546 cur_save.next = cur;
12547 prev_chk_var_recursive = &cur_save;
12549 t->val = arith (p, &errcode);
12550 /* restore previous ptr after recursiving */
12551 prev_chk_var_recursive = cur;
12554 /* allow undefined var as 0 */
12560 /* "applying" a token means performing it on the top elements on the integer
12561 * stack. For a unary operator it will only change the top element, but a
12562 * binary operator will pop two arguments and push a result */
12564 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12567 arith_t numptr_val, rez;
12568 int ret_arith_lookup_val;
12570 /* There is no operator that can work without arguments */
12571 if (NUMPTR == numstack) goto err;
12572 numptr_m1 = NUMPTR - 1;
12574 /* check operand is var with noninteger value */
12575 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12576 if (ret_arith_lookup_val)
12577 return ret_arith_lookup_val;
12579 rez = numptr_m1->val;
12580 if (op == TOK_UMINUS)
12582 else if (op == TOK_NOT)
12584 else if (op == TOK_BNOT)
12586 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12588 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12590 else if (op != TOK_UPLUS) {
12591 /* Binary operators */
12593 /* check and binary operators need two arguments */
12594 if (numptr_m1 == numstack) goto err;
12596 /* ... and they pop one */
12599 if (op == TOK_CONDITIONAL) {
12600 if (! numptr_m1->contidional_second_val_initialized) {
12601 /* protect $((expr1 ? expr2)) without ": expr" */
12604 rez = numptr_m1->contidional_second_val;
12605 } else if (numptr_m1->contidional_second_val_initialized) {
12606 /* protect $((expr1 : expr2)) without "expr ? " */
12609 numptr_m1 = NUMPTR - 1;
12610 if (op != TOK_ASSIGN) {
12611 /* check operand is var with noninteger value for not '=' */
12612 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12613 if (ret_arith_lookup_val)
12614 return ret_arith_lookup_val;
12616 if (op == TOK_CONDITIONAL) {
12617 numptr_m1->contidional_second_val = rez;
12619 rez = numptr_m1->val;
12620 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12622 else if (op == TOK_OR)
12623 rez = numptr_val || rez;
12624 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12626 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12628 else if (op == TOK_AND)
12629 rez = rez && numptr_val;
12630 else if (op == TOK_EQ)
12631 rez = (rez == numptr_val);
12632 else if (op == TOK_NE)
12633 rez = (rez != numptr_val);
12634 else if (op == TOK_GE)
12635 rez = (rez >= numptr_val);
12636 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12637 rez >>= numptr_val;
12638 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12639 rez <<= numptr_val;
12640 else if (op == TOK_GT)
12641 rez = (rez > numptr_val);
12642 else if (op == TOK_LT)
12643 rez = (rez < numptr_val);
12644 else if (op == TOK_LE)
12645 rez = (rez <= numptr_val);
12646 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12648 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12650 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12652 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12654 else if (op == TOK_CONDITIONAL_SEP) {
12655 if (numptr_m1 == numstack) {
12656 /* protect $((expr : expr)) without "expr ? " */
12659 numptr_m1->contidional_second_val_initialized = op;
12660 numptr_m1->contidional_second_val = numptr_val;
12661 } else if (op == TOK_CONDITIONAL) {
12663 numptr_val : numptr_m1->contidional_second_val;
12664 } else if (op == TOK_EXPONENT) {
12665 if (numptr_val < 0)
12666 return -3; /* exponent less than 0 */
12671 while (numptr_val--)
12675 } else if (numptr_val==0) /* zero divisor check */
12677 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12679 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12682 if (tok_have_assign(op)) {
12683 char buf[sizeof(arith_t_type)*3 + 2];
12685 if (numptr_m1->var == NULL) {
12689 /* save to shell variable */
12690 #if ENABLE_ASH_MATH_SUPPORT_64
12691 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12693 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12695 setvar(numptr_m1->var, buf, 0);
12696 /* after saving, make previous value for v++ or v-- */
12697 if (op == TOK_POST_INC)
12699 else if (op == TOK_POST_DEC)
12702 numptr_m1->val = rez;
12703 /* protect geting var value, is number now */
12704 numptr_m1->var = NULL;
12710 /* longest must be first */
12711 static const char op_tokens[] = {
12712 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12713 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12714 '<','<', 0, TOK_LSHIFT,
12715 '>','>', 0, TOK_RSHIFT,
12716 '|','|', 0, TOK_OR,
12717 '&','&', 0, TOK_AND,
12718 '!','=', 0, TOK_NE,
12719 '<','=', 0, TOK_LE,
12720 '>','=', 0, TOK_GE,
12721 '=','=', 0, TOK_EQ,
12722 '|','=', 0, TOK_OR_ASSIGN,
12723 '&','=', 0, TOK_AND_ASSIGN,
12724 '*','=', 0, TOK_MUL_ASSIGN,
12725 '/','=', 0, TOK_DIV_ASSIGN,
12726 '%','=', 0, TOK_REM_ASSIGN,
12727 '+','=', 0, TOK_PLUS_ASSIGN,
12728 '-','=', 0, TOK_MINUS_ASSIGN,
12729 '-','-', 0, TOK_POST_DEC,
12730 '^','=', 0, TOK_XOR_ASSIGN,
12731 '+','+', 0, TOK_POST_INC,
12732 '*','*', 0, TOK_EXPONENT,
12736 '=', 0, TOK_ASSIGN,
12748 '?', 0, TOK_CONDITIONAL,
12749 ':', 0, TOK_CONDITIONAL_SEP,
12750 ')', 0, TOK_RPAREN,
12751 '(', 0, TOK_LPAREN,
12755 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12759 arith(const char *expr, int *perrcode)
12761 char arithval; /* Current character under analysis */
12762 operator lasttok, op;
12765 const char *p = endexpression;
12768 size_t datasizes = strlen(expr) + 2;
12770 /* Stack of integers */
12771 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12772 * in any given correct or incorrect expression is left as an exercise to
12774 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12775 *numstackptr = numstack;
12776 /* Stack of operator tokens */
12777 operator *stack = alloca((datasizes) * sizeof(operator)),
12780 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12781 *perrcode = errcode = 0;
12785 if (arithval == 0) {
12786 if (p == endexpression) {
12787 /* Null expression. */
12791 /* This is only reached after all tokens have been extracted from the
12792 * input stream. If there are still tokens on the operator stack, they
12793 * are to be applied in order. At the end, there should be a final
12794 * result on the integer stack */
12796 if (expr != endexpression + 1) {
12797 /* If we haven't done so already, */
12798 /* append a closing right paren */
12799 expr = endexpression;
12800 /* and let the loop process it. */
12803 /* At this point, we're done with the expression. */
12804 if (numstackptr != numstack+1) {
12805 /* ... but if there isn't, it's bad */
12807 return (*perrcode = -1);
12809 if (numstack->var) {
12810 /* expression is $((var)) only, lookup now */
12811 errcode = arith_lookup_val(numstack);
12814 *perrcode = errcode;
12815 return numstack->val;
12818 /* Continue processing the expression. */
12819 if (arith_isspace(arithval)) {
12820 /* Skip whitespace */
12823 p = endofname(expr);
12825 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12827 numstackptr->var = alloca(var_name_size);
12828 safe_strncpy(numstackptr->var, expr, var_name_size);
12831 numstackptr->contidional_second_val_initialized = 0;
12836 if (isdigit(arithval)) {
12837 numstackptr->var = NULL;
12838 #if ENABLE_ASH_MATH_SUPPORT_64
12839 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12841 numstackptr->val = strtol(expr, (char **) &expr, 0);
12845 for (p = op_tokens; ; p++) {
12849 /* strange operator not found */
12852 for (o = expr; *p && *o == *p; p++)
12859 /* skip tail uncompared token */
12862 /* skip zero delim */
12867 /* post grammar: a++ reduce to num */
12868 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12871 /* Plus and minus are binary (not unary) _only_ if the last
12872 * token was as number, or a right paren (which pretends to be
12873 * a number, since it evaluates to one). Think about it.
12874 * It makes sense. */
12875 if (lasttok != TOK_NUM) {
12891 /* We don't want a unary operator to cause recursive descent on the
12892 * stack, because there can be many in a row and it could cause an
12893 * operator to be evaluated before its argument is pushed onto the
12894 * integer stack. */
12895 /* But for binary operators, "apply" everything on the operator
12896 * stack until we find an operator with a lesser priority than the
12897 * one we have just extracted. */
12898 /* Left paren is given the lowest priority so it will never be
12899 * "applied" in this way.
12900 * if associativity is right and priority eq, applied also skip
12903 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12904 /* not left paren or unary */
12905 if (lasttok != TOK_NUM) {
12906 /* binary op must be preceded by a num */
12909 while (stackptr != stack) {
12910 if (op == TOK_RPAREN) {
12911 /* The algorithm employed here is simple: while we don't
12912 * hit an open paren nor the bottom of the stack, pop
12913 * tokens and apply them */
12914 if (stackptr[-1] == TOK_LPAREN) {
12916 /* Any operator directly after a */
12918 /* close paren should consider itself binary */
12922 operator prev_prec = PREC(stackptr[-1]);
12924 convert_prec_is_assing(prec);
12925 convert_prec_is_assing(prev_prec);
12926 if (prev_prec < prec)
12928 /* check right assoc */
12929 if (prev_prec == prec && is_right_associativity(prec))
12932 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12933 if (errcode) goto ret;
12935 if (op == TOK_RPAREN) {
12940 /* Push this operator to the stack and remember it. */
12941 *stackptr++ = lasttok = op;
12946 #endif /* ASH_MATH_SUPPORT */
12949 /* ============ main() and helpers
12951 * Main routine. We initialize things, parse the arguments, execute
12952 * profiles if we're a login shell, and then call cmdloop to execute
12953 * commands. The setjmp call sets up the location to jump to when an
12954 * exception occurs. When an exception occurs the variable "state"
12955 * is used to figure out how far we had gotten.
12960 /* from input.c: */
12961 basepf.nextc = basepf.buf = basebuf;
12964 signal(SIGCHLD, SIG_DFL);
12969 char ppid[sizeof(int)*3 + 1];
12971 struct stat st1, st2;
12974 for (envp = environ; envp && *envp; envp++) {
12975 if (strchr(*envp, '=')) {
12976 setvareq(*envp, VEXPORT|VTEXTFIXED);
12980 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12981 setvar("PPID", ppid, 0);
12983 p = lookupvar("PWD");
12985 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12986 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12993 * Process the shell command line arguments.
12996 procargs(int argc, char **argv)
12999 const char *xminusc;
13006 for (i = 0; i < NOPTS; i++)
13012 if (*xargv == NULL) {
13014 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13017 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13021 for (i = 0; i < NOPTS; i++)
13022 if (optlist[i] == 2)
13027 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13032 } else if (!sflag) {
13033 setinputfile(*xargv, 0);
13036 commandname = arg0;
13039 shellparam.p = xargv;
13040 #if ENABLE_ASH_GETOPTS
13041 shellparam.optind = 1;
13042 shellparam.optoff = -1;
13044 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
13046 shellparam.nparam++;
13053 * Read /etc/profile or .profile.
13056 read_profile(const char *name)
13060 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13069 * This routine is called when an error or an interrupt occurs in an
13070 * interactive shell and control is returned to the main command loop.
13078 /* from input.c: */
13079 parselleft = parsenleft = 0; /* clear input buffer */
13081 /* from parser.c: */
13084 /* from redir.c: */
13089 static short profile_buf[16384];
13090 extern int etext();
13093 int ash_main(int argc, char **argv);
13094 int ash_main(int argc, char **argv)
13097 volatile int state;
13098 struct jmploc jmploc;
13099 struct stackmark smark;
13102 dash_errno = __errno_location();
13106 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13109 #if ENABLE_FEATURE_EDITING
13110 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13113 if (setjmp(jmploc.loc)) {
13123 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13127 outcslow('\n', stderr);
13129 popstackmark(&smark);
13130 FORCE_INT_ON; /* enable interrupts */
13139 exception_handler = &jmploc;
13142 trace_puts("Shell args: ");
13143 trace_puts_args(argv);
13145 rootpid = getpid();
13147 #if ENABLE_ASH_RANDOM_SUPPORT
13148 rseed = rootpid + time(NULL);
13151 setstackmark(&smark);
13152 procargs(argc, argv);
13153 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13155 const char *hp = lookupvar("HISTFILE");
13158 hp = lookupvar("HOME");
13160 char *defhp = concat_path_file(hp, ".ash_history");
13161 setvar("HISTFILE", defhp, 0);
13167 if (argv[0] && argv[0][0] == '-')
13171 read_profile("/etc/profile");
13174 read_profile(".profile");
13180 getuid() == geteuid() && getgid() == getegid() &&
13184 shinit = lookupvar("ENV");
13185 if (shinit != NULL && *shinit != '\0') {
13186 read_profile(shinit);
13192 evalstring(minusc, 0);
13194 if (sflag || minusc == NULL) {
13195 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13197 const char *hp = lookupvar("HISTFILE");
13200 line_input_state->hist_file = hp;
13203 state4: /* XXX ??? - why isn't this before the "if" statement */
13211 extern void _mcleanup(void);
13220 const char *applet_name = "debug stuff usage";
13221 int main(int argc, char **argv)
13223 return ash_main(argc, argv);
13229 * Copyright (c) 1989, 1991, 1993, 1994
13230 * The Regents of the University of California. All rights reserved.
13232 * This code is derived from software contributed to Berkeley by
13233 * Kenneth Almquist.
13235 * Redistribution and use in source and binary forms, with or without
13236 * modification, are permitted provided that the following conditions
13238 * 1. Redistributions of source code must retain the above copyright
13239 * notice, this list of conditions and the following disclaimer.
13240 * 2. Redistributions in binary form must reproduce the above copyright
13241 * notice, this list of conditions and the following disclaimer in the
13242 * documentation and/or other materials provided with the distribution.
13243 * 3. Neither the name of the University nor the names of its contributors
13244 * may be used to endorse or promote products derived from this software
13245 * without specific prior written permission.
13247 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13248 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13249 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13250 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13251 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13252 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13253 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13254 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13255 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13256 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF