1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
12 * This code is derived from software contributed to Berkeley by
15 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
17 * Original BSD copyright notice is retained at the end of this file.
21 * rewrite arith.y to micro stack based cryptic algorithm by
22 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
24 * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
27 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
28 * used in busybox and size optimizations,
29 * rewrote arith (see notes to this), added locale support,
30 * rewrote dynamic variables.
35 * The follow should be set to reflect the type of system you have:
36 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
37 * define SYSV if you are running under System V.
38 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
39 * define DEBUG=2 to compile in and turn on debugging.
41 * When debugging is on, debugging info will be written to ./trace and
42 * a quit signal will generate a core dump.
47 #if ENABLE_ASH_JOB_CONTROL
56 #include "busybox.h" /* for applet_names */
60 #if JOBS || ENABLE_ASH_READ_NCHARS
64 #if defined(__uClinux__)
65 #error "Do not even bother, ash will not run on uClinux"
69 /* ============ Hash table sizes. Configurable. */
73 #define CMDTABLESIZE 31 /* should be prime */
76 /* ============ Misc helpers */
78 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
80 /* C99 say: "char" declaration may be signed or unsigned default */
81 #define signed_char2int(sc) ((int)((signed char)sc))
84 /* ============ Shell options */
86 static const char *const optletters_optnames[] = {
107 #define optletters(n) optletters_optnames[(n)][0]
108 #define optnames(n) (&optletters_optnames[(n)][1])
110 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
112 static char optlist[NOPTS] ALIGN1;
114 #define eflag optlist[0]
115 #define fflag optlist[1]
116 #define Iflag optlist[2]
117 #define iflag optlist[3]
118 #define mflag optlist[4]
119 #define nflag optlist[5]
120 #define sflag optlist[6]
121 #define xflag optlist[7]
122 #define vflag optlist[8]
123 #define Cflag optlist[9]
124 #define aflag optlist[10]
125 #define bflag optlist[11]
126 #define uflag optlist[12]
127 #define viflag optlist[13]
129 #define nolog optlist[14]
130 #define debug optlist[15]
134 /* ============ Misc data */
136 static const char homestr[] ALIGN1 = "HOME";
137 static const char snlfmt[] ALIGN1 = "%s\n";
138 static const char illnum[] ALIGN1 = "Illegal number: %s";
141 * We enclose jmp_buf in a structure so that we can declare pointers to
142 * jump locations. The global variable handler contains the location to
143 * jump to when an exception occurs, and the global variable exception
144 * contains a code identifying the exception. To implement nested
145 * exception handlers, the user should save the value of handler on entry
146 * to an inner scope, set handler to point to a jmploc structure for the
147 * inner scope, and restore handler on exit from the scope.
153 struct globals_misc {
154 /* pid of main shell */
156 /* shell level: 0 for the main shell, 1 for its children, and so on */
158 #define rootshell (!shlvl)
159 char *minusc; /* argument to -c option */
161 char *curdir; // = nullstr; /* current working directory */
162 char *physdir; // = nullstr; /* physical working directory */
164 char *arg0; /* value of $0 */
166 struct jmploc *exception_handler;
168 // disabled by vda: cannot understand how it was supposed to work -
169 // cannot fix bugs. That's why you have to explain your non-trivial designs!
170 // /* do we generate EXSIG events */
171 // int exsig; /* counter */
172 volatile int suppressint; /* counter */
173 volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
174 /* last pending signal */
175 volatile /*sig_atomic_t*/ smallint pendingsig;
176 smallint exception; /* kind of exception (0..5) */
178 #define EXINT 0 /* SIGINT received */
179 #define EXERROR 1 /* a generic error */
180 #define EXSHELLPROC 2 /* execute a shell procedure */
181 #define EXEXEC 3 /* command execution failed */
182 #define EXEXIT 4 /* exit the shell */
183 #define EXSIG 5 /* trapped signal in wait(1) */
185 /* trap handler commands */
188 char nullstr[1]; /* zero length string */
190 * Sigmode records the current value of the signal handlers for the various
191 * modes. A value of zero means that the current handler is not known.
192 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
194 char sigmode[NSIG - 1];
195 #define S_DFL 1 /* default signal handling (SIG_DFL) */
196 #define S_CATCH 2 /* signal is caught */
197 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
198 #define S_HARD_IGN 4 /* signal is ignored permenantly */
199 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
201 /* indicates specified signal received */
202 char gotsig[NSIG - 1];
204 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
205 static struct globals_misc *const ptr_to_globals_misc __attribute__ ((section (".data")));
206 #define G_misc (*ptr_to_globals_misc)
207 #define rootpid (G_misc.rootpid )
208 #define shlvl (G_misc.shlvl )
209 #define minusc (G_misc.minusc )
210 #define curdir (G_misc.curdir )
211 #define physdir (G_misc.physdir )
212 #define arg0 (G_misc.arg0 )
213 #define exception_handler (G_misc.exception_handler)
214 #define exception (G_misc.exception )
215 #define suppressint (G_misc.suppressint )
216 #define intpending (G_misc.intpending )
217 //#define exsig (G_misc.exsig )
218 #define pendingsig (G_misc.pendingsig )
219 #define trap (G_misc.trap )
220 #define isloginsh (G_misc.isloginsh)
221 #define nullstr (G_misc.nullstr )
222 #define sigmode (G_misc.sigmode )
223 #define gotsig (G_misc.gotsig )
224 #define INIT_G_misc() do { \
225 (*(struct globals_misc**)&ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
231 /* ============ Interrupts / exceptions */
234 * These macros allow the user to suspend the handling of interrupt signals
235 * over a period of time. This is similar to SIGHOLD or to sigblock, but
236 * much more efficient and portable. (But hacking the kernel is so much
237 * more fun than worrying about efficiency and portability. :-))
246 * Called to raise an exception. Since C doesn't include exceptions, we
247 * just do a longjmp to the exception handler. The type of exception is
248 * stored in the global variable "exception".
250 static void raise_exception(int) ATTRIBUTE_NORETURN;
252 raise_exception(int e)
255 if (exception_handler == NULL)
260 longjmp(exception_handler->loc, 1);
264 * Called from trap.c when a SIGINT is received. (If the user specifies
265 * that SIGINT is to be trapped or ignored using the trap builtin, then
266 * this routine is not called.) Suppressint is nonzero when interrupts
267 * are held using the INT_OFF macro. (The test for iflag is just
268 * defensive programming.)
270 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
272 raise_interrupt(void)
278 /* Signal is not automatically unmasked after it is raised,
279 * do it ourself - unmask all signals */
281 sigprocmask(SIG_SETMASK, &mask, NULL);
282 /* pendingsig = 0; - now done in onsig() */
285 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
286 if (!(rootshell && iflag)) {
287 /* Kill ourself with SIGINT */
288 signal(SIGINT, SIG_DFL);
297 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
301 if (--suppressint == 0 && intpending) {
305 #define INT_ON int_on()
313 #define FORCE_INT_ON force_int_on()
318 if (--suppressint == 0 && intpending) \
321 #define FORCE_INT_ON \
328 #endif /* ASH_OPTIMIZE_FOR_SIZE */
330 #define SAVE_INT(v) ((v) = suppressint)
332 #define RESTORE_INT(v) \
336 if (suppressint == 0 && intpending) \
341 * Ignore a signal. Only one usage site - in forkchild()
346 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
347 signal(signo, SIG_IGN);
349 sigmode[signo - 1] = S_HARD_IGN;
353 * Signal handler. Only one usage site - in setsignal()
358 gotsig[signo - 1] = 1;
361 if ( /* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
364 raise_interrupt(); /* does not return */
371 /* ============ Stdout/stderr output */
374 outstr(const char *p, FILE *file)
382 flush_stdout_stderr(void)
399 outcslow(int c, FILE *dest)
407 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
409 out1fmt(const char *fmt, ...)
416 r = vprintf(fmt, ap);
422 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
424 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
431 ret = vsnprintf(outbuf, length, fmt, ap);
438 out1str(const char *p)
444 out2str(const char *p)
451 /* ============ Parser structures */
453 /* control characters in argument strings */
454 #define CTLESC '\201' /* escape next character */
455 #define CTLVAR '\202' /* variable defn */
456 #define CTLENDVAR '\203'
457 #define CTLBACKQ '\204'
458 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
459 /* CTLBACKQ | CTLQUOTE == '\205' */
460 #define CTLARI '\206' /* arithmetic expression */
461 #define CTLENDARI '\207'
462 #define CTLQUOTEMARK '\210'
464 /* variable substitution byte (follows CTLVAR) */
465 #define VSTYPE 0x0f /* type of variable substitution */
466 #define VSNUL 0x10 /* colon--treat the empty string as unset */
467 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
469 /* values of VSTYPE field */
470 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
471 #define VSMINUS 0x2 /* ${var-text} */
472 #define VSPLUS 0x3 /* ${var+text} */
473 #define VSQUESTION 0x4 /* ${var?message} */
474 #define VSASSIGN 0x5 /* ${var=text} */
475 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
476 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
477 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
478 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
479 #define VSLENGTH 0xa /* ${#var} */
481 static const char dolatstr[] ALIGN1 = {
482 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
518 union node *redirect;
524 struct nodelist *cmdlist;
530 union node *redirect;
543 union node *elsepart;
570 struct nodelist *backquote;
605 struct nredir nredir;
606 struct nbinary nbinary;
610 struct nclist nclist;
619 struct nodelist *next;
632 freefunc(struct funcnode *f)
634 if (f && --f->count < 0)
639 /* ============ Debugging output */
643 static FILE *tracefile;
646 trace_printf(const char *fmt, ...)
653 vfprintf(tracefile, fmt, va);
658 trace_vprintf(const char *fmt, va_list va)
662 vfprintf(tracefile, fmt, va);
666 trace_puts(const char *s)
674 trace_puts_quoted(char *s)
681 putc('"', tracefile);
682 for (p = s; *p; p++) {
684 case '\n': c = 'n'; goto backslash;
685 case '\t': c = 't'; goto backslash;
686 case '\r': c = 'r'; goto backslash;
687 case '"': c = '"'; goto backslash;
688 case '\\': c = '\\'; goto backslash;
689 case CTLESC: c = 'e'; goto backslash;
690 case CTLVAR: c = 'v'; goto backslash;
691 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
692 case CTLBACKQ: c = 'q'; goto backslash;
693 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
695 putc('\\', tracefile);
699 if (*p >= ' ' && *p <= '~')
702 putc('\\', tracefile);
703 putc(*p >> 6 & 03, tracefile);
704 putc(*p >> 3 & 07, tracefile);
705 putc(*p & 07, tracefile);
710 putc('"', tracefile);
714 trace_puts_args(char **ap)
721 trace_puts_quoted(*ap);
723 putc('\n', tracefile);
726 putc(' ', tracefile);
741 /* leave open because libedit might be using it */
744 strcpy(s, "./trace");
746 if (!freopen(s, "a", tracefile)) {
747 fprintf(stderr, "Can't re-open %s\n", s);
752 tracefile = fopen(s, "a");
753 if (tracefile == NULL) {
754 fprintf(stderr, "Can't open %s\n", s);
760 flags = fcntl(fileno(tracefile), F_GETFL);
762 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
764 setlinebuf(tracefile);
765 fputs("\nTracing started.\n", tracefile);
769 indent(int amount, char *pfx, FILE *fp)
773 for (i = 0; i < amount; i++) {
774 if (pfx && i == amount - 1)
780 /* little circular references here... */
781 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
784 sharg(union node *arg, FILE *fp)
787 struct nodelist *bqlist;
790 if (arg->type != NARG) {
791 out1fmt("<node type %d>\n", arg->type);
794 bqlist = arg->narg.backquote;
795 for (p = arg->narg.text; *p; p++) {
804 if (subtype == VSLENGTH)
813 switch (subtype & VSTYPE) {
846 out1fmt("<subtype %d>", subtype);
853 case CTLBACKQ|CTLQUOTE:
856 shtree(bqlist->n, -1, NULL, fp);
867 shcmd(union node *cmd, FILE *fp)
875 for (np = cmd->ncmd.args; np; np = np->narg.next) {
881 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
885 switch (np->nfile.type) {
886 case NTO: s = ">>"+1; dftfd = 1; break;
887 case NCLOBBER: s = ">|"; dftfd = 1; break;
888 case NAPPEND: s = ">>"; dftfd = 1; break;
889 case NTOFD: s = ">&"; dftfd = 1; break;
890 case NFROM: s = "<"; break;
891 case NFROMFD: s = "<&"; break;
892 case NFROMTO: s = "<>"; break;
893 default: s = "*error*"; break;
895 if (np->nfile.fd != dftfd)
896 fprintf(fp, "%d", np->nfile.fd);
898 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
899 fprintf(fp, "%d", np->ndup.dupfd);
901 sharg(np->nfile.fname, fp);
908 shtree(union node *n, int ind, char *pfx, FILE *fp)
916 indent(ind, pfx, fp);
927 shtree(n->nbinary.ch1, ind, NULL, fp);
930 shtree(n->nbinary.ch2, ind, NULL, fp);
938 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
943 if (n->npipe.backgnd)
949 fprintf(fp, "<node type %d>", n->type);
957 showtree(union node *n)
959 trace_puts("showtree called\n");
960 shtree(n, 1, NULL, stdout);
963 #define TRACE(param) trace_printf param
964 #define TRACEV(param) trace_vprintf param
969 #define TRACEV(param)
974 /* ============ Parser data */
977 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
980 struct strlist *next;
989 struct strpush *prev; /* preceding string on stack */
993 struct alias *ap; /* if push was associated with an alias */
995 char *string; /* remember the string since it may change */
999 struct parsefile *prev; /* preceding file on stack */
1000 int linno; /* current line */
1001 int fd; /* file descriptor (or -1 if string) */
1002 int nleft; /* number of chars left in this line */
1003 int lleft; /* number of chars left in this buffer */
1004 char *nextc; /* next char in buffer */
1005 char *buf; /* input buffer */
1006 struct strpush *strpush; /* for pushing strings at this level */
1007 struct strpush basestrpush; /* so pushing one is fast */
1010 static struct parsefile basepf; /* top level input file */
1011 static struct parsefile *parsefile = &basepf; /* current input file */
1012 static int startlinno; /* line # where last token started */
1013 static char *commandname; /* currently executing command */
1014 static struct strlist *cmdenviron; /* environment for builtin command */
1015 static int exitstatus; /* exit status of last command */
1018 /* ============ Message printing */
1021 ash_vmsg(const char *msg, va_list ap)
1023 fprintf(stderr, "%s: ", arg0);
1025 if (strcmp(arg0, commandname))
1026 fprintf(stderr, "%s: ", commandname);
1027 if (!iflag || parsefile->fd)
1028 fprintf(stderr, "line %d: ", startlinno);
1030 vfprintf(stderr, msg, ap);
1031 outcslow('\n', stderr);
1035 * Exverror is called to raise the error exception. If the second argument
1036 * is not NULL then error prints an error message using printf style
1037 * formatting. It then raises the error exception.
1039 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1041 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1045 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1047 TRACE(("\") pid=%d\n", getpid()));
1049 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1054 flush_stdout_stderr();
1055 raise_exception(cond);
1059 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1061 ash_msg_and_raise_error(const char *msg, ...)
1066 ash_vmsg_and_raise(EXERROR, msg, ap);
1071 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1073 ash_msg_and_raise(int cond, const char *msg, ...)
1078 ash_vmsg_and_raise(cond, msg, ap);
1084 * error/warning routines for external builtins
1087 ash_msg(const char *fmt, ...)
1097 * Return a string describing an error. The returned string may be a
1098 * pointer to a static buffer that will be overwritten on the next call.
1099 * Action describes the operation that got the error.
1102 errmsg(int e, const char *em)
1104 if (e == ENOENT || e == ENOTDIR) {
1111 /* ============ Memory allocation */
1114 * It appears that grabstackstr() will barf with such alignments
1115 * because stalloc() will return a string allocated in a new stackblock.
1117 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1119 /* Most machines require the value returned from malloc to be aligned
1120 * in some way. The following macro will get this right
1121 * on many machines. */
1122 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1123 /* Minimum size of a block */
1124 MINSIZE = SHELL_ALIGN(504),
1127 struct stack_block {
1128 struct stack_block *prev;
1129 char space[MINSIZE];
1133 struct stack_block *stackp;
1136 struct stackmark *marknext;
1140 struct globals_memstack {
1141 struct stack_block *g_stackp; // = &stackbase;
1142 struct stackmark *markp;
1143 char *g_stacknxt; // = stackbase.space;
1144 char *sstrend; // = stackbase.space + MINSIZE;
1145 size_t g_stacknleft; // = MINSIZE;
1146 int herefd; // = -1;
1147 struct stack_block stackbase;
1149 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1150 static struct globals_memstack *const ptr_to_globals_memstack __attribute__ ((section (".data")));
1151 #define G_memstack (*ptr_to_globals_memstack)
1152 #define g_stackp (G_memstack.g_stackp )
1153 #define markp (G_memstack.markp )
1154 #define g_stacknxt (G_memstack.g_stacknxt )
1155 #define sstrend (G_memstack.sstrend )
1156 #define g_stacknleft (G_memstack.g_stacknleft)
1157 #define herefd (G_memstack.herefd )
1158 #define stackbase (G_memstack.stackbase )
1159 #define INIT_G_memstack() do { \
1160 (*(struct globals_memstack**)&ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1161 g_stackp = &stackbase; \
1162 g_stacknxt = stackbase.space; \
1163 g_stacknleft = MINSIZE; \
1164 sstrend = stackbase.space + MINSIZE; \
1168 #define stackblock() ((void *)g_stacknxt)
1169 #define stackblocksize() g_stacknleft
1173 ckrealloc(void * p, size_t nbytes)
1175 p = realloc(p, nbytes);
1177 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1182 ckmalloc(size_t nbytes)
1184 return ckrealloc(NULL, nbytes);
1188 * Make a copy of a string in safe storage.
1191 ckstrdup(const char *s)
1193 char *p = strdup(s);
1195 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1200 * Parse trees for commands are allocated in lifo order, so we use a stack
1201 * to make this more efficient, and also to avoid all sorts of exception
1202 * handling code to handle interrupts in the middle of a parse.
1204 * The size 504 was chosen because the Ultrix malloc handles that size
1208 stalloc(size_t nbytes)
1213 aligned = SHELL_ALIGN(nbytes);
1214 if (aligned > g_stacknleft) {
1217 struct stack_block *sp;
1219 blocksize = aligned;
1220 if (blocksize < MINSIZE)
1221 blocksize = MINSIZE;
1222 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1223 if (len < blocksize)
1224 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1227 sp->prev = g_stackp;
1228 g_stacknxt = sp->space;
1229 g_stacknleft = blocksize;
1230 sstrend = g_stacknxt + blocksize;
1235 g_stacknxt += aligned;
1236 g_stacknleft -= aligned;
1244 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1245 write(2, "stunalloc\n", 10);
1249 g_stacknleft += g_stacknxt - (char *)p;
1254 * Like strdup but works with the ash stack.
1257 ststrdup(const char *p)
1259 size_t len = strlen(p) + 1;
1260 return memcpy(stalloc(len), p, len);
1264 setstackmark(struct stackmark *mark)
1266 mark->stackp = g_stackp;
1267 mark->stacknxt = g_stacknxt;
1268 mark->stacknleft = g_stacknleft;
1269 mark->marknext = markp;
1274 popstackmark(struct stackmark *mark)
1276 struct stack_block *sp;
1282 markp = mark->marknext;
1283 while (g_stackp != mark->stackp) {
1285 g_stackp = sp->prev;
1288 g_stacknxt = mark->stacknxt;
1289 g_stacknleft = mark->stacknleft;
1290 sstrend = mark->stacknxt + mark->stacknleft;
1295 * When the parser reads in a string, it wants to stick the string on the
1296 * stack and only adjust the stack pointer when it knows how big the
1297 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1298 * of space on top of the stack and stackblocklen returns the length of
1299 * this block. Growstackblock will grow this space by at least one byte,
1300 * possibly moving it (like realloc). Grabstackblock actually allocates the
1301 * part of the block that has been used.
1304 growstackblock(void)
1308 newlen = g_stacknleft * 2;
1309 if (newlen < g_stacknleft)
1310 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1314 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1315 struct stack_block *oldstackp;
1316 struct stackmark *xmark;
1317 struct stack_block *sp;
1318 struct stack_block *prevstackp;
1322 oldstackp = g_stackp;
1324 prevstackp = sp->prev;
1325 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1326 sp = ckrealloc(sp, grosslen);
1327 sp->prev = prevstackp;
1329 g_stacknxt = sp->space;
1330 g_stacknleft = newlen;
1331 sstrend = sp->space + newlen;
1334 * Stack marks pointing to the start of the old block
1335 * must be relocated to point to the new block
1338 while (xmark != NULL && xmark->stackp == oldstackp) {
1339 xmark->stackp = g_stackp;
1340 xmark->stacknxt = g_stacknxt;
1341 xmark->stacknleft = g_stacknleft;
1342 xmark = xmark->marknext;
1346 char *oldspace = g_stacknxt;
1347 int oldlen = g_stacknleft;
1348 char *p = stalloc(newlen);
1350 /* free the space we just allocated */
1351 g_stacknxt = memcpy(p, oldspace, oldlen);
1352 g_stacknleft += newlen;
1357 grabstackblock(size_t len)
1359 len = SHELL_ALIGN(len);
1361 g_stacknleft -= len;
1365 * The following routines are somewhat easier to use than the above.
1366 * The user declares a variable of type STACKSTR, which may be declared
1367 * to be a register. The macro STARTSTACKSTR initializes things. Then
1368 * the user uses the macro STPUTC to add characters to the string. In
1369 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1370 * grown as necessary. When the user is done, she can just leave the
1371 * string there and refer to it using stackblock(). Or she can allocate
1372 * the space for it using grabstackstr(). If it is necessary to allow
1373 * someone else to use the stack temporarily and then continue to grow
1374 * the string, the user should use grabstack to allocate the space, and
1375 * then call ungrabstr(p) to return to the previous mode of operation.
1377 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1378 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1379 * is space for at least one character.
1384 size_t len = stackblocksize();
1385 if (herefd >= 0 && len >= 1024) {
1386 full_write(herefd, stackblock(), len);
1387 return stackblock();
1390 return stackblock() + len;
1394 * Called from CHECKSTRSPACE.
1397 makestrspace(size_t newlen, char *p)
1399 size_t len = p - g_stacknxt;
1400 size_t size = stackblocksize();
1405 size = stackblocksize();
1407 if (nleft >= newlen)
1411 return stackblock() + len;
1415 stack_nputstr(const char *s, size_t n, char *p)
1417 p = makestrspace(n, p);
1418 p = memcpy(p, s, n) + n;
1423 stack_putstr(const char *s, char *p)
1425 return stack_nputstr(s, strlen(s), p);
1429 _STPUTC(int c, char *p)
1437 #define STARTSTACKSTR(p) ((p) = stackblock())
1438 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1439 #define CHECKSTRSPACE(n, p) \
1443 size_t m = sstrend - q; \
1445 (p) = makestrspace(l, q); \
1447 #define USTPUTC(c, p) (*p++ = (c))
1448 #define STACKSTRNUL(p) \
1450 if ((p) == sstrend) \
1451 p = growstackstr(); \
1454 #define STUNPUTC(p) (--p)
1455 #define STTOPC(p) (p[-1])
1456 #define STADJUST(amount, p) (p += (amount))
1458 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1459 #define ungrabstackstr(s, p) stunalloc((s))
1460 #define stackstrend() ((void *)sstrend)
1463 /* ============ String helpers */
1466 * prefix -- see if pfx is a prefix of string.
1469 prefix(const char *string, const char *pfx)
1472 if (*pfx++ != *string++)
1475 return (char *) string;
1479 * Check for a valid number. This should be elsewhere.
1482 is_number(const char *p)
1487 } while (*++p != '\0');
1492 * Convert a string of digits to an integer, printing an error message on
1496 number(const char *s)
1499 ash_msg_and_raise_error(illnum, s);
1504 * Produce a possibly single quoted string suitable as input to the shell.
1505 * The return string is allocated on the stack.
1508 single_quote(const char *s)
1518 len = strchrnul(s, '\'') - s;
1520 q = p = makestrspace(len + 3, p);
1523 q = memcpy(q, s, len) + len;
1529 len = strspn(s, "'");
1533 q = p = makestrspace(len + 3, p);
1536 q = memcpy(q, s, len) + len;
1545 return stackblock();
1549 /* ============ nextopt */
1551 static char **argptr; /* argument list for builtin commands */
1552 static char *optionarg; /* set by nextopt (like getopt) */
1553 static char *optptr; /* used by nextopt */
1556 * XXX - should get rid of. have all builtins use getopt(3). the
1557 * library getopt must have the BSD extension static variable "optreset"
1558 * otherwise it can't be used within the shell safely.
1560 * Standard option processing (a la getopt) for builtin routines. The
1561 * only argument that is passed to nextopt is the option string; the
1562 * other arguments are unnecessary. It return the character, or '\0' on
1566 nextopt(const char *optstring)
1573 if (p == NULL || *p == '\0') {
1575 if (p == NULL || *p != '-' || *++p == '\0')
1578 if (LONE_DASH(p)) /* check for "--" */
1582 for (q = optstring; *q != c; ) {
1584 ash_msg_and_raise_error("illegal option -%c", c);
1589 if (*p == '\0' && (p = *argptr++) == NULL)
1590 ash_msg_and_raise_error("no arg for -%c option", c);
1599 /* ============ Math support definitions */
1601 #if ENABLE_ASH_MATH_SUPPORT_64
1602 typedef int64_t arith_t;
1603 #define arith_t_type long long
1605 typedef long arith_t;
1606 #define arith_t_type long
1609 #if ENABLE_ASH_MATH_SUPPORT
1610 static arith_t dash_arith(const char *);
1611 static arith_t arith(const char *expr, int *perrcode);
1614 #if ENABLE_ASH_RANDOM_SUPPORT
1615 static unsigned long rseed;
1622 /* ============ Shell variables */
1625 * The parsefile structure pointed to by the global variable parsefile
1626 * contains information about the current file being read.
1629 struct redirtab *next;
1635 int nparam; /* # of positional parameters (without $0) */
1636 #if ENABLE_ASH_GETOPTS
1637 int optind; /* next parameter to be processed by getopts */
1638 int optoff; /* used by getopts */
1640 unsigned char malloced; /* if parameter list dynamically allocated */
1641 char **p; /* parameter list */
1645 * Free the list of positional parameters.
1648 freeparam(volatile struct shparam *param)
1652 if (param->malloced) {
1653 for (ap = param->p; *ap; ap++)
1659 #if ENABLE_ASH_GETOPTS
1660 static void getoptsreset(const char *value);
1664 struct var *next; /* next entry in hash list */
1665 int flags; /* flags are defined above */
1666 const char *text; /* name=value */
1667 void (*func)(const char *); /* function to be called when */
1668 /* the variable gets set/unset */
1672 struct localvar *next; /* next local variable in list */
1673 struct var *vp; /* the variable that was made local */
1674 int flags; /* saved flags */
1675 const char *text; /* saved text */
1679 #define VEXPORT 0x01 /* variable is exported */
1680 #define VREADONLY 0x02 /* variable cannot be modified */
1681 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1682 #define VTEXTFIXED 0x08 /* text is statically allocated */
1683 #define VSTACK 0x10 /* text is allocated on the stack */
1684 #define VUNSET 0x20 /* the variable is not set */
1685 #define VNOFUNC 0x40 /* don't call the callback function */
1686 #define VNOSET 0x80 /* do not set variable - just readonly test */
1687 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1689 # define VDYNAMIC 0x200 /* dynamic variable */
1695 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1696 #define defifs (defifsvar + 4)
1698 static const char defifs[] ALIGN1 = " \t\n";
1702 /* Need to be before varinit_data[] */
1703 #if ENABLE_LOCALE_SUPPORT
1705 change_lc_all(const char *value)
1707 if (value && *value != '\0')
1708 setlocale(LC_ALL, value);
1711 change_lc_ctype(const char *value)
1713 if (value && *value != '\0')
1714 setlocale(LC_CTYPE, value);
1718 static void chkmail(void);
1719 static void changemail(const char *);
1721 static void changepath(const char *);
1722 #if ENABLE_ASH_RANDOM_SUPPORT
1723 static void change_random(const char *);
1726 static const struct {
1729 void (*func)(const char *);
1730 } varinit_data[] = {
1732 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1734 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1737 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1738 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1740 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1741 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1742 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1743 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1744 #if ENABLE_ASH_GETOPTS
1745 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1747 #if ENABLE_ASH_RANDOM_SUPPORT
1748 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1750 #if ENABLE_LOCALE_SUPPORT
1751 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1752 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1754 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1755 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1760 struct globals_var {
1761 struct shparam shellparam; /* $@ current positional parameters */
1762 struct redirtab *redirlist;
1764 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1765 struct var *vartab[VTABSIZE];
1766 struct var varinit[ARRAY_SIZE(varinit_data)];
1768 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1769 static struct globals_var *const ptr_to_globals_var __attribute__ ((section (".data")));
1770 #define G_var (*ptr_to_globals_var)
1771 #define shellparam (G_var.shellparam )
1772 #define redirlist (G_var.redirlist )
1773 #define g_nullredirs (G_var.g_nullredirs )
1774 #define preverrout_fd (G_var.preverrout_fd)
1775 #define vartab (G_var.vartab )
1776 #define varinit (G_var.varinit )
1777 #define INIT_G_var() do { \
1779 (*(struct globals_var**)&ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1780 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1781 varinit[i].flags = varinit_data[i].flags; \
1782 varinit[i].text = varinit_data[i].text; \
1783 varinit[i].func = varinit_data[i].func; \
1787 #define vifs varinit[0]
1789 #define vmail (&vifs)[1]
1790 #define vmpath (&vmail)[1]
1794 #define vpath (&vmpath)[1]
1795 #define vps1 (&vpath)[1]
1796 #define vps2 (&vps1)[1]
1797 #define vps4 (&vps2)[1]
1798 #define voptind (&vps4)[1]
1799 #if ENABLE_ASH_GETOPTS
1800 #define vrandom (&voptind)[1]
1802 #define vrandom (&vps4)[1]
1806 * The following macros access the values of the above variables.
1807 * They have to skip over the name. They return the null string
1808 * for unset variables.
1810 #define ifsval() (vifs.text + 4)
1811 #define ifsset() ((vifs.flags & VUNSET) == 0)
1812 #define mailval() (vmail.text + 5)
1813 #define mpathval() (vmpath.text + 9)
1814 #define pathval() (vpath.text + 5)
1815 #define ps1val() (vps1.text + 4)
1816 #define ps2val() (vps2.text + 4)
1817 #define ps4val() (vps4.text + 4)
1818 #define optindval() (voptind.text + 7)
1820 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1823 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1824 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1826 #if ENABLE_ASH_GETOPTS
1828 getoptsreset(const char *value)
1830 shellparam.optind = number(value);
1831 shellparam.optoff = -1;
1836 * Return of a legal variable name (a letter or underscore followed by zero or
1837 * more letters, underscores, and digits).
1840 endofname(const char *name)
1848 if (!is_in_name(*p))
1855 * Compares two strings up to the first = or '\0'. The first
1856 * string must be terminated by '='; the second may be terminated by
1857 * either '=' or '\0'.
1860 varcmp(const char *p, const char *q)
1864 while ((c = *p) == (d = *q)) {
1879 varequal(const char *a, const char *b)
1881 return !varcmp(a, b);
1885 * Find the appropriate entry in the hash table from the name.
1887 static struct var **
1888 hashvar(const char *p)
1892 hashval = ((unsigned char) *p) << 4;
1893 while (*p && *p != '=')
1894 hashval += (unsigned char) *p++;
1895 return &vartab[hashval % VTABSIZE];
1899 vpcmp(const void *a, const void *b)
1901 return varcmp(*(const char **)a, *(const char **)b);
1905 * This routine initializes the builtin variables.
1915 * PS1 depends on uid
1917 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1918 vps1.text = "PS1=\\w \\$ ";
1921 vps1.text = "PS1=# ";
1924 end = vp + ARRAY_SIZE(varinit);
1926 vpp = hashvar(vp->text);
1929 } while (++vp < end);
1932 static struct var **
1933 findvar(struct var **vpp, const char *name)
1935 for (; *vpp; vpp = &(*vpp)->next) {
1936 if (varequal((*vpp)->text, name)) {
1944 * Find the value of a variable. Returns NULL if not set.
1947 lookupvar(const char *name)
1951 v = *findvar(hashvar(name), name);
1955 * Dynamic variables are implemented roughly the same way they are
1956 * in bash. Namely, they're "special" so long as they aren't unset.
1957 * As soon as they're unset, they're no longer dynamic, and dynamic
1958 * lookup will no longer happen at that point. -- PFM.
1960 if ((v->flags & VDYNAMIC))
1963 if (!(v->flags & VUNSET))
1964 return strchrnul(v->text, '=') + 1;
1970 * Search the environment of a builtin command.
1973 bltinlookup(const char *name)
1977 for (sp = cmdenviron; sp; sp = sp->next) {
1978 if (varequal(sp->text, name))
1979 return strchrnul(sp->text, '=') + 1;
1981 return lookupvar(name);
1985 * Same as setvar except that the variable and value are passed in
1986 * the first argument as name=value. Since the first argument will
1987 * be actually stored in the table, it should not be a string that
1989 * Called with interrupts off.
1992 setvareq(char *s, int flags)
1994 struct var *vp, **vpp;
1997 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1998 vp = *findvar(vpp, s);
2000 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2003 if (flags & VNOSAVE)
2006 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2012 if (vp->func && (flags & VNOFUNC) == 0)
2013 (*vp->func)(strchrnul(s, '=') + 1);
2015 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2016 free((char*)vp->text);
2018 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2023 vp = ckmalloc(sizeof(*vp));
2028 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2035 * Set the value of a variable. The flags argument is ored with the
2036 * flags of the variable. If val is NULL, the variable is unset.
2039 setvar(const char *name, const char *val, int flags)
2046 q = endofname(name);
2047 p = strchrnul(q, '=');
2049 if (!namelen || p != q)
2050 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2055 vallen = strlen(val);
2058 nameeq = ckmalloc(namelen + vallen + 2);
2059 p = memcpy(nameeq, name, namelen) + namelen;
2062 p = memcpy(p, val, vallen) + vallen;
2065 setvareq(nameeq, flags | VNOSAVE);
2069 #if ENABLE_ASH_GETOPTS
2071 * Safe version of setvar, returns 1 on success 0 on failure.
2074 setvarsafe(const char *name, const char *val, int flags)
2077 volatile int saveint;
2078 struct jmploc *volatile savehandler = exception_handler;
2079 struct jmploc jmploc;
2082 if (setjmp(jmploc.loc))
2085 exception_handler = &jmploc;
2086 setvar(name, val, flags);
2089 exception_handler = savehandler;
2090 RESTORE_INT(saveint);
2096 * Unset the specified variable.
2099 unsetvar(const char *s)
2105 vpp = findvar(hashvar(s), s);
2109 int flags = vp->flags;
2112 if (flags & VREADONLY)
2115 vp->flags &= ~VDYNAMIC;
2119 if ((flags & VSTRFIXED) == 0) {
2121 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2122 free((char*)vp->text);
2128 vp->flags &= ~VEXPORT;
2138 * Process a linked list of variable assignments.
2141 listsetvar(struct strlist *list_set_var, int flags)
2143 struct strlist *lp = list_set_var;
2149 setvareq(lp->text, flags);
2156 * Generate a list of variables satisfying the given conditions.
2159 listvars(int on, int off, char ***end)
2170 for (vp = *vpp; vp; vp = vp->next) {
2171 if ((vp->flags & mask) == on) {
2172 if (ep == stackstrend())
2173 ep = growstackstr();
2174 *ep++ = (char *) vp->text;
2177 } while (++vpp < vartab + VTABSIZE);
2178 if (ep == stackstrend())
2179 ep = growstackstr();
2183 return grabstackstr(ep);
2187 /* ============ Path search helper
2189 * The variable path (passed by reference) should be set to the start
2190 * of the path before the first call; padvance will update
2191 * this value as it proceeds. Successive calls to padvance will return
2192 * the possible path expansions in sequence. If an option (indicated by
2193 * a percent sign) appears in the path entry then the global variable
2194 * pathopt will be set to point to it; otherwise pathopt will be set to
2197 static const char *pathopt; /* set by padvance */
2200 padvance(const char **path, const char *name)
2210 for (p = start; *p && *p != ':' && *p != '%'; p++);
2211 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2212 while (stackblocksize() < len)
2216 memcpy(q, start, p - start);
2224 while (*p && *p != ':') p++;
2230 return stalloc(len);
2234 /* ============ Prompt */
2236 static smallint doprompt; /* if set, prompt the user */
2237 static smallint needprompt; /* true if interactive and at start of line */
2239 #if ENABLE_FEATURE_EDITING
2240 static line_input_t *line_input_state;
2241 static const char *cmdedit_prompt;
2243 putprompt(const char *s)
2245 if (ENABLE_ASH_EXPAND_PRMT) {
2246 free((char*)cmdedit_prompt);
2247 cmdedit_prompt = ckstrdup(s);
2254 putprompt(const char *s)
2260 #if ENABLE_ASH_EXPAND_PRMT
2261 /* expandstr() needs parsing machinery, so it is far away ahead... */
2262 static const char *expandstr(const char *ps);
2264 #define expandstr(s) s
2268 setprompt(int whichprompt)
2271 #if ENABLE_ASH_EXPAND_PRMT
2272 struct stackmark smark;
2277 switch (whichprompt) {
2287 #if ENABLE_ASH_EXPAND_PRMT
2288 setstackmark(&smark);
2289 stalloc(stackblocksize());
2291 putprompt(expandstr(prompt));
2292 #if ENABLE_ASH_EXPAND_PRMT
2293 popstackmark(&smark);
2298 /* ============ The cd and pwd commands */
2300 #define CD_PHYSICAL 1
2303 static int docd(const char *, int);
2312 while ((i = nextopt("LP"))) {
2314 flags ^= CD_PHYSICAL;
2323 * Update curdir (the name of the current directory) in response to a
2327 updatepwd(const char *dir)
2334 cdcomppath = ststrdup(dir);
2337 if (curdir == nullstr)
2339 new = stack_putstr(curdir, new);
2341 new = makestrspace(strlen(dir) + 2, new);
2342 lim = stackblock() + 1;
2346 if (new > lim && *lim == '/')
2351 if (dir[1] == '/' && dir[2] != '/') {
2357 p = strtok(cdcomppath, "/");
2361 if (p[1] == '.' && p[2] == '\0') {
2373 new = stack_putstr(p, new);
2381 return stackblock();
2385 * Find out what the current directory is. If we already know the current
2386 * directory, this routine returns immediately.
2391 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2392 return dir ? dir : nullstr;
2396 setpwd(const char *val, int setold)
2400 oldcur = dir = curdir;
2403 setvar("OLDPWD", oldcur, VEXPORT);
2406 if (physdir != nullstr) {
2407 if (physdir != oldcur)
2411 if (oldcur == val || !val) {
2417 dir = ckstrdup(val);
2418 if (oldcur != dir && oldcur != nullstr) {
2423 setvar("PWD", dir, VEXPORT);
2426 static void hashcd(void);
2429 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2430 * know that the current directory has changed.
2433 docd(const char *dest, int flags)
2435 const char *dir = 0;
2438 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2441 if (!(flags & CD_PHYSICAL)) {
2442 dir = updatepwd(dest);
2457 cdcmd(int argc, char **argv)
2469 dest = bltinlookup(homestr);
2470 else if (LONE_DASH(dest)) {
2471 dest = bltinlookup("OLDPWD");
2493 path = bltinlookup("CDPATH");
2502 p = padvance(&path, dest);
2503 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2507 if (!docd(p, flags))
2512 ash_msg_and_raise_error("can't cd to %s", dest);
2515 if (flags & CD_PRINT)
2516 out1fmt(snlfmt, curdir);
2521 pwdcmd(int argc, char **argv)
2524 const char *dir = curdir;
2528 if (physdir == nullstr)
2532 out1fmt(snlfmt, dir);
2537 /* ============ ... */
2539 #define IBUFSIZ COMMON_BUFSIZE
2540 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2542 /* Syntax classes */
2543 #define CWORD 0 /* character is nothing special */
2544 #define CNL 1 /* newline character */
2545 #define CBACK 2 /* a backslash character */
2546 #define CSQUOTE 3 /* single quote */
2547 #define CDQUOTE 4 /* double quote */
2548 #define CENDQUOTE 5 /* a terminating quote */
2549 #define CBQUOTE 6 /* backwards single quote */
2550 #define CVAR 7 /* a dollar sign */
2551 #define CENDVAR 8 /* a '}' character */
2552 #define CLP 9 /* a left paren in arithmetic */
2553 #define CRP 10 /* a right paren in arithmetic */
2554 #define CENDFILE 11 /* end of file */
2555 #define CCTL 12 /* like CWORD, except it must be escaped */
2556 #define CSPCL 13 /* these terminate a word */
2557 #define CIGN 14 /* character should be ignored */
2559 #if ENABLE_ASH_ALIAS
2563 #define PEOA_OR_PEOF PEOA
2567 #define PEOA_OR_PEOF PEOF
2570 /* number syntax index */
2571 #define BASESYNTAX 0 /* not in quotes */
2572 #define DQSYNTAX 1 /* in double quotes */
2573 #define SQSYNTAX 2 /* in single quotes */
2574 #define ARISYNTAX 3 /* in arithmetic */
2575 #define PSSYNTAX 4 /* prompt */
2577 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2578 #define USE_SIT_FUNCTION
2581 #if ENABLE_ASH_MATH_SUPPORT
2582 static const char S_I_T[][4] = {
2583 #if ENABLE_ASH_ALIAS
2584 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2586 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2587 { CNL, CNL, CNL, CNL }, /* 2, \n */
2588 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2589 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2590 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2591 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2592 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2593 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2594 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2595 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2596 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2597 #ifndef USE_SIT_FUNCTION
2598 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2599 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2600 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2604 static const char S_I_T[][3] = {
2605 #if ENABLE_ASH_ALIAS
2606 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2608 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2609 { CNL, CNL, CNL }, /* 2, \n */
2610 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2611 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2612 { CVAR, CVAR, CWORD }, /* 5, $ */
2613 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2614 { CSPCL, CWORD, CWORD }, /* 7, ( */
2615 { CSPCL, CWORD, CWORD }, /* 8, ) */
2616 { CBACK, CBACK, CCTL }, /* 9, \ */
2617 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2618 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2619 #ifndef USE_SIT_FUNCTION
2620 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2621 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2622 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2625 #endif /* ASH_MATH_SUPPORT */
2627 #ifdef USE_SIT_FUNCTION
2630 SIT(int c, int syntax)
2632 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2633 #if ENABLE_ASH_ALIAS
2634 static const char syntax_index_table[] ALIGN1 = {
2635 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2636 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2637 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2641 static const char syntax_index_table[] ALIGN1 = {
2642 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2643 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2644 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2651 if (c == PEOF) /* 2^8+2 */
2653 #if ENABLE_ASH_ALIAS
2654 if (c == PEOA) /* 2^8+1 */
2658 #define U_C(c) ((unsigned char)(c))
2660 if ((unsigned char)c >= (unsigned char)(CTLESC)
2661 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2665 s = strchr(spec_symbls, c);
2666 if (s == NULL || *s == '\0')
2668 indx = syntax_index_table[(s - spec_symbls)];
2670 return S_I_T[indx][syntax];
2673 #else /* !USE_SIT_FUNCTION */
2675 #if ENABLE_ASH_ALIAS
2676 #define CSPCL_CIGN_CIGN_CIGN 0
2677 #define CSPCL_CWORD_CWORD_CWORD 1
2678 #define CNL_CNL_CNL_CNL 2
2679 #define CWORD_CCTL_CCTL_CWORD 3
2680 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2681 #define CVAR_CVAR_CWORD_CVAR 5
2682 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2683 #define CSPCL_CWORD_CWORD_CLP 7
2684 #define CSPCL_CWORD_CWORD_CRP 8
2685 #define CBACK_CBACK_CCTL_CBACK 9
2686 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2687 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2688 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2689 #define CWORD_CWORD_CWORD_CWORD 13
2690 #define CCTL_CCTL_CCTL_CCTL 14
2692 #define CSPCL_CWORD_CWORD_CWORD 0
2693 #define CNL_CNL_CNL_CNL 1
2694 #define CWORD_CCTL_CCTL_CWORD 2
2695 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2696 #define CVAR_CVAR_CWORD_CVAR 4
2697 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2698 #define CSPCL_CWORD_CWORD_CLP 6
2699 #define CSPCL_CWORD_CWORD_CRP 7
2700 #define CBACK_CBACK_CCTL_CBACK 8
2701 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2702 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2703 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2704 #define CWORD_CWORD_CWORD_CWORD 12
2705 #define CCTL_CCTL_CCTL_CCTL 13
2708 static const char syntax_index_table[258] = {
2709 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2710 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2711 #if ENABLE_ASH_ALIAS
2712 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2714 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2715 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2716 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2717 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2718 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2719 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2720 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2721 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2722 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2723 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2853 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2875 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2876 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2877 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2879 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2881 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2882 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2883 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2884 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2885 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2887 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2888 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2889 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2935 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2939 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2967 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2968 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2969 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2972 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2974 #endif /* USE_SIT_FUNCTION */
2977 /* ============ Alias handling */
2979 #if ENABLE_ASH_ALIAS
2981 #define ALIASINUSE 1
2992 static struct alias **atab; // [ATABSIZE];
2993 #define INIT_G_alias() do { \
2994 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
2998 static struct alias **
2999 __lookupalias(const char *name) {
3000 unsigned int hashval;
3007 ch = (unsigned char)*p;
3011 ch = (unsigned char)*++p;
3013 app = &atab[hashval % ATABSIZE];
3015 for (; *app; app = &(*app)->next) {
3016 if (strcmp(name, (*app)->name) == 0) {
3024 static struct alias *
3025 lookupalias(const char *name, int check)
3027 struct alias *ap = *__lookupalias(name);
3029 if (check && ap && (ap->flag & ALIASINUSE))
3034 static struct alias *
3035 freealias(struct alias *ap)
3039 if (ap->flag & ALIASINUSE) {
3040 ap->flag |= ALIASDEAD;
3052 setalias(const char *name, const char *val)
3054 struct alias *ap, **app;
3056 app = __lookupalias(name);
3060 if (!(ap->flag & ALIASINUSE)) {
3063 ap->val = ckstrdup(val);
3064 ap->flag &= ~ALIASDEAD;
3067 ap = ckmalloc(sizeof(struct alias));
3068 ap->name = ckstrdup(name);
3069 ap->val = ckstrdup(val);
3078 unalias(const char *name)
3082 app = __lookupalias(name);
3086 *app = freealias(*app);
3097 struct alias *ap, **app;
3101 for (i = 0; i < ATABSIZE; i++) {
3103 for (ap = *app; ap; ap = *app) {
3104 *app = freealias(*app);
3114 printalias(const struct alias *ap)
3116 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3120 * TODO - sort output
3123 aliascmd(int argc, char **argv)
3132 for (i = 0; i < ATABSIZE; i++)
3133 for (ap = atab[i]; ap; ap = ap->next) {
3138 while ((n = *++argv) != NULL) {
3139 v = strchr(n+1, '=');
3140 if (v == NULL) { /* n+1: funny ksh stuff */
3141 ap = *__lookupalias(n);
3143 fprintf(stderr, "%s: %s not found\n", "alias", n);
3157 unaliascmd(int argc, char **argv)
3161 while ((i = nextopt("a")) != '\0') {
3167 for (i = 0; *argptr; argptr++) {
3168 if (unalias(*argptr)) {
3169 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3177 #endif /* ASH_ALIAS */
3180 /* ============ jobs.c */
3182 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3185 #define FORK_NOJOB 2
3187 /* mode flags for showjob(s) */
3188 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3189 #define SHOW_PID 0x04 /* include process pid */
3190 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3193 * A job structure contains information about a job. A job is either a
3194 * single process or a set of processes contained in a pipeline. In the
3195 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3200 pid_t pid; /* process id */
3201 int status; /* last process status from wait() */
3202 char *cmd; /* text of command being run */
3206 struct procstat ps0; /* status of process */
3207 struct procstat *ps; /* status or processes when more than one */
3209 int stopstatus; /* status of a stopped job */
3212 nprocs: 16, /* number of processes */
3214 #define JOBRUNNING 0 /* at least one proc running */
3215 #define JOBSTOPPED 1 /* all procs are stopped */
3216 #define JOBDONE 2 /* all procs are completed */
3218 sigint: 1, /* job was killed by SIGINT */
3219 jobctl: 1, /* job running under job control */
3221 waited: 1, /* true if this entry has been waited for */
3222 used: 1, /* true if this entry is in used */
3223 changed: 1; /* true if status has changed */
3224 struct job *prev_job; /* previous job */
3227 static pid_t backgndpid; /* pid of last background process */
3228 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3230 static struct job *makejob(union node *, int);
3231 static int forkshell(struct job *, union node *, int);
3232 static int waitforjob(struct job *);
3235 enum { jobctl = 0 };
3236 #define setjobctl(on) do {} while (0)
3238 static smallint jobctl; /* true if doing job control */
3239 static void setjobctl(int);
3243 * Set the signal handler for the specified signal. The routine figures
3244 * out what it should be set to.
3247 setsignal(int signo)
3251 struct sigaction act;
3257 else if (*t != '\0')
3259 if (rootshell && action == S_DFL) {
3262 if (iflag || minusc || sflag == 0)
3285 t = &sigmode[signo - 1];
3289 * current setting unknown
3291 if (sigaction(signo, NULL, &act) == -1) {
3293 * Pretend it worked; maybe we should give a warning
3294 * here, but other shells don't. We don't alter
3295 * sigmode, so that we retry every time.
3299 tsig = S_RESET; /* force to be set */
3300 if (act.sa_handler == SIG_IGN) {
3303 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3305 tsig = S_IGN; /* don't hard ignore these */
3309 if (tsig == S_HARD_IGN || tsig == action)
3311 act.sa_handler = SIG_DFL;
3314 act.sa_handler = onsig;
3317 act.sa_handler = SIG_IGN;
3322 sigfillset(&act.sa_mask);
3323 sigaction(signo, &act, NULL);
3326 /* mode flags for set_curjob */
3327 #define CUR_DELETE 2
3328 #define CUR_RUNNING 1
3329 #define CUR_STOPPED 0
3331 /* mode flags for dowait */
3332 #define DOWAIT_NONBLOCK WNOHANG
3333 #define DOWAIT_BLOCK 0
3336 /* pgrp of shell on invocation */
3337 static int initialpgrp;
3338 static int ttyfd = -1;
3341 static struct job *jobtab;
3343 static unsigned njobs;
3345 static struct job *curjob;
3346 /* number of presumed living untracked jobs */
3350 set_curjob(struct job *jp, unsigned mode)
3353 struct job **jpp, **curp;
3355 /* first remove from list */
3356 jpp = curp = &curjob;
3361 jpp = &jp1->prev_job;
3363 *jpp = jp1->prev_job;
3365 /* Then re-insert in correct position */
3373 /* job being deleted */
3376 /* newly created job or backgrounded job,
3377 put after all stopped jobs. */
3381 if (!jp1 || jp1->state != JOBSTOPPED)
3384 jpp = &jp1->prev_job;
3390 /* newly stopped job - becomes curjob */
3391 jp->prev_job = *jpp;
3399 jobno(const struct job *jp)
3401 return jp - jobtab + 1;
3406 * Convert a job name to a job structure.
3409 getjob(const char *name, int getctl)
3413 const char *err_msg = "No such job: %s";
3417 char *(*match)(const char *, const char *);
3432 if (c == '+' || c == '%') {
3434 err_msg = "No current job";
3440 err_msg = "No previous job";
3451 jp = jobtab + num - 1;
3468 if (match(jp->ps[0].cmd, p)) {
3472 err_msg = "%s: ambiguous";
3479 err_msg = "job %s not created under job control";
3480 if (getctl && jp->jobctl == 0)
3485 ash_msg_and_raise_error(err_msg, name);
3489 * Mark a job structure as unused.
3492 freejob(struct job *jp)
3494 struct procstat *ps;
3498 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3499 if (ps->cmd != nullstr)
3502 if (jp->ps != &jp->ps0)
3505 set_curjob(jp, CUR_DELETE);
3511 xtcsetpgrp(int fd, pid_t pgrp)
3513 if (tcsetpgrp(fd, pgrp))
3514 ash_msg_and_raise_error("cannot set tty process group (%m)");
3518 * Turn job control on and off.
3520 * Note: This code assumes that the third arg to ioctl is a character
3521 * pointer, which is true on Berkeley systems but not System V. Since
3522 * System V doesn't have job control yet, this isn't a problem now.
3524 * Called with interrupts off.
3532 if (on == jobctl || rootshell == 0)
3536 ofd = fd = open(_PATH_TTY, O_RDWR);
3538 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3539 * That sometimes helps to acquire controlling tty.
3540 * Obviously, a workaround for bugs when someone
3541 * failed to provide a controlling tty to bash! :) */
3547 fd = fcntl(fd, F_DUPFD, 10);
3552 /* fd is a tty at this point */
3553 close_on_exec_on(fd);
3554 do { /* while we are in the background */
3555 pgrp = tcgetpgrp(fd);
3558 ash_msg("can't access tty; job control turned off");
3562 if (pgrp == getpgrp())
3573 xtcsetpgrp(fd, pgrp);
3575 /* turning job control off */
3578 /* was xtcsetpgrp, but this can make exiting ash
3579 * loop forever if pty is already deleted */
3580 tcsetpgrp(fd, pgrp);
3595 killcmd(int argc, char **argv)
3597 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3600 if (argv[i][0] == '%') {
3601 struct job *jp = getjob(argv[i], 0);
3602 unsigned pid = jp->ps[0].pid;
3603 /* Enough space for ' -NNN<nul>' */
3604 argv[i] = alloca(sizeof(int)*3 + 3);
3605 /* kill_main has matching code to expect
3606 * leading space. Needed to not confuse
3607 * negative pids with "kill -SIGNAL_NO" syntax */
3608 sprintf(argv[i], " -%u", pid);
3610 } while (argv[++i]);
3612 return kill_main(argc, argv);
3616 showpipe(struct job *jp, FILE *out)
3618 struct procstat *sp;
3619 struct procstat *spend;
3621 spend = jp->ps + jp->nprocs;
3622 for (sp = jp->ps + 1; sp < spend; sp++)
3623 fprintf(out, " | %s", sp->cmd);
3624 outcslow('\n', out);
3625 flush_stdout_stderr();
3630 restartjob(struct job *jp, int mode)
3632 struct procstat *ps;
3638 if (jp->state == JOBDONE)
3640 jp->state = JOBRUNNING;
3642 if (mode == FORK_FG)
3643 xtcsetpgrp(ttyfd, pgid);
3644 killpg(pgid, SIGCONT);
3648 if (WIFSTOPPED(ps->status)) {
3654 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3660 fg_bgcmd(int argc, char **argv)
3667 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3672 jp = getjob(*argv, 1);
3673 if (mode == FORK_BG) {
3674 set_curjob(jp, CUR_RUNNING);
3675 fprintf(out, "[%d] ", jobno(jp));
3677 outstr(jp->ps->cmd, out);
3679 retval = restartjob(jp, mode);
3680 } while (*argv && *++argv);
3686 sprint_status(char *s, int status, int sigonly)
3692 if (!WIFEXITED(status)) {
3694 if (WIFSTOPPED(status))
3695 st = WSTOPSIG(status);
3698 st = WTERMSIG(status);
3700 if (st == SIGINT || st == SIGPIPE)
3703 if (WIFSTOPPED(status))
3708 col = fmtstr(s, 32, strsignal(st));
3709 if (WCOREDUMP(status)) {
3710 col += fmtstr(s + col, 16, " (core dumped)");
3712 } else if (!sigonly) {
3713 st = WEXITSTATUS(status);
3715 col = fmtstr(s, 16, "Done(%d)", st);
3717 col = fmtstr(s, 16, "Done");
3724 * Do a wait system call. If job control is compiled in, we accept
3725 * stopped processes. If block is zero, we return a value of zero
3726 * rather than blocking.
3728 * System V doesn't have a non-blocking wait system call. It does
3729 * have a SIGCLD signal that is sent to a process when one of it's
3730 * children dies. The obvious way to use SIGCLD would be to install
3731 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3732 * was received, and have waitproc bump another counter when it got
3733 * the status of a process. Waitproc would then know that a wait
3734 * system call would not block if the two counters were different.
3735 * This approach doesn't work because if a process has children that
3736 * have not been waited for, System V will send it a SIGCLD when it
3737 * installs a signal handler for SIGCLD. What this means is that when
3738 * a child exits, the shell will be sent SIGCLD signals continuously
3739 * until is runs out of stack space, unless it does a wait call before
3740 * restoring the signal handler. The code below takes advantage of
3741 * this (mis)feature by installing a signal handler for SIGCLD and
3742 * then checking to see whether it was called. If there are any
3743 * children to be waited for, it will be.
3745 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3746 * waits at all. In this case, the user will not be informed when
3747 * a background process until the next time she runs a real program
3748 * (as opposed to running a builtin command or just typing return),
3749 * and the jobs command may give out of date information.
3752 waitproc(int wait_flags, int *status)
3756 wait_flags |= WUNTRACED;
3758 /* NB: _not_ safe_waitpid, we need to detect EINTR */
3759 return waitpid(-1, status, wait_flags);
3763 * Wait for a process to terminate.
3766 dowait(int wait_flags, struct job *job)
3771 struct job *thisjob;
3774 TRACE(("dowait(%d) called\n", wait_flags));
3775 pid = waitproc(wait_flags, &status);
3776 TRACE(("wait returns pid=%d, status=%d\n", pid, status));
3778 /* If we were doing blocking wait and (probably) got EINTR,
3779 * check for pending sigs received while waiting.
3780 * (NB: can be moved into callers if needed) */
3781 if (wait_flags == DOWAIT_BLOCK && pendingsig)
3782 raise_exception(EXSIG);
3787 for (jp = curjob; jp; jp = jp->prev_job) {
3788 struct procstat *sp;
3789 struct procstat *spend;
3790 if (jp->state == JOBDONE)
3793 spend = jp->ps + jp->nprocs;
3796 if (sp->pid == pid) {
3797 TRACE(("Job %d: changing status of proc %d "
3798 "from 0x%x to 0x%x\n",
3799 jobno(jp), pid, sp->status, status));
3800 sp->status = status;
3803 if (sp->status == -1)
3806 if (state == JOBRUNNING)
3808 if (WIFSTOPPED(sp->status)) {
3809 jp->stopstatus = sp->status;
3813 } while (++sp < spend);
3818 if (!WIFSTOPPED(status))
3824 if (state != JOBRUNNING) {
3825 thisjob->changed = 1;
3827 if (thisjob->state != state) {
3828 TRACE(("Job %d: changing state from %d to %d\n",
3829 jobno(thisjob), thisjob->state, state));
3830 thisjob->state = state;
3832 if (state == JOBSTOPPED) {
3833 set_curjob(thisjob, CUR_STOPPED);
3842 if (thisjob && thisjob == job) {
3846 len = sprint_status(s, status, 1);
3858 showjob(FILE *out, struct job *jp, int mode)
3860 struct procstat *ps;
3861 struct procstat *psend;
3868 if (mode & SHOW_PGID) {
3869 /* just output process (group) id of pipeline */
3870 fprintf(out, "%d\n", ps->pid);
3874 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3879 else if (curjob && jp == curjob->prev_job)
3882 if (mode & SHOW_PID)
3883 col += fmtstr(s + col, 16, "%d ", ps->pid);
3885 psend = ps + jp->nprocs;
3887 if (jp->state == JOBRUNNING) {
3888 strcpy(s + col, "Running");
3889 col += sizeof("Running") - 1;
3891 int status = psend[-1].status;
3892 if (jp->state == JOBSTOPPED)
3893 status = jp->stopstatus;
3894 col += sprint_status(s + col, status, 0);
3900 /* for each process */
3901 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3903 fprintf(out, "%s%*c%s",
3904 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3906 if (!(mode & SHOW_PID)) {
3910 if (++ps == psend) {
3911 outcslow('\n', out);
3918 if (jp->state == JOBDONE) {
3919 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3925 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3926 * statuses have changed since the last call to showjobs.
3929 showjobs(FILE *out, int mode)
3933 TRACE(("showjobs(%x) called\n", mode));
3935 /* If not even one job changed, there is nothing to do */
3936 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3939 for (jp = curjob; jp; jp = jp->prev_job) {
3940 if (!(mode & SHOW_CHANGED) || jp->changed) {
3941 showjob(out, jp, mode);
3947 jobscmd(int argc, char **argv)
3952 while ((m = nextopt("lp"))) {
3962 showjob(stdout, getjob(*argv,0), mode);
3965 showjobs(stdout, mode);
3972 getstatus(struct job *job)
3977 status = job->ps[job->nprocs - 1].status;
3978 retval = WEXITSTATUS(status);
3979 if (!WIFEXITED(status)) {
3981 retval = WSTOPSIG(status);
3982 if (!WIFSTOPPED(status))
3985 /* XXX: limits number of signals */
3986 retval = WTERMSIG(status);
3988 if (retval == SIGINT)
3994 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3995 jobno(job), job->nprocs, status, retval));
4000 waitcmd(int argc, char **argv)
4009 raise_exception(EXSIG);
4016 /* wait for all jobs */
4020 if (!jp) /* no running procs */
4022 if (jp->state == JOBRUNNING)
4027 dowait(DOWAIT_BLOCK, NULL);
4033 if (**argv != '%') {
4034 pid_t pid = number(*argv);
4039 if (job->ps[job->nprocs - 1].pid == pid)
4041 job = job->prev_job;
4044 job = getjob(*argv, 0);
4045 /* loop until process terminated or stopped */
4046 while (job->state == JOBRUNNING)
4047 dowait(DOWAIT_BLOCK, NULL);
4049 retval = getstatus(job);
4063 struct job *jp, *jq;
4065 len = njobs * sizeof(*jp);
4067 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4069 offset = (char *)jp - (char *)jq;
4071 /* Relocate pointers */
4074 jq = (struct job *)((char *)jq + l);
4078 #define joff(p) ((struct job *)((char *)(p) + l))
4079 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4080 if (joff(jp)->ps == &jq->ps0)
4081 jmove(joff(jp)->ps);
4082 if (joff(jp)->prev_job)
4083 jmove(joff(jp)->prev_job);
4093 jp = (struct job *)((char *)jp + len);
4097 } while (--jq >= jp);
4102 * Return a new job structure.
4103 * Called with interrupts off.
4106 makejob(union node *node, int nprocs)
4111 for (i = njobs, jp = jobtab; ; jp++) {
4118 if (jp->state != JOBDONE || !jp->waited)
4127 memset(jp, 0, sizeof(*jp));
4129 /* jp->jobctl is a bitfield.
4130 * "jp->jobctl |= jobctl" likely to give awful code */
4134 jp->prev_job = curjob;
4139 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4141 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4148 * Return a string identifying a command (to be printed by the
4151 static char *cmdnextc;
4154 cmdputs(const char *s)
4156 const char *p, *str;
4157 char c, cc[2] = " ";
4161 static const char vstype[VSTYPE + 1][4] = {
4162 "", "}", "-", "+", "?", "=",
4163 "%", "%%", "#", "##"
4166 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4168 while ((c = *p++) != 0) {
4176 if ((subtype & VSTYPE) == VSLENGTH)
4180 if (!(subtype & VSQUOTE) == !(quoted & 1))
4186 str = "\"}" + !(quoted & 1);
4193 case CTLBACKQ+CTLQUOTE:
4196 #if ENABLE_ASH_MATH_SUPPORT
4211 if ((subtype & VSTYPE) != VSNORMAL)
4213 str = vstype[subtype & VSTYPE];
4214 if (subtype & VSNUL)
4223 /* These can only happen inside quotes */
4236 while ((c = *str++)) {
4241 USTPUTC('"', nextc);
4247 /* cmdtxt() and cmdlist() call each other */
4248 static void cmdtxt(union node *n);
4251 cmdlist(union node *np, int sep)
4253 for (; np; np = np->narg.next) {
4257 if (sep && np->narg.next)
4263 cmdtxt(union node *n)
4266 struct nodelist *lp;
4278 lp = n->npipe.cmdlist;
4296 cmdtxt(n->nbinary.ch1);
4312 cmdtxt(n->nif.test);
4315 if (n->nif.elsepart) {
4318 n = n->nif.elsepart;
4334 cmdtxt(n->nbinary.ch1);
4344 cmdputs(n->nfor.var);
4346 cmdlist(n->nfor.args, 1);
4351 cmdputs(n->narg.text);
4355 cmdlist(n->ncmd.args, 1);
4356 cmdlist(n->ncmd.redirect, 0);
4369 cmdputs(n->ncase.expr->narg.text);
4371 for (np = n->ncase.cases; np; np = np->nclist.next) {
4372 cmdtxt(np->nclist.pattern);
4374 cmdtxt(np->nclist.body);
4400 s[0] = n->nfile.fd + '0';
4404 if (n->type == NTOFD || n->type == NFROMFD) {
4405 s[0] = n->ndup.dupfd + '0';
4415 commandtext(union node *n)
4419 STARTSTACKSTR(cmdnextc);
4421 name = stackblock();
4422 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4423 name, cmdnextc, cmdnextc));
4424 return ckstrdup(name);
4429 * Fork off a subshell. If we are doing job control, give the subshell its
4430 * own process group. Jp is a job structure that the job is to be added to.
4431 * N is the command that will be evaluated by the child. Both jp and n may
4432 * be NULL. The mode parameter can be one of the following:
4433 * FORK_FG - Fork off a foreground process.
4434 * FORK_BG - Fork off a background process.
4435 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4436 * process group even if job control is on.
4438 * When job control is turned off, background processes have their standard
4439 * input redirected to /dev/null (except for the second and later processes
4442 * Called with interrupts off.
4445 * Clear traps on a fork.
4452 for (tp = trap; tp < &trap[NSIG]; tp++) {
4453 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4458 setsignal(tp - trap);
4464 /* Lives far away from here, needed for forkchild */
4465 static void closescript(void);
4467 /* Called after fork(), in child */
4469 forkchild(struct job *jp, union node *n, int mode)
4473 TRACE(("Child shell %d\n", getpid()));
4480 /* do job control only in root shell */
4482 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4485 if (jp->nprocs == 0)
4488 pgrp = jp->ps[0].pid;
4489 /* This can fail because we are doing it in the parent also */
4490 (void)setpgid(0, pgrp);
4491 if (mode == FORK_FG)
4492 xtcsetpgrp(ttyfd, pgrp);
4497 if (mode == FORK_BG) {
4500 if (jp->nprocs == 0) {
4502 if (open(bb_dev_null, O_RDONLY) != 0)
4503 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4506 if (!oldlvl && iflag) {
4511 for (jp = curjob; jp; jp = jp->prev_job)
4516 /* Called after fork(), in parent */
4518 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4520 TRACE(("In parent shell: child = %d\n", pid));
4522 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4528 if (mode != FORK_NOJOB && jp->jobctl) {
4531 if (jp->nprocs == 0)
4534 pgrp = jp->ps[0].pid;
4535 /* This can fail because we are doing it in the child also */
4539 if (mode == FORK_BG) {
4540 backgndpid = pid; /* set $! */
4541 set_curjob(jp, CUR_RUNNING);
4544 struct procstat *ps = &jp->ps[jp->nprocs++];
4550 ps->cmd = commandtext(n);
4556 forkshell(struct job *jp, union node *n, int mode)
4560 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4563 TRACE(("Fork failed, errno=%d", errno));
4566 ash_msg_and_raise_error("cannot fork");
4569 forkchild(jp, n, mode);
4571 forkparent(jp, n, mode, pid);
4576 * Wait for job to finish.
4578 * Under job control we have the problem that while a child process is
4579 * running interrupts generated by the user are sent to the child but not
4580 * to the shell. This means that an infinite loop started by an inter-
4581 * active user may be hard to kill. With job control turned off, an
4582 * interactive user may place an interactive program inside a loop. If
4583 * the interactive program catches interrupts, the user doesn't want
4584 * these interrupts to also abort the loop. The approach we take here
4585 * is to have the shell ignore interrupt signals while waiting for a
4586 * foreground process to terminate, and then send itself an interrupt
4587 * signal if the child process was terminated by an interrupt signal.
4588 * Unfortunately, some programs want to do a bit of cleanup and then
4589 * exit on interrupt; unless these processes terminate themselves by
4590 * sending a signal to themselves (instead of calling exit) they will
4591 * confuse this approach.
4593 * Called with interrupts off.
4596 waitforjob(struct job *jp)
4600 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4601 while (jp->state == JOBRUNNING) {
4602 dowait(DOWAIT_BLOCK, jp);
4607 xtcsetpgrp(ttyfd, rootpid);
4609 * This is truly gross.
4610 * If we're doing job control, then we did a TIOCSPGRP which
4611 * caused us (the shell) to no longer be in the controlling
4612 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4613 * intuit from the subprocess exit status whether a SIGINT
4614 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4616 if (jp->sigint) /* TODO: do the same with all signals */
4617 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4619 if (jp->state == JOBDONE)
4626 * return 1 if there are stopped jobs, otherwise 0
4638 if (jp && jp->state == JOBSTOPPED) {
4639 out2str("You have stopped jobs.\n");
4648 /* ============ redir.c
4650 * Code for dealing with input/output redirection.
4653 #define EMPTY -2 /* marks an unused slot in redirtab */
4654 #define CLOSED -3 /* marks a slot of previously-closed fd */
4656 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4658 # define PIPESIZE PIPE_BUF
4662 * Open a file in noclobber mode.
4663 * The code was copied from bash.
4666 noclobberopen(const char *fname)
4669 struct stat finfo, finfo2;
4672 * If the file exists and is a regular file, return an error
4675 r = stat(fname, &finfo);
4676 if (r == 0 && S_ISREG(finfo.st_mode)) {
4682 * If the file was not present (r != 0), make sure we open it
4683 * exclusively so that if it is created before we open it, our open
4684 * will fail. Make sure that we do not truncate an existing file.
4685 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4686 * file was not a regular file, we leave O_EXCL off.
4689 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4690 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4692 /* If the open failed, return the file descriptor right away. */
4697 * OK, the open succeeded, but the file may have been changed from a
4698 * non-regular file to a regular file between the stat and the open.
4699 * We are assuming that the O_EXCL open handles the case where FILENAME
4700 * did not exist and is symlinked to an existing file between the stat
4705 * If we can open it and fstat the file descriptor, and neither check
4706 * revealed that it was a regular file, and the file has not been
4707 * replaced, return the file descriptor.
4709 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4710 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4713 /* The file has been replaced. badness. */
4720 * Handle here documents. Normally we fork off a process to write the
4721 * data to a pipe. If the document is short, we can stuff the data in
4722 * the pipe without forking.
4724 /* openhere needs this forward reference */
4725 static void expandhere(union node *arg, int fd);
4727 openhere(union node *redir)
4733 ash_msg_and_raise_error("pipe call failed");
4734 if (redir->type == NHERE) {
4735 len = strlen(redir->nhere.doc->narg.text);
4736 if (len <= PIPESIZE) {
4737 full_write(pip[1], redir->nhere.doc->narg.text, len);
4741 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4743 signal(SIGINT, SIG_IGN);
4744 signal(SIGQUIT, SIG_IGN);
4745 signal(SIGHUP, SIG_IGN);
4747 signal(SIGTSTP, SIG_IGN);
4749 signal(SIGPIPE, SIG_DFL);
4750 if (redir->type == NHERE)
4751 full_write(pip[1], redir->nhere.doc->narg.text, len);
4753 expandhere(redir->nhere.doc, pip[1]);
4762 openredirect(union node *redir)
4767 switch (redir->nfile.type) {
4769 fname = redir->nfile.expfname;
4770 f = open(fname, O_RDONLY);
4775 fname = redir->nfile.expfname;
4776 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4781 /* Take care of noclobber mode. */
4783 fname = redir->nfile.expfname;
4784 f = noclobberopen(fname);
4791 fname = redir->nfile.expfname;
4792 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4797 fname = redir->nfile.expfname;
4798 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4806 /* Fall through to eliminate warning. */
4813 f = openhere(redir);
4819 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4821 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4825 * Copy a file descriptor to be >= to. Returns -1
4826 * if the source file descriptor is closed, EMPTY if there are no unused
4827 * file descriptors left.
4830 copyfd(int from, int to)
4834 newfd = fcntl(from, F_DUPFD, to);
4836 if (errno == EMFILE)
4838 ash_msg_and_raise_error("%d: %m", from);
4844 dupredirect(union node *redir, int f)
4846 int fd = redir->nfile.fd;
4848 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4849 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4850 copyfd(redir->ndup.dupfd, fd);
4862 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4863 * old file descriptors are stashed away so that the redirection can be
4864 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4865 * standard output, and the standard error if it becomes a duplicate of
4866 * stdout, is saved in memory.
4868 /* flags passed to redirect */
4869 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4870 #define REDIR_SAVEFD2 03 /* set preverrout */
4872 redirect(union node *redir, int flags)
4875 struct redirtab *sv;
4886 if (flags & REDIR_PUSH) {
4887 sv = ckmalloc(sizeof(*sv));
4888 sv->next = redirlist;
4890 sv->nullredirs = g_nullredirs - 1;
4891 for (i = 0; i < 10; i++)
4892 sv->renamed[i] = EMPTY;
4898 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4899 && n->ndup.dupfd == fd)
4900 continue; /* redirect from/to same file descriptor */
4902 newfd = openredirect(n);
4904 /* Descriptor wasn't open before redirect.
4905 * Mark it for close in the future */
4906 if (sv && sv->renamed[fd] == EMPTY)
4907 sv->renamed[fd] = CLOSED;
4910 if (sv && sv->renamed[fd] == EMPTY) {
4911 i = fcntl(fd, F_DUPFD, 10);
4918 ash_msg_and_raise_error("%d: %m", fd);
4922 sv->renamed[fd] = i;
4928 dupredirect(n, newfd);
4929 } while ((n = n->nfile.next));
4931 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
4932 preverrout_fd = sv->renamed[2];
4936 * Undo the effects of the last redirection.
4941 struct redirtab *rp;
4944 if (--g_nullredirs >= 0)
4948 for (i = 0; i < 10; i++) {
4949 if (rp->renamed[i] == CLOSED) {
4954 if (rp->renamed[i] != EMPTY) {
4957 copyfd(rp->renamed[i], i);
4959 close(rp->renamed[i]);
4962 redirlist = rp->next;
4963 g_nullredirs = rp->nullredirs;
4969 * Undo all redirections. Called on error or interrupt.
4973 * Discard all saved file descriptors.
4976 clearredir(int drop)
4987 redirectsafe(union node *redir, int flags)
4990 volatile int saveint;
4991 struct jmploc *volatile savehandler = exception_handler;
4992 struct jmploc jmploc;
4995 err = setjmp(jmploc.loc) * 2;
4997 exception_handler = &jmploc;
4998 redirect(redir, flags);
5000 exception_handler = savehandler;
5001 if (err && exception != EXERROR)
5002 longjmp(exception_handler->loc, 1);
5003 RESTORE_INT(saveint);
5008 /* ============ Routines to expand arguments to commands
5010 * We have to deal with backquotes, shell variables, and file metacharacters.
5016 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5017 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5018 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5019 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5020 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5021 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5022 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5023 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5024 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5028 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5029 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5030 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5031 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5032 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5035 * Structure specifying which parts of the string should be searched
5036 * for IFS characters.
5039 struct ifsregion *next; /* next region in list */
5040 int begoff; /* offset of start of region */
5041 int endoff; /* offset of end of region */
5042 int nulonly; /* search for nul bytes only */
5046 struct strlist *list;
5047 struct strlist **lastp;
5050 /* output of current string */
5051 static char *expdest;
5052 /* list of back quote expressions */
5053 static struct nodelist *argbackq;
5054 /* first struct in list of ifs regions */
5055 static struct ifsregion ifsfirst;
5056 /* last struct in list */
5057 static struct ifsregion *ifslastp;
5058 /* holds expanded arg list */
5059 static struct arglist exparg;
5069 expdest = makestrspace(32, expdest);
5070 #if ENABLE_ASH_MATH_SUPPORT_64
5071 len = fmtstr(expdest, 32, "%lld", (long long) num);
5073 len = fmtstr(expdest, 32, "%ld", num);
5075 STADJUST(len, expdest);
5080 esclen(const char *start, const char *p)
5084 while (p > start && *--p == CTLESC) {
5091 * Remove any CTLESC characters from a string.
5094 _rmescapes(char *str, int flag)
5096 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5103 p = strpbrk(str, qchars);
5109 if (flag & RMESCAPE_ALLOC) {
5110 size_t len = p - str;
5111 size_t fulllen = len + strlen(p) + 1;
5113 if (flag & RMESCAPE_GROW) {
5114 r = makestrspace(fulllen, expdest);
5115 } else if (flag & RMESCAPE_HEAP) {
5116 r = ckmalloc(fulllen);
5118 r = stalloc(fulllen);
5122 q = memcpy(q, str, len) + len;
5125 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5126 globbing = flag & RMESCAPE_GLOB;
5127 notescaped = globbing;
5129 if (*p == CTLQUOTEMARK) {
5130 inquotes = ~inquotes;
5132 notescaped = globbing;
5136 /* naked back slash */
5142 if (notescaped && inquotes && *p != '/') {
5146 notescaped = globbing;
5151 if (flag & RMESCAPE_GROW) {
5153 STADJUST(q - r + 1, expdest);
5157 #define rmescapes(p) _rmescapes((p), 0)
5159 #define pmatch(a, b) !fnmatch((a), (b), 0)
5162 * Prepare a pattern for a expmeta (internal glob(3)) call.
5164 * Returns an stalloced string.
5167 preglob(const char *pattern, int quoted, int flag)
5169 flag |= RMESCAPE_GLOB;
5171 flag |= RMESCAPE_QUOTED;
5173 return _rmescapes((char *)pattern, flag);
5177 * Put a string on the stack.
5180 memtodest(const char *p, size_t len, int syntax, int quotes)
5184 q = makestrspace(len * 2, q);
5187 int c = signed_char2int(*p++);
5190 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5199 strtodest(const char *p, int syntax, int quotes)
5201 memtodest(p, strlen(p), syntax, quotes);
5205 * Record the fact that we have to scan this region of the
5206 * string for IFS characters.
5209 recordregion(int start, int end, int nulonly)
5211 struct ifsregion *ifsp;
5213 if (ifslastp == NULL) {
5217 ifsp = ckmalloc(sizeof(*ifsp));
5219 ifslastp->next = ifsp;
5223 ifslastp->begoff = start;
5224 ifslastp->endoff = end;
5225 ifslastp->nulonly = nulonly;
5229 removerecordregions(int endoff)
5231 if (ifslastp == NULL)
5234 if (ifsfirst.endoff > endoff) {
5235 while (ifsfirst.next != NULL) {
5236 struct ifsregion *ifsp;
5238 ifsp = ifsfirst.next->next;
5239 free(ifsfirst.next);
5240 ifsfirst.next = ifsp;
5243 if (ifsfirst.begoff > endoff)
5246 ifslastp = &ifsfirst;
5247 ifsfirst.endoff = endoff;
5252 ifslastp = &ifsfirst;
5253 while (ifslastp->next && ifslastp->next->begoff < endoff)
5254 ifslastp=ifslastp->next;
5255 while (ifslastp->next != NULL) {
5256 struct ifsregion *ifsp;
5258 ifsp = ifslastp->next->next;
5259 free(ifslastp->next);
5260 ifslastp->next = ifsp;
5263 if (ifslastp->endoff > endoff)
5264 ifslastp->endoff = endoff;
5268 exptilde(char *startp, char *p, int flag)
5274 int quotes = flag & (EXP_FULL | EXP_CASE);
5279 while ((c = *++p) != '\0') {
5286 if (flag & EXP_VARTILDE)
5296 if (*name == '\0') {
5297 home = lookupvar(homestr);
5299 pw = getpwnam(name);
5304 if (!home || !*home)
5307 startloc = expdest - (char *)stackblock();
5308 strtodest(home, SQSYNTAX, quotes);
5309 recordregion(startloc, expdest - (char *)stackblock(), 0);
5317 * Execute a command inside back quotes. If it's a builtin command, we
5318 * want to save its output in a block obtained from malloc. Otherwise
5319 * we fork off a subprocess and get the output of the command via a pipe.
5320 * Should be called with interrupts off.
5322 struct backcmd { /* result of evalbackcmd */
5323 int fd; /* file descriptor to read from */
5324 char *buf; /* buffer */
5325 int nleft; /* number of chars in buffer */
5326 struct job *jp; /* job structure for command */
5329 /* These forward decls are needed to use "eval" code for backticks handling: */
5330 static int back_exitstatus; /* exit status of backquoted command */
5331 #define EV_EXIT 01 /* exit after evaluating tree */
5332 static void evaltree(union node *, int);
5335 evalbackcmd(union node *n, struct backcmd *result)
5347 saveherefd = herefd;
5355 ash_msg_and_raise_error("pipe call failed");
5357 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5366 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5370 result->fd = pip[0];
5373 herefd = saveherefd;
5375 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5376 result->fd, result->buf, result->nleft, result->jp));
5380 * Expand stuff in backwards quotes.
5383 expbackq(union node *cmd, int quoted, int quotes)
5391 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5392 struct stackmark smark;
5395 setstackmark(&smark);
5397 startloc = dest - (char *)stackblock();
5399 evalbackcmd(cmd, &in);
5400 popstackmark(&smark);
5407 memtodest(p, i, syntax, quotes);
5411 i = safe_read(in.fd, buf, sizeof(buf));
5412 TRACE(("expbackq: read returns %d\n", i));
5421 back_exitstatus = waitforjob(in.jp);
5425 /* Eat all trailing newlines */
5427 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5432 recordregion(startloc, dest - (char *)stackblock(), 0);
5433 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5434 (dest - (char *)stackblock()) - startloc,
5435 (dest - (char *)stackblock()) - startloc,
5436 stackblock() + startloc));
5439 #if ENABLE_ASH_MATH_SUPPORT
5441 * Expand arithmetic expression. Backup to start of expression,
5442 * evaluate, place result in (backed up) result, adjust string position.
5455 * This routine is slightly over-complicated for
5456 * efficiency. Next we scan backwards looking for the
5457 * start of arithmetic.
5459 start = stackblock();
5466 while (*p != CTLARI) {
5470 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5475 esc = esclen(start, p);
5485 removerecordregions(begoff);
5494 len = cvtnum(dash_arith(p + 2));
5497 recordregion(begoff, begoff + len, 0);
5501 /* argstr needs it */
5502 static char *evalvar(char *p, int flag);
5505 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5506 * characters to allow for further processing. Otherwise treat
5507 * $@ like $* since no splitting will be performed.
5510 argstr(char *p, int flag)
5512 static const char spclchars[] ALIGN1 = {
5520 CTLBACKQ | CTLQUOTE,
5521 #if ENABLE_ASH_MATH_SUPPORT
5526 const char *reject = spclchars;
5528 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5529 int breakall = flag & EXP_WORD;
5534 if (!(flag & EXP_VARTILDE)) {
5536 } else if (flag & EXP_VARTILDE2) {
5541 if (flag & EXP_TILDE) {
5547 if (*q == CTLESC && (flag & EXP_QWORD))
5550 p = exptilde(p, q, flag);
5553 startloc = expdest - (char *)stackblock();
5555 length += strcspn(p + length, reject);
5557 if (c && (!(c & 0x80)
5558 #if ENABLE_ASH_MATH_SUPPORT
5562 /* c == '=' || c == ':' || c == CTLENDARI */
5567 expdest = stack_nputstr(p, length, expdest);
5568 newloc = expdest - (char *)stackblock();
5569 if (breakall && !inquotes && newloc > startloc) {
5570 recordregion(startloc, newloc, 0);
5581 if (flag & EXP_VARTILDE2) {
5585 flag |= EXP_VARTILDE2;
5590 * sort of a hack - expand tildes in variable
5591 * assignments (after the first '=' and after ':'s).
5600 case CTLENDVAR: /* ??? */
5603 /* "$@" syntax adherence hack */
5606 !memcmp(p, dolatstr, 4) &&
5607 (p[4] == CTLQUOTEMARK || (
5608 p[4] == CTLENDVAR &&
5609 p[5] == CTLQUOTEMARK
5612 p = evalvar(p + 1, flag) + 1;
5615 inquotes = !inquotes;
5628 p = evalvar(p, flag);
5632 case CTLBACKQ|CTLQUOTE:
5633 expbackq(argbackq->n, c, quotes);
5634 argbackq = argbackq->next;
5636 #if ENABLE_ASH_MATH_SUPPORT
5649 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5660 const char *s = loc2;
5666 match = pmatch(str, s);
5670 if (quotes && *loc == CTLESC)
5679 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5686 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5689 const char *s = loc2;
5694 match = pmatch(str, s);
5701 esc = esclen(startp, loc);
5712 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5714 varunset(const char *end, const char *var, const char *umsg, int varflags)
5720 msg = "parameter not set";
5722 if (*end == CTLENDVAR) {
5723 if (varflags & VSNUL)
5728 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5732 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5736 int saveherefd = herefd;
5737 struct nodelist *saveargbackq = argbackq;
5739 char *rmesc, *rmescend;
5741 char *(*scan)(char *, char *, char *, char *, int , int);
5744 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5745 STPUTC('\0', expdest);
5746 herefd = saveherefd;
5747 argbackq = saveargbackq;
5748 startp = stackblock() + startloc;
5752 setvar(str, startp, 0);
5753 amount = startp - expdest;
5754 STADJUST(amount, expdest);
5758 varunset(p, str, startp, varflags);
5762 subtype -= VSTRIMRIGHT;
5764 if (subtype < 0 || subtype > 3)
5769 rmescend = stackblock() + strloc;
5771 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5772 if (rmesc != startp) {
5774 startp = stackblock() + startloc;
5778 str = stackblock() + strloc;
5779 preglob(str, varflags & VSQUOTE, 0);
5781 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5782 zero = subtype >> 1;
5783 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5784 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5786 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5789 memmove(startp, loc, str - loc);
5790 loc = startp + (str - loc) - 1;
5793 amount = loc - expdest;
5794 STADJUST(amount, expdest);
5800 * Add the value of a specialized variable to the stack string.
5803 varvalue(char *name, int varflags, int flags)
5813 int quoted = varflags & VSQUOTE;
5814 int subtype = varflags & VSTYPE;
5815 int quotes = flags & (EXP_FULL | EXP_CASE);
5817 if (quoted && (flags & EXP_FULL))
5818 sep = 1 << CHAR_BIT;
5820 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5829 num = shellparam.nparam;
5839 p = makestrspace(NOPTS, expdest);
5840 for (i = NOPTS - 1; i >= 0; i--) {
5842 USTPUTC(optletters(i), p);
5853 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5854 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5860 while ((p = *ap++)) {
5863 partlen = strlen(p);
5866 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5867 memtodest(p, partlen, syntax, quotes);
5873 if (subtype == VSPLUS || subtype == VSLENGTH) {
5895 if (num < 0 || num > shellparam.nparam)
5897 p = num ? shellparam.p[num - 1] : arg0;
5900 p = lookupvar(name);
5906 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5907 memtodest(p, len, syntax, quotes);
5911 if (subtype == VSPLUS || subtype == VSLENGTH)
5912 STADJUST(-len, expdest);
5917 * Expand a variable, and return a pointer to the next character in the
5921 evalvar(char *p, int flag)
5934 quotes = flag & (EXP_FULL | EXP_CASE);
5936 subtype = varflags & VSTYPE;
5937 quoted = varflags & VSQUOTE;
5939 easy = (!quoted || (*var == '@' && shellparam.nparam));
5940 startloc = expdest - (char *)stackblock();
5941 p = strchr(p, '=') + 1;
5944 varlen = varvalue(var, varflags, flag);
5945 if (varflags & VSNUL)
5948 if (subtype == VSPLUS) {
5949 varlen = -1 - varlen;
5953 if (subtype == VSMINUS) {
5957 p, flag | EXP_TILDE |
5958 (quoted ? EXP_QWORD : EXP_WORD)
5967 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5969 if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
5972 * Remove any recorded regions beyond
5975 removerecordregions(startloc);
5985 if (varlen < 0 && uflag)
5986 varunset(p, var, 0, 0);
5988 if (subtype == VSLENGTH) {
5989 cvtnum(varlen > 0 ? varlen : 0);
5993 if (subtype == VSNORMAL) {
5997 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6006 case VSTRIMRIGHTMAX:
6015 * Terminate the string and start recording the pattern
6018 STPUTC('\0', expdest);
6019 patloc = expdest - (char *)stackblock();
6020 if (subevalvar(p, NULL, patloc, subtype,
6021 startloc, varflags, quotes) == 0) {
6022 int amount = expdest - (
6023 (char *)stackblock() + patloc - 1
6025 STADJUST(-amount, expdest);
6027 /* Remove any recorded regions beyond start of variable */
6028 removerecordregions(startloc);
6033 if (subtype != VSNORMAL) { /* skip to end of alternative */
6039 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6041 argbackq = argbackq->next;
6042 } else if (c == CTLVAR) {
6043 if ((*p++ & VSTYPE) != VSNORMAL)
6045 } else if (c == CTLENDVAR) {
6055 * Break the argument string into pieces based upon IFS and add the
6056 * strings to the argument list. The regions of the string to be
6057 * searched for IFS characters have been stored by recordregion.
6060 ifsbreakup(char *string, struct arglist *arglist)
6062 struct ifsregion *ifsp;
6067 const char *ifs, *realifs;
6072 if (ifslastp != NULL) {
6075 realifs = ifsset() ? ifsval() : defifs;
6078 p = string + ifsp->begoff;
6079 nulonly = ifsp->nulonly;
6080 ifs = nulonly ? nullstr : realifs;
6082 while (p < string + ifsp->endoff) {
6086 if (!strchr(ifs, *p)) {
6091 ifsspc = (strchr(defifs, *p) != NULL);
6092 /* Ignore IFS whitespace at start */
6093 if (q == start && ifsspc) {
6099 sp = stalloc(sizeof(*sp));
6101 *arglist->lastp = sp;
6102 arglist->lastp = &sp->next;
6106 if (p >= string + ifsp->endoff) {
6112 if (strchr(ifs, *p) == NULL ) {
6115 } else if (strchr(defifs, *p) == NULL) {
6130 } while (ifsp != NULL);
6139 sp = stalloc(sizeof(*sp));
6141 *arglist->lastp = sp;
6142 arglist->lastp = &sp->next;
6148 struct ifsregion *p;
6153 struct ifsregion *ifsp;
6159 ifsfirst.next = NULL;
6164 * Add a file name to the list.
6167 addfname(const char *name)
6171 sp = stalloc(sizeof(*sp));
6172 sp->text = ststrdup(name);
6174 exparg.lastp = &sp->next;
6177 static char *expdir;
6180 * Do metacharacter (i.e. *, ?, [...]) expansion.
6183 expmeta(char *enddir, char *name)
6198 for (p = name; *p; p++) {
6199 if (*p == '*' || *p == '?')
6201 else if (*p == '[') {
6208 if (*q == '/' || *q == '\0')
6215 } else if (*p == '\\')
6217 else if (*p == '/') {
6224 if (metaflag == 0) { /* we've reached the end of the file name */
6225 if (enddir != expdir)
6233 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6244 } while (p < start);
6246 if (enddir == expdir) {
6248 } else if (enddir == expdir + 1 && *expdir == '/') {
6257 if (enddir != expdir)
6259 if (*endname == 0) {
6271 while (!intpending && (dp = readdir(dirp)) != NULL) {
6272 if (dp->d_name[0] == '.' && ! matchdot)
6274 if (pmatch(start, dp->d_name)) {
6276 strcpy(enddir, dp->d_name);
6279 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6282 expmeta(p, endname);
6291 static struct strlist *
6292 msort(struct strlist *list, int len)
6294 struct strlist *p, *q = NULL;
6295 struct strlist **lpp;
6303 for (n = half; --n >= 0; ) {
6307 q->next = NULL; /* terminate first half of list */
6308 q = msort(list, half); /* sort first half of list */
6309 p = msort(p, len - half); /* sort second half */
6312 #if ENABLE_LOCALE_SUPPORT
6313 if (strcoll(p->text, q->text) < 0)
6315 if (strcmp(p->text, q->text) < 0)
6339 * Sort the results of file name expansion. It calculates the number of
6340 * strings to sort and then calls msort (short for merge sort) to do the
6343 static struct strlist *
6344 expsort(struct strlist *str)
6350 for (sp = str; sp; sp = sp->next)
6352 return msort(str, len);
6356 expandmeta(struct strlist *str, int flag)
6358 static const char metachars[] ALIGN1 = {
6361 /* TODO - EXP_REDIR */
6364 struct strlist **savelastp;
6370 if (!strpbrk(str->text, metachars))
6372 savelastp = exparg.lastp;
6375 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6377 int i = strlen(str->text);
6378 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6386 if (exparg.lastp == savelastp) {
6391 *exparg.lastp = str;
6392 rmescapes(str->text);
6393 exparg.lastp = &str->next;
6395 *exparg.lastp = NULL;
6396 *savelastp = sp = expsort(*savelastp);
6397 while (sp->next != NULL)
6399 exparg.lastp = &sp->next;
6406 * Perform variable substitution and command substitution on an argument,
6407 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6408 * perform splitting and file name expansion. When arglist is NULL, perform
6409 * here document expansion.
6412 expandarg(union node *arg, struct arglist *arglist, int flag)
6417 argbackq = arg->narg.backquote;
6418 STARTSTACKSTR(expdest);
6419 ifsfirst.next = NULL;
6421 argstr(arg->narg.text, flag);
6422 p = _STPUTC('\0', expdest);
6424 if (arglist == NULL) {
6425 return; /* here document expanded */
6427 p = grabstackstr(p);
6428 exparg.lastp = &exparg.list;
6432 if (flag & EXP_FULL) {
6433 ifsbreakup(p, &exparg);
6434 *exparg.lastp = NULL;
6435 exparg.lastp = &exparg.list;
6436 expandmeta(exparg.list, flag);
6438 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6440 sp = stalloc(sizeof(*sp));
6443 exparg.lastp = &sp->next;
6447 *exparg.lastp = NULL;
6449 *arglist->lastp = exparg.list;
6450 arglist->lastp = exparg.lastp;
6455 * Expand shell variables and backquotes inside a here document.
6458 expandhere(union node *arg, int fd)
6461 expandarg(arg, (struct arglist *)NULL, 0);
6462 full_write(fd, stackblock(), expdest - (char *)stackblock());
6466 * Returns true if the pattern matches the string.
6469 patmatch(char *pattern, const char *string)
6471 return pmatch(preglob(pattern, 0, 0), string);
6475 * See if a pattern matches in a case statement.
6478 casematch(union node *pattern, char *val)
6480 struct stackmark smark;
6483 setstackmark(&smark);
6484 argbackq = pattern->narg.backquote;
6485 STARTSTACKSTR(expdest);
6487 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
6488 STACKSTRNUL(expdest);
6489 result = patmatch(stackblock(), val);
6490 popstackmark(&smark);
6495 /* ============ find_command */
6499 int (*builtin)(int, char **);
6500 /* unsigned flags; */
6502 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6503 /* "regular" bltins always take precedence over commands,
6504 * regardless of PATH=....%builtin... position */
6505 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6506 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6512 const struct builtincmd *cmd;
6513 struct funcnode *func;
6516 /* values of cmdtype */
6517 #define CMDUNKNOWN -1 /* no entry in table for command */
6518 #define CMDNORMAL 0 /* command is an executable program */
6519 #define CMDFUNCTION 1 /* command is a shell function */
6520 #define CMDBUILTIN 2 /* command is a shell builtin */
6522 /* action to find_command() */
6523 #define DO_ERR 0x01 /* prints errors */
6524 #define DO_ABS 0x02 /* checks absolute paths */
6525 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6526 #define DO_ALTPATH 0x08 /* using alternate path */
6527 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6529 static void find_command(char *, struct cmdentry *, int, const char *);
6532 /* ============ Hashing commands */
6535 * When commands are first encountered, they are entered in a hash table.
6536 * This ensures that a full path search will not have to be done for them
6537 * on each invocation.
6539 * We should investigate converting to a linear search, even though that
6540 * would make the command name "hash" a misnomer.
6543 #define ARB 1 /* actual size determined at run time */
6546 struct tblentry *next; /* next entry in hash chain */
6547 union param param; /* definition of builtin function */
6548 short cmdtype; /* index identifying command */
6549 char rehash; /* if set, cd done since entry created */
6550 char cmdname[ARB]; /* name of command */
6553 static struct tblentry **cmdtable;
6554 #define INIT_G_cmdtable() do { \
6555 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
6558 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6562 tryexec(char *cmd, char **argv, char **envp)
6566 #if ENABLE_FEATURE_SH_STANDALONE
6567 if (strchr(cmd, '/') == NULL) {
6568 int a = find_applet_by_name(cmd);
6570 if (APPLET_IS_NOEXEC(a))
6571 run_applet_no_and_exit(a, argv);
6572 /* re-exec ourselves with the new arguments */
6573 execve(bb_busybox_exec_path, argv, envp);
6574 /* If they called chroot or otherwise made the binary no longer
6575 * executable, fall through */
6583 execve(cmd, argv, envp);
6584 } while (errno == EINTR);
6586 execve(cmd, argv, envp);
6590 } else if (errno == ENOEXEC) {
6594 for (ap = argv; *ap; ap++)
6596 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6598 ap[0] = cmd = (char *)DEFAULT_SHELL;
6601 while ((*ap++ = *argv++))
6609 * Exec a program. Never returns. If you change this routine, you may
6610 * have to change the find_command routine as well.
6612 #define environment() listvars(VEXPORT, VUNSET, 0)
6613 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6615 shellexec(char **argv, const char *path, int idx)
6623 envp = environment();
6624 if (strchr(argv[0], '/')
6625 #if ENABLE_FEATURE_SH_STANDALONE
6626 || find_applet_by_name(argv[0]) >= 0
6629 tryexec(argv[0], argv, envp);
6633 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6634 if (--idx < 0 && pathopt == NULL) {
6635 tryexec(cmdname, argv, envp);
6636 if (errno != ENOENT && errno != ENOTDIR)
6643 /* Map to POSIX errors */
6655 exitstatus = exerrno;
6656 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6657 argv[0], e, suppressint ));
6658 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6663 printentry(struct tblentry *cmdp)
6669 idx = cmdp->param.index;
6672 name = padvance(&path, cmdp->cmdname);
6674 } while (--idx >= 0);
6675 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6679 * Clear out command entries. The argument specifies the first entry in
6680 * PATH which has changed.
6683 clearcmdentry(int firstchange)
6685 struct tblentry **tblp;
6686 struct tblentry **pp;
6687 struct tblentry *cmdp;
6690 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6692 while ((cmdp = *pp) != NULL) {
6693 if ((cmdp->cmdtype == CMDNORMAL &&
6694 cmdp->param.index >= firstchange)
6695 || (cmdp->cmdtype == CMDBUILTIN &&
6696 builtinloc >= firstchange)
6709 * Locate a command in the command hash table. If "add" is nonzero,
6710 * add the command to the table if it is not already present. The
6711 * variable "lastcmdentry" is set to point to the address of the link
6712 * pointing to the entry, so that delete_cmd_entry can delete the
6715 * Interrupts must be off if called with add != 0.
6717 static struct tblentry **lastcmdentry;
6719 static struct tblentry *
6720 cmdlookup(const char *name, int add)
6722 unsigned int hashval;
6724 struct tblentry *cmdp;
6725 struct tblentry **pp;
6728 hashval = (unsigned char)*p << 4;
6730 hashval += (unsigned char)*p++;
6732 pp = &cmdtable[hashval % CMDTABLESIZE];
6733 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6734 if (strcmp(cmdp->cmdname, name) == 0)
6738 if (add && cmdp == NULL) {
6739 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6740 + strlen(name) + 1);
6742 cmdp->cmdtype = CMDUNKNOWN;
6743 strcpy(cmdp->cmdname, name);
6750 * Delete the command entry returned on the last lookup.
6753 delete_cmd_entry(void)
6755 struct tblentry *cmdp;
6758 cmdp = *lastcmdentry;
6759 *lastcmdentry = cmdp->next;
6760 if (cmdp->cmdtype == CMDFUNCTION)
6761 freefunc(cmdp->param.func);
6767 * Add a new command entry, replacing any existing command entry for
6768 * the same name - except special builtins.
6771 addcmdentry(char *name, struct cmdentry *entry)
6773 struct tblentry *cmdp;
6775 cmdp = cmdlookup(name, 1);
6776 if (cmdp->cmdtype == CMDFUNCTION) {
6777 freefunc(cmdp->param.func);
6779 cmdp->cmdtype = entry->cmdtype;
6780 cmdp->param = entry->u;
6785 hashcmd(int argc, char **argv)
6787 struct tblentry **pp;
6788 struct tblentry *cmdp;
6790 struct cmdentry entry;
6793 if (nextopt("r") != '\0') {
6798 if (*argptr == NULL) {
6799 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6800 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6801 if (cmdp->cmdtype == CMDNORMAL)
6809 while ((name = *argptr) != NULL) {
6810 cmdp = cmdlookup(name, 0);
6812 && (cmdp->cmdtype == CMDNORMAL
6813 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
6817 find_command(name, &entry, DO_ERR, pathval());
6818 if (entry.cmdtype == CMDUNKNOWN)
6826 * Called when a cd is done. Marks all commands so the next time they
6827 * are executed they will be rehashed.
6832 struct tblentry **pp;
6833 struct tblentry *cmdp;
6835 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6836 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6837 if (cmdp->cmdtype == CMDNORMAL
6838 || (cmdp->cmdtype == CMDBUILTIN
6839 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
6849 * Fix command hash table when PATH changed.
6850 * Called before PATH is changed. The argument is the new value of PATH;
6851 * pathval() still returns the old value at this point.
6852 * Called with interrupts off.
6855 changepath(const char *new)
6863 firstchange = 9999; /* assume no change */
6869 if ((*old == '\0' && *new == ':')
6870 || (*old == ':' && *new == '\0'))
6872 old = new; /* ignore subsequent differences */
6876 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6882 if (builtinloc < 0 && idx_bltin >= 0)
6883 builtinloc = idx_bltin; /* zap builtins */
6884 if (builtinloc >= 0 && idx_bltin < 0)
6886 clearcmdentry(firstchange);
6887 builtinloc = idx_bltin;
6902 #define TENDBQUOTE 12
6920 /* first char is indicating which tokens mark the end of a list */
6921 static const char *const tokname_array[] = {
6935 #define KWDOFFSET 13
6936 /* the following are keywords */
6958 static char buf[16];
6961 //if (tok < TSEMI) return tokname_array[tok] + 1;
6962 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
6967 sprintf(buf + (tok >= TSEMI), "%s%c",
6968 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
6972 /* Wrapper around strcmp for qsort/bsearch/... */
6974 pstrcmp(const void *a, const void *b)
6976 return strcmp((char*) a, (*(char**) b) + 1);
6979 static const char *const *
6980 findkwd(const char *s)
6982 return bsearch(s, tokname_array + KWDOFFSET,
6983 ARRAY_SIZE(tokname_array) - KWDOFFSET,
6984 sizeof(tokname_array[0]), pstrcmp);
6988 * Locate and print what a word is...
6991 describe_command(char *command, int describe_command_verbose)
6993 struct cmdentry entry;
6994 struct tblentry *cmdp;
6995 #if ENABLE_ASH_ALIAS
6996 const struct alias *ap;
6998 const char *path = pathval();
7000 if (describe_command_verbose) {
7004 /* First look at the keywords */
7005 if (findkwd(command)) {
7006 out1str(describe_command_verbose ? " is a shell keyword" : command);
7010 #if ENABLE_ASH_ALIAS
7011 /* Then look at the aliases */
7012 ap = lookupalias(command, 0);
7014 if (!describe_command_verbose) {
7019 out1fmt(" is an alias for %s", ap->val);
7023 /* Then check if it is a tracked alias */
7024 cmdp = cmdlookup(command, 0);
7026 entry.cmdtype = cmdp->cmdtype;
7027 entry.u = cmdp->param;
7029 /* Finally use brute force */
7030 find_command(command, &entry, DO_ABS, path);
7033 switch (entry.cmdtype) {
7035 int j = entry.u.index;
7041 p = padvance(&path, command);
7045 if (describe_command_verbose) {
7047 (cmdp ? " a tracked alias for" : nullstr), p
7056 if (describe_command_verbose) {
7057 out1str(" is a shell function");
7064 if (describe_command_verbose) {
7065 out1fmt(" is a %sshell builtin",
7066 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7067 "special " : nullstr
7075 if (describe_command_verbose) {
7076 out1str(": not found\n");
7081 outstr("\n", stdout);
7086 typecmd(int argc, char **argv)
7092 /* type -p ... ? (we don't bother checking for 'p') */
7093 if (argv[1] && argv[1][0] == '-') {
7098 err |= describe_command(argv[i++], verbose);
7103 #if ENABLE_ASH_CMDCMD
7105 commandcmd(int argc, char **argv)
7113 while ((c = nextopt("pvV")) != '\0')
7115 verify |= VERIFY_VERBOSE;
7117 verify |= VERIFY_BRIEF;
7123 return describe_command(*argptr, verify - VERIFY_BRIEF);
7130 /* ============ eval.c */
7132 static int funcblocksize; /* size of structures in function */
7133 static int funcstringsize; /* size of strings in node */
7134 static void *funcblock; /* block to allocate function from */
7135 static char *funcstring; /* block to allocate strings from */
7137 /* flags in argument to evaltree */
7138 #define EV_EXIT 01 /* exit after evaluating tree */
7139 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7140 #define EV_BACKCMD 04 /* command executing within back quotes */
7142 static const short nodesize[26] = {
7143 SHELL_ALIGN(sizeof(struct ncmd)),
7144 SHELL_ALIGN(sizeof(struct npipe)),
7145 SHELL_ALIGN(sizeof(struct nredir)),
7146 SHELL_ALIGN(sizeof(struct nredir)),
7147 SHELL_ALIGN(sizeof(struct nredir)),
7148 SHELL_ALIGN(sizeof(struct nbinary)),
7149 SHELL_ALIGN(sizeof(struct nbinary)),
7150 SHELL_ALIGN(sizeof(struct nbinary)),
7151 SHELL_ALIGN(sizeof(struct nif)),
7152 SHELL_ALIGN(sizeof(struct nbinary)),
7153 SHELL_ALIGN(sizeof(struct nbinary)),
7154 SHELL_ALIGN(sizeof(struct nfor)),
7155 SHELL_ALIGN(sizeof(struct ncase)),
7156 SHELL_ALIGN(sizeof(struct nclist)),
7157 SHELL_ALIGN(sizeof(struct narg)),
7158 SHELL_ALIGN(sizeof(struct narg)),
7159 SHELL_ALIGN(sizeof(struct nfile)),
7160 SHELL_ALIGN(sizeof(struct nfile)),
7161 SHELL_ALIGN(sizeof(struct nfile)),
7162 SHELL_ALIGN(sizeof(struct nfile)),
7163 SHELL_ALIGN(sizeof(struct nfile)),
7164 SHELL_ALIGN(sizeof(struct ndup)),
7165 SHELL_ALIGN(sizeof(struct ndup)),
7166 SHELL_ALIGN(sizeof(struct nhere)),
7167 SHELL_ALIGN(sizeof(struct nhere)),
7168 SHELL_ALIGN(sizeof(struct nnot)),
7171 static void calcsize(union node *n);
7174 sizenodelist(struct nodelist *lp)
7177 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7184 calcsize(union node *n)
7188 funcblocksize += nodesize[n->type];
7191 calcsize(n->ncmd.redirect);
7192 calcsize(n->ncmd.args);
7193 calcsize(n->ncmd.assign);
7196 sizenodelist(n->npipe.cmdlist);
7201 calcsize(n->nredir.redirect);
7202 calcsize(n->nredir.n);
7209 calcsize(n->nbinary.ch2);
7210 calcsize(n->nbinary.ch1);
7213 calcsize(n->nif.elsepart);
7214 calcsize(n->nif.ifpart);
7215 calcsize(n->nif.test);
7218 funcstringsize += strlen(n->nfor.var) + 1;
7219 calcsize(n->nfor.body);
7220 calcsize(n->nfor.args);
7223 calcsize(n->ncase.cases);
7224 calcsize(n->ncase.expr);
7227 calcsize(n->nclist.body);
7228 calcsize(n->nclist.pattern);
7229 calcsize(n->nclist.next);
7233 sizenodelist(n->narg.backquote);
7234 funcstringsize += strlen(n->narg.text) + 1;
7235 calcsize(n->narg.next);
7242 calcsize(n->nfile.fname);
7243 calcsize(n->nfile.next);
7247 calcsize(n->ndup.vname);
7248 calcsize(n->ndup.next);
7252 calcsize(n->nhere.doc);
7253 calcsize(n->nhere.next);
7256 calcsize(n->nnot.com);
7262 nodeckstrdup(char *s)
7264 char *rtn = funcstring;
7266 strcpy(funcstring, s);
7267 funcstring += strlen(s) + 1;
7271 static union node *copynode(union node *);
7273 static struct nodelist *
7274 copynodelist(struct nodelist *lp)
7276 struct nodelist *start;
7277 struct nodelist **lpp;
7282 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7283 (*lpp)->n = copynode(lp->n);
7285 lpp = &(*lpp)->next;
7292 copynode(union node *n)
7299 funcblock = (char *) funcblock + nodesize[n->type];
7303 new->ncmd.redirect = copynode(n->ncmd.redirect);
7304 new->ncmd.args = copynode(n->ncmd.args);
7305 new->ncmd.assign = copynode(n->ncmd.assign);
7308 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7309 new->npipe.backgnd = n->npipe.backgnd;
7314 new->nredir.redirect = copynode(n->nredir.redirect);
7315 new->nredir.n = copynode(n->nredir.n);
7322 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7323 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7326 new->nif.elsepart = copynode(n->nif.elsepart);
7327 new->nif.ifpart = copynode(n->nif.ifpart);
7328 new->nif.test = copynode(n->nif.test);
7331 new->nfor.var = nodeckstrdup(n->nfor.var);
7332 new->nfor.body = copynode(n->nfor.body);
7333 new->nfor.args = copynode(n->nfor.args);
7336 new->ncase.cases = copynode(n->ncase.cases);
7337 new->ncase.expr = copynode(n->ncase.expr);
7340 new->nclist.body = copynode(n->nclist.body);
7341 new->nclist.pattern = copynode(n->nclist.pattern);
7342 new->nclist.next = copynode(n->nclist.next);
7346 new->narg.backquote = copynodelist(n->narg.backquote);
7347 new->narg.text = nodeckstrdup(n->narg.text);
7348 new->narg.next = copynode(n->narg.next);
7355 new->nfile.fname = copynode(n->nfile.fname);
7356 new->nfile.fd = n->nfile.fd;
7357 new->nfile.next = copynode(n->nfile.next);
7361 new->ndup.vname = copynode(n->ndup.vname);
7362 new->ndup.dupfd = n->ndup.dupfd;
7363 new->ndup.fd = n->ndup.fd;
7364 new->ndup.next = copynode(n->ndup.next);
7368 new->nhere.doc = copynode(n->nhere.doc);
7369 new->nhere.fd = n->nhere.fd;
7370 new->nhere.next = copynode(n->nhere.next);
7373 new->nnot.com = copynode(n->nnot.com);
7376 new->type = n->type;
7381 * Make a copy of a parse tree.
7383 static struct funcnode *
7384 copyfunc(union node *n)
7389 funcblocksize = offsetof(struct funcnode, n);
7392 blocksize = funcblocksize;
7393 f = ckmalloc(blocksize + funcstringsize);
7394 funcblock = (char *) f + offsetof(struct funcnode, n);
7395 funcstring = (char *) f + blocksize;
7402 * Define a shell function.
7405 defun(char *name, union node *func)
7407 struct cmdentry entry;
7410 entry.cmdtype = CMDFUNCTION;
7411 entry.u.func = copyfunc(func);
7412 addcmdentry(name, &entry);
7416 static int evalskip; /* set if we are skipping commands */
7417 /* reasons for skipping commands (see comment on breakcmd routine) */
7418 #define SKIPBREAK (1 << 0)
7419 #define SKIPCONT (1 << 1)
7420 #define SKIPFUNC (1 << 2)
7421 #define SKIPFILE (1 << 3)
7422 #define SKIPEVAL (1 << 4)
7423 static int skipcount; /* number of levels to skip */
7424 static int funcnest; /* depth of function calls */
7426 /* forward decl way out to parsing code - dotrap needs it */
7427 static int evalstring(char *s, int mask);
7430 * Called to execute a trap. Perhaps we should avoid entering new trap
7431 * handlers while we are executing a trap handler.
7442 savestatus = exitstatus;
7446 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7454 skip = evalstring(p, SKIPEVAL);
7455 exitstatus = savestatus;
7463 /* forward declarations - evaluation is fairly recursive business... */
7464 static void evalloop(union node *, int);
7465 static void evalfor(union node *, int);
7466 static void evalcase(union node *, int);
7467 static void evalsubshell(union node *, int);
7468 static void expredir(union node *);
7469 static void evalpipe(union node *, int);
7470 static void evalcommand(union node *, int);
7471 static int evalbltin(const struct builtincmd *, int, char **);
7472 static void prehash(union node *);
7475 * Evaluate a parse tree. The value is left in the global variable
7479 evaltree(union node *n, int flags)
7482 void (*evalfn)(union node *, int);
7486 TRACE(("evaltree(NULL) called\n"));
7489 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7490 getpid(), n, n->type, flags));
7494 out1fmt("Node type = %d\n", n->type);
7499 evaltree(n->nnot.com, EV_TESTED);
7500 status = !exitstatus;
7503 expredir(n->nredir.redirect);
7504 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7506 evaltree(n->nredir.n, flags & EV_TESTED);
7507 status = exitstatus;
7512 evalfn = evalcommand;
7514 if (eflag && !(flags & EV_TESTED))
7526 evalfn = evalsubshell;
7538 #error NAND + 1 != NOR
7540 #if NOR + 1 != NSEMI
7541 #error NOR + 1 != NSEMI
7543 isor = n->type - NAND;
7546 (flags | ((isor >> 1) - 1)) & EV_TESTED
7548 if (!exitstatus == isor)
7560 evaltree(n->nif.test, EV_TESTED);
7563 if (exitstatus == 0) {
7566 } else if (n->nif.elsepart) {
7567 n = n->nif.elsepart;
7572 defun(n->narg.text, n->narg.next);
7576 exitstatus = status;
7580 if ((checkexit & exitstatus))
7581 evalskip |= SKIPEVAL;
7582 else if (pendingsig && dotrap())
7585 if (flags & EV_EXIT) {
7587 raise_exception(EXEXIT);
7591 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7594 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7596 static int loopnest; /* current loop nesting level */
7599 evalloop(union node *n, int flags)
7609 evaltree(n->nbinary.ch1, EV_TESTED);
7612 if (evalskip == SKIPCONT && --skipcount <= 0) {
7616 if (evalskip == SKIPBREAK && --skipcount <= 0)
7621 if (n->type != NWHILE)
7625 evaltree(n->nbinary.ch2, flags);
7626 status = exitstatus;
7631 exitstatus = status;
7635 evalfor(union node *n, int flags)
7637 struct arglist arglist;
7640 struct stackmark smark;
7642 setstackmark(&smark);
7643 arglist.lastp = &arglist.list;
7644 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7645 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7650 *arglist.lastp = NULL;
7655 for (sp = arglist.list; sp; sp = sp->next) {
7656 setvar(n->nfor.var, sp->text, 0);
7657 evaltree(n->nfor.body, flags);
7659 if (evalskip == SKIPCONT && --skipcount <= 0) {
7663 if (evalskip == SKIPBREAK && --skipcount <= 0)
7670 popstackmark(&smark);
7674 evalcase(union node *n, int flags)
7678 struct arglist arglist;
7679 struct stackmark smark;
7681 setstackmark(&smark);
7682 arglist.lastp = &arglist.list;
7683 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7685 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7686 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7687 if (casematch(patp, arglist.list->text)) {
7688 if (evalskip == 0) {
7689 evaltree(cp->nclist.body, flags);
7696 popstackmark(&smark);
7700 * Kick off a subshell to evaluate a tree.
7703 evalsubshell(union node *n, int flags)
7706 int backgnd = (n->type == NBACKGND);
7709 expredir(n->nredir.redirect);
7710 if (!backgnd && flags & EV_EXIT && !trap[0])
7714 if (forkshell(jp, n, backgnd) == 0) {
7718 flags &=~ EV_TESTED;
7720 redirect(n->nredir.redirect, 0);
7721 evaltreenr(n->nredir.n, flags);
7726 status = waitforjob(jp);
7727 exitstatus = status;
7732 * Compute the names of the files in a redirection list.
7734 static void fixredir(union node *, const char *, int);
7736 expredir(union node *n)
7740 for (redir = n; redir; redir = redir->nfile.next) {
7743 memset(&fn, 0, sizeof(fn));
7744 fn.lastp = &fn.list;
7745 switch (redir->type) {
7751 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7752 redir->nfile.expfname = fn.list->text;
7756 if (redir->ndup.vname) {
7757 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7758 if (fn.list == NULL)
7759 ash_msg_and_raise_error("redir error");
7760 fixredir(redir, fn.list->text, 1);
7768 * Evaluate a pipeline. All the processes in the pipeline are children
7769 * of the process creating the pipeline. (This differs from some versions
7770 * of the shell, which make the last process in a pipeline the parent
7774 evalpipe(union node *n, int flags)
7777 struct nodelist *lp;
7782 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7784 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7788 jp = makejob(n, pipelen);
7790 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7794 if (pipe(pip) < 0) {
7796 ash_msg_and_raise_error("pipe call failed");
7799 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7812 evaltreenr(lp->n, flags);
7820 if (n->npipe.backgnd == 0) {
7821 exitstatus = waitforjob(jp);
7822 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7828 * Controls whether the shell is interactive or not.
7831 setinteractive(int on)
7833 static int is_interactive;
7835 if (++on == is_interactive)
7837 is_interactive = on;
7841 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7842 if (is_interactive > 1) {
7843 /* Looks like they want an interactive shell */
7844 static smallint did_banner;
7849 "%s built-in shell (ash)\n"
7850 "Enter 'help' for a list of built-in commands."
7859 #if ENABLE_FEATURE_EDITING_VI
7860 #define setvimode(on) do { \
7861 if (on) line_input_state->flags |= VI_MODE; \
7862 else line_input_state->flags &= ~VI_MODE; \
7865 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7874 setinteractive(iflag);
7879 static struct localvar *localvars;
7882 * Called after a function returns.
7883 * Interrupts must be off.
7888 struct localvar *lvp;
7891 while ((lvp = localvars) != NULL) {
7892 localvars = lvp->next;
7894 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7895 if (vp == NULL) { /* $- saved */
7896 memcpy(optlist, lvp->text, sizeof(optlist));
7897 free((char*)lvp->text);
7899 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7903 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7904 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7905 free((char*)vp->text);
7906 vp->flags = lvp->flags;
7907 vp->text = lvp->text;
7914 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7916 volatile struct shparam saveparam;
7917 struct localvar *volatile savelocalvars;
7918 struct jmploc *volatile savehandler;
7919 struct jmploc jmploc;
7922 saveparam = shellparam;
7923 savelocalvars = localvars;
7924 e = setjmp(jmploc.loc);
7929 savehandler = exception_handler;
7930 exception_handler = &jmploc;
7932 shellparam.malloced = 0;
7936 shellparam.nparam = argc - 1;
7937 shellparam.p = argv + 1;
7938 #if ENABLE_ASH_GETOPTS
7939 shellparam.optind = 1;
7940 shellparam.optoff = -1;
7942 evaltree(&func->n, flags & EV_TESTED);
7948 localvars = savelocalvars;
7949 freeparam(&shellparam);
7950 shellparam = saveparam;
7951 exception_handler = savehandler;
7953 evalskip &= ~SKIPFUNC;
7957 #if ENABLE_ASH_CMDCMD
7959 parse_command_args(char **argv, const char **path)
7972 if (c == '-' && !*cp) {
7979 *path = bb_default_path;
7982 /* run 'typecmd' for other options */
7993 * Make a variable a local variable. When a variable is made local, it's
7994 * value and flags are saved in a localvar structure. The saved values
7995 * will be restored when the shell function returns. We handle the name
7996 * "-" as a special case.
8001 struct localvar *lvp;
8006 lvp = ckmalloc(sizeof(struct localvar));
8007 if (LONE_DASH(name)) {
8009 p = ckmalloc(sizeof(optlist));
8010 lvp->text = memcpy(p, optlist, sizeof(optlist));
8015 vpp = hashvar(name);
8016 vp = *findvar(vpp, name);
8017 eq = strchr(name, '=');
8020 setvareq(name, VSTRFIXED);
8022 setvar(name, NULL, VSTRFIXED);
8023 vp = *vpp; /* the new variable */
8024 lvp->flags = VUNSET;
8026 lvp->text = vp->text;
8027 lvp->flags = vp->flags;
8028 vp->flags |= VSTRFIXED|VTEXTFIXED;
8034 lvp->next = localvars;
8040 * The "local" command.
8043 localcmd(int argc, char **argv)
8048 while ((name = *argv++) != NULL) {
8055 falsecmd(int argc, char **argv)
8061 truecmd(int argc, char **argv)
8067 execcmd(int argc, char **argv)
8070 iflag = 0; /* exit on error */
8073 shellexec(argv + 1, pathval(), 0);
8079 * The return command.
8082 returncmd(int argc, char **argv)
8085 * If called outside a function, do what ksh does;
8086 * skip the rest of the file.
8088 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8089 return argv[1] ? number(argv[1]) : exitstatus;
8092 /* Forward declarations for builtintab[] */
8093 static int breakcmd(int, char **);
8094 static int dotcmd(int, char **);
8095 static int evalcmd(int, char **);
8096 #if ENABLE_ASH_BUILTIN_ECHO
8097 static int echocmd(int, char **);
8099 #if ENABLE_ASH_BUILTIN_TEST
8100 static int testcmd(int, char **);
8102 static int exitcmd(int, char **);
8103 static int exportcmd(int, char **);
8104 #if ENABLE_ASH_GETOPTS
8105 static int getoptscmd(int, char **);
8107 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8108 static int helpcmd(int argc, char **argv);
8110 #if ENABLE_ASH_MATH_SUPPORT
8111 static int letcmd(int, char **);
8113 static int readcmd(int, char **);
8114 static int setcmd(int, char **);
8115 static int shiftcmd(int, char **);
8116 static int timescmd(int, char **);
8117 static int trapcmd(int, char **);
8118 static int umaskcmd(int, char **);
8119 static int unsetcmd(int, char **);
8120 static int ulimitcmd(int, char **);
8122 #define BUILTIN_NOSPEC "0"
8123 #define BUILTIN_SPECIAL "1"
8124 #define BUILTIN_REGULAR "2"
8125 #define BUILTIN_SPEC_REG "3"
8126 #define BUILTIN_ASSIGN "4"
8127 #define BUILTIN_SPEC_ASSG "5"
8128 #define BUILTIN_REG_ASSG "6"
8129 #define BUILTIN_SPEC_REG_ASSG "7"
8131 /* make sure to keep these in proper order since it is searched via bsearch() */
8132 static const struct builtincmd builtintab[] = {
8133 { BUILTIN_SPEC_REG ".", dotcmd },
8134 { BUILTIN_SPEC_REG ":", truecmd },
8135 #if ENABLE_ASH_BUILTIN_TEST
8136 { BUILTIN_REGULAR "[", testcmd },
8137 { BUILTIN_REGULAR "[[", testcmd },
8139 #if ENABLE_ASH_ALIAS
8140 { BUILTIN_REG_ASSG "alias", aliascmd },
8143 { BUILTIN_REGULAR "bg", fg_bgcmd },
8145 { BUILTIN_SPEC_REG "break", breakcmd },
8146 { BUILTIN_REGULAR "cd", cdcmd },
8147 { BUILTIN_NOSPEC "chdir", cdcmd },
8148 #if ENABLE_ASH_CMDCMD
8149 { BUILTIN_REGULAR "command", commandcmd },
8151 { BUILTIN_SPEC_REG "continue", breakcmd },
8152 #if ENABLE_ASH_BUILTIN_ECHO
8153 { BUILTIN_REGULAR "echo", echocmd },
8155 { BUILTIN_SPEC_REG "eval", evalcmd },
8156 { BUILTIN_SPEC_REG "exec", execcmd },
8157 { BUILTIN_SPEC_REG "exit", exitcmd },
8158 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8159 { BUILTIN_REGULAR "false", falsecmd },
8161 { BUILTIN_REGULAR "fg", fg_bgcmd },
8163 #if ENABLE_ASH_GETOPTS
8164 { BUILTIN_REGULAR "getopts", getoptscmd },
8166 { BUILTIN_NOSPEC "hash", hashcmd },
8167 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8168 { BUILTIN_NOSPEC "help", helpcmd },
8171 { BUILTIN_REGULAR "jobs", jobscmd },
8172 { BUILTIN_REGULAR "kill", killcmd },
8174 #if ENABLE_ASH_MATH_SUPPORT
8175 { BUILTIN_NOSPEC "let", letcmd },
8177 { BUILTIN_ASSIGN "local", localcmd },
8178 { BUILTIN_NOSPEC "pwd", pwdcmd },
8179 { BUILTIN_REGULAR "read", readcmd },
8180 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8181 { BUILTIN_SPEC_REG "return", returncmd },
8182 { BUILTIN_SPEC_REG "set", setcmd },
8183 { BUILTIN_SPEC_REG "shift", shiftcmd },
8184 { BUILTIN_SPEC_REG "source", dotcmd },
8185 #if ENABLE_ASH_BUILTIN_TEST
8186 { BUILTIN_REGULAR "test", testcmd },
8188 { BUILTIN_SPEC_REG "times", timescmd },
8189 { BUILTIN_SPEC_REG "trap", trapcmd },
8190 { BUILTIN_REGULAR "true", truecmd },
8191 { BUILTIN_NOSPEC "type", typecmd },
8192 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8193 { BUILTIN_REGULAR "umask", umaskcmd },
8194 #if ENABLE_ASH_ALIAS
8195 { BUILTIN_REGULAR "unalias", unaliascmd },
8197 { BUILTIN_SPEC_REG "unset", unsetcmd },
8198 { BUILTIN_REGULAR "wait", waitcmd },
8202 #define COMMANDCMD (builtintab + 5 + \
8203 2 * ENABLE_ASH_BUILTIN_TEST + \
8204 ENABLE_ASH_ALIAS + \
8205 ENABLE_ASH_JOB_CONTROL)
8206 #define EXECCMD (builtintab + 7 + \
8207 2 * ENABLE_ASH_BUILTIN_TEST + \
8208 ENABLE_ASH_ALIAS + \
8209 ENABLE_ASH_JOB_CONTROL + \
8210 ENABLE_ASH_CMDCMD + \
8211 ENABLE_ASH_BUILTIN_ECHO)
8214 * Search the table of builtin commands.
8216 static struct builtincmd *
8217 find_builtin(const char *name)
8219 struct builtincmd *bp;
8222 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8229 * Execute a simple command.
8231 static int back_exitstatus; /* exit status of backquoted command */
8233 isassignment(const char *p)
8235 const char *q = endofname(p);
8241 bltincmd(int argc, char **argv)
8243 /* Preserve exitstatus of a previous possible redirection
8244 * as POSIX mandates */
8245 return back_exitstatus;
8248 evalcommand(union node *cmd, int flags)
8250 static const struct builtincmd bltin = {
8253 struct stackmark smark;
8255 struct arglist arglist;
8256 struct arglist varlist;
8259 const struct strlist *sp;
8260 struct cmdentry cmdentry;
8268 struct builtincmd *bcmd;
8269 int pseudovarflag = 0;
8271 /* First expand the arguments. */
8272 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8273 setstackmark(&smark);
8274 back_exitstatus = 0;
8276 cmdentry.cmdtype = CMDBUILTIN;
8277 cmdentry.u.cmd = &bltin;
8278 varlist.lastp = &varlist.list;
8279 *varlist.lastp = NULL;
8280 arglist.lastp = &arglist.list;
8281 *arglist.lastp = NULL;
8284 if (cmd->ncmd.args) {
8285 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8286 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8289 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8290 struct strlist **spp;
8292 spp = arglist.lastp;
8293 if (pseudovarflag && isassignment(argp->narg.text))
8294 expandarg(argp, &arglist, EXP_VARTILDE);
8296 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8298 for (sp = *spp; sp; sp = sp->next)
8302 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8303 for (sp = arglist.list; sp; sp = sp->next) {
8304 TRACE(("evalcommand arg: %s\n", sp->text));
8305 *nargv++ = sp->text;
8310 if (iflag && funcnest == 0 && argc > 0)
8311 lastarg = nargv[-1];
8314 expredir(cmd->ncmd.redirect);
8315 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8318 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8319 struct strlist **spp;
8322 spp = varlist.lastp;
8323 expandarg(argp, &varlist, EXP_VARTILDE);
8326 * Modify the command lookup path, if a PATH= assignment
8330 if (varequal(p, path))
8334 /* Print the command if xflag is set. */
8337 const char *p = " %s";
8340 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8343 for (n = 0; n < 2; n++) {
8345 fdprintf(preverrout_fd, p, sp->text);
8353 full_write(preverrout_fd, "\n", 1);
8359 /* Now locate the command. */
8361 const char *oldpath;
8362 int cmd_flag = DO_ERR;
8367 find_command(argv[0], &cmdentry, cmd_flag, path);
8368 if (cmdentry.cmdtype == CMDUNKNOWN) {
8374 /* implement bltin and command here */
8375 if (cmdentry.cmdtype != CMDBUILTIN)
8378 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8379 if (cmdentry.u.cmd == EXECCMD)
8381 #if ENABLE_ASH_CMDCMD
8382 if (cmdentry.u.cmd == COMMANDCMD) {
8384 nargv = parse_command_args(argv, &path);
8387 argc -= nargv - argv;
8389 cmd_flag |= DO_NOFUNC;
8397 /* We have a redirection error. */
8399 raise_exception(EXERROR);
8401 exitstatus = status;
8405 /* Execute the command. */
8406 switch (cmdentry.cmdtype) {
8408 /* Fork off a child process if necessary. */
8409 if (!(flags & EV_EXIT) || trap[0]) {
8411 jp = makejob(cmd, 1);
8412 if (forkshell(jp, cmd, FORK_FG) != 0) {
8413 exitstatus = waitforjob(jp);
8419 listsetvar(varlist.list, VEXPORT|VSTACK);
8420 shellexec(argv, path, cmdentry.u.index);
8424 cmdenviron = varlist.list;
8426 struct strlist *list = cmdenviron;
8428 if (spclbltin > 0 || argc == 0) {
8430 if (cmd_is_exec && argc > 1)
8433 listsetvar(list, i);
8435 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8442 exit_status = 128 + SIGINT;
8444 exit_status = 128 + pendingsig;
8445 exitstatus = exit_status;
8446 if (i == EXINT || spclbltin > 0) {
8448 longjmp(exception_handler->loc, 1);
8455 listsetvar(varlist.list, 0);
8456 if (evalfun(cmdentry.u.func, argc, argv, flags))
8462 popredir(cmd_is_exec);
8464 /* dsl: I think this is intended to be used to support
8465 * '_' in 'vi' command mode during line editing...
8466 * However I implemented that within libedit itself.
8468 setvar("_", lastarg, 0);
8469 popstackmark(&smark);
8473 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8475 char *volatile savecmdname;
8476 struct jmploc *volatile savehandler;
8477 struct jmploc jmploc;
8480 savecmdname = commandname;
8481 i = setjmp(jmploc.loc);
8484 savehandler = exception_handler;
8485 exception_handler = &jmploc;
8486 commandname = argv[0];
8488 optptr = NULL; /* initialize nextopt */
8489 exitstatus = (*cmd->builtin)(argc, argv);
8490 flush_stdout_stderr();
8492 exitstatus |= ferror(stdout);
8494 commandname = savecmdname;
8496 exception_handler = savehandler;
8502 goodname(const char *p)
8504 return !*endofname(p);
8509 * Search for a command. This is called before we fork so that the
8510 * location of the command will be available in the parent as well as
8511 * the child. The check for "goodname" is an overly conservative
8512 * check that the name will not be subject to expansion.
8515 prehash(union node *n)
8517 struct cmdentry entry;
8519 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8520 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8524 /* ============ Builtin commands
8526 * Builtin commands whose functions are closely tied to evaluation
8527 * are implemented here.
8531 * Handle break and continue commands. Break, continue, and return are
8532 * all handled by setting the evalskip flag. The evaluation routines
8533 * above all check this flag, and if it is set they start skipping
8534 * commands rather than executing them. The variable skipcount is
8535 * the number of loops to break/continue, or the number of function
8536 * levels to return. (The latter is always 1.) It should probably
8537 * be an error to break out of more loops than exist, but it isn't
8538 * in the standard shell so we don't make it one here.
8541 breakcmd(int argc, char **argv)
8543 int n = argc > 1 ? number(argv[1]) : 1;
8546 ash_msg_and_raise_error(illnum, argv[1]);
8550 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8557 /* ============ input.c
8559 * This implements the input routines used by the parser.
8562 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8565 INPUT_PUSH_FILE = 1,
8566 INPUT_NOFILE_OK = 2,
8569 static int plinno = 1; /* input line number */
8570 /* number of characters left in input buffer */
8571 static int parsenleft; /* copy of parsefile->nleft */
8572 static int parselleft; /* copy of parsefile->lleft */
8573 /* next character in input buffer */
8574 static char *parsenextc; /* copy of parsefile->nextc */
8576 static int checkkwd;
8577 /* values of checkkwd variable */
8578 #define CHKALIAS 0x1
8585 struct strpush *sp = parsefile->strpush;
8588 #if ENABLE_ASH_ALIAS
8590 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8591 checkkwd |= CHKALIAS;
8593 if (sp->string != sp->ap->val) {
8596 sp->ap->flag &= ~ALIASINUSE;
8597 if (sp->ap->flag & ALIASDEAD) {
8598 unalias(sp->ap->name);
8602 parsenextc = sp->prevstring;
8603 parsenleft = sp->prevnleft;
8604 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8605 parsefile->strpush = sp->prev;
8606 if (sp != &(parsefile->basestrpush))
8615 char *buf = parsefile->buf;
8619 #if ENABLE_FEATURE_EDITING
8620 if (!iflag || parsefile->fd)
8621 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8623 #if ENABLE_FEATURE_TAB_COMPLETION
8624 line_input_state->path_lookup = pathval();
8626 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8628 /* Ctrl+C pressed */
8637 if (nr < 0 && errno == 0) {
8638 /* Ctrl+D pressed */
8643 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8647 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8648 int flags = fcntl(0, F_GETFL);
8649 if (flags >= 0 && (flags & O_NONBLOCK)) {
8650 flags &= ~O_NONBLOCK;
8651 if (fcntl(0, F_SETFL, flags) >= 0) {
8652 out2str("sh: turning off NDELAY mode\n");
8662 * Refill the input buffer and return the next input character:
8664 * 1) If a string was pushed back on the input, pop it;
8665 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8666 * from a string so we can't refill the buffer, return EOF.
8667 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8668 * 4) Process input up to the next newline, deleting nul characters.
8677 while (parsefile->strpush) {
8678 #if ENABLE_ASH_ALIAS
8679 if (parsenleft == -1 && parsefile->strpush->ap &&
8680 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8685 if (--parsenleft >= 0)
8686 return signed_char2int(*parsenextc++);
8688 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8690 flush_stdout_stderr();
8697 parselleft = parsenleft = EOF_NLEFT;
8704 /* delete nul characters */
8712 memmove(q, q + 1, more);
8716 parsenleft = q - parsenextc - 1;
8722 parsenleft = q - parsenextc - 1;
8734 out2str(parsenextc);
8739 return signed_char2int(*parsenextc++);
8742 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8746 return pgetc_as_macro();
8749 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8750 #define pgetc_macro() pgetc()
8752 #define pgetc_macro() pgetc_as_macro()
8756 * Same as pgetc(), but ignores PEOA.
8758 #if ENABLE_ASH_ALIAS
8766 } while (c == PEOA);
8773 return pgetc_macro();
8778 * Read a line from the script.
8781 pfgets(char *line, int len)
8787 while (--nleft > 0) {
8803 * Undo the last call to pgetc. Only one character may be pushed back.
8804 * PEOF may be pushed back.
8814 * Push a string back onto the input at this current parsefile level.
8815 * We handle aliases this way.
8818 pushstring(char *s, void *ap)
8825 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8826 if (parsefile->strpush) {
8827 sp = ckmalloc(sizeof(struct strpush));
8828 sp->prev = parsefile->strpush;
8829 parsefile->strpush = sp;
8831 sp = parsefile->strpush = &(parsefile->basestrpush);
8832 sp->prevstring = parsenextc;
8833 sp->prevnleft = parsenleft;
8834 #if ENABLE_ASH_ALIAS
8835 sp->ap = (struct alias *)ap;
8837 ((struct alias *)ap)->flag |= ALIASINUSE;
8847 * To handle the "." command, a stack of input files is used. Pushfile
8848 * adds a new entry to the stack and popfile restores the previous level.
8853 struct parsefile *pf;
8855 parsefile->nleft = parsenleft;
8856 parsefile->lleft = parselleft;
8857 parsefile->nextc = parsenextc;
8858 parsefile->linno = plinno;
8859 pf = ckmalloc(sizeof(*pf));
8860 pf->prev = parsefile;
8863 pf->basestrpush.prev = NULL;
8870 struct parsefile *pf = parsefile;
8878 parsefile = pf->prev;
8880 parsenleft = parsefile->nleft;
8881 parselleft = parsefile->lleft;
8882 parsenextc = parsefile->nextc;
8883 plinno = parsefile->linno;
8888 * Return to top level.
8893 while (parsefile != &basepf)
8898 * Close the file(s) that the shell is reading commands from. Called
8899 * after a fork is done.
8905 if (parsefile->fd > 0) {
8906 close(parsefile->fd);
8912 * Like setinputfile, but takes an open file descriptor. Call this with
8916 setinputfd(int fd, int push)
8918 close_on_exec_on(fd);
8924 if (parsefile->buf == NULL)
8925 parsefile->buf = ckmalloc(IBUFSIZ);
8926 parselleft = parsenleft = 0;
8931 * Set the input to take input from a file. If push is set, push the
8932 * old input onto the stack first.
8935 setinputfile(const char *fname, int flags)
8941 fd = open(fname, O_RDONLY);
8943 if (flags & INPUT_NOFILE_OK)
8945 ash_msg_and_raise_error("can't open %s", fname);
8948 fd2 = copyfd(fd, 10);
8951 ash_msg_and_raise_error("out of file descriptors");
8954 setinputfd(fd, flags & INPUT_PUSH_FILE);
8961 * Like setinputfile, but takes input from a string.
8964 setinputstring(char *string)
8968 parsenextc = string;
8969 parsenleft = strlen(string);
8970 parsefile->buf = NULL;
8976 /* ============ mail.c
8978 * Routines to check for mail.
8983 #define MAXMBOXES 10
8985 /* times of mailboxes */
8986 static time_t mailtime[MAXMBOXES];
8987 /* Set if MAIL or MAILPATH is changed. */
8988 static smallint mail_var_path_changed;
8991 * Print appropriate message(s) if mail has arrived.
8992 * If mail_var_path_changed is set,
8993 * then the value of MAIL has mail_var_path_changed,
8994 * so we just update the values.
9003 struct stackmark smark;
9006 setstackmark(&smark);
9007 mpath = mpathset() ? mpathval() : mailval();
9008 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9009 p = padvance(&mpath, nullstr);
9014 for (q = p; *q; q++);
9019 q[-1] = '\0'; /* delete trailing '/' */
9020 if (stat(p, &statb) < 0) {
9024 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9027 pathopt ? pathopt : "you have mail"
9030 *mtp = statb.st_mtime;
9032 mail_var_path_changed = 0;
9033 popstackmark(&smark);
9037 changemail(const char *val)
9039 mail_var_path_changed = 1;
9042 #endif /* ASH_MAIL */
9045 /* ============ ??? */
9048 * Set the shell parameters.
9051 setparam(char **argv)
9057 for (nparam = 0; argv[nparam]; nparam++);
9058 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9060 *ap++ = ckstrdup(*argv++);
9063 freeparam(&shellparam);
9064 shellparam.malloced = 1;
9065 shellparam.nparam = nparam;
9066 shellparam.p = newparam;
9067 #if ENABLE_ASH_GETOPTS
9068 shellparam.optind = 1;
9069 shellparam.optoff = -1;
9074 * Process shell options. The global variable argptr contains a pointer
9075 * to the argument list; we advance it past the options.
9078 minus_o(char *name, int val)
9083 for (i = 0; i < NOPTS; i++) {
9084 if (strcmp(name, optnames(i)) == 0) {
9089 ash_msg_and_raise_error("illegal option -o %s", name);
9091 out1str("Current option settings\n");
9092 for (i = 0; i < NOPTS; i++)
9093 out1fmt("%-16s%s\n", optnames(i),
9094 optlist[i] ? "on" : "off");
9097 setoption(int flag, int val)
9101 for (i = 0; i < NOPTS; i++) {
9102 if (optletters(i) == flag) {
9107 ash_msg_and_raise_error("illegal option -%c", flag);
9111 options(int cmdline)
9119 while ((p = *argptr) != NULL) {
9121 if (c != '-' && c != '+')
9124 val = 0; /* val = 0 if c == '+' */
9127 if (p[0] == '\0' || LONE_DASH(p)) {
9129 /* "-" means turn off -x and -v */
9132 /* "--" means reset params */
9133 else if (*argptr == NULL)
9136 break; /* "-" or "--" terminates options */
9139 /* first char was + or - */
9140 while ((c = *p++) != '\0') {
9141 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9142 if (c == 'c' && cmdline) {
9143 minusc = p; /* command is after shell args */
9144 } else if (c == 'o') {
9145 minus_o(*argptr, val);
9148 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9150 /* bash does not accept +-login, we also won't */
9151 } else if (cmdline && val && (c == '-')) { /* long options */
9152 if (strcmp(p, "login") == 0)
9163 * The shift builtin command.
9166 shiftcmd(int argc, char **argv)
9173 n = number(argv[1]);
9174 if (n > shellparam.nparam)
9175 ash_msg_and_raise_error("can't shift that many");
9177 shellparam.nparam -= n;
9178 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9179 if (shellparam.malloced)
9183 while ((*ap2++ = *ap1++) != NULL);
9184 #if ENABLE_ASH_GETOPTS
9185 shellparam.optind = 1;
9186 shellparam.optoff = -1;
9193 * POSIX requires that 'set' (but not export or readonly) output the
9194 * variables in lexicographic order - by the locale's collating order (sigh).
9195 * Maybe we could keep them in an ordered balanced binary tree
9196 * instead of hashed lists.
9197 * For now just roll 'em through qsort for printing...
9200 showvars(const char *sep_prefix, int on, int off)
9205 ep = listvars(on, off, &epend);
9206 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9208 sep = *sep_prefix ? " " : sep_prefix;
9210 for (; ep < epend; ep++) {
9214 p = strchrnul(*ep, '=');
9217 q = single_quote(++p);
9218 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9224 * The set command builtin.
9227 setcmd(int argc, char **argv)
9230 return showvars(nullstr, 0, VUNSET);
9234 if (*argptr != NULL) {
9241 #if ENABLE_ASH_RANDOM_SUPPORT
9242 /* Roughly copied from bash.. */
9244 change_random(const char *value)
9246 if (value == NULL) {
9247 /* "get", generate */
9250 rseed = rseed * 1103515245 + 12345;
9251 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9252 /* set without recursion */
9253 setvar(vrandom.text, buf, VNOFUNC);
9254 vrandom.flags &= ~VNOFUNC;
9257 rseed = strtoul(value, (char **)NULL, 10);
9262 #if ENABLE_ASH_GETOPTS
9264 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9273 if (*param_optind < 1)
9275 optnext = optfirst + *param_optind - 1;
9277 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9280 p = optnext[-1] + *optoff;
9281 if (p == NULL || *p == '\0') {
9282 /* Current word is done, advance */
9284 if (p == NULL || *p != '-' || *++p == '\0') {
9291 if (LONE_DASH(p)) /* check for "--" */
9296 for (q = optstr; *q != c; ) {
9298 if (optstr[0] == ':') {
9301 err |= setvarsafe("OPTARG", s, 0);
9303 fprintf(stderr, "Illegal option -%c\n", c);
9314 if (*p == '\0' && (p = *optnext) == NULL) {
9315 if (optstr[0] == ':') {
9318 err |= setvarsafe("OPTARG", s, 0);
9321 fprintf(stderr, "No arg for -%c option\n", c);
9330 err |= setvarsafe("OPTARG", p, 0);
9333 err |= setvarsafe("OPTARG", nullstr, 0);
9335 *optoff = p ? p - *(optnext - 1) : -1;
9336 *param_optind = optnext - optfirst + 1;
9337 fmtstr(s, sizeof(s), "%d", *param_optind);
9338 err |= setvarsafe("OPTIND", s, VNOFUNC);
9341 err |= setvarsafe(optvar, s, 0);
9345 flush_stdout_stderr();
9346 raise_exception(EXERROR);
9352 * The getopts builtin. Shellparam.optnext points to the next argument
9353 * to be processed. Shellparam.optptr points to the next character to
9354 * be processed in the current argument. If shellparam.optnext is NULL,
9355 * then it's the first time getopts has been called.
9358 getoptscmd(int argc, char **argv)
9363 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9365 optbase = shellparam.p;
9366 if (shellparam.optind > shellparam.nparam + 1) {
9367 shellparam.optind = 1;
9368 shellparam.optoff = -1;
9372 if (shellparam.optind > argc - 2) {
9373 shellparam.optind = 1;
9374 shellparam.optoff = -1;
9378 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9379 &shellparam.optoff);
9381 #endif /* ASH_GETOPTS */
9384 /* ============ Shell parser */
9387 * NEOF is returned by parsecmd when it encounters an end of file. It
9388 * must be distinct from NULL, so we use the address of a variable that
9389 * happens to be handy.
9391 static smallint tokpushback; /* last token pushed back */
9392 #define NEOF ((union node *)&tokpushback)
9393 static smallint parsebackquote; /* nonzero if we are inside backquotes */
9394 static int lasttoken; /* last token read */
9395 static char *wordtext; /* text of last word returned by readtoken */
9396 static struct nodelist *backquotelist;
9397 static union node *redirnode;
9398 static struct heredoc *heredoc;
9399 static smallint quoteflag; /* set if (part of) last token was quoted */
9401 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9403 raise_error_syntax(const char *msg)
9405 ash_msg_and_raise_error("syntax error: %s", msg);
9410 * Called when an unexpected token is read during the parse. The argument
9411 * is the token that is expected, or -1 if more than one type of token can
9412 * occur at this point.
9414 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9416 raise_error_unexpected_syntax(int token)
9421 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9423 sprintf(msg + l, " (expecting %s)", tokname(token));
9424 raise_error_syntax(msg);
9428 #define EOFMARKLEN 79
9431 struct heredoc *next; /* next here document in list */
9432 union node *here; /* redirection node */
9433 char *eofmark; /* string indicating end of input */
9434 int striptabs; /* if set, strip leading tabs */
9437 static struct heredoc *heredoclist; /* list of here documents to read */
9439 /* parsing is heavily cross-recursive, need these forward decls */
9440 static union node *andor(void);
9441 static union node *pipeline(void);
9442 static union node *parse_command(void);
9443 static void parseheredoc(void);
9444 static char peektoken(void);
9445 static int readtoken(void);
9450 union node *n1, *n2, *n3;
9453 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9454 if (nlflag == 2 && peektoken())
9460 if (tok == TBACKGND) {
9461 if (n2->type == NPIPE) {
9462 n2->npipe.backgnd = 1;
9464 if (n2->type != NREDIR) {
9465 n3 = stalloc(sizeof(struct nredir));
9467 n3->nredir.redirect = NULL;
9470 n2->type = NBACKGND;
9476 n3 = stalloc(sizeof(struct nbinary));
9478 n3->nbinary.ch1 = n1;
9479 n3->nbinary.ch2 = n2;
9495 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9503 pungetc(); /* push back EOF on input */
9507 raise_error_unexpected_syntax(-1);
9517 union node *n1, *n2, *n3;
9525 } else if (t == TOR) {
9531 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9533 n3 = stalloc(sizeof(struct nbinary));
9535 n3->nbinary.ch1 = n1;
9536 n3->nbinary.ch2 = n2;
9544 union node *n1, *n2, *pipenode;
9545 struct nodelist *lp, *prev;
9549 TRACE(("pipeline: entered\n"));
9550 if (readtoken() == TNOT) {
9552 checkkwd = CHKKWD | CHKALIAS;
9555 n1 = parse_command();
9556 if (readtoken() == TPIPE) {
9557 pipenode = stalloc(sizeof(struct npipe));
9558 pipenode->type = NPIPE;
9559 pipenode->npipe.backgnd = 0;
9560 lp = stalloc(sizeof(struct nodelist));
9561 pipenode->npipe.cmdlist = lp;
9565 lp = stalloc(sizeof(struct nodelist));
9566 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9567 lp->n = parse_command();
9569 } while (readtoken() == TPIPE);
9575 n2 = stalloc(sizeof(struct nnot));
9588 n = stalloc(sizeof(struct narg));
9590 n->narg.next = NULL;
9591 n->narg.text = wordtext;
9592 n->narg.backquote = backquotelist;
9597 fixredir(union node *n, const char *text, int err)
9599 TRACE(("Fix redir %s %d\n", text, err));
9601 n->ndup.vname = NULL;
9603 if (isdigit(text[0]) && text[1] == '\0')
9604 n->ndup.dupfd = text[0] - '0';
9605 else if (LONE_DASH(text))
9609 raise_error_syntax("Bad fd number");
9610 n->ndup.vname = makename();
9615 * Returns true if the text contains nothing to expand (no dollar signs
9619 noexpand(char *text)
9625 while ((c = *p++) != '\0') {
9626 if (c == CTLQUOTEMARK)
9630 else if (SIT(c, BASESYNTAX) == CCTL)
9639 union node *n = redirnode;
9641 if (readtoken() != TWORD)
9642 raise_error_unexpected_syntax(-1);
9643 if (n->type == NHERE) {
9644 struct heredoc *here = heredoc;
9650 TRACE(("Here document %d\n", n->type));
9651 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9652 raise_error_syntax("Illegal eof marker for << redirection");
9653 rmescapes(wordtext);
9654 here->eofmark = wordtext;
9656 if (heredoclist == NULL)
9659 for (p = heredoclist; p->next; p = p->next);
9662 } else if (n->type == NTOFD || n->type == NFROMFD) {
9663 fixredir(n, wordtext, 0);
9665 n->nfile.fname = makename();
9672 union node *args, **app;
9673 union node *n = NULL;
9674 union node *vars, **vpp;
9675 union node **rpp, *redir;
9685 savecheckkwd = CHKALIAS;
9687 checkkwd = savecheckkwd;
9688 switch (readtoken()) {
9690 n = stalloc(sizeof(struct narg));
9692 n->narg.text = wordtext;
9693 n->narg.backquote = backquotelist;
9694 if (savecheckkwd && isassignment(wordtext)) {
9696 vpp = &n->narg.next;
9699 app = &n->narg.next;
9704 *rpp = n = redirnode;
9705 rpp = &n->nfile.next;
9706 parsefname(); /* read name of redirection file */
9709 if (args && app == &args->narg.next
9712 struct builtincmd *bcmd;
9715 /* We have a function */
9716 if (readtoken() != TRP)
9717 raise_error_unexpected_syntax(TRP);
9718 name = n->narg.text;
9720 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9722 raise_error_syntax("Bad function name");
9725 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9726 n->narg.next = parse_command();
9739 n = stalloc(sizeof(struct ncmd));
9741 n->ncmd.args = args;
9742 n->ncmd.assign = vars;
9743 n->ncmd.redirect = redir;
9750 union node *n1, *n2;
9751 union node *ap, **app;
9752 union node *cp, **cpp;
9753 union node *redir, **rpp;
9760 switch (readtoken()) {
9762 raise_error_unexpected_syntax(-1);
9765 n1 = stalloc(sizeof(struct nif));
9767 n1->nif.test = list(0);
9768 if (readtoken() != TTHEN)
9769 raise_error_unexpected_syntax(TTHEN);
9770 n1->nif.ifpart = list(0);
9772 while (readtoken() == TELIF) {
9773 n2->nif.elsepart = stalloc(sizeof(struct nif));
9774 n2 = n2->nif.elsepart;
9776 n2->nif.test = list(0);
9777 if (readtoken() != TTHEN)
9778 raise_error_unexpected_syntax(TTHEN);
9779 n2->nif.ifpart = list(0);
9781 if (lasttoken == TELSE)
9782 n2->nif.elsepart = list(0);
9784 n2->nif.elsepart = NULL;
9792 n1 = stalloc(sizeof(struct nbinary));
9793 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9794 n1->nbinary.ch1 = list(0);
9797 TRACE(("expecting DO got %s %s\n", tokname(got),
9798 got == TWORD ? wordtext : ""));
9799 raise_error_unexpected_syntax(TDO);
9801 n1->nbinary.ch2 = list(0);
9806 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9807 raise_error_syntax("Bad for loop variable");
9808 n1 = stalloc(sizeof(struct nfor));
9810 n1->nfor.var = wordtext;
9811 checkkwd = CHKKWD | CHKALIAS;
9812 if (readtoken() == TIN) {
9814 while (readtoken() == TWORD) {
9815 n2 = stalloc(sizeof(struct narg));
9817 n2->narg.text = wordtext;
9818 n2->narg.backquote = backquotelist;
9820 app = &n2->narg.next;
9824 if (lasttoken != TNL && lasttoken != TSEMI)
9825 raise_error_unexpected_syntax(-1);
9827 n2 = stalloc(sizeof(struct narg));
9829 n2->narg.text = (char *)dolatstr;
9830 n2->narg.backquote = NULL;
9831 n2->narg.next = NULL;
9834 * Newline or semicolon here is optional (but note
9835 * that the original Bourne shell only allowed NL).
9837 if (lasttoken != TNL && lasttoken != TSEMI)
9840 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9841 if (readtoken() != TDO)
9842 raise_error_unexpected_syntax(TDO);
9843 n1->nfor.body = list(0);
9847 n1 = stalloc(sizeof(struct ncase));
9849 if (readtoken() != TWORD)
9850 raise_error_unexpected_syntax(TWORD);
9851 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9853 n2->narg.text = wordtext;
9854 n2->narg.backquote = backquotelist;
9855 n2->narg.next = NULL;
9857 checkkwd = CHKKWD | CHKALIAS;
9858 } while (readtoken() == TNL);
9859 if (lasttoken != TIN)
9860 raise_error_unexpected_syntax(TIN);
9861 cpp = &n1->ncase.cases;
9863 checkkwd = CHKNL | CHKKWD;
9865 while (t != TESAC) {
9866 if (lasttoken == TLP)
9868 *cpp = cp = stalloc(sizeof(struct nclist));
9870 app = &cp->nclist.pattern;
9872 *app = ap = stalloc(sizeof(struct narg));
9874 ap->narg.text = wordtext;
9875 ap->narg.backquote = backquotelist;
9876 if (readtoken() != TPIPE)
9878 app = &ap->narg.next;
9881 ap->narg.next = NULL;
9882 if (lasttoken != TRP)
9883 raise_error_unexpected_syntax(TRP);
9884 cp->nclist.body = list(2);
9886 cpp = &cp->nclist.next;
9888 checkkwd = CHKNL | CHKKWD;
9892 raise_error_unexpected_syntax(TENDCASE);
9899 n1 = stalloc(sizeof(struct nredir));
9900 n1->type = NSUBSHELL;
9901 n1->nredir.n = list(0);
9902 n1->nredir.redirect = NULL;
9915 if (readtoken() != t)
9916 raise_error_unexpected_syntax(t);
9919 /* Now check for redirection which may follow command */
9920 checkkwd = CHKKWD | CHKALIAS;
9922 while (readtoken() == TREDIR) {
9923 *rpp = n2 = redirnode;
9924 rpp = &n2->nfile.next;
9930 if (n1->type != NSUBSHELL) {
9931 n2 = stalloc(sizeof(struct nredir));
9936 n1->nredir.redirect = redir;
9942 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9943 * is not NULL, read a here document. In the latter case, eofmark is the
9944 * word which marks the end of the document and striptabs is true if
9945 * leading tabs should be stripped from the document. The argument firstc
9946 * is the first character of the input token or document.
9948 * Because C does not have internal subroutines, I have simulated them
9949 * using goto's to implement the subroutine linkage. The following macros
9950 * will run code that appears at the end of readtoken1.
9953 #define CHECKEND() {goto checkend; checkend_return:;}
9954 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9955 #define PARSESUB() {goto parsesub; parsesub_return:;}
9956 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9957 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9958 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9961 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
9963 /* NB: syntax parameter fits into smallint */
9967 char line[EOFMARKLEN + 1];
9968 struct nodelist *bqlist;
9972 smallint prevsyntax; /* syntax before arithmetic */
9973 #if ENABLE_ASH_EXPAND_PRMT
9974 smallint pssyntax; /* we are expanding a prompt string */
9976 int varnest; /* levels of variables expansion */
9977 int arinest; /* levels of arithmetic expansion */
9978 int parenlevel; /* levels of parens in arithmetic */
9979 int dqvarnest; /* levels of variables expansion within double quotes */
9982 /* Avoid longjmp clobbering */
9994 startlinno = plinno;
9999 #if ENABLE_ASH_EXPAND_PRMT
10000 pssyntax = (syntax == PSSYNTAX);
10004 dblquote = (syntax == DQSYNTAX);
10010 STARTSTACKSTR(out);
10011 loop: { /* for each line, until end of word */
10012 CHECKEND(); /* set c to PEOF if at end of here document */
10013 for (;;) { /* until end of line or end of word */
10014 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10015 switch (SIT(c, syntax)) {
10016 case CNL: /* '\n' */
10017 if (syntax == BASESYNTAX)
10018 goto endword; /* exit outer loop */
10024 goto loop; /* continue outer loop */
10029 if (eofmark == NULL || dblquote)
10030 USTPUTC(CTLESC, out);
10033 case CBACK: /* backslash */
10036 USTPUTC(CTLESC, out);
10037 USTPUTC('\\', out);
10039 } else if (c == '\n') {
10043 #if ENABLE_ASH_EXPAND_PRMT
10044 if (c == '$' && pssyntax) {
10045 USTPUTC(CTLESC, out);
10046 USTPUTC('\\', out);
10050 c != '\\' && c != '`' &&
10055 USTPUTC(CTLESC, out);
10056 USTPUTC('\\', out);
10058 if (SIT(c, SQSYNTAX) == CCTL)
10059 USTPUTC(CTLESC, out);
10067 if (eofmark == NULL) {
10068 USTPUTC(CTLQUOTEMARK, out);
10076 if (eofmark != NULL && arinest == 0
10081 if (dqvarnest == 0) {
10082 syntax = BASESYNTAX;
10089 case CVAR: /* '$' */
10090 PARSESUB(); /* parse substitution */
10092 case CENDVAR: /* '}' */
10095 if (dqvarnest > 0) {
10098 USTPUTC(CTLENDVAR, out);
10103 #if ENABLE_ASH_MATH_SUPPORT
10104 case CLP: /* '(' in arithmetic */
10108 case CRP: /* ')' in arithmetic */
10109 if (parenlevel > 0) {
10113 if (pgetc() == ')') {
10114 if (--arinest == 0) {
10115 USTPUTC(CTLENDARI, out);
10116 syntax = prevsyntax;
10117 dblquote = (syntax == DQSYNTAX);
10122 * unbalanced parens
10123 * (don't 2nd guess - no error)
10131 case CBQUOTE: /* '`' */
10135 goto endword; /* exit outer loop */
10140 goto endword; /* exit outer loop */
10141 #if ENABLE_ASH_ALIAS
10151 #if ENABLE_ASH_MATH_SUPPORT
10152 if (syntax == ARISYNTAX)
10153 raise_error_syntax("Missing '))'");
10155 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10156 raise_error_syntax("Unterminated quoted string");
10157 if (varnest != 0) {
10158 startlinno = plinno;
10160 raise_error_syntax("Missing '}'");
10162 USTPUTC('\0', out);
10163 len = out - (char *)stackblock();
10164 out = stackblock();
10165 if (eofmark == NULL) {
10166 if ((c == '>' || c == '<')
10169 && (*out == '\0' || isdigit(*out))) {
10171 return lasttoken = TREDIR;
10176 quoteflag = quotef;
10177 backquotelist = bqlist;
10178 grabstackblock(len);
10182 /* end of readtoken routine */
10185 * Check to see whether we are at the end of the here document. When this
10186 * is called, c is set to the first character of the next input line. If
10187 * we are at the end of the here document, this routine sets the c to PEOF.
10191 #if ENABLE_ASH_ALIAS
10197 while (c == '\t') {
10201 if (c == *eofmark) {
10202 if (pfgets(line, sizeof(line)) != NULL) {
10206 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10207 if (*p == '\n' && *q == '\0') {
10210 needprompt = doprompt;
10212 pushstring(line, NULL);
10217 goto checkend_return;
10221 * Parse a redirection operator. The variable "out" points to a string
10222 * specifying the fd to be redirected. The variable "c" contains the
10223 * first character of the redirection operator.
10229 np = stalloc(sizeof(struct nfile));
10234 np->type = NAPPEND;
10236 np->type = NCLOBBER;
10243 } else { /* c == '<' */
10248 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10249 np = stalloc(sizeof(struct nhere));
10253 heredoc = stalloc(sizeof(struct heredoc));
10254 heredoc->here = np;
10257 heredoc->striptabs = 1;
10259 heredoc->striptabs = 0;
10265 np->type = NFROMFD;
10269 np->type = NFROMTO;
10279 np->nfile.fd = fd - '0';
10281 goto parseredir_return;
10285 * Parse a substitution. At this point, we have read the dollar sign
10286 * and nothing else.
10289 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10290 * (assuming ascii char codes, as the original implementation did) */
10291 #define is_special(c) \
10292 ((((unsigned int)c) - 33 < 32) \
10293 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10299 static const char types[] ALIGN1 = "}-+?=";
10303 c <= PEOA_OR_PEOF ||
10304 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10308 } else if (c == '(') { /* $(command) or $((arith)) */
10309 if (pgetc() == '(') {
10310 #if ENABLE_ASH_MATH_SUPPORT
10313 raise_error_syntax("We unsupport $((arith))");
10320 USTPUTC(CTLVAR, out);
10321 typeloc = out - (char *)stackblock();
10322 USTPUTC(VSNORMAL, out);
10323 subtype = VSNORMAL;
10331 subtype = VSLENGTH;
10335 if (c > PEOA_OR_PEOF && is_name(c)) {
10339 } while (c > PEOA_OR_PEOF && is_in_name(c));
10340 } else if (isdigit(c)) {
10344 } while (isdigit(c));
10345 } else if (is_special(c)) {
10349 badsub: raise_error_syntax("Bad substitution");
10353 if (subtype == 0) {
10360 p = strchr(types, c);
10363 subtype = p - types + VSNORMAL;
10369 subtype = c == '#' ? VSTRIMLEFT :
10382 if (dblquote || arinest)
10384 *((char *)stackblock() + typeloc) = subtype | flags;
10385 if (subtype != VSNORMAL) {
10387 if (dblquote || arinest) {
10392 goto parsesub_return;
10396 * Called to parse command substitutions. Newstyle is set if the command
10397 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10398 * list of commands (passed by reference), and savelen is the number of
10399 * characters on the top of the stack which must be preserved.
10402 struct nodelist **nlpp;
10405 char *volatile str;
10406 struct jmploc jmploc;
10407 struct jmploc *volatile savehandler;
10409 smallint saveprompt = 0;
10412 (void) &saveprompt;
10414 savepbq = parsebackquote;
10415 if (setjmp(jmploc.loc)) {
10417 parsebackquote = 0;
10418 exception_handler = savehandler;
10419 longjmp(exception_handler->loc, 1);
10423 savelen = out - (char *)stackblock();
10425 str = ckmalloc(savelen);
10426 memcpy(str, stackblock(), savelen);
10428 savehandler = exception_handler;
10429 exception_handler = &jmploc;
10432 /* We must read until the closing backquote, giving special
10433 treatment to some slashes, and then push the string and
10434 reread it as input, interpreting it normally. */
10441 STARTSTACKSTR(pout);
10458 * If eating a newline, avoid putting
10459 * the newline into the new character
10460 * stream (via the STPUTC after the
10465 if (pc != '\\' && pc != '`' && pc != '$'
10466 && (!dblquote || pc != '"'))
10467 STPUTC('\\', pout);
10468 if (pc > PEOA_OR_PEOF) {
10474 #if ENABLE_ASH_ALIAS
10477 startlinno = plinno;
10478 raise_error_syntax("EOF in backquote substitution");
10482 needprompt = doprompt;
10491 STPUTC('\0', pout);
10492 psavelen = pout - (char *)stackblock();
10493 if (psavelen > 0) {
10494 pstr = grabstackstr(pout);
10495 setinputstring(pstr);
10500 nlpp = &(*nlpp)->next;
10501 *nlpp = stalloc(sizeof(**nlpp));
10502 (*nlpp)->next = NULL;
10503 parsebackquote = oldstyle;
10506 saveprompt = doprompt;
10513 doprompt = saveprompt;
10514 else if (readtoken() != TRP)
10515 raise_error_unexpected_syntax(TRP);
10520 * Start reading from old file again, ignoring any pushed back
10521 * tokens left from the backquote parsing
10526 while (stackblocksize() <= savelen)
10528 STARTSTACKSTR(out);
10530 memcpy(out, str, savelen);
10531 STADJUST(savelen, out);
10537 parsebackquote = savepbq;
10538 exception_handler = savehandler;
10539 if (arinest || dblquote)
10540 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10542 USTPUTC(CTLBACKQ, out);
10544 goto parsebackq_oldreturn;
10545 goto parsebackq_newreturn;
10548 #if ENABLE_ASH_MATH_SUPPORT
10550 * Parse an arithmetic expansion (indicate start of one and set state)
10553 if (++arinest == 1) {
10554 prevsyntax = syntax;
10555 syntax = ARISYNTAX;
10556 USTPUTC(CTLARI, out);
10563 * we collapse embedded arithmetic expansion to
10564 * parenthesis, which should be equivalent
10568 goto parsearith_return;
10572 } /* end of readtoken */
10575 * Read the next input token.
10576 * If the token is a word, we set backquotelist to the list of cmds in
10577 * backquotes. We set quoteflag to true if any part of the word was
10579 * If the token is TREDIR, then we set redirnode to a structure containing
10581 * In all cases, the variable startlinno is set to the number of the line
10582 * on which the token starts.
10584 * [Change comment: here documents and internal procedures]
10585 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10586 * word parsing code into a separate routine. In this case, readtoken
10587 * doesn't need to have any internal procedures, but parseword does.
10588 * We could also make parseoperator in essence the main routine, and
10589 * have parseword (readtoken1?) handle both words and redirection.]
10591 #define NEW_xxreadtoken
10592 #ifdef NEW_xxreadtoken
10593 /* singles must be first! */
10594 static const char xxreadtoken_chars[7] ALIGN1 = {
10595 '\n', '(', ')', '&', '|', ';', 0
10598 static const char xxreadtoken_tokens[] ALIGN1 = {
10599 TNL, TLP, TRP, /* only single occurrence allowed */
10600 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10601 TEOF, /* corresponds to trailing nul */
10602 TAND, TOR, TENDCASE /* if double occurrence */
10605 #define xxreadtoken_doubles \
10606 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10607 #define xxreadtoken_singles \
10608 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10622 startlinno = plinno;
10623 for (;;) { /* until token or start of word found */
10626 if ((c != ' ') && (c != '\t')
10627 #if ENABLE_ASH_ALIAS
10632 while ((c = pgetc()) != '\n' && c != PEOF);
10634 } else if (c == '\\') {
10635 if (pgetc() != '\n') {
10639 startlinno = ++plinno;
10644 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10649 needprompt = doprompt;
10652 p = strchr(xxreadtoken_chars, c);
10655 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10658 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10659 if (pgetc() == *p) { /* double occurrence? */
10660 p += xxreadtoken_doubles + 1;
10666 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10672 #define RETURN(token) return lasttoken = token
10685 startlinno = plinno;
10686 for (;;) { /* until token or start of word found */
10689 case ' ': case '\t':
10690 #if ENABLE_ASH_ALIAS
10695 while ((c = pgetc()) != '\n' && c != PEOF);
10699 if (pgetc() == '\n') {
10700 startlinno = ++plinno;
10709 needprompt = doprompt;
10714 if (pgetc() == '&')
10719 if (pgetc() == '|')
10724 if (pgetc() == ';')
10737 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10740 #endif /* NEW_xxreadtoken */
10747 smallint alreadyseen = tokpushback;
10750 #if ENABLE_ASH_ALIAS
10759 if (checkkwd & CHKNL) {
10766 if (t != TWORD || quoteflag) {
10771 * check for keywords
10773 if (checkkwd & CHKKWD) {
10774 const char *const *pp;
10776 pp = findkwd(wordtext);
10778 lasttoken = t = pp - tokname_array;
10779 TRACE(("keyword %s recognized\n", tokname(t)));
10784 if (checkkwd & CHKALIAS) {
10785 #if ENABLE_ASH_ALIAS
10787 ap = lookupalias(wordtext, 1);
10790 pushstring(ap->val, ap);
10800 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10802 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10814 return tokname_array[t][0];
10818 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10819 * valid parse tree indicating a blank line.)
10821 static union node *
10822 parsecmd(int interact)
10827 doprompt = interact;
10829 setprompt(doprompt);
10841 * Input any here documents.
10846 struct heredoc *here;
10849 here = heredoclist;
10856 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10857 here->eofmark, here->striptabs);
10858 n = stalloc(sizeof(struct narg));
10859 n->narg.type = NARG;
10860 n->narg.next = NULL;
10861 n->narg.text = wordtext;
10862 n->narg.backquote = backquotelist;
10863 here->here->nhere.doc = n;
10870 * called by editline -- any expansions to the prompt should be added here.
10872 #if ENABLE_ASH_EXPAND_PRMT
10873 static const char *
10874 expandstr(const char *ps)
10878 /* XXX Fix (char *) cast. */
10879 setinputstring((char *)ps);
10880 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
10883 n.narg.type = NARG;
10884 n.narg.next = NULL;
10885 n.narg.text = wordtext;
10886 n.narg.backquote = backquotelist;
10888 expandarg(&n, NULL, 0);
10889 return stackblock();
10894 * Execute a command or commands contained in a string.
10897 evalstring(char *s, int mask)
10900 struct stackmark smark;
10904 setstackmark(&smark);
10907 while ((n = parsecmd(0)) != NEOF) {
10909 popstackmark(&smark);
10922 * The eval command.
10925 evalcmd(int argc, char **argv)
10934 STARTSTACKSTR(concat);
10937 concat = stack_putstr(p, concat);
10941 STPUTC(' ', concat);
10943 STPUTC('\0', concat);
10944 p = grabstackstr(concat);
10946 evalstring(p, ~SKIPEVAL);
10953 * Read and execute commands. "Top" is nonzero for the top level command
10954 * loop; it turns on prompting if the shell is interactive.
10960 struct stackmark smark;
10964 TRACE(("cmdloop(%d) called\n", top));
10968 setstackmark(&smark);
10971 showjobs(stderr, SHOW_CHANGED);
10974 if (iflag && top) {
10976 #if ENABLE_ASH_MAIL
10980 n = parsecmd(inter);
10981 /* showtree(n); DEBUG */
10983 if (!top || numeof >= 50)
10985 if (!stoppedjobs()) {
10988 out2str("\nUse \"exit\" to leave shell.\n");
10991 } else if (nflag == 0) {
10992 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
10997 popstackmark(&smark);
11002 return skip & SKIPEVAL;
11009 * Take commands from a file. To be compatible we should do a path
11010 * search for the file, which is necessary to find sub-commands.
11013 find_dot_file(char *name)
11016 const char *path = pathval();
11019 /* don't try this for absolute or relative paths */
11020 if (strchr(name, '/'))
11023 while ((fullname = padvance(&path, name)) != NULL) {
11024 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11026 * Don't bother freeing here, since it will
11027 * be freed by the caller.
11031 stunalloc(fullname);
11034 /* not found in the PATH */
11035 ash_msg_and_raise_error("%s: not found", name);
11040 dotcmd(int argc, char **argv)
11042 struct strlist *sp;
11043 volatile struct shparam saveparam;
11046 for (sp = cmdenviron; sp; sp = sp->next)
11047 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11049 if (argc >= 2) { /* That's what SVR2 does */
11052 fullname = find_dot_file(argv[1]);
11055 saveparam = shellparam;
11056 shellparam.malloced = 0;
11057 shellparam.nparam = argc - 2;
11058 shellparam.p = argv + 2;
11061 setinputfile(fullname, INPUT_PUSH_FILE);
11062 commandname = fullname;
11067 freeparam(&shellparam);
11068 shellparam = saveparam;
11070 status = exitstatus;
11076 exitcmd(int argc, char **argv)
11081 exitstatus = number(argv[1]);
11082 raise_exception(EXEXIT);
11086 #if ENABLE_ASH_BUILTIN_ECHO
11088 echocmd(int argc, char **argv)
11090 return echo_main(argc, argv);
11094 #if ENABLE_ASH_BUILTIN_TEST
11096 testcmd(int argc, char **argv)
11098 return test_main(argc, argv);
11103 * Read a file containing shell functions.
11106 readcmdfile(char *name)
11108 setinputfile(name, INPUT_PUSH_FILE);
11114 /* ============ find_command inplementation */
11117 * Resolve a command name. If you change this routine, you may have to
11118 * change the shellexec routine as well.
11121 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11123 struct tblentry *cmdp;
11130 struct builtincmd *bcmd;
11132 /* If name contains a slash, don't use PATH or hash table */
11133 if (strchr(name, '/') != NULL) {
11134 entry->u.index = -1;
11135 if (act & DO_ABS) {
11136 while (stat(name, &statb) < 0) {
11138 if (errno == EINTR)
11141 entry->cmdtype = CMDUNKNOWN;
11145 entry->cmdtype = CMDNORMAL;
11149 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11151 updatetbl = (path == pathval());
11154 if (strstr(path, "%builtin") != NULL)
11155 act |= DO_ALTBLTIN;
11158 /* If name is in the table, check answer will be ok */
11159 cmdp = cmdlookup(name, 0);
11160 if (cmdp != NULL) {
11163 switch (cmdp->cmdtype) {
11181 } else if (cmdp->rehash == 0)
11182 /* if not invalidated by cd, we're done */
11186 /* If %builtin not in path, check for builtin next */
11187 bcmd = find_builtin(name);
11189 if (IS_BUILTIN_REGULAR(bcmd))
11190 goto builtin_success;
11191 if (act & DO_ALTPATH) {
11192 if (!(act & DO_ALTBLTIN))
11193 goto builtin_success;
11194 } else if (builtinloc <= 0) {
11195 goto builtin_success;
11199 #if ENABLE_FEATURE_SH_STANDALONE
11200 if (find_applet_by_name(name) >= 0) {
11201 entry->cmdtype = CMDNORMAL;
11202 entry->u.index = -1;
11207 /* We have to search path. */
11208 prev = -1; /* where to start */
11209 if (cmdp && cmdp->rehash) { /* doing a rehash */
11210 if (cmdp->cmdtype == CMDBUILTIN)
11213 prev = cmdp->param.index;
11219 while ((fullname = padvance(&path, name)) != NULL) {
11220 stunalloc(fullname);
11221 /* NB: code below will still use fullname
11222 * despite it being "unallocated" */
11225 if (prefix(pathopt, "builtin")) {
11227 goto builtin_success;
11229 } else if (!(act & DO_NOFUNC)
11230 && prefix(pathopt, "func")) {
11231 /* handled below */
11233 /* ignore unimplemented options */
11237 /* if rehash, don't redo absolute path names */
11238 if (fullname[0] == '/' && idx <= prev) {
11241 TRACE(("searchexec \"%s\": no change\n", name));
11244 while (stat(fullname, &statb) < 0) {
11246 if (errno == EINTR)
11249 if (errno != ENOENT && errno != ENOTDIR)
11253 e = EACCES; /* if we fail, this will be the error */
11254 if (!S_ISREG(statb.st_mode))
11256 if (pathopt) { /* this is a %func directory */
11257 stalloc(strlen(fullname) + 1);
11258 /* NB: stalloc will return space pointed by fullname
11259 * (because we don't have any intervening allocations
11260 * between stunalloc above and this stalloc) */
11261 readcmdfile(fullname);
11262 cmdp = cmdlookup(name, 0);
11263 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11264 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11265 stunalloc(fullname);
11268 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11270 entry->cmdtype = CMDNORMAL;
11271 entry->u.index = idx;
11275 cmdp = cmdlookup(name, 1);
11276 cmdp->cmdtype = CMDNORMAL;
11277 cmdp->param.index = idx;
11282 /* We failed. If there was an entry for this command, delete it */
11283 if (cmdp && updatetbl)
11284 delete_cmd_entry();
11286 ash_msg("%s: %s", name, errmsg(e, "not found"));
11287 entry->cmdtype = CMDUNKNOWN;
11292 entry->cmdtype = CMDBUILTIN;
11293 entry->u.cmd = bcmd;
11297 cmdp = cmdlookup(name, 1);
11298 cmdp->cmdtype = CMDBUILTIN;
11299 cmdp->param.cmd = bcmd;
11303 entry->cmdtype = cmdp->cmdtype;
11304 entry->u = cmdp->param;
11308 /* ============ trap.c */
11311 * The trap builtin.
11314 trapcmd(int argc, char **argv)
11323 for (signo = 0; signo < NSIG; signo++) {
11324 if (trap[signo] != NULL) {
11327 sn = get_signame(signo);
11328 out1fmt("trap -- %s %s\n",
11329 single_quote(trap[signo]), sn);
11339 signo = get_signum(*ap);
11341 ash_msg_and_raise_error("%s: bad trap", *ap);
11344 if (LONE_DASH(action))
11347 action = ckstrdup(action);
11350 trap[signo] = action;
11360 /* ============ Builtins */
11362 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11364 * Lists available builtins
11367 helpcmd(int argc, char **argv)
11371 out1fmt("\nBuilt-in commands:\n-------------------\n");
11372 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11373 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11374 builtintab[i].name + 1);
11380 #if ENABLE_FEATURE_SH_STANDALONE
11382 const char *a = applet_names;
11384 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11389 a += strlen(a) + 1;
11394 return EXIT_SUCCESS;
11396 #endif /* FEATURE_SH_EXTRA_QUIET */
11399 * The export and readonly commands.
11402 exportcmd(int argc, char **argv)
11408 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11410 if (nextopt("p") != 'p') {
11415 p = strchr(name, '=');
11419 vp = *findvar(hashvar(name), name);
11425 setvar(name, p, flag);
11426 } while ((name = *++aptr) != NULL);
11430 showvars(argv[0], flag, 0);
11435 * Delete a function if it exists.
11438 unsetfunc(const char *name)
11440 struct tblentry *cmdp;
11442 cmdp = cmdlookup(name, 0);
11443 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11444 delete_cmd_entry();
11448 * The unset builtin command. We unset the function before we unset the
11449 * variable to allow a function to be unset when there is a readonly variable
11450 * with the same name.
11453 unsetcmd(int argc, char **argv)
11460 while ((i = nextopt("vf")) != '\0') {
11464 for (ap = argptr; *ap; ap++) {
11480 #include <sys/times.h>
11482 static const unsigned char timescmd_str[] ALIGN1 = {
11483 ' ', offsetof(struct tms, tms_utime),
11484 '\n', offsetof(struct tms, tms_stime),
11485 ' ', offsetof(struct tms, tms_cutime),
11486 '\n', offsetof(struct tms, tms_cstime),
11491 timescmd(int ac, char **av)
11493 long clk_tck, s, t;
11494 const unsigned char *p;
11497 clk_tck = sysconf(_SC_CLK_TCK);
11502 t = *(clock_t *)(((char *) &buf) + p[1]);
11504 out1fmt("%ldm%ld.%.3lds%c",
11506 ((t - s * clk_tck) * 1000) / clk_tck,
11508 } while (*(p += 2));
11513 #if ENABLE_ASH_MATH_SUPPORT
11515 dash_arith(const char *s)
11521 result = arith(s, &errcode);
11524 ash_msg_and_raise_error("exponent less than 0");
11526 ash_msg_and_raise_error("divide by zero");
11528 ash_msg_and_raise_error("expression recursion loop detected");
11529 raise_error_syntax(s);
11537 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11538 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11540 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11543 letcmd(int argc, char **argv)
11550 ash_msg_and_raise_error("expression expected");
11551 for (ap = argv + 1; *ap; ap++) {
11552 i = dash_arith(*ap);
11557 #endif /* ASH_MATH_SUPPORT */
11560 /* ============ miscbltin.c
11562 * Miscellaneous builtins.
11567 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11568 typedef enum __rlimit_resource rlim_t;
11572 * The read builtin. The -e option causes backslashes to escape the
11573 * following character.
11575 * This uses unbuffered input, which may be avoidable in some cases.
11578 readcmd(int argc, char **argv)
11590 #if ENABLE_ASH_READ_NCHARS
11594 struct termios tty, old_tty;
11596 #if ENABLE_ASH_READ_TIMEOUT
11600 ts.tv_sec = ts.tv_usec = 0;
11605 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11606 while ((i = nextopt("p:rt:n:s")) != '\0')
11607 #elif ENABLE_ASH_READ_NCHARS
11608 while ((i = nextopt("p:rn:s")) != '\0')
11609 #elif ENABLE_ASH_READ_TIMEOUT
11610 while ((i = nextopt("p:rt:")) != '\0')
11612 while ((i = nextopt("p:r")) != '\0')
11617 prompt = optionarg;
11619 #if ENABLE_ASH_READ_NCHARS
11621 nchars = bb_strtou(optionarg, NULL, 10);
11622 if (nchars < 0 || errno)
11623 ash_msg_and_raise_error("invalid count");
11624 n_flag = nchars; /* just a flag "nchars is nonzero" */
11630 #if ENABLE_ASH_READ_TIMEOUT
11632 ts.tv_sec = bb_strtou(optionarg, &p, 10);
11634 /* EINVAL means number is ok, but not terminated by NUL */
11635 if (*p == '.' && errno == EINVAL) {
11639 ts.tv_usec = bb_strtou(p, &p2, 10);
11641 ash_msg_and_raise_error("invalid timeout");
11643 /* normalize to usec */
11645 ash_msg_and_raise_error("invalid timeout");
11646 while (scale++ < 6)
11649 } else if (ts.tv_sec < 0 || errno) {
11650 ash_msg_and_raise_error("invalid timeout");
11652 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
11653 ash_msg_and_raise_error("invalid timeout");
11664 if (prompt && isatty(0)) {
11669 ash_msg_and_raise_error("arg count");
11670 ifs = bltinlookup("IFS");
11673 #if ENABLE_ASH_READ_NCHARS
11674 if (n_flag || silent) {
11675 if (tcgetattr(0, &tty) != 0) {
11682 tty.c_lflag &= ~ICANON;
11683 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
11686 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
11688 tcsetattr(0, TCSANOW, &tty);
11692 #if ENABLE_ASH_READ_TIMEOUT
11693 if (ts.tv_sec || ts.tv_usec) {
11697 /* poll-based wait produces bigger code, using select */
11698 i = select(1, &set, NULL, NULL, &ts);
11699 if (!i) { /* timed out! */
11700 #if ENABLE_ASH_READ_NCHARS
11702 tcsetattr(0, TCSANOW, &old_tty);
11713 if (read(0, &c, 1) != 1) {
11725 if (!rflag && c == '\\') {
11731 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11735 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11737 setvar(*ap, stackblock(), 0);
11746 /* end of do {} while: */
11747 #if ENABLE_ASH_READ_NCHARS
11748 while (!n_flag || --nchars);
11753 #if ENABLE_ASH_READ_NCHARS
11754 if (n_flag || silent)
11755 tcsetattr(0, TCSANOW, &old_tty);
11759 /* Remove trailing blanks */
11760 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11762 setvar(*ap, stackblock(), 0);
11763 while (*++ap != NULL)
11764 setvar(*ap, nullstr, 0);
11769 umaskcmd(int argc, char **argv)
11771 static const char permuser[3] ALIGN1 = "ugo";
11772 static const char permmode[3] ALIGN1 = "rwx";
11773 static const short permmask[] ALIGN2 = {
11774 S_IRUSR, S_IWUSR, S_IXUSR,
11775 S_IRGRP, S_IWGRP, S_IXGRP,
11776 S_IROTH, S_IWOTH, S_IXOTH
11782 int symbolic_mode = 0;
11784 while (nextopt("S") != '\0') {
11795 if (symbolic_mode) {
11799 for (i = 0; i < 3; i++) {
11802 *p++ = permuser[i];
11804 for (j = 0; j < 3; j++) {
11805 if ((mask & permmask[3 * i + j]) == 0) {
11806 *p++ = permmode[j];
11814 out1fmt("%.4o\n", mask);
11817 if (isdigit((unsigned char) *ap)) {
11820 if (*ap >= '8' || *ap < '0')
11821 ash_msg_and_raise_error(illnum, argv[1]);
11822 mask = (mask << 3) + (*ap - '0');
11823 } while (*++ap != '\0');
11826 mask = ~mask & 0777;
11827 if (!bb_parse_mode(ap, &mask)) {
11828 ash_msg_and_raise_error("illegal mode: %s", ap);
11830 umask(~mask & 0777);
11839 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11840 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11841 * ash by J.T. Conklin.
11847 uint8_t cmd; /* RLIMIT_xxx fit into it */
11848 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
11852 static const struct limits limits_tbl[] = {
11854 { RLIMIT_CPU, 0, 't' },
11856 #ifdef RLIMIT_FSIZE
11857 { RLIMIT_FSIZE, 9, 'f' },
11860 { RLIMIT_DATA, 10, 'd' },
11862 #ifdef RLIMIT_STACK
11863 { RLIMIT_STACK, 10, 's' },
11866 { RLIMIT_CORE, 9, 'c' },
11869 { RLIMIT_RSS, 10, 'm' },
11871 #ifdef RLIMIT_MEMLOCK
11872 { RLIMIT_MEMLOCK, 10, 'l' },
11874 #ifdef RLIMIT_NPROC
11875 { RLIMIT_NPROC, 0, 'p' },
11877 #ifdef RLIMIT_NOFILE
11878 { RLIMIT_NOFILE, 0, 'n' },
11881 { RLIMIT_AS, 10, 'v' },
11883 #ifdef RLIMIT_LOCKS
11884 { RLIMIT_LOCKS, 0, 'w' },
11887 static const char limits_name[] =
11889 "time(seconds)" "\0"
11891 #ifdef RLIMIT_FSIZE
11892 "file(blocks)" "\0"
11897 #ifdef RLIMIT_STACK
11901 "coredump(blocks)" "\0"
11906 #ifdef RLIMIT_MEMLOCK
11907 "locked memory(kb)" "\0"
11909 #ifdef RLIMIT_NPROC
11912 #ifdef RLIMIT_NOFILE
11918 #ifdef RLIMIT_LOCKS
11923 enum limtype { SOFT = 0x1, HARD = 0x2 };
11926 printlim(enum limtype how, const struct rlimit *limit,
11927 const struct limits *l)
11931 val = limit->rlim_max;
11933 val = limit->rlim_cur;
11935 if (val == RLIM_INFINITY)
11936 out1fmt("unlimited\n");
11938 val >>= l->factor_shift;
11939 out1fmt("%lld\n", (long long) val);
11944 ulimitcmd(int argc, char **argv)
11948 enum limtype how = SOFT | HARD;
11949 const struct limits *l;
11952 struct rlimit limit;
11955 while ((optc = nextopt("HSa"
11959 #ifdef RLIMIT_FSIZE
11965 #ifdef RLIMIT_STACK
11974 #ifdef RLIMIT_MEMLOCK
11977 #ifdef RLIMIT_NPROC
11980 #ifdef RLIMIT_NOFILE
11986 #ifdef RLIMIT_LOCKS
12004 for (l = limits_tbl; l->option != what; l++)
12007 set = *argptr ? 1 : 0;
12011 if (all || argptr[1])
12012 ash_msg_and_raise_error("too many arguments");
12013 if (strncmp(p, "unlimited\n", 9) == 0)
12014 val = RLIM_INFINITY;
12018 while ((c = *p++) >= '0' && c <= '9') {
12019 val = (val * 10) + (long)(c - '0');
12020 if (val < (rlim_t) 0)
12024 ash_msg_and_raise_error("bad number");
12025 val <<= l->factor_shift;
12029 const char *lname = limits_name;
12030 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12031 getrlimit(l->cmd, &limit);
12032 out1fmt("%-20s ", lname);
12033 lname += strlen(lname) + 1;
12034 printlim(how, &limit, l);
12039 getrlimit(l->cmd, &limit);
12042 limit.rlim_max = val;
12044 limit.rlim_cur = val;
12045 if (setrlimit(l->cmd, &limit) < 0)
12046 ash_msg_and_raise_error("error setting limit (%m)");
12048 printlim(how, &limit, l);
12054 /* ============ Math support */
12056 #if ENABLE_ASH_MATH_SUPPORT
12058 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12060 Permission is hereby granted, free of charge, to any person obtaining
12061 a copy of this software and associated documentation files (the
12062 "Software"), to deal in the Software without restriction, including
12063 without limitation the rights to use, copy, modify, merge, publish,
12064 distribute, sublicense, and/or sell copies of the Software, and to
12065 permit persons to whom the Software is furnished to do so, subject to
12066 the following conditions:
12068 The above copyright notice and this permission notice shall be
12069 included in all copies or substantial portions of the Software.
12071 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12072 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12073 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12074 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12075 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12076 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12077 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12080 /* This is my infix parser/evaluator. It is optimized for size, intended
12081 * as a replacement for yacc-based parsers. However, it may well be faster
12082 * than a comparable parser written in yacc. The supported operators are
12083 * listed in #defines below. Parens, order of operations, and error handling
12084 * are supported. This code is thread safe. The exact expression format should
12085 * be that which POSIX specifies for shells. */
12087 /* The code uses a simple two-stack algorithm. See
12088 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12089 * for a detailed explanation of the infix-to-postfix algorithm on which
12090 * this is based (this code differs in that it applies operators immediately
12091 * to the stack instead of adding them to a queue to end up with an
12094 /* To use the routine, call it with an expression string and error return
12098 * Aug 24, 2001 Manuel Novoa III
12100 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12102 * 1) In arith_apply():
12103 * a) Cached values of *numptr and &(numptr[-1]).
12104 * b) Removed redundant test for zero denominator.
12107 * a) Eliminated redundant code for processing operator tokens by moving
12108 * to a table-based implementation. Also folded handling of parens
12110 * b) Combined all 3 loops which called arith_apply to reduce generated
12111 * code size at the cost of speed.
12113 * 3) The following expressions were treated as valid by the original code:
12114 * 1() , 0! , 1 ( *3 ) .
12115 * These bugs have been fixed by internally enclosing the expression in
12116 * parens and then checking that all binary ops and right parens are
12117 * preceded by a valid expression (NUM_TOKEN).
12119 * Note: It may be desirable to replace Aaron's test for whitespace with
12120 * ctype's isspace() if it is used by another busybox applet or if additional
12121 * whitespace chars should be considered. Look below the "#include"s for a
12122 * precompiler test.
12126 * Aug 26, 2001 Manuel Novoa III
12128 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12130 * Merge in Aaron's comments previously posted to the busybox list,
12131 * modified slightly to take account of my changes to the code.
12136 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12138 * - allow access to variable,
12139 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12140 * - realize assign syntax (VAR=expr, +=, *= etc)
12141 * - realize exponentiation (** operator)
12142 * - realize comma separated - expr, expr
12143 * - realise ++expr --expr expr++ expr--
12144 * - realise expr ? expr : expr (but, second expr calculate always)
12145 * - allow hexadecimal and octal numbers
12146 * - was restored loses XOR operator
12147 * - remove one goto label, added three ;-)
12148 * - protect $((num num)) as true zero expr (Manuel`s error)
12149 * - always use special isspace(), see comment from bash ;-)
12152 #define arith_isspace(arithval) \
12153 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12155 typedef unsigned char operator;
12157 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12158 * precedence, and 3 high bits are an ID unique across operators of that
12159 * precedence. The ID portion is so that multiple operators can have the
12160 * same precedence, ensuring that the leftmost one is evaluated first.
12161 * Consider * and /. */
12163 #define tok_decl(prec,id) (((id)<<5)|(prec))
12164 #define PREC(op) ((op) & 0x1F)
12166 #define TOK_LPAREN tok_decl(0,0)
12168 #define TOK_COMMA tok_decl(1,0)
12170 #define TOK_ASSIGN tok_decl(2,0)
12171 #define TOK_AND_ASSIGN tok_decl(2,1)
12172 #define TOK_OR_ASSIGN tok_decl(2,2)
12173 #define TOK_XOR_ASSIGN tok_decl(2,3)
12174 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12175 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12176 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12177 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12179 #define TOK_MUL_ASSIGN tok_decl(3,0)
12180 #define TOK_DIV_ASSIGN tok_decl(3,1)
12181 #define TOK_REM_ASSIGN tok_decl(3,2)
12183 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12184 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12186 /* conditional is right associativity too */
12187 #define TOK_CONDITIONAL tok_decl(4,0)
12188 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12190 #define TOK_OR tok_decl(5,0)
12192 #define TOK_AND tok_decl(6,0)
12194 #define TOK_BOR tok_decl(7,0)
12196 #define TOK_BXOR tok_decl(8,0)
12198 #define TOK_BAND tok_decl(9,0)
12200 #define TOK_EQ tok_decl(10,0)
12201 #define TOK_NE tok_decl(10,1)
12203 #define TOK_LT tok_decl(11,0)
12204 #define TOK_GT tok_decl(11,1)
12205 #define TOK_GE tok_decl(11,2)
12206 #define TOK_LE tok_decl(11,3)
12208 #define TOK_LSHIFT tok_decl(12,0)
12209 #define TOK_RSHIFT tok_decl(12,1)
12211 #define TOK_ADD tok_decl(13,0)
12212 #define TOK_SUB tok_decl(13,1)
12214 #define TOK_MUL tok_decl(14,0)
12215 #define TOK_DIV tok_decl(14,1)
12216 #define TOK_REM tok_decl(14,2)
12218 /* exponent is right associativity */
12219 #define TOK_EXPONENT tok_decl(15,1)
12221 /* For now unary operators. */
12222 #define UNARYPREC 16
12223 #define TOK_BNOT tok_decl(UNARYPREC,0)
12224 #define TOK_NOT tok_decl(UNARYPREC,1)
12226 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12227 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12229 #define PREC_PRE (UNARYPREC+2)
12231 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12232 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12234 #define PREC_POST (UNARYPREC+3)
12236 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12237 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12239 #define SPEC_PREC (UNARYPREC+4)
12241 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12242 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12244 #define NUMPTR (*numstackptr)
12247 tok_have_assign(operator op)
12249 operator prec = PREC(op);
12251 convert_prec_is_assing(prec);
12252 return (prec == PREC(TOK_ASSIGN) ||
12253 prec == PREC_PRE || prec == PREC_POST);
12257 is_right_associativity(operator prec)
12259 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12260 || prec == PREC(TOK_CONDITIONAL));
12263 typedef struct ARITCH_VAR_NUM {
12265 arith_t contidional_second_val;
12266 char contidional_second_val_initialized;
12267 char *var; /* if NULL then is regular number,
12268 else is variable name */
12271 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12273 struct CHK_VAR_RECURSIVE_LOOPED *next;
12274 } chk_var_recursive_looped_t;
12276 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12279 arith_lookup_val(v_n_t *t)
12282 const char * p = lookupvar(t->var);
12287 /* recursive try as expression */
12288 chk_var_recursive_looped_t *cur;
12289 chk_var_recursive_looped_t cur_save;
12291 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12292 if (strcmp(cur->var, t->var) == 0) {
12293 /* expression recursion loop detected */
12297 /* save current lookuped var name */
12298 cur = prev_chk_var_recursive;
12299 cur_save.var = t->var;
12300 cur_save.next = cur;
12301 prev_chk_var_recursive = &cur_save;
12303 t->val = arith (p, &errcode);
12304 /* restore previous ptr after recursiving */
12305 prev_chk_var_recursive = cur;
12308 /* allow undefined var as 0 */
12314 /* "applying" a token means performing it on the top elements on the integer
12315 * stack. For a unary operator it will only change the top element, but a
12316 * binary operator will pop two arguments and push a result */
12318 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12321 arith_t numptr_val, rez;
12322 int ret_arith_lookup_val;
12324 /* There is no operator that can work without arguments */
12325 if (NUMPTR == numstack) goto err;
12326 numptr_m1 = NUMPTR - 1;
12328 /* check operand is var with noninteger value */
12329 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12330 if (ret_arith_lookup_val)
12331 return ret_arith_lookup_val;
12333 rez = numptr_m1->val;
12334 if (op == TOK_UMINUS)
12336 else if (op == TOK_NOT)
12338 else if (op == TOK_BNOT)
12340 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12342 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12344 else if (op != TOK_UPLUS) {
12345 /* Binary operators */
12347 /* check and binary operators need two arguments */
12348 if (numptr_m1 == numstack) goto err;
12350 /* ... and they pop one */
12353 if (op == TOK_CONDITIONAL) {
12354 if (! numptr_m1->contidional_second_val_initialized) {
12355 /* protect $((expr1 ? expr2)) without ": expr" */
12358 rez = numptr_m1->contidional_second_val;
12359 } else if (numptr_m1->contidional_second_val_initialized) {
12360 /* protect $((expr1 : expr2)) without "expr ? " */
12363 numptr_m1 = NUMPTR - 1;
12364 if (op != TOK_ASSIGN) {
12365 /* check operand is var with noninteger value for not '=' */
12366 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12367 if (ret_arith_lookup_val)
12368 return ret_arith_lookup_val;
12370 if (op == TOK_CONDITIONAL) {
12371 numptr_m1->contidional_second_val = rez;
12373 rez = numptr_m1->val;
12374 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12376 else if (op == TOK_OR)
12377 rez = numptr_val || rez;
12378 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12380 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12382 else if (op == TOK_AND)
12383 rez = rez && numptr_val;
12384 else if (op == TOK_EQ)
12385 rez = (rez == numptr_val);
12386 else if (op == TOK_NE)
12387 rez = (rez != numptr_val);
12388 else if (op == TOK_GE)
12389 rez = (rez >= numptr_val);
12390 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12391 rez >>= numptr_val;
12392 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12393 rez <<= numptr_val;
12394 else if (op == TOK_GT)
12395 rez = (rez > numptr_val);
12396 else if (op == TOK_LT)
12397 rez = (rez < numptr_val);
12398 else if (op == TOK_LE)
12399 rez = (rez <= numptr_val);
12400 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12402 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12404 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12406 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12408 else if (op == TOK_CONDITIONAL_SEP) {
12409 if (numptr_m1 == numstack) {
12410 /* protect $((expr : expr)) without "expr ? " */
12413 numptr_m1->contidional_second_val_initialized = op;
12414 numptr_m1->contidional_second_val = numptr_val;
12415 } else if (op == TOK_CONDITIONAL) {
12417 numptr_val : numptr_m1->contidional_second_val;
12418 } else if (op == TOK_EXPONENT) {
12419 if (numptr_val < 0)
12420 return -3; /* exponent less than 0 */
12425 while (numptr_val--)
12429 } else if (numptr_val==0) /* zero divisor check */
12431 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12433 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12436 if (tok_have_assign(op)) {
12437 char buf[sizeof(arith_t_type)*3 + 2];
12439 if (numptr_m1->var == NULL) {
12443 /* save to shell variable */
12444 #if ENABLE_ASH_MATH_SUPPORT_64
12445 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12447 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12449 setvar(numptr_m1->var, buf, 0);
12450 /* after saving, make previous value for v++ or v-- */
12451 if (op == TOK_POST_INC)
12453 else if (op == TOK_POST_DEC)
12456 numptr_m1->val = rez;
12457 /* protect geting var value, is number now */
12458 numptr_m1->var = NULL;
12464 /* longest must be first */
12465 static const char op_tokens[] ALIGN1 = {
12466 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12467 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12468 '<','<', 0, TOK_LSHIFT,
12469 '>','>', 0, TOK_RSHIFT,
12470 '|','|', 0, TOK_OR,
12471 '&','&', 0, TOK_AND,
12472 '!','=', 0, TOK_NE,
12473 '<','=', 0, TOK_LE,
12474 '>','=', 0, TOK_GE,
12475 '=','=', 0, TOK_EQ,
12476 '|','=', 0, TOK_OR_ASSIGN,
12477 '&','=', 0, TOK_AND_ASSIGN,
12478 '*','=', 0, TOK_MUL_ASSIGN,
12479 '/','=', 0, TOK_DIV_ASSIGN,
12480 '%','=', 0, TOK_REM_ASSIGN,
12481 '+','=', 0, TOK_PLUS_ASSIGN,
12482 '-','=', 0, TOK_MINUS_ASSIGN,
12483 '-','-', 0, TOK_POST_DEC,
12484 '^','=', 0, TOK_XOR_ASSIGN,
12485 '+','+', 0, TOK_POST_INC,
12486 '*','*', 0, TOK_EXPONENT,
12490 '=', 0, TOK_ASSIGN,
12502 '?', 0, TOK_CONDITIONAL,
12503 ':', 0, TOK_CONDITIONAL_SEP,
12504 ')', 0, TOK_RPAREN,
12505 '(', 0, TOK_LPAREN,
12509 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12512 arith(const char *expr, int *perrcode)
12514 char arithval; /* Current character under analysis */
12515 operator lasttok, op;
12518 const char *p = endexpression;
12521 size_t datasizes = strlen(expr) + 2;
12523 /* Stack of integers */
12524 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12525 * in any given correct or incorrect expression is left as an exercise to
12527 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12528 *numstackptr = numstack;
12529 /* Stack of operator tokens */
12530 operator *stack = alloca((datasizes) * sizeof(operator)),
12533 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12534 *perrcode = errcode = 0;
12538 if (arithval == 0) {
12539 if (p == endexpression) {
12540 /* Null expression. */
12544 /* This is only reached after all tokens have been extracted from the
12545 * input stream. If there are still tokens on the operator stack, they
12546 * are to be applied in order. At the end, there should be a final
12547 * result on the integer stack */
12549 if (expr != endexpression + 1) {
12550 /* If we haven't done so already, */
12551 /* append a closing right paren */
12552 expr = endexpression;
12553 /* and let the loop process it. */
12556 /* At this point, we're done with the expression. */
12557 if (numstackptr != numstack+1) {
12558 /* ... but if there isn't, it's bad */
12560 return (*perrcode = -1);
12562 if (numstack->var) {
12563 /* expression is $((var)) only, lookup now */
12564 errcode = arith_lookup_val(numstack);
12567 *perrcode = errcode;
12568 return numstack->val;
12571 /* Continue processing the expression. */
12572 if (arith_isspace(arithval)) {
12573 /* Skip whitespace */
12576 p = endofname(expr);
12578 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12580 numstackptr->var = alloca(var_name_size);
12581 safe_strncpy(numstackptr->var, expr, var_name_size);
12584 numstackptr->contidional_second_val_initialized = 0;
12589 if (isdigit(arithval)) {
12590 numstackptr->var = NULL;
12591 #if ENABLE_ASH_MATH_SUPPORT_64
12592 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12594 numstackptr->val = strtol(expr, (char **) &expr, 0);
12598 for (p = op_tokens; ; p++) {
12602 /* strange operator not found */
12605 for (o = expr; *p && *o == *p; p++)
12612 /* skip tail uncompared token */
12615 /* skip zero delim */
12620 /* post grammar: a++ reduce to num */
12621 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12624 /* Plus and minus are binary (not unary) _only_ if the last
12625 * token was as number, or a right paren (which pretends to be
12626 * a number, since it evaluates to one). Think about it.
12627 * It makes sense. */
12628 if (lasttok != TOK_NUM) {
12644 /* We don't want a unary operator to cause recursive descent on the
12645 * stack, because there can be many in a row and it could cause an
12646 * operator to be evaluated before its argument is pushed onto the
12647 * integer stack. */
12648 /* But for binary operators, "apply" everything on the operator
12649 * stack until we find an operator with a lesser priority than the
12650 * one we have just extracted. */
12651 /* Left paren is given the lowest priority so it will never be
12652 * "applied" in this way.
12653 * if associativity is right and priority eq, applied also skip
12656 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12657 /* not left paren or unary */
12658 if (lasttok != TOK_NUM) {
12659 /* binary op must be preceded by a num */
12662 while (stackptr != stack) {
12663 if (op == TOK_RPAREN) {
12664 /* The algorithm employed here is simple: while we don't
12665 * hit an open paren nor the bottom of the stack, pop
12666 * tokens and apply them */
12667 if (stackptr[-1] == TOK_LPAREN) {
12669 /* Any operator directly after a */
12671 /* close paren should consider itself binary */
12675 operator prev_prec = PREC(stackptr[-1]);
12677 convert_prec_is_assing(prec);
12678 convert_prec_is_assing(prev_prec);
12679 if (prev_prec < prec)
12681 /* check right assoc */
12682 if (prev_prec == prec && is_right_associativity(prec))
12685 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12686 if (errcode) goto ret;
12688 if (op == TOK_RPAREN) {
12693 /* Push this operator to the stack and remember it. */
12694 *stackptr++ = lasttok = op;
12699 #endif /* ASH_MATH_SUPPORT */
12702 /* ============ main() and helpers */
12705 * Called to exit the shell.
12707 static void exitshell(void) ATTRIBUTE_NORETURN;
12715 status = exitstatus;
12716 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12717 if (setjmp(loc.loc)) {
12718 if (exception == EXEXIT)
12719 /* dash bug: it just does _exit(exitstatus) here
12720 * but we have to do setjobctl(0) first!
12721 * (bug is still not fixed in dash-0.5.3 - if you run dash
12722 * under Midnight Commander, on exit from dash MC is backgrounded) */
12723 status = exitstatus;
12726 exception_handler = &loc;
12732 flush_stdout_stderr();
12742 /* from input.c: */
12743 basepf.nextc = basepf.buf = basebuf;
12746 signal(SIGCHLD, SIG_DFL);
12751 char ppid[sizeof(int)*3 + 1];
12753 struct stat st1, st2;
12756 for (envp = environ; envp && *envp; envp++) {
12757 if (strchr(*envp, '=')) {
12758 setvareq(*envp, VEXPORT|VTEXTFIXED);
12762 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12763 setvar("PPID", ppid, 0);
12765 p = lookupvar("PWD");
12767 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12768 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12775 * Process the shell command line arguments.
12778 procargs(int argc, char **argv)
12781 const char *xminusc;
12788 for (i = 0; i < NOPTS; i++)
12794 if (*xargv == NULL) {
12796 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12799 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12803 for (i = 0; i < NOPTS; i++)
12804 if (optlist[i] == 2)
12809 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12814 } else if (!sflag) {
12815 setinputfile(*xargv, 0);
12818 commandname = arg0;
12821 shellparam.p = xargv;
12822 #if ENABLE_ASH_GETOPTS
12823 shellparam.optind = 1;
12824 shellparam.optoff = -1;
12826 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12828 shellparam.nparam++;
12835 * Read /etc/profile or .profile.
12838 read_profile(const char *name)
12842 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12851 * This routine is called when an error or an interrupt occurs in an
12852 * interactive shell and control is returned to the main command loop.
12860 /* from input.c: */
12861 parselleft = parsenleft = 0; /* clear input buffer */
12863 /* from parser.c: */
12866 /* from redir.c: */
12871 static short profile_buf[16384];
12872 extern int etext();
12876 * Main routine. We initialize things, parse the arguments, execute
12877 * profiles if we're a login shell, and then call cmdloop to execute
12878 * commands. The setjmp call sets up the location to jump to when an
12879 * exception occurs. When an exception occurs the variable "state"
12880 * is used to figure out how far we had gotten.
12882 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12883 int ash_main(int argc, char **argv)
12886 volatile int state;
12887 struct jmploc jmploc;
12888 struct stackmark smark;
12890 /* Initialize global data */
12894 #if ENABLE_ASH_ALIAS
12900 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12903 #if ENABLE_FEATURE_EDITING
12904 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12907 if (setjmp(jmploc.loc)) {
12917 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12921 outcslow('\n', stderr);
12923 popstackmark(&smark);
12924 FORCE_INT_ON; /* enable interrupts */
12933 exception_handler = &jmploc;
12936 trace_puts("Shell args: ");
12937 trace_puts_args(argv);
12939 rootpid = getpid();
12941 #if ENABLE_ASH_RANDOM_SUPPORT
12942 rseed = rootpid + time(NULL);
12945 setstackmark(&smark);
12946 procargs(argc, argv);
12947 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12949 const char *hp = lookupvar("HISTFILE");
12952 hp = lookupvar("HOME");
12954 char *defhp = concat_path_file(hp, ".ash_history");
12955 setvar("HISTFILE", defhp, 0);
12961 if (argv[0] && argv[0][0] == '-')
12965 read_profile("/etc/profile");
12968 read_profile(".profile");
12974 getuid() == geteuid() && getgid() == getegid() &&
12978 shinit = lookupvar("ENV");
12979 if (shinit != NULL && *shinit != '\0') {
12980 read_profile(shinit);
12986 evalstring(minusc, 0);
12988 if (sflag || minusc == NULL) {
12989 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
12991 const char *hp = lookupvar("HISTFILE");
12994 line_input_state->hist_file = hp;
12997 state4: /* XXX ??? - why isn't this before the "if" statement */
13005 extern void _mcleanup(void);
13014 const char *applet_name = "debug stuff usage";
13015 int main(int argc, char **argv)
13017 return ash_main(argc, argv);
13023 * Copyright (c) 1989, 1991, 1993, 1994
13024 * The Regents of the University of California. All rights reserved.
13026 * This code is derived from software contributed to Berkeley by
13027 * Kenneth Almquist.
13029 * Redistribution and use in source and binary forms, with or without
13030 * modification, are permitted provided that the following conditions
13032 * 1. Redistributions of source code must retain the above copyright
13033 * notice, this list of conditions and the following disclaimer.
13034 * 2. Redistributions in binary form must reproduce the above copyright
13035 * notice, this list of conditions and the following disclaimer in the
13036 * documentation and/or other materials provided with the distribution.
13037 * 3. Neither the name of the University nor the names of its contributors
13038 * may be used to endorse or promote products derived from this software
13039 * without specific prior written permission.
13041 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13042 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13043 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13044 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13045 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13046 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13047 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13048 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13049 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13050 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF