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.
49 #define JOBS ENABLE_ASH_JOB_CONTROL
57 #include "busybox.h" /* for applet_names */
61 #if JOBS || ENABLE_ASH_READ_NCHARS
65 #if defined(__uClinux__)
66 #error "Do not even bother, ash will not run on uClinux"
70 /* ============ Hash table sizes. Configurable. */
74 #define CMDTABLESIZE 31 /* should be prime */
77 /* ============ Misc helpers */
79 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
81 /* C99 say: "char" declaration may be signed or unsigned default */
82 #define signed_char2int(sc) ((int)((signed char)sc))
85 /* ============ Shell options */
87 static const char *const optletters_optnames[] = {
108 #define optletters(n) optletters_optnames[(n)][0]
109 #define optnames(n) (&optletters_optnames[(n)][1])
111 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
113 static char optlist[NOPTS] ALIGN1;
115 #define eflag optlist[0]
116 #define fflag optlist[1]
117 #define Iflag optlist[2]
118 #define iflag optlist[3]
119 #define mflag optlist[4]
120 #define nflag optlist[5]
121 #define sflag optlist[6]
122 #define xflag optlist[7]
123 #define vflag optlist[8]
124 #define Cflag optlist[9]
125 #define aflag optlist[10]
126 #define bflag optlist[11]
127 #define uflag optlist[12]
128 #define viflag optlist[13]
130 #define nolog optlist[14]
131 #define debug optlist[15]
135 /* ============ Misc data */
137 static const char homestr[] ALIGN1 = "HOME";
138 static const char snlfmt[] ALIGN1 = "%s\n";
139 static const char illnum[] ALIGN1 = "Illegal number: %s";
142 * We enclose jmp_buf in a structure so that we can declare pointers to
143 * jump locations. The global variable handler contains the location to
144 * jump to when an exception occurs, and the global variable exception
145 * contains a code identifying the exception. To implement nested
146 * exception handlers, the user should save the value of handler on entry
147 * to an inner scope, set handler to point to a jmploc structure for the
148 * inner scope, and restore handler on exit from the scope.
154 struct globals_misc {
155 /* pid of main shell */
157 /* shell level: 0 for the main shell, 1 for its children, and so on */
159 #define rootshell (!shlvl)
160 char *minusc; /* argument to -c option */
162 char *curdir; // = nullstr; /* current working directory */
163 char *physdir; // = nullstr; /* physical working directory */
165 char *arg0; /* value of $0 */
167 struct jmploc *exception_handler;
169 // disabled by vda: cannot understand how it was supposed to work -
170 // cannot fix bugs. That's why you have to explain your non-trivial designs!
171 // /* do we generate EXSIG events */
172 // int exsig; /* counter */
173 volatile int suppressint; /* counter */
174 volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
175 /* last pending signal */
176 volatile /*sig_atomic_t*/ smallint pendingsig;
177 smallint exception; /* kind of exception (0..5) */
179 #define EXINT 0 /* SIGINT received */
180 #define EXERROR 1 /* a generic error */
181 #define EXSHELLPROC 2 /* execute a shell procedure */
182 #define EXEXEC 3 /* command execution failed */
183 #define EXEXIT 4 /* exit the shell */
184 #define EXSIG 5 /* trapped signal in wait(1) */
186 /* trap handler commands */
189 char nullstr[1]; /* zero length string */
191 * Sigmode records the current value of the signal handlers for the various
192 * modes. A value of zero means that the current handler is not known.
193 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
195 char sigmode[NSIG - 1];
196 #define S_DFL 1 /* default signal handling (SIG_DFL) */
197 #define S_CATCH 2 /* signal is caught */
198 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
199 #define S_HARD_IGN 4 /* signal is ignored permenantly */
200 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
202 /* indicates specified signal received */
203 char gotsig[NSIG - 1];
205 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
206 static struct globals_misc *const ptr_to_globals_misc __attribute__ ((section (".data")));
207 #define G_misc (*ptr_to_globals_misc)
208 #define rootpid (G_misc.rootpid )
209 #define shlvl (G_misc.shlvl )
210 #define minusc (G_misc.minusc )
211 #define curdir (G_misc.curdir )
212 #define physdir (G_misc.physdir )
213 #define arg0 (G_misc.arg0 )
214 #define exception_handler (G_misc.exception_handler)
215 #define exception (G_misc.exception )
216 #define suppressint (G_misc.suppressint )
217 #define intpending (G_misc.intpending )
218 //#define exsig (G_misc.exsig )
219 #define pendingsig (G_misc.pendingsig )
220 #define trap (G_misc.trap )
221 #define isloginsh (G_misc.isloginsh)
222 #define nullstr (G_misc.nullstr )
223 #define sigmode (G_misc.sigmode )
224 #define gotsig (G_misc.gotsig )
225 #define INIT_G_misc() do { \
226 (*(struct globals_misc**)&ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
232 /* ============ Interrupts / exceptions */
235 * These macros allow the user to suspend the handling of interrupt signals
236 * over a period of time. This is similar to SIGHOLD or to sigblock, but
237 * much more efficient and portable. (But hacking the kernel is so much
238 * more fun than worrying about efficiency and portability. :-))
247 * Called to raise an exception. Since C doesn't include exceptions, we
248 * just do a longjmp to the exception handler. The type of exception is
249 * stored in the global variable "exception".
251 static void raise_exception(int) ATTRIBUTE_NORETURN;
253 raise_exception(int e)
256 if (exception_handler == NULL)
261 longjmp(exception_handler->loc, 1);
265 * Called from trap.c when a SIGINT is received. (If the user specifies
266 * that SIGINT is to be trapped or ignored using the trap builtin, then
267 * this routine is not called.) Suppressint is nonzero when interrupts
268 * are held using the INT_OFF macro. (The test for iflag is just
269 * defensive programming.)
271 static void raise_interrupt(void) ATTRIBUTE_NORETURN;
273 raise_interrupt(void)
279 /* Signal is not automatically unmasked after it is raised,
280 * do it ourself - unmask all signals */
282 sigprocmask(SIG_SETMASK, &mask, NULL);
283 /* pendingsig = 0; - now done in onsig() */
286 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
287 if (!(rootshell && iflag)) {
288 /* Kill ourself with SIGINT */
289 signal(SIGINT, SIG_DFL);
298 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
302 if (--suppressint == 0 && intpending) {
306 #define INT_ON int_on()
314 #define FORCE_INT_ON force_int_on()
319 if (--suppressint == 0 && intpending) \
322 #define FORCE_INT_ON \
329 #endif /* ASH_OPTIMIZE_FOR_SIZE */
331 #define SAVE_INT(v) ((v) = suppressint)
333 #define RESTORE_INT(v) \
337 if (suppressint == 0 && intpending) \
342 * Ignore a signal. Only one usage site - in forkchild()
347 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
348 signal(signo, SIG_IGN);
350 sigmode[signo - 1] = S_HARD_IGN;
354 * Signal handler. Only one usage site - in setsignal()
359 gotsig[signo - 1] = 1;
362 if ( /* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
365 raise_interrupt(); /* does not return */
372 /* ============ Stdout/stderr output */
375 outstr(const char *p, FILE *file)
383 flush_stdout_stderr(void)
400 outcslow(int c, FILE *dest)
408 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
410 out1fmt(const char *fmt, ...)
417 r = vprintf(fmt, ap);
423 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
425 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
432 ret = vsnprintf(outbuf, length, fmt, ap);
439 out1str(const char *p)
445 out2str(const char *p)
452 /* ============ Parser structures */
454 /* control characters in argument strings */
455 #define CTLESC '\201' /* escape next character */
456 #define CTLVAR '\202' /* variable defn */
457 #define CTLENDVAR '\203'
458 #define CTLBACKQ '\204'
459 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
460 /* CTLBACKQ | CTLQUOTE == '\205' */
461 #define CTLARI '\206' /* arithmetic expression */
462 #define CTLENDARI '\207'
463 #define CTLQUOTEMARK '\210'
465 /* variable substitution byte (follows CTLVAR) */
466 #define VSTYPE 0x0f /* type of variable substitution */
467 #define VSNUL 0x10 /* colon--treat the empty string as unset */
468 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
470 /* values of VSTYPE field */
471 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
472 #define VSMINUS 0x2 /* ${var-text} */
473 #define VSPLUS 0x3 /* ${var+text} */
474 #define VSQUESTION 0x4 /* ${var?message} */
475 #define VSASSIGN 0x5 /* ${var=text} */
476 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
477 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
478 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
479 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
480 #define VSLENGTH 0xa /* ${#var} */
482 static const char dolatstr[] ALIGN1 = {
483 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
519 union node *redirect;
525 struct nodelist *cmdlist;
531 union node *redirect;
544 union node *elsepart;
571 struct nodelist *backquote;
606 struct nredir nredir;
607 struct nbinary nbinary;
611 struct nclist nclist;
620 struct nodelist *next;
633 freefunc(struct funcnode *f)
635 if (f && --f->count < 0)
640 /* ============ Debugging output */
644 static FILE *tracefile;
647 trace_printf(const char *fmt, ...)
654 vfprintf(tracefile, fmt, va);
659 trace_vprintf(const char *fmt, va_list va)
663 vfprintf(tracefile, fmt, va);
667 trace_puts(const char *s)
675 trace_puts_quoted(char *s)
682 putc('"', tracefile);
683 for (p = s; *p; p++) {
685 case '\n': c = 'n'; goto backslash;
686 case '\t': c = 't'; goto backslash;
687 case '\r': c = 'r'; goto backslash;
688 case '"': c = '"'; goto backslash;
689 case '\\': c = '\\'; goto backslash;
690 case CTLESC: c = 'e'; goto backslash;
691 case CTLVAR: c = 'v'; goto backslash;
692 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
693 case CTLBACKQ: c = 'q'; goto backslash;
694 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
696 putc('\\', tracefile);
700 if (*p >= ' ' && *p <= '~')
703 putc('\\', tracefile);
704 putc(*p >> 6 & 03, tracefile);
705 putc(*p >> 3 & 07, tracefile);
706 putc(*p & 07, tracefile);
711 putc('"', tracefile);
715 trace_puts_args(char **ap)
722 trace_puts_quoted(*ap);
724 putc('\n', tracefile);
727 putc(' ', tracefile);
742 /* leave open because libedit might be using it */
745 strcpy(s, "./trace");
747 if (!freopen(s, "a", tracefile)) {
748 fprintf(stderr, "Can't re-open %s\n", s);
753 tracefile = fopen(s, "a");
754 if (tracefile == NULL) {
755 fprintf(stderr, "Can't open %s\n", s);
761 flags = fcntl(fileno(tracefile), F_GETFL);
763 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
765 setlinebuf(tracefile);
766 fputs("\nTracing started.\n", tracefile);
770 indent(int amount, char *pfx, FILE *fp)
774 for (i = 0; i < amount; i++) {
775 if (pfx && i == amount - 1)
781 /* little circular references here... */
782 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
785 sharg(union node *arg, FILE *fp)
788 struct nodelist *bqlist;
791 if (arg->type != NARG) {
792 out1fmt("<node type %d>\n", arg->type);
795 bqlist = arg->narg.backquote;
796 for (p = arg->narg.text; *p; p++) {
805 if (subtype == VSLENGTH)
814 switch (subtype & VSTYPE) {
847 out1fmt("<subtype %d>", subtype);
854 case CTLBACKQ|CTLQUOTE:
857 shtree(bqlist->n, -1, NULL, fp);
868 shcmd(union node *cmd, FILE *fp)
876 for (np = cmd->ncmd.args; np; np = np->narg.next) {
882 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
886 switch (np->nfile.type) {
887 case NTO: s = ">>"+1; dftfd = 1; break;
888 case NCLOBBER: s = ">|"; dftfd = 1; break;
889 case NAPPEND: s = ">>"; dftfd = 1; break;
890 case NTOFD: s = ">&"; dftfd = 1; break;
891 case NFROM: s = "<"; break;
892 case NFROMFD: s = "<&"; break;
893 case NFROMTO: s = "<>"; break;
894 default: s = "*error*"; break;
896 if (np->nfile.fd != dftfd)
897 fprintf(fp, "%d", np->nfile.fd);
899 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
900 fprintf(fp, "%d", np->ndup.dupfd);
902 sharg(np->nfile.fname, fp);
909 shtree(union node *n, int ind, char *pfx, FILE *fp)
917 indent(ind, pfx, fp);
928 shtree(n->nbinary.ch1, ind, NULL, fp);
931 shtree(n->nbinary.ch2, ind, NULL, fp);
939 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
944 if (n->npipe.backgnd)
950 fprintf(fp, "<node type %d>", n->type);
958 showtree(union node *n)
960 trace_puts("showtree called\n");
961 shtree(n, 1, NULL, stdout);
964 #define TRACE(param) trace_printf param
965 #define TRACEV(param) trace_vprintf param
970 #define TRACEV(param)
975 /* ============ Parser data */
978 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
981 struct strlist *next;
990 struct strpush *prev; /* preceding string on stack */
994 struct alias *ap; /* if push was associated with an alias */
996 char *string; /* remember the string since it may change */
1000 struct parsefile *prev; /* preceding file on stack */
1001 int linno; /* current line */
1002 int fd; /* file descriptor (or -1 if string) */
1003 int nleft; /* number of chars left in this line */
1004 int lleft; /* number of chars left in this buffer */
1005 char *nextc; /* next char in buffer */
1006 char *buf; /* input buffer */
1007 struct strpush *strpush; /* for pushing strings at this level */
1008 struct strpush basestrpush; /* so pushing one is fast */
1011 static struct parsefile basepf; /* top level input file */
1012 static struct parsefile *parsefile = &basepf; /* current input file */
1013 static int startlinno; /* line # where last token started */
1014 static char *commandname; /* currently executing command */
1015 static struct strlist *cmdenviron; /* environment for builtin command */
1016 static int exitstatus; /* exit status of last command */
1019 /* ============ Message printing */
1022 ash_vmsg(const char *msg, va_list ap)
1024 fprintf(stderr, "%s: ", arg0);
1026 if (strcmp(arg0, commandname))
1027 fprintf(stderr, "%s: ", commandname);
1028 if (!iflag || parsefile->fd)
1029 fprintf(stderr, "line %d: ", startlinno);
1031 vfprintf(stderr, msg, ap);
1032 outcslow('\n', stderr);
1036 * Exverror is called to raise the error exception. If the second argument
1037 * is not NULL then error prints an error message using printf style
1038 * formatting. It then raises the error exception.
1040 static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1042 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1046 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1048 TRACE(("\") pid=%d\n", getpid()));
1050 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1055 flush_stdout_stderr();
1056 raise_exception(cond);
1060 static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1062 ash_msg_and_raise_error(const char *msg, ...)
1067 ash_vmsg_and_raise(EXERROR, msg, ap);
1072 static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1074 ash_msg_and_raise(int cond, const char *msg, ...)
1079 ash_vmsg_and_raise(cond, msg, ap);
1085 * error/warning routines for external builtins
1088 ash_msg(const char *fmt, ...)
1098 * Return a string describing an error. The returned string may be a
1099 * pointer to a static buffer that will be overwritten on the next call.
1100 * Action describes the operation that got the error.
1103 errmsg(int e, const char *em)
1105 if (e == ENOENT || e == ENOTDIR) {
1112 /* ============ Memory allocation */
1115 * It appears that grabstackstr() will barf with such alignments
1116 * because stalloc() will return a string allocated in a new stackblock.
1118 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1120 /* Most machines require the value returned from malloc to be aligned
1121 * in some way. The following macro will get this right
1122 * on many machines. */
1123 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1124 /* Minimum size of a block */
1125 MINSIZE = SHELL_ALIGN(504),
1128 struct stack_block {
1129 struct stack_block *prev;
1130 char space[MINSIZE];
1134 struct stack_block *stackp;
1137 struct stackmark *marknext;
1141 struct globals_memstack {
1142 struct stack_block *g_stackp; // = &stackbase;
1143 struct stackmark *markp;
1144 char *g_stacknxt; // = stackbase.space;
1145 char *sstrend; // = stackbase.space + MINSIZE;
1146 size_t g_stacknleft; // = MINSIZE;
1147 int herefd; // = -1;
1148 struct stack_block stackbase;
1150 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1151 static struct globals_memstack *const ptr_to_globals_memstack __attribute__ ((section (".data")));
1152 #define G_memstack (*ptr_to_globals_memstack)
1153 #define g_stackp (G_memstack.g_stackp )
1154 #define markp (G_memstack.markp )
1155 #define g_stacknxt (G_memstack.g_stacknxt )
1156 #define sstrend (G_memstack.sstrend )
1157 #define g_stacknleft (G_memstack.g_stacknleft)
1158 #define herefd (G_memstack.herefd )
1159 #define stackbase (G_memstack.stackbase )
1160 #define INIT_G_memstack() do { \
1161 (*(struct globals_memstack**)&ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1162 g_stackp = &stackbase; \
1163 g_stacknxt = stackbase.space; \
1164 g_stacknleft = MINSIZE; \
1165 sstrend = stackbase.space + MINSIZE; \
1169 #define stackblock() ((void *)g_stacknxt)
1170 #define stackblocksize() g_stacknleft
1174 ckrealloc(void * p, size_t nbytes)
1176 p = realloc(p, nbytes);
1178 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1183 ckmalloc(size_t nbytes)
1185 return ckrealloc(NULL, nbytes);
1189 * Make a copy of a string in safe storage.
1192 ckstrdup(const char *s)
1194 char *p = strdup(s);
1196 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1201 * Parse trees for commands are allocated in lifo order, so we use a stack
1202 * to make this more efficient, and also to avoid all sorts of exception
1203 * handling code to handle interrupts in the middle of a parse.
1205 * The size 504 was chosen because the Ultrix malloc handles that size
1209 stalloc(size_t nbytes)
1214 aligned = SHELL_ALIGN(nbytes);
1215 if (aligned > g_stacknleft) {
1218 struct stack_block *sp;
1220 blocksize = aligned;
1221 if (blocksize < MINSIZE)
1222 blocksize = MINSIZE;
1223 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1224 if (len < blocksize)
1225 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1228 sp->prev = g_stackp;
1229 g_stacknxt = sp->space;
1230 g_stacknleft = blocksize;
1231 sstrend = g_stacknxt + blocksize;
1236 g_stacknxt += aligned;
1237 g_stacknleft -= aligned;
1245 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1246 write(2, "stunalloc\n", 10);
1250 g_stacknleft += g_stacknxt - (char *)p;
1255 * Like strdup but works with the ash stack.
1258 ststrdup(const char *p)
1260 size_t len = strlen(p) + 1;
1261 return memcpy(stalloc(len), p, len);
1265 setstackmark(struct stackmark *mark)
1267 mark->stackp = g_stackp;
1268 mark->stacknxt = g_stacknxt;
1269 mark->stacknleft = g_stacknleft;
1270 mark->marknext = markp;
1275 popstackmark(struct stackmark *mark)
1277 struct stack_block *sp;
1283 markp = mark->marknext;
1284 while (g_stackp != mark->stackp) {
1286 g_stackp = sp->prev;
1289 g_stacknxt = mark->stacknxt;
1290 g_stacknleft = mark->stacknleft;
1291 sstrend = mark->stacknxt + mark->stacknleft;
1296 * When the parser reads in a string, it wants to stick the string on the
1297 * stack and only adjust the stack pointer when it knows how big the
1298 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1299 * of space on top of the stack and stackblocklen returns the length of
1300 * this block. Growstackblock will grow this space by at least one byte,
1301 * possibly moving it (like realloc). Grabstackblock actually allocates the
1302 * part of the block that has been used.
1305 growstackblock(void)
1309 newlen = g_stacknleft * 2;
1310 if (newlen < g_stacknleft)
1311 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1315 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1316 struct stack_block *oldstackp;
1317 struct stackmark *xmark;
1318 struct stack_block *sp;
1319 struct stack_block *prevstackp;
1323 oldstackp = g_stackp;
1325 prevstackp = sp->prev;
1326 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1327 sp = ckrealloc(sp, grosslen);
1328 sp->prev = prevstackp;
1330 g_stacknxt = sp->space;
1331 g_stacknleft = newlen;
1332 sstrend = sp->space + newlen;
1335 * Stack marks pointing to the start of the old block
1336 * must be relocated to point to the new block
1339 while (xmark != NULL && xmark->stackp == oldstackp) {
1340 xmark->stackp = g_stackp;
1341 xmark->stacknxt = g_stacknxt;
1342 xmark->stacknleft = g_stacknleft;
1343 xmark = xmark->marknext;
1347 char *oldspace = g_stacknxt;
1348 int oldlen = g_stacknleft;
1349 char *p = stalloc(newlen);
1351 /* free the space we just allocated */
1352 g_stacknxt = memcpy(p, oldspace, oldlen);
1353 g_stacknleft += newlen;
1358 grabstackblock(size_t len)
1360 len = SHELL_ALIGN(len);
1362 g_stacknleft -= len;
1366 * The following routines are somewhat easier to use than the above.
1367 * The user declares a variable of type STACKSTR, which may be declared
1368 * to be a register. The macro STARTSTACKSTR initializes things. Then
1369 * the user uses the macro STPUTC to add characters to the string. In
1370 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1371 * grown as necessary. When the user is done, she can just leave the
1372 * string there and refer to it using stackblock(). Or she can allocate
1373 * the space for it using grabstackstr(). If it is necessary to allow
1374 * someone else to use the stack temporarily and then continue to grow
1375 * the string, the user should use grabstack to allocate the space, and
1376 * then call ungrabstr(p) to return to the previous mode of operation.
1378 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1379 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1380 * is space for at least one character.
1385 size_t len = stackblocksize();
1386 if (herefd >= 0 && len >= 1024) {
1387 full_write(herefd, stackblock(), len);
1388 return stackblock();
1391 return stackblock() + len;
1395 * Called from CHECKSTRSPACE.
1398 makestrspace(size_t newlen, char *p)
1400 size_t len = p - g_stacknxt;
1401 size_t size = stackblocksize();
1406 size = stackblocksize();
1408 if (nleft >= newlen)
1412 return stackblock() + len;
1416 stack_nputstr(const char *s, size_t n, char *p)
1418 p = makestrspace(n, p);
1419 p = memcpy(p, s, n) + n;
1424 stack_putstr(const char *s, char *p)
1426 return stack_nputstr(s, strlen(s), p);
1430 _STPUTC(int c, char *p)
1438 #define STARTSTACKSTR(p) ((p) = stackblock())
1439 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1440 #define CHECKSTRSPACE(n, p) \
1444 size_t m = sstrend - q; \
1446 (p) = makestrspace(l, q); \
1448 #define USTPUTC(c, p) (*p++ = (c))
1449 #define STACKSTRNUL(p) \
1451 if ((p) == sstrend) \
1452 p = growstackstr(); \
1455 #define STUNPUTC(p) (--p)
1456 #define STTOPC(p) (p[-1])
1457 #define STADJUST(amount, p) (p += (amount))
1459 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1460 #define ungrabstackstr(s, p) stunalloc((s))
1461 #define stackstrend() ((void *)sstrend)
1464 /* ============ String helpers */
1467 * prefix -- see if pfx is a prefix of string.
1470 prefix(const char *string, const char *pfx)
1473 if (*pfx++ != *string++)
1476 return (char *) string;
1480 * Check for a valid number. This should be elsewhere.
1483 is_number(const char *p)
1488 } while (*++p != '\0');
1493 * Convert a string of digits to an integer, printing an error message on
1497 number(const char *s)
1500 ash_msg_and_raise_error(illnum, s);
1505 * Produce a possibly single quoted string suitable as input to the shell.
1506 * The return string is allocated on the stack.
1509 single_quote(const char *s)
1519 len = strchrnul(s, '\'') - s;
1521 q = p = makestrspace(len + 3, p);
1524 q = memcpy(q, s, len) + len;
1530 len = strspn(s, "'");
1534 q = p = makestrspace(len + 3, p);
1537 q = memcpy(q, s, len) + len;
1546 return stackblock();
1550 /* ============ nextopt */
1552 static char **argptr; /* argument list for builtin commands */
1553 static char *optionarg; /* set by nextopt (like getopt) */
1554 static char *optptr; /* used by nextopt */
1557 * XXX - should get rid of. have all builtins use getopt(3). the
1558 * library getopt must have the BSD extension static variable "optreset"
1559 * otherwise it can't be used within the shell safely.
1561 * Standard option processing (a la getopt) for builtin routines. The
1562 * only argument that is passed to nextopt is the option string; the
1563 * other arguments are unnecessary. It return the character, or '\0' on
1567 nextopt(const char *optstring)
1574 if (p == NULL || *p == '\0') {
1576 if (p == NULL || *p != '-' || *++p == '\0')
1579 if (LONE_DASH(p)) /* check for "--" */
1583 for (q = optstring; *q != c; ) {
1585 ash_msg_and_raise_error("illegal option -%c", c);
1590 if (*p == '\0' && (p = *argptr++) == NULL)
1591 ash_msg_and_raise_error("no arg for -%c option", c);
1600 /* ============ Math support definitions */
1602 #if ENABLE_ASH_MATH_SUPPORT_64
1603 typedef int64_t arith_t;
1604 #define arith_t_type long long
1606 typedef long arith_t;
1607 #define arith_t_type long
1610 #if ENABLE_ASH_MATH_SUPPORT
1611 static arith_t dash_arith(const char *);
1612 static arith_t arith(const char *expr, int *perrcode);
1615 #if ENABLE_ASH_RANDOM_SUPPORT
1616 static unsigned long rseed;
1623 /* ============ Shell variables */
1626 * The parsefile structure pointed to by the global variable parsefile
1627 * contains information about the current file being read.
1630 struct redirtab *next;
1636 int nparam; /* # of positional parameters (without $0) */
1637 #if ENABLE_ASH_GETOPTS
1638 int optind; /* next parameter to be processed by getopts */
1639 int optoff; /* used by getopts */
1641 unsigned char malloced; /* if parameter list dynamically allocated */
1642 char **p; /* parameter list */
1646 * Free the list of positional parameters.
1649 freeparam(volatile struct shparam *param)
1653 if (param->malloced) {
1654 for (ap = param->p; *ap; ap++)
1660 #if ENABLE_ASH_GETOPTS
1661 static void getoptsreset(const char *value);
1665 struct var *next; /* next entry in hash list */
1666 int flags; /* flags are defined above */
1667 const char *text; /* name=value */
1668 void (*func)(const char *); /* function to be called when */
1669 /* the variable gets set/unset */
1673 struct localvar *next; /* next local variable in list */
1674 struct var *vp; /* the variable that was made local */
1675 int flags; /* saved flags */
1676 const char *text; /* saved text */
1680 #define VEXPORT 0x01 /* variable is exported */
1681 #define VREADONLY 0x02 /* variable cannot be modified */
1682 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1683 #define VTEXTFIXED 0x08 /* text is statically allocated */
1684 #define VSTACK 0x10 /* text is allocated on the stack */
1685 #define VUNSET 0x20 /* the variable is not set */
1686 #define VNOFUNC 0x40 /* don't call the callback function */
1687 #define VNOSET 0x80 /* do not set variable - just readonly test */
1688 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1690 # define VDYNAMIC 0x200 /* dynamic variable */
1696 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1697 #define defifs (defifsvar + 4)
1699 static const char defifs[] ALIGN1 = " \t\n";
1703 /* Need to be before varinit_data[] */
1704 #if ENABLE_LOCALE_SUPPORT
1706 change_lc_all(const char *value)
1708 if (value && *value != '\0')
1709 setlocale(LC_ALL, value);
1712 change_lc_ctype(const char *value)
1714 if (value && *value != '\0')
1715 setlocale(LC_CTYPE, value);
1719 static void chkmail(void);
1720 static void changemail(const char *);
1722 static void changepath(const char *);
1723 #if ENABLE_ASH_RANDOM_SUPPORT
1724 static void change_random(const char *);
1727 static const struct {
1730 void (*func)(const char *);
1731 } varinit_data[] = {
1733 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1735 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1738 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1739 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1741 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1742 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1743 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1744 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1745 #if ENABLE_ASH_GETOPTS
1746 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1748 #if ENABLE_ASH_RANDOM_SUPPORT
1749 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1751 #if ENABLE_LOCALE_SUPPORT
1752 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1753 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1755 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1756 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1761 struct globals_var {
1762 struct shparam shellparam; /* $@ current positional parameters */
1763 struct redirtab *redirlist;
1765 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1766 struct var *vartab[VTABSIZE];
1767 struct var varinit[ARRAY_SIZE(varinit_data)];
1769 /* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1770 static struct globals_var *const ptr_to_globals_var __attribute__ ((section (".data")));
1771 #define G_var (*ptr_to_globals_var)
1772 #define shellparam (G_var.shellparam )
1773 #define redirlist (G_var.redirlist )
1774 #define g_nullredirs (G_var.g_nullredirs )
1775 #define preverrout_fd (G_var.preverrout_fd)
1776 #define vartab (G_var.vartab )
1777 #define varinit (G_var.varinit )
1778 #define INIT_G_var() do { \
1780 (*(struct globals_var**)&ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1781 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1782 varinit[i].flags = varinit_data[i].flags; \
1783 varinit[i].text = varinit_data[i].text; \
1784 varinit[i].func = varinit_data[i].func; \
1788 #define vifs varinit[0]
1790 #define vmail (&vifs)[1]
1791 #define vmpath (&vmail)[1]
1795 #define vpath (&vmpath)[1]
1796 #define vps1 (&vpath)[1]
1797 #define vps2 (&vps1)[1]
1798 #define vps4 (&vps2)[1]
1799 #define voptind (&vps4)[1]
1800 #if ENABLE_ASH_GETOPTS
1801 #define vrandom (&voptind)[1]
1803 #define vrandom (&vps4)[1]
1807 * The following macros access the values of the above variables.
1808 * They have to skip over the name. They return the null string
1809 * for unset variables.
1811 #define ifsval() (vifs.text + 4)
1812 #define ifsset() ((vifs.flags & VUNSET) == 0)
1813 #define mailval() (vmail.text + 5)
1814 #define mpathval() (vmpath.text + 9)
1815 #define pathval() (vpath.text + 5)
1816 #define ps1val() (vps1.text + 4)
1817 #define ps2val() (vps2.text + 4)
1818 #define ps4val() (vps4.text + 4)
1819 #define optindval() (voptind.text + 7)
1821 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1824 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1825 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1827 #if ENABLE_ASH_GETOPTS
1829 getoptsreset(const char *value)
1831 shellparam.optind = number(value);
1832 shellparam.optoff = -1;
1837 * Return of a legal variable name (a letter or underscore followed by zero or
1838 * more letters, underscores, and digits).
1841 endofname(const char *name)
1849 if (!is_in_name(*p))
1856 * Compares two strings up to the first = or '\0'. The first
1857 * string must be terminated by '='; the second may be terminated by
1858 * either '=' or '\0'.
1861 varcmp(const char *p, const char *q)
1865 while ((c = *p) == (d = *q)) {
1880 varequal(const char *a, const char *b)
1882 return !varcmp(a, b);
1886 * Find the appropriate entry in the hash table from the name.
1888 static struct var **
1889 hashvar(const char *p)
1893 hashval = ((unsigned char) *p) << 4;
1894 while (*p && *p != '=')
1895 hashval += (unsigned char) *p++;
1896 return &vartab[hashval % VTABSIZE];
1900 vpcmp(const void *a, const void *b)
1902 return varcmp(*(const char **)a, *(const char **)b);
1906 * This routine initializes the builtin variables.
1916 * PS1 depends on uid
1918 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1919 vps1.text = "PS1=\\w \\$ ";
1922 vps1.text = "PS1=# ";
1925 end = vp + ARRAY_SIZE(varinit);
1927 vpp = hashvar(vp->text);
1930 } while (++vp < end);
1933 static struct var **
1934 findvar(struct var **vpp, const char *name)
1936 for (; *vpp; vpp = &(*vpp)->next) {
1937 if (varequal((*vpp)->text, name)) {
1945 * Find the value of a variable. Returns NULL if not set.
1948 lookupvar(const char *name)
1952 v = *findvar(hashvar(name), name);
1956 * Dynamic variables are implemented roughly the same way they are
1957 * in bash. Namely, they're "special" so long as they aren't unset.
1958 * As soon as they're unset, they're no longer dynamic, and dynamic
1959 * lookup will no longer happen at that point. -- PFM.
1961 if ((v->flags & VDYNAMIC))
1964 if (!(v->flags & VUNSET))
1965 return strchrnul(v->text, '=') + 1;
1971 * Search the environment of a builtin command.
1974 bltinlookup(const char *name)
1978 for (sp = cmdenviron; sp; sp = sp->next) {
1979 if (varequal(sp->text, name))
1980 return strchrnul(sp->text, '=') + 1;
1982 return lookupvar(name);
1986 * Same as setvar except that the variable and value are passed in
1987 * the first argument as name=value. Since the first argument will
1988 * be actually stored in the table, it should not be a string that
1990 * Called with interrupts off.
1993 setvareq(char *s, int flags)
1995 struct var *vp, **vpp;
1998 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
1999 vp = *findvar(vpp, s);
2001 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2004 if (flags & VNOSAVE)
2007 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2013 if (vp->func && (flags & VNOFUNC) == 0)
2014 (*vp->func)(strchrnul(s, '=') + 1);
2016 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2017 free((char*)vp->text);
2019 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2024 vp = ckmalloc(sizeof(*vp));
2029 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2036 * Set the value of a variable. The flags argument is ored with the
2037 * flags of the variable. If val is NULL, the variable is unset.
2040 setvar(const char *name, const char *val, int flags)
2047 q = endofname(name);
2048 p = strchrnul(q, '=');
2050 if (!namelen || p != q)
2051 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2056 vallen = strlen(val);
2059 nameeq = ckmalloc(namelen + vallen + 2);
2060 p = memcpy(nameeq, name, namelen) + namelen;
2063 p = memcpy(p, val, vallen) + vallen;
2066 setvareq(nameeq, flags | VNOSAVE);
2070 #if ENABLE_ASH_GETOPTS
2072 * Safe version of setvar, returns 1 on success 0 on failure.
2075 setvarsafe(const char *name, const char *val, int flags)
2078 volatile int saveint;
2079 struct jmploc *volatile savehandler = exception_handler;
2080 struct jmploc jmploc;
2083 if (setjmp(jmploc.loc))
2086 exception_handler = &jmploc;
2087 setvar(name, val, flags);
2090 exception_handler = savehandler;
2091 RESTORE_INT(saveint);
2097 * Unset the specified variable.
2100 unsetvar(const char *s)
2106 vpp = findvar(hashvar(s), s);
2110 int flags = vp->flags;
2113 if (flags & VREADONLY)
2116 vp->flags &= ~VDYNAMIC;
2120 if ((flags & VSTRFIXED) == 0) {
2122 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2123 free((char*)vp->text);
2129 vp->flags &= ~VEXPORT;
2139 * Process a linked list of variable assignments.
2142 listsetvar(struct strlist *list_set_var, int flags)
2144 struct strlist *lp = list_set_var;
2150 setvareq(lp->text, flags);
2157 * Generate a list of variables satisfying the given conditions.
2160 listvars(int on, int off, char ***end)
2171 for (vp = *vpp; vp; vp = vp->next) {
2172 if ((vp->flags & mask) == on) {
2173 if (ep == stackstrend())
2174 ep = growstackstr();
2175 *ep++ = (char *) vp->text;
2178 } while (++vpp < vartab + VTABSIZE);
2179 if (ep == stackstrend())
2180 ep = growstackstr();
2184 return grabstackstr(ep);
2188 /* ============ Path search helper
2190 * The variable path (passed by reference) should be set to the start
2191 * of the path before the first call; padvance will update
2192 * this value as it proceeds. Successive calls to padvance will return
2193 * the possible path expansions in sequence. If an option (indicated by
2194 * a percent sign) appears in the path entry then the global variable
2195 * pathopt will be set to point to it; otherwise pathopt will be set to
2198 static const char *pathopt; /* set by padvance */
2201 padvance(const char **path, const char *name)
2211 for (p = start; *p && *p != ':' && *p != '%'; p++);
2212 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2213 while (stackblocksize() < len)
2217 memcpy(q, start, p - start);
2225 while (*p && *p != ':') p++;
2231 return stalloc(len);
2235 /* ============ Prompt */
2237 static smallint doprompt; /* if set, prompt the user */
2238 static smallint needprompt; /* true if interactive and at start of line */
2240 #if ENABLE_FEATURE_EDITING
2241 static line_input_t *line_input_state;
2242 static const char *cmdedit_prompt;
2244 putprompt(const char *s)
2246 if (ENABLE_ASH_EXPAND_PRMT) {
2247 free((char*)cmdedit_prompt);
2248 cmdedit_prompt = ckstrdup(s);
2255 putprompt(const char *s)
2261 #if ENABLE_ASH_EXPAND_PRMT
2262 /* expandstr() needs parsing machinery, so it is far away ahead... */
2263 static const char *expandstr(const char *ps);
2265 #define expandstr(s) s
2269 setprompt(int whichprompt)
2272 #if ENABLE_ASH_EXPAND_PRMT
2273 struct stackmark smark;
2278 switch (whichprompt) {
2288 #if ENABLE_ASH_EXPAND_PRMT
2289 setstackmark(&smark);
2290 stalloc(stackblocksize());
2292 putprompt(expandstr(prompt));
2293 #if ENABLE_ASH_EXPAND_PRMT
2294 popstackmark(&smark);
2299 /* ============ The cd and pwd commands */
2301 #define CD_PHYSICAL 1
2304 static int docd(const char *, int);
2313 while ((i = nextopt("LP"))) {
2315 flags ^= CD_PHYSICAL;
2324 * Update curdir (the name of the current directory) in response to a
2328 updatepwd(const char *dir)
2335 cdcomppath = ststrdup(dir);
2338 if (curdir == nullstr)
2340 new = stack_putstr(curdir, new);
2342 new = makestrspace(strlen(dir) + 2, new);
2343 lim = stackblock() + 1;
2347 if (new > lim && *lim == '/')
2352 if (dir[1] == '/' && dir[2] != '/') {
2358 p = strtok(cdcomppath, "/");
2362 if (p[1] == '.' && p[2] == '\0') {
2374 new = stack_putstr(p, new);
2382 return stackblock();
2386 * Find out what the current directory is. If we already know the current
2387 * directory, this routine returns immediately.
2392 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2393 return dir ? dir : nullstr;
2397 setpwd(const char *val, int setold)
2401 oldcur = dir = curdir;
2404 setvar("OLDPWD", oldcur, VEXPORT);
2407 if (physdir != nullstr) {
2408 if (physdir != oldcur)
2412 if (oldcur == val || !val) {
2418 dir = ckstrdup(val);
2419 if (oldcur != dir && oldcur != nullstr) {
2424 setvar("PWD", dir, VEXPORT);
2427 static void hashcd(void);
2430 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2431 * know that the current directory has changed.
2434 docd(const char *dest, int flags)
2436 const char *dir = 0;
2439 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2442 if (!(flags & CD_PHYSICAL)) {
2443 dir = updatepwd(dest);
2458 cdcmd(int argc, char **argv)
2470 dest = bltinlookup(homestr);
2471 else if (LONE_DASH(dest)) {
2472 dest = bltinlookup("OLDPWD");
2494 path = bltinlookup("CDPATH");
2503 p = padvance(&path, dest);
2504 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2508 if (!docd(p, flags))
2513 ash_msg_and_raise_error("can't cd to %s", dest);
2516 if (flags & CD_PRINT)
2517 out1fmt(snlfmt, curdir);
2522 pwdcmd(int argc, char **argv)
2525 const char *dir = curdir;
2529 if (physdir == nullstr)
2533 out1fmt(snlfmt, dir);
2538 /* ============ ... */
2540 #define IBUFSIZ COMMON_BUFSIZE
2541 #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
2543 /* Syntax classes */
2544 #define CWORD 0 /* character is nothing special */
2545 #define CNL 1 /* newline character */
2546 #define CBACK 2 /* a backslash character */
2547 #define CSQUOTE 3 /* single quote */
2548 #define CDQUOTE 4 /* double quote */
2549 #define CENDQUOTE 5 /* a terminating quote */
2550 #define CBQUOTE 6 /* backwards single quote */
2551 #define CVAR 7 /* a dollar sign */
2552 #define CENDVAR 8 /* a '}' character */
2553 #define CLP 9 /* a left paren in arithmetic */
2554 #define CRP 10 /* a right paren in arithmetic */
2555 #define CENDFILE 11 /* end of file */
2556 #define CCTL 12 /* like CWORD, except it must be escaped */
2557 #define CSPCL 13 /* these terminate a word */
2558 #define CIGN 14 /* character should be ignored */
2560 #if ENABLE_ASH_ALIAS
2564 #define PEOA_OR_PEOF PEOA
2568 #define PEOA_OR_PEOF PEOF
2571 /* number syntax index */
2572 #define BASESYNTAX 0 /* not in quotes */
2573 #define DQSYNTAX 1 /* in double quotes */
2574 #define SQSYNTAX 2 /* in single quotes */
2575 #define ARISYNTAX 3 /* in arithmetic */
2576 #define PSSYNTAX 4 /* prompt */
2578 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2579 #define USE_SIT_FUNCTION
2582 #if ENABLE_ASH_MATH_SUPPORT
2583 static const char S_I_T[][4] = {
2584 #if ENABLE_ASH_ALIAS
2585 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2587 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2588 { CNL, CNL, CNL, CNL }, /* 2, \n */
2589 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2590 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2591 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2592 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2593 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2594 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2595 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2596 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2597 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2598 #ifndef USE_SIT_FUNCTION
2599 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2600 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2601 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2605 static const char S_I_T[][3] = {
2606 #if ENABLE_ASH_ALIAS
2607 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2609 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2610 { CNL, CNL, CNL }, /* 2, \n */
2611 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2612 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2613 { CVAR, CVAR, CWORD }, /* 5, $ */
2614 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2615 { CSPCL, CWORD, CWORD }, /* 7, ( */
2616 { CSPCL, CWORD, CWORD }, /* 8, ) */
2617 { CBACK, CBACK, CCTL }, /* 9, \ */
2618 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2619 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2620 #ifndef USE_SIT_FUNCTION
2621 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2622 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2623 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2626 #endif /* ASH_MATH_SUPPORT */
2628 #ifdef USE_SIT_FUNCTION
2631 SIT(int c, int syntax)
2633 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2634 #if ENABLE_ASH_ALIAS
2635 static const char syntax_index_table[] ALIGN1 = {
2636 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2637 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2638 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2642 static const char syntax_index_table[] ALIGN1 = {
2643 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2644 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2645 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2652 if (c == PEOF) /* 2^8+2 */
2654 #if ENABLE_ASH_ALIAS
2655 if (c == PEOA) /* 2^8+1 */
2659 #define U_C(c) ((unsigned char)(c))
2661 if ((unsigned char)c >= (unsigned char)(CTLESC)
2662 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2666 s = strchr(spec_symbls, c);
2667 if (s == NULL || *s == '\0')
2669 indx = syntax_index_table[(s - spec_symbls)];
2671 return S_I_T[indx][syntax];
2674 #else /* !USE_SIT_FUNCTION */
2676 #if ENABLE_ASH_ALIAS
2677 #define CSPCL_CIGN_CIGN_CIGN 0
2678 #define CSPCL_CWORD_CWORD_CWORD 1
2679 #define CNL_CNL_CNL_CNL 2
2680 #define CWORD_CCTL_CCTL_CWORD 3
2681 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2682 #define CVAR_CVAR_CWORD_CVAR 5
2683 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2684 #define CSPCL_CWORD_CWORD_CLP 7
2685 #define CSPCL_CWORD_CWORD_CRP 8
2686 #define CBACK_CBACK_CCTL_CBACK 9
2687 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2688 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2689 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2690 #define CWORD_CWORD_CWORD_CWORD 13
2691 #define CCTL_CCTL_CCTL_CCTL 14
2693 #define CSPCL_CWORD_CWORD_CWORD 0
2694 #define CNL_CNL_CNL_CNL 1
2695 #define CWORD_CCTL_CCTL_CWORD 2
2696 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2697 #define CVAR_CVAR_CWORD_CVAR 4
2698 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2699 #define CSPCL_CWORD_CWORD_CLP 6
2700 #define CSPCL_CWORD_CWORD_CRP 7
2701 #define CBACK_CBACK_CCTL_CBACK 8
2702 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2703 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2704 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2705 #define CWORD_CWORD_CWORD_CWORD 12
2706 #define CCTL_CCTL_CCTL_CCTL 13
2709 static const char syntax_index_table[258] = {
2710 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2711 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2712 #if ENABLE_ASH_ALIAS
2713 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2715 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2716 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2717 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2718 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2719 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2720 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2721 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2722 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2723 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2724 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2854 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2876 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2877 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2878 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2880 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2882 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2883 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2884 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2885 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2886 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2888 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2889 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2890 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2904 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2936 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2937 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2940 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2968 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2969 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2970 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
2973 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2975 #endif /* USE_SIT_FUNCTION */
2978 /* ============ Alias handling */
2980 #if ENABLE_ASH_ALIAS
2982 #define ALIASINUSE 1
2993 static struct alias **atab; // [ATABSIZE];
2994 #define INIT_G_alias() do { \
2995 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
2999 static struct alias **
3000 __lookupalias(const char *name) {
3001 unsigned int hashval;
3008 ch = (unsigned char)*p;
3012 ch = (unsigned char)*++p;
3014 app = &atab[hashval % ATABSIZE];
3016 for (; *app; app = &(*app)->next) {
3017 if (strcmp(name, (*app)->name) == 0) {
3025 static struct alias *
3026 lookupalias(const char *name, int check)
3028 struct alias *ap = *__lookupalias(name);
3030 if (check && ap && (ap->flag & ALIASINUSE))
3035 static struct alias *
3036 freealias(struct alias *ap)
3040 if (ap->flag & ALIASINUSE) {
3041 ap->flag |= ALIASDEAD;
3053 setalias(const char *name, const char *val)
3055 struct alias *ap, **app;
3057 app = __lookupalias(name);
3061 if (!(ap->flag & ALIASINUSE)) {
3064 ap->val = ckstrdup(val);
3065 ap->flag &= ~ALIASDEAD;
3068 ap = ckmalloc(sizeof(struct alias));
3069 ap->name = ckstrdup(name);
3070 ap->val = ckstrdup(val);
3079 unalias(const char *name)
3083 app = __lookupalias(name);
3087 *app = freealias(*app);
3098 struct alias *ap, **app;
3102 for (i = 0; i < ATABSIZE; i++) {
3104 for (ap = *app; ap; ap = *app) {
3105 *app = freealias(*app);
3115 printalias(const struct alias *ap)
3117 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3121 * TODO - sort output
3124 aliascmd(int argc, char **argv)
3133 for (i = 0; i < ATABSIZE; i++)
3134 for (ap = atab[i]; ap; ap = ap->next) {
3139 while ((n = *++argv) != NULL) {
3140 v = strchr(n+1, '=');
3141 if (v == NULL) { /* n+1: funny ksh stuff */
3142 ap = *__lookupalias(n);
3144 fprintf(stderr, "%s: %s not found\n", "alias", n);
3158 unaliascmd(int argc, char **argv)
3162 while ((i = nextopt("a")) != '\0') {
3168 for (i = 0; *argptr; argptr++) {
3169 if (unalias(*argptr)) {
3170 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3178 #endif /* ASH_ALIAS */
3181 /* ============ jobs.c */
3183 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3186 #define FORK_NOJOB 2
3188 /* mode flags for showjob(s) */
3189 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3190 #define SHOW_PID 0x04 /* include process pid */
3191 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3194 * A job structure contains information about a job. A job is either a
3195 * single process or a set of processes contained in a pipeline. In the
3196 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3201 pid_t pid; /* process id */
3202 int status; /* last process status from wait() */
3203 char *cmd; /* text of command being run */
3207 struct procstat ps0; /* status of process */
3208 struct procstat *ps; /* status or processes when more than one */
3210 int stopstatus; /* status of a stopped job */
3213 nprocs: 16, /* number of processes */
3215 #define JOBRUNNING 0 /* at least one proc running */
3216 #define JOBSTOPPED 1 /* all procs are stopped */
3217 #define JOBDONE 2 /* all procs are completed */
3219 sigint: 1, /* job was killed by SIGINT */
3220 jobctl: 1, /* job running under job control */
3222 waited: 1, /* true if this entry has been waited for */
3223 used: 1, /* true if this entry is in used */
3224 changed: 1; /* true if status has changed */
3225 struct job *prev_job; /* previous job */
3228 static pid_t backgndpid; /* pid of last background process */
3229 static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
3231 static struct job *makejob(union node *, int);
3232 static int forkshell(struct job *, union node *, int);
3233 static int waitforjob(struct job *);
3236 enum { jobctl = 0 };
3237 #define setjobctl(on) do {} while (0)
3239 static smallint jobctl; /* true if doing job control */
3240 static void setjobctl(int);
3244 * Set the signal handler for the specified signal. The routine figures
3245 * out what it should be set to.
3248 setsignal(int signo)
3252 struct sigaction act;
3258 else if (*t != '\0')
3260 if (rootshell && action == S_DFL) {
3263 if (iflag || minusc || sflag == 0)
3286 t = &sigmode[signo - 1];
3290 * current setting unknown
3292 if (sigaction(signo, NULL, &act) == -1) {
3294 * Pretend it worked; maybe we should give a warning
3295 * here, but other shells don't. We don't alter
3296 * sigmode, so that we retry every time.
3300 tsig = S_RESET; /* force to be set */
3301 if (act.sa_handler == SIG_IGN) {
3304 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3306 tsig = S_IGN; /* don't hard ignore these */
3310 if (tsig == S_HARD_IGN || tsig == action)
3312 act.sa_handler = SIG_DFL;
3315 act.sa_handler = onsig;
3318 act.sa_handler = SIG_IGN;
3323 sigfillset(&act.sa_mask);
3324 sigaction(signo, &act, NULL);
3327 /* mode flags for set_curjob */
3328 #define CUR_DELETE 2
3329 #define CUR_RUNNING 1
3330 #define CUR_STOPPED 0
3332 /* mode flags for dowait */
3333 #define DOWAIT_NONBLOCK WNOHANG
3334 #define DOWAIT_BLOCK 0
3337 /* pgrp of shell on invocation */
3338 static int initialpgrp;
3339 static int ttyfd = -1;
3342 static struct job *jobtab;
3344 static unsigned njobs;
3346 static struct job *curjob;
3347 /* number of presumed living untracked jobs */
3351 set_curjob(struct job *jp, unsigned mode)
3354 struct job **jpp, **curp;
3356 /* first remove from list */
3357 jpp = curp = &curjob;
3362 jpp = &jp1->prev_job;
3364 *jpp = jp1->prev_job;
3366 /* Then re-insert in correct position */
3374 /* job being deleted */
3377 /* newly created job or backgrounded job,
3378 put after all stopped jobs. */
3382 if (!jp1 || jp1->state != JOBSTOPPED)
3385 jpp = &jp1->prev_job;
3391 /* newly stopped job - becomes curjob */
3392 jp->prev_job = *jpp;
3400 jobno(const struct job *jp)
3402 return jp - jobtab + 1;
3407 * Convert a job name to a job structure.
3410 getjob(const char *name, int getctl)
3414 const char *err_msg = "No such job: %s";
3418 char *(*match)(const char *, const char *);
3433 if (c == '+' || c == '%') {
3435 err_msg = "No current job";
3441 err_msg = "No previous job";
3452 jp = jobtab + num - 1;
3469 if (match(jp->ps[0].cmd, p)) {
3473 err_msg = "%s: ambiguous";
3480 err_msg = "job %s not created under job control";
3481 if (getctl && jp->jobctl == 0)
3486 ash_msg_and_raise_error(err_msg, name);
3490 * Mark a job structure as unused.
3493 freejob(struct job *jp)
3495 struct procstat *ps;
3499 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3500 if (ps->cmd != nullstr)
3503 if (jp->ps != &jp->ps0)
3506 set_curjob(jp, CUR_DELETE);
3512 xtcsetpgrp(int fd, pid_t pgrp)
3514 if (tcsetpgrp(fd, pgrp))
3515 ash_msg_and_raise_error("cannot set tty process group (%m)");
3519 * Turn job control on and off.
3521 * Note: This code assumes that the third arg to ioctl is a character
3522 * pointer, which is true on Berkeley systems but not System V. Since
3523 * System V doesn't have job control yet, this isn't a problem now.
3525 * Called with interrupts off.
3533 if (on == jobctl || rootshell == 0)
3537 ofd = fd = open(_PATH_TTY, O_RDWR);
3539 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3540 * That sometimes helps to acquire controlling tty.
3541 * Obviously, a workaround for bugs when someone
3542 * failed to provide a controlling tty to bash! :) */
3548 fd = fcntl(fd, F_DUPFD, 10);
3553 /* fd is a tty at this point */
3554 close_on_exec_on(fd);
3555 do { /* while we are in the background */
3556 pgrp = tcgetpgrp(fd);
3559 ash_msg("can't access tty; job control turned off");
3563 if (pgrp == getpgrp())
3574 xtcsetpgrp(fd, pgrp);
3576 /* turning job control off */
3579 /* was xtcsetpgrp, but this can make exiting ash
3580 * loop forever if pty is already deleted */
3581 tcsetpgrp(fd, pgrp);
3596 killcmd(int argc, char **argv)
3598 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3601 if (argv[i][0] == '%') {
3602 struct job *jp = getjob(argv[i], 0);
3603 unsigned pid = jp->ps[0].pid;
3604 /* Enough space for ' -NNN<nul>' */
3605 argv[i] = alloca(sizeof(int)*3 + 3);
3606 /* kill_main has matching code to expect
3607 * leading space. Needed to not confuse
3608 * negative pids with "kill -SIGNAL_NO" syntax */
3609 sprintf(argv[i], " -%u", pid);
3611 } while (argv[++i]);
3613 return kill_main(argc, argv);
3617 showpipe(struct job *jp, FILE *out)
3619 struct procstat *sp;
3620 struct procstat *spend;
3622 spend = jp->ps + jp->nprocs;
3623 for (sp = jp->ps + 1; sp < spend; sp++)
3624 fprintf(out, " | %s", sp->cmd);
3625 outcslow('\n', out);
3626 flush_stdout_stderr();
3631 restartjob(struct job *jp, int mode)
3633 struct procstat *ps;
3639 if (jp->state == JOBDONE)
3641 jp->state = JOBRUNNING;
3643 if (mode == FORK_FG)
3644 xtcsetpgrp(ttyfd, pgid);
3645 killpg(pgid, SIGCONT);
3649 if (WIFSTOPPED(ps->status)) {
3655 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3661 fg_bgcmd(int argc, char **argv)
3668 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3673 jp = getjob(*argv, 1);
3674 if (mode == FORK_BG) {
3675 set_curjob(jp, CUR_RUNNING);
3676 fprintf(out, "[%d] ", jobno(jp));
3678 outstr(jp->ps->cmd, out);
3680 retval = restartjob(jp, mode);
3681 } while (*argv && *++argv);
3687 sprint_status(char *s, int status, int sigonly)
3693 if (!WIFEXITED(status)) {
3695 if (WIFSTOPPED(status))
3696 st = WSTOPSIG(status);
3699 st = WTERMSIG(status);
3701 if (st == SIGINT || st == SIGPIPE)
3704 if (WIFSTOPPED(status))
3709 col = fmtstr(s, 32, strsignal(st));
3710 if (WCOREDUMP(status)) {
3711 col += fmtstr(s + col, 16, " (core dumped)");
3713 } else if (!sigonly) {
3714 st = WEXITSTATUS(status);
3716 col = fmtstr(s, 16, "Done(%d)", st);
3718 col = fmtstr(s, 16, "Done");
3725 * Do a wait system call. If job control is compiled in, we accept
3726 * stopped processes. If block is zero, we return a value of zero
3727 * rather than blocking.
3729 * System V doesn't have a non-blocking wait system call. It does
3730 * have a SIGCLD signal that is sent to a process when one of it's
3731 * children dies. The obvious way to use SIGCLD would be to install
3732 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3733 * was received, and have waitproc bump another counter when it got
3734 * the status of a process. Waitproc would then know that a wait
3735 * system call would not block if the two counters were different.
3736 * This approach doesn't work because if a process has children that
3737 * have not been waited for, System V will send it a SIGCLD when it
3738 * installs a signal handler for SIGCLD. What this means is that when
3739 * a child exits, the shell will be sent SIGCLD signals continuously
3740 * until is runs out of stack space, unless it does a wait call before
3741 * restoring the signal handler. The code below takes advantage of
3742 * this (mis)feature by installing a signal handler for SIGCLD and
3743 * then checking to see whether it was called. If there are any
3744 * children to be waited for, it will be.
3746 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3747 * waits at all. In this case, the user will not be informed when
3748 * a background process until the next time she runs a real program
3749 * (as opposed to running a builtin command or just typing return),
3750 * and the jobs command may give out of date information.
3753 waitproc(int wait_flags, int *status)
3757 wait_flags |= WUNTRACED;
3759 /* NB: _not_ safe_waitpid, we need to detect EINTR */
3760 return waitpid(-1, status, wait_flags);
3764 * Wait for a process to terminate.
3767 dowait(int wait_flags, struct job *job)
3772 struct job *thisjob;
3775 TRACE(("dowait(%d) called\n", wait_flags));
3776 pid = waitproc(wait_flags, &status);
3777 TRACE(("wait returns pid=%d, status=%d\n", pid, status));
3779 /* If we were doing blocking wait and (probably) got EINTR,
3780 * check for pending sigs received while waiting.
3781 * (NB: can be moved into callers if needed) */
3782 if (wait_flags == DOWAIT_BLOCK && pendingsig)
3783 raise_exception(EXSIG);
3788 for (jp = curjob; jp; jp = jp->prev_job) {
3789 struct procstat *sp;
3790 struct procstat *spend;
3791 if (jp->state == JOBDONE)
3794 spend = jp->ps + jp->nprocs;
3797 if (sp->pid == pid) {
3798 TRACE(("Job %d: changing status of proc %d "
3799 "from 0x%x to 0x%x\n",
3800 jobno(jp), pid, sp->status, status));
3801 sp->status = status;
3804 if (sp->status == -1)
3807 if (state == JOBRUNNING)
3809 if (WIFSTOPPED(sp->status)) {
3810 jp->stopstatus = sp->status;
3814 } while (++sp < spend);
3819 if (!WIFSTOPPED(status))
3825 if (state != JOBRUNNING) {
3826 thisjob->changed = 1;
3828 if (thisjob->state != state) {
3829 TRACE(("Job %d: changing state from %d to %d\n",
3830 jobno(thisjob), thisjob->state, state));
3831 thisjob->state = state;
3833 if (state == JOBSTOPPED) {
3834 set_curjob(thisjob, CUR_STOPPED);
3843 if (thisjob && thisjob == job) {
3847 len = sprint_status(s, status, 1);
3859 showjob(FILE *out, struct job *jp, int mode)
3861 struct procstat *ps;
3862 struct procstat *psend;
3869 if (mode & SHOW_PGID) {
3870 /* just output process (group) id of pipeline */
3871 fprintf(out, "%d\n", ps->pid);
3875 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3880 else if (curjob && jp == curjob->prev_job)
3883 if (mode & SHOW_PID)
3884 col += fmtstr(s + col, 16, "%d ", ps->pid);
3886 psend = ps + jp->nprocs;
3888 if (jp->state == JOBRUNNING) {
3889 strcpy(s + col, "Running");
3890 col += sizeof("Running") - 1;
3892 int status = psend[-1].status;
3893 if (jp->state == JOBSTOPPED)
3894 status = jp->stopstatus;
3895 col += sprint_status(s + col, status, 0);
3901 /* for each process */
3902 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3904 fprintf(out, "%s%*c%s",
3905 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3907 if (!(mode & SHOW_PID)) {
3911 if (++ps == psend) {
3912 outcslow('\n', out);
3919 if (jp->state == JOBDONE) {
3920 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3926 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3927 * statuses have changed since the last call to showjobs.
3930 showjobs(FILE *out, int mode)
3934 TRACE(("showjobs(%x) called\n", mode));
3936 /* If not even one job changed, there is nothing to do */
3937 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3940 for (jp = curjob; jp; jp = jp->prev_job) {
3941 if (!(mode & SHOW_CHANGED) || jp->changed) {
3942 showjob(out, jp, mode);
3948 jobscmd(int argc, char **argv)
3953 while ((m = nextopt("lp"))) {
3963 showjob(stdout, getjob(*argv,0), mode);
3966 showjobs(stdout, mode);
3973 getstatus(struct job *job)
3978 status = job->ps[job->nprocs - 1].status;
3979 retval = WEXITSTATUS(status);
3980 if (!WIFEXITED(status)) {
3982 retval = WSTOPSIG(status);
3983 if (!WIFSTOPPED(status))
3986 /* XXX: limits number of signals */
3987 retval = WTERMSIG(status);
3989 if (retval == SIGINT)
3995 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
3996 jobno(job), job->nprocs, status, retval));
4001 waitcmd(int argc, char **argv)
4010 raise_exception(EXSIG);
4017 /* wait for all jobs */
4021 if (!jp) /* no running procs */
4023 if (jp->state == JOBRUNNING)
4028 dowait(DOWAIT_BLOCK, NULL);
4034 if (**argv != '%') {
4035 pid_t pid = number(*argv);
4040 if (job->ps[job->nprocs - 1].pid == pid)
4042 job = job->prev_job;
4045 job = getjob(*argv, 0);
4046 /* loop until process terminated or stopped */
4047 while (job->state == JOBRUNNING)
4048 dowait(DOWAIT_BLOCK, NULL);
4050 retval = getstatus(job);
4064 struct job *jp, *jq;
4066 len = njobs * sizeof(*jp);
4068 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4070 offset = (char *)jp - (char *)jq;
4072 /* Relocate pointers */
4075 jq = (struct job *)((char *)jq + l);
4079 #define joff(p) ((struct job *)((char *)(p) + l))
4080 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4081 if (joff(jp)->ps == &jq->ps0)
4082 jmove(joff(jp)->ps);
4083 if (joff(jp)->prev_job)
4084 jmove(joff(jp)->prev_job);
4094 jp = (struct job *)((char *)jp + len);
4098 } while (--jq >= jp);
4103 * Return a new job structure.
4104 * Called with interrupts off.
4107 makejob(union node *node, int nprocs)
4112 for (i = njobs, jp = jobtab; ; jp++) {
4119 if (jp->state != JOBDONE || !jp->waited)
4128 memset(jp, 0, sizeof(*jp));
4130 /* jp->jobctl is a bitfield.
4131 * "jp->jobctl |= jobctl" likely to give awful code */
4135 jp->prev_job = curjob;
4140 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4142 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4149 * Return a string identifying a command (to be printed by the
4152 static char *cmdnextc;
4155 cmdputs(const char *s)
4157 const char *p, *str;
4158 char c, cc[2] = " ";
4162 static const char vstype[VSTYPE + 1][4] = {
4163 "", "}", "-", "+", "?", "=",
4164 "%", "%%", "#", "##"
4167 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4169 while ((c = *p++) != 0) {
4177 if ((subtype & VSTYPE) == VSLENGTH)
4181 if (!(subtype & VSQUOTE) == !(quoted & 1))
4187 str = "\"}" + !(quoted & 1);
4194 case CTLBACKQ+CTLQUOTE:
4197 #if ENABLE_ASH_MATH_SUPPORT
4212 if ((subtype & VSTYPE) != VSNORMAL)
4214 str = vstype[subtype & VSTYPE];
4215 if (subtype & VSNUL)
4224 /* These can only happen inside quotes */
4237 while ((c = *str++)) {
4242 USTPUTC('"', nextc);
4248 /* cmdtxt() and cmdlist() call each other */
4249 static void cmdtxt(union node *n);
4252 cmdlist(union node *np, int sep)
4254 for (; np; np = np->narg.next) {
4258 if (sep && np->narg.next)
4264 cmdtxt(union node *n)
4267 struct nodelist *lp;
4279 lp = n->npipe.cmdlist;
4297 cmdtxt(n->nbinary.ch1);
4313 cmdtxt(n->nif.test);
4316 if (n->nif.elsepart) {
4319 n = n->nif.elsepart;
4335 cmdtxt(n->nbinary.ch1);
4345 cmdputs(n->nfor.var);
4347 cmdlist(n->nfor.args, 1);
4352 cmdputs(n->narg.text);
4356 cmdlist(n->ncmd.args, 1);
4357 cmdlist(n->ncmd.redirect, 0);
4370 cmdputs(n->ncase.expr->narg.text);
4372 for (np = n->ncase.cases; np; np = np->nclist.next) {
4373 cmdtxt(np->nclist.pattern);
4375 cmdtxt(np->nclist.body);
4401 s[0] = n->nfile.fd + '0';
4405 if (n->type == NTOFD || n->type == NFROMFD) {
4406 s[0] = n->ndup.dupfd + '0';
4416 commandtext(union node *n)
4420 STARTSTACKSTR(cmdnextc);
4422 name = stackblock();
4423 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4424 name, cmdnextc, cmdnextc));
4425 return ckstrdup(name);
4430 * Fork off a subshell. If we are doing job control, give the subshell its
4431 * own process group. Jp is a job structure that the job is to be added to.
4432 * N is the command that will be evaluated by the child. Both jp and n may
4433 * be NULL. The mode parameter can be one of the following:
4434 * FORK_FG - Fork off a foreground process.
4435 * FORK_BG - Fork off a background process.
4436 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4437 * process group even if job control is on.
4439 * When job control is turned off, background processes have their standard
4440 * input redirected to /dev/null (except for the second and later processes
4443 * Called with interrupts off.
4446 * Clear traps on a fork.
4453 for (tp = trap; tp < &trap[NSIG]; tp++) {
4454 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4459 setsignal(tp - trap);
4465 /* Lives far away from here, needed for forkchild */
4466 static void closescript(void);
4468 /* Called after fork(), in child */
4470 forkchild(struct job *jp, union node *n, int mode)
4474 TRACE(("Child shell %d\n", getpid()));
4481 /* do job control only in root shell */
4483 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4486 if (jp->nprocs == 0)
4489 pgrp = jp->ps[0].pid;
4490 /* This can fail because we are doing it in the parent also */
4491 (void)setpgid(0, pgrp);
4492 if (mode == FORK_FG)
4493 xtcsetpgrp(ttyfd, pgrp);
4498 if (mode == FORK_BG) {
4501 if (jp->nprocs == 0) {
4503 if (open(bb_dev_null, O_RDONLY) != 0)
4504 ash_msg_and_raise_error("can't open %s", bb_dev_null);
4507 if (!oldlvl && iflag) {
4512 for (jp = curjob; jp; jp = jp->prev_job)
4517 /* Called after fork(), in parent */
4519 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4521 TRACE(("In parent shell: child = %d\n", pid));
4523 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4529 if (mode != FORK_NOJOB && jp->jobctl) {
4532 if (jp->nprocs == 0)
4535 pgrp = jp->ps[0].pid;
4536 /* This can fail because we are doing it in the child also */
4540 if (mode == FORK_BG) {
4541 backgndpid = pid; /* set $! */
4542 set_curjob(jp, CUR_RUNNING);
4545 struct procstat *ps = &jp->ps[jp->nprocs++];
4551 ps->cmd = commandtext(n);
4557 forkshell(struct job *jp, union node *n, int mode)
4561 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4564 TRACE(("Fork failed, errno=%d", errno));
4567 ash_msg_and_raise_error("cannot fork");
4570 forkchild(jp, n, mode);
4572 forkparent(jp, n, mode, pid);
4577 * Wait for job to finish.
4579 * Under job control we have the problem that while a child process is
4580 * running interrupts generated by the user are sent to the child but not
4581 * to the shell. This means that an infinite loop started by an inter-
4582 * active user may be hard to kill. With job control turned off, an
4583 * interactive user may place an interactive program inside a loop. If
4584 * the interactive program catches interrupts, the user doesn't want
4585 * these interrupts to also abort the loop. The approach we take here
4586 * is to have the shell ignore interrupt signals while waiting for a
4587 * foreground process to terminate, and then send itself an interrupt
4588 * signal if the child process was terminated by an interrupt signal.
4589 * Unfortunately, some programs want to do a bit of cleanup and then
4590 * exit on interrupt; unless these processes terminate themselves by
4591 * sending a signal to themselves (instead of calling exit) they will
4592 * confuse this approach.
4594 * Called with interrupts off.
4597 waitforjob(struct job *jp)
4601 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4602 while (jp->state == JOBRUNNING) {
4603 dowait(DOWAIT_BLOCK, jp);
4608 xtcsetpgrp(ttyfd, rootpid);
4610 * This is truly gross.
4611 * If we're doing job control, then we did a TIOCSPGRP which
4612 * caused us (the shell) to no longer be in the controlling
4613 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4614 * intuit from the subprocess exit status whether a SIGINT
4615 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4617 if (jp->sigint) /* TODO: do the same with all signals */
4618 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4620 if (jp->state == JOBDONE)
4627 * return 1 if there are stopped jobs, otherwise 0
4639 if (jp && jp->state == JOBSTOPPED) {
4640 out2str("You have stopped jobs.\n");
4649 /* ============ redir.c
4651 * Code for dealing with input/output redirection.
4654 #define EMPTY -2 /* marks an unused slot in redirtab */
4655 #define CLOSED -3 /* marks a slot of previously-closed fd */
4657 # define PIPESIZE 4096 /* amount of buffering in a pipe */
4659 # define PIPESIZE PIPE_BUF
4663 * Open a file in noclobber mode.
4664 * The code was copied from bash.
4667 noclobberopen(const char *fname)
4670 struct stat finfo, finfo2;
4673 * If the file exists and is a regular file, return an error
4676 r = stat(fname, &finfo);
4677 if (r == 0 && S_ISREG(finfo.st_mode)) {
4683 * If the file was not present (r != 0), make sure we open it
4684 * exclusively so that if it is created before we open it, our open
4685 * will fail. Make sure that we do not truncate an existing file.
4686 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4687 * file was not a regular file, we leave O_EXCL off.
4690 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4691 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4693 /* If the open failed, return the file descriptor right away. */
4698 * OK, the open succeeded, but the file may have been changed from a
4699 * non-regular file to a regular file between the stat and the open.
4700 * We are assuming that the O_EXCL open handles the case where FILENAME
4701 * did not exist and is symlinked to an existing file between the stat
4706 * If we can open it and fstat the file descriptor, and neither check
4707 * revealed that it was a regular file, and the file has not been
4708 * replaced, return the file descriptor.
4710 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4711 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4714 /* The file has been replaced. badness. */
4721 * Handle here documents. Normally we fork off a process to write the
4722 * data to a pipe. If the document is short, we can stuff the data in
4723 * the pipe without forking.
4725 /* openhere needs this forward reference */
4726 static void expandhere(union node *arg, int fd);
4728 openhere(union node *redir)
4734 ash_msg_and_raise_error("pipe call failed");
4735 if (redir->type == NHERE) {
4736 len = strlen(redir->nhere.doc->narg.text);
4737 if (len <= PIPESIZE) {
4738 full_write(pip[1], redir->nhere.doc->narg.text, len);
4742 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4744 signal(SIGINT, SIG_IGN);
4745 signal(SIGQUIT, SIG_IGN);
4746 signal(SIGHUP, SIG_IGN);
4748 signal(SIGTSTP, SIG_IGN);
4750 signal(SIGPIPE, SIG_DFL);
4751 if (redir->type == NHERE)
4752 full_write(pip[1], redir->nhere.doc->narg.text, len);
4754 expandhere(redir->nhere.doc, pip[1]);
4763 openredirect(union node *redir)
4768 switch (redir->nfile.type) {
4770 fname = redir->nfile.expfname;
4771 f = open(fname, O_RDONLY);
4776 fname = redir->nfile.expfname;
4777 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4782 /* Take care of noclobber mode. */
4784 fname = redir->nfile.expfname;
4785 f = noclobberopen(fname);
4792 fname = redir->nfile.expfname;
4793 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4798 fname = redir->nfile.expfname;
4799 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4807 /* Fall through to eliminate warning. */
4814 f = openhere(redir);
4820 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4822 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
4826 * Copy a file descriptor to be >= to. Returns -1
4827 * if the source file descriptor is closed, EMPTY if there are no unused
4828 * file descriptors left.
4831 copyfd(int from, int to)
4835 newfd = fcntl(from, F_DUPFD, to);
4837 if (errno == EMFILE)
4839 ash_msg_and_raise_error("%d: %m", from);
4845 dupredirect(union node *redir, int f)
4847 int fd = redir->nfile.fd;
4849 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4850 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4851 copyfd(redir->ndup.dupfd, fd);
4863 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4864 * old file descriptors are stashed away so that the redirection can be
4865 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4866 * standard output, and the standard error if it becomes a duplicate of
4867 * stdout, is saved in memory.
4869 /* flags passed to redirect */
4870 #define REDIR_PUSH 01 /* save previous values of file descriptors */
4871 #define REDIR_SAVEFD2 03 /* set preverrout */
4873 redirect(union node *redir, int flags)
4876 struct redirtab *sv;
4887 if (flags & REDIR_PUSH) {
4888 sv = ckmalloc(sizeof(*sv));
4889 sv->next = redirlist;
4891 sv->nullredirs = g_nullredirs - 1;
4892 for (i = 0; i < 10; i++)
4893 sv->renamed[i] = EMPTY;
4899 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4900 && n->ndup.dupfd == fd)
4901 continue; /* redirect from/to same file descriptor */
4903 newfd = openredirect(n);
4905 /* Descriptor wasn't open before redirect.
4906 * Mark it for close in the future */
4907 if (sv && sv->renamed[fd] == EMPTY)
4908 sv->renamed[fd] = CLOSED;
4911 if (sv && sv->renamed[fd] == EMPTY) {
4912 i = fcntl(fd, F_DUPFD, 10);
4919 ash_msg_and_raise_error("%d: %m", fd);
4923 sv->renamed[fd] = i;
4929 dupredirect(n, newfd);
4930 } while ((n = n->nfile.next));
4932 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
4933 preverrout_fd = sv->renamed[2];
4937 * Undo the effects of the last redirection.
4942 struct redirtab *rp;
4945 if (--g_nullredirs >= 0)
4949 for (i = 0; i < 10; i++) {
4950 if (rp->renamed[i] == CLOSED) {
4955 if (rp->renamed[i] != EMPTY) {
4958 copyfd(rp->renamed[i], i);
4960 close(rp->renamed[i]);
4963 redirlist = rp->next;
4964 g_nullredirs = rp->nullredirs;
4970 * Undo all redirections. Called on error or interrupt.
4974 * Discard all saved file descriptors.
4977 clearredir(int drop)
4988 redirectsafe(union node *redir, int flags)
4991 volatile int saveint;
4992 struct jmploc *volatile savehandler = exception_handler;
4993 struct jmploc jmploc;
4996 err = setjmp(jmploc.loc) * 2;
4998 exception_handler = &jmploc;
4999 redirect(redir, flags);
5001 exception_handler = savehandler;
5002 if (err && exception != EXERROR)
5003 longjmp(exception_handler->loc, 1);
5004 RESTORE_INT(saveint);
5009 /* ============ Routines to expand arguments to commands
5011 * We have to deal with backquotes, shell variables, and file metacharacters.
5017 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5018 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5019 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5020 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5021 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5022 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5023 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5024 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5025 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5029 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5030 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5031 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5032 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5033 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5036 * Structure specifying which parts of the string should be searched
5037 * for IFS characters.
5040 struct ifsregion *next; /* next region in list */
5041 int begoff; /* offset of start of region */
5042 int endoff; /* offset of end of region */
5043 int nulonly; /* search for nul bytes only */
5047 struct strlist *list;
5048 struct strlist **lastp;
5051 /* output of current string */
5052 static char *expdest;
5053 /* list of back quote expressions */
5054 static struct nodelist *argbackq;
5055 /* first struct in list of ifs regions */
5056 static struct ifsregion ifsfirst;
5057 /* last struct in list */
5058 static struct ifsregion *ifslastp;
5059 /* holds expanded arg list */
5060 static struct arglist exparg;
5070 expdest = makestrspace(32, expdest);
5071 #if ENABLE_ASH_MATH_SUPPORT_64
5072 len = fmtstr(expdest, 32, "%lld", (long long) num);
5074 len = fmtstr(expdest, 32, "%ld", num);
5076 STADJUST(len, expdest);
5081 esclen(const char *start, const char *p)
5085 while (p > start && *--p == CTLESC) {
5092 * Remove any CTLESC characters from a string.
5095 _rmescapes(char *str, int flag)
5097 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5104 p = strpbrk(str, qchars);
5110 if (flag & RMESCAPE_ALLOC) {
5111 size_t len = p - str;
5112 size_t fulllen = len + strlen(p) + 1;
5114 if (flag & RMESCAPE_GROW) {
5115 r = makestrspace(fulllen, expdest);
5116 } else if (flag & RMESCAPE_HEAP) {
5117 r = ckmalloc(fulllen);
5119 r = stalloc(fulllen);
5123 q = memcpy(q, str, len) + len;
5126 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5127 globbing = flag & RMESCAPE_GLOB;
5128 notescaped = globbing;
5130 if (*p == CTLQUOTEMARK) {
5131 inquotes = ~inquotes;
5133 notescaped = globbing;
5137 /* naked back slash */
5143 if (notescaped && inquotes && *p != '/') {
5147 notescaped = globbing;
5152 if (flag & RMESCAPE_GROW) {
5154 STADJUST(q - r + 1, expdest);
5158 #define rmescapes(p) _rmescapes((p), 0)
5160 #define pmatch(a, b) !fnmatch((a), (b), 0)
5163 * Prepare a pattern for a expmeta (internal glob(3)) call.
5165 * Returns an stalloced string.
5168 preglob(const char *pattern, int quoted, int flag)
5170 flag |= RMESCAPE_GLOB;
5172 flag |= RMESCAPE_QUOTED;
5174 return _rmescapes((char *)pattern, flag);
5178 * Put a string on the stack.
5181 memtodest(const char *p, size_t len, int syntax, int quotes)
5185 q = makestrspace(len * 2, q);
5188 int c = signed_char2int(*p++);
5191 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5200 strtodest(const char *p, int syntax, int quotes)
5202 memtodest(p, strlen(p), syntax, quotes);
5206 * Record the fact that we have to scan this region of the
5207 * string for IFS characters.
5210 recordregion(int start, int end, int nulonly)
5212 struct ifsregion *ifsp;
5214 if (ifslastp == NULL) {
5218 ifsp = ckmalloc(sizeof(*ifsp));
5220 ifslastp->next = ifsp;
5224 ifslastp->begoff = start;
5225 ifslastp->endoff = end;
5226 ifslastp->nulonly = nulonly;
5230 removerecordregions(int endoff)
5232 if (ifslastp == NULL)
5235 if (ifsfirst.endoff > endoff) {
5236 while (ifsfirst.next != NULL) {
5237 struct ifsregion *ifsp;
5239 ifsp = ifsfirst.next->next;
5240 free(ifsfirst.next);
5241 ifsfirst.next = ifsp;
5244 if (ifsfirst.begoff > endoff)
5247 ifslastp = &ifsfirst;
5248 ifsfirst.endoff = endoff;
5253 ifslastp = &ifsfirst;
5254 while (ifslastp->next && ifslastp->next->begoff < endoff)
5255 ifslastp=ifslastp->next;
5256 while (ifslastp->next != NULL) {
5257 struct ifsregion *ifsp;
5259 ifsp = ifslastp->next->next;
5260 free(ifslastp->next);
5261 ifslastp->next = ifsp;
5264 if (ifslastp->endoff > endoff)
5265 ifslastp->endoff = endoff;
5269 exptilde(char *startp, char *p, int flag)
5275 int quotes = flag & (EXP_FULL | EXP_CASE);
5280 while ((c = *++p) != '\0') {
5287 if (flag & EXP_VARTILDE)
5297 if (*name == '\0') {
5298 home = lookupvar(homestr);
5300 pw = getpwnam(name);
5305 if (!home || !*home)
5308 startloc = expdest - (char *)stackblock();
5309 strtodest(home, SQSYNTAX, quotes);
5310 recordregion(startloc, expdest - (char *)stackblock(), 0);
5318 * Execute a command inside back quotes. If it's a builtin command, we
5319 * want to save its output in a block obtained from malloc. Otherwise
5320 * we fork off a subprocess and get the output of the command via a pipe.
5321 * Should be called with interrupts off.
5323 struct backcmd { /* result of evalbackcmd */
5324 int fd; /* file descriptor to read from */
5325 char *buf; /* buffer */
5326 int nleft; /* number of chars in buffer */
5327 struct job *jp; /* job structure for command */
5330 /* These forward decls are needed to use "eval" code for backticks handling: */
5331 static int back_exitstatus; /* exit status of backquoted command */
5332 #define EV_EXIT 01 /* exit after evaluating tree */
5333 static void evaltree(union node *, int);
5336 evalbackcmd(union node *n, struct backcmd *result)
5348 saveherefd = herefd;
5356 ash_msg_and_raise_error("pipe call failed");
5358 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5367 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5371 result->fd = pip[0];
5374 herefd = saveherefd;
5376 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5377 result->fd, result->buf, result->nleft, result->jp));
5381 * Expand stuff in backwards quotes.
5384 expbackq(union node *cmd, int quoted, int quotes)
5392 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5393 struct stackmark smark;
5396 setstackmark(&smark);
5398 startloc = dest - (char *)stackblock();
5400 evalbackcmd(cmd, &in);
5401 popstackmark(&smark);
5408 memtodest(p, i, syntax, quotes);
5412 i = safe_read(in.fd, buf, sizeof(buf));
5413 TRACE(("expbackq: read returns %d\n", i));
5422 back_exitstatus = waitforjob(in.jp);
5426 /* Eat all trailing newlines */
5428 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5433 recordregion(startloc, dest - (char *)stackblock(), 0);
5434 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5435 (dest - (char *)stackblock()) - startloc,
5436 (dest - (char *)stackblock()) - startloc,
5437 stackblock() + startloc));
5440 #if ENABLE_ASH_MATH_SUPPORT
5442 * Expand arithmetic expression. Backup to start of expression,
5443 * evaluate, place result in (backed up) result, adjust string position.
5456 * This routine is slightly over-complicated for
5457 * efficiency. Next we scan backwards looking for the
5458 * start of arithmetic.
5460 start = stackblock();
5467 while (*p != CTLARI) {
5471 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5476 esc = esclen(start, p);
5486 removerecordregions(begoff);
5495 len = cvtnum(dash_arith(p + 2));
5498 recordregion(begoff, begoff + len, 0);
5502 /* argstr needs it */
5503 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5506 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5507 * characters to allow for further processing. Otherwise treat
5508 * $@ like $* since no splitting will be performed.
5510 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5511 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5512 * for correct expansion of "B=$A" word.
5515 argstr(char *p, int flag, struct strlist *var_str_list)
5517 static const char spclchars[] ALIGN1 = {
5525 CTLBACKQ | CTLQUOTE,
5526 #if ENABLE_ASH_MATH_SUPPORT
5531 const char *reject = spclchars;
5533 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5534 int breakall = flag & EXP_WORD;
5539 if (!(flag & EXP_VARTILDE)) {
5541 } else if (flag & EXP_VARTILDE2) {
5546 if (flag & EXP_TILDE) {
5552 if (*q == CTLESC && (flag & EXP_QWORD))
5555 p = exptilde(p, q, flag);
5558 startloc = expdest - (char *)stackblock();
5560 length += strcspn(p + length, reject);
5562 if (c && (!(c & 0x80)
5563 #if ENABLE_ASH_MATH_SUPPORT
5567 /* c == '=' || c == ':' || c == CTLENDARI */
5572 expdest = stack_nputstr(p, length, expdest);
5573 newloc = expdest - (char *)stackblock();
5574 if (breakall && !inquotes && newloc > startloc) {
5575 recordregion(startloc, newloc, 0);
5586 if (flag & EXP_VARTILDE2) {
5590 flag |= EXP_VARTILDE2;
5595 * sort of a hack - expand tildes in variable
5596 * assignments (after the first '=' and after ':'s).
5605 case CTLENDVAR: /* ??? */
5608 /* "$@" syntax adherence hack */
5611 !memcmp(p, dolatstr, 4) &&
5612 (p[4] == CTLQUOTEMARK || (
5613 p[4] == CTLENDVAR &&
5614 p[5] == CTLQUOTEMARK
5617 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5620 inquotes = !inquotes;
5633 p = evalvar(p, flag, var_str_list);
5637 case CTLBACKQ|CTLQUOTE:
5638 expbackq(argbackq->n, c, quotes);
5639 argbackq = argbackq->next;
5641 #if ENABLE_ASH_MATH_SUPPORT
5654 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5665 const char *s = loc2;
5671 match = pmatch(str, s);
5675 if (quotes && *loc == CTLESC)
5684 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5691 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5694 const char *s = loc2;
5699 match = pmatch(str, s);
5706 esc = esclen(startp, loc);
5717 static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5719 varunset(const char *end, const char *var, const char *umsg, int varflags)
5725 msg = "parameter not set";
5727 if (*end == CTLENDVAR) {
5728 if (varflags & VSNUL)
5733 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5737 subevalvar(char *p, char *str, int strloc, int subtype,
5738 int startloc, int varflags, int quotes, struct strlist *var_str_list)
5742 int saveherefd = herefd;
5743 struct nodelist *saveargbackq = argbackq;
5745 char *rmesc, *rmescend;
5747 char *(*scan)(char *, char *, char *, char *, int , int);
5750 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
5752 STPUTC('\0', expdest);
5753 herefd = saveherefd;
5754 argbackq = saveargbackq;
5755 startp = stackblock() + startloc;
5759 setvar(str, startp, 0);
5760 amount = startp - expdest;
5761 STADJUST(amount, expdest);
5765 varunset(p, str, startp, varflags);
5769 subtype -= VSTRIMRIGHT;
5771 if (subtype < 0 || subtype > 3)
5776 rmescend = stackblock() + strloc;
5778 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5779 if (rmesc != startp) {
5781 startp = stackblock() + startloc;
5785 str = stackblock() + strloc;
5786 preglob(str, varflags & VSQUOTE, 0);
5788 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5789 zero = subtype >> 1;
5790 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5791 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5793 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5796 memmove(startp, loc, str - loc);
5797 loc = startp + (str - loc) - 1;
5800 amount = loc - expdest;
5801 STADJUST(amount, expdest);
5807 * Add the value of a specialized variable to the stack string.
5810 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
5820 int quoted = varflags & VSQUOTE;
5821 int subtype = varflags & VSTYPE;
5822 int quotes = flags & (EXP_FULL | EXP_CASE);
5824 if (quoted && (flags & EXP_FULL))
5825 sep = 1 << CHAR_BIT;
5827 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5836 num = shellparam.nparam;
5846 p = makestrspace(NOPTS, expdest);
5847 for (i = NOPTS - 1; i >= 0; i--) {
5849 USTPUTC(optletters(i), p);
5860 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
5861 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5867 while ((p = *ap++)) {
5870 partlen = strlen(p);
5873 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5874 memtodest(p, partlen, syntax, quotes);
5880 if (subtype == VSPLUS || subtype == VSLENGTH) {
5902 if (num < 0 || num > shellparam.nparam)
5904 p = num ? shellparam.p[num - 1] : arg0;
5907 /* NB: name has form "VAR=..." */
5909 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
5910 * which should be considered before we check variables. */
5912 unsigned name_len = (strchrnul(name, '=') - name) + 1;
5915 char *str = var_str_list->text;
5916 char *eq = strchr(str, '=');
5917 if (!eq) /* stop at first non-assignment */
5920 if (name_len == (eq - str)
5921 && strncmp(str, name, name_len) == 0) {
5923 /* goto value; - WRONG! */
5924 /* think "A=1 A=2 B=$A" */
5926 var_str_list = var_str_list->next;
5927 } while (var_str_list);
5931 p = lookupvar(name);
5937 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5938 memtodest(p, len, syntax, quotes);
5942 if (subtype == VSPLUS || subtype == VSLENGTH)
5943 STADJUST(-len, expdest);
5948 * Expand a variable, and return a pointer to the next character in the
5952 evalvar(char *p, int flag, struct strlist *var_str_list)
5964 subtype = varflags & VSTYPE;
5965 quoted = varflags & VSQUOTE;
5967 easy = (!quoted || (*var == '@' && shellparam.nparam));
5968 startloc = expdest - (char *)stackblock();
5969 p = strchr(p, '=') + 1;
5972 varlen = varvalue(var, varflags, flag, var_str_list);
5973 if (varflags & VSNUL)
5976 if (subtype == VSPLUS) {
5977 varlen = -1 - varlen;
5981 if (subtype == VSMINUS) {
5985 p, flag | EXP_TILDE |
5986 (quoted ? EXP_QWORD : EXP_WORD),
5996 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5998 if (subevalvar(p, var, /* strloc: */ 0,
5999 subtype, startloc, varflags,
6005 * Remove any recorded regions beyond
6008 removerecordregions(startloc);
6018 if (varlen < 0 && uflag)
6019 varunset(p, var, 0, 0);
6021 if (subtype == VSLENGTH) {
6022 cvtnum(varlen > 0 ? varlen : 0);
6026 if (subtype == VSNORMAL) {
6037 case VSTRIMRIGHTMAX:
6046 * Terminate the string and start recording the pattern
6049 STPUTC('\0', expdest);
6050 patloc = expdest - (char *)stackblock();
6051 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6053 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6056 int amount = expdest - (
6057 (char *)stackblock() + patloc - 1
6059 STADJUST(-amount, expdest);
6061 /* Remove any recorded regions beyond start of variable */
6062 removerecordregions(startloc);
6064 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6068 if (subtype != VSNORMAL) { /* skip to end of alternative */
6074 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6076 argbackq = argbackq->next;
6077 } else if (c == CTLVAR) {
6078 if ((*p++ & VSTYPE) != VSNORMAL)
6080 } else if (c == CTLENDVAR) {
6090 * Break the argument string into pieces based upon IFS and add the
6091 * strings to the argument list. The regions of the string to be
6092 * searched for IFS characters have been stored by recordregion.
6095 ifsbreakup(char *string, struct arglist *arglist)
6097 struct ifsregion *ifsp;
6102 const char *ifs, *realifs;
6107 if (ifslastp != NULL) {
6110 realifs = ifsset() ? ifsval() : defifs;
6113 p = string + ifsp->begoff;
6114 nulonly = ifsp->nulonly;
6115 ifs = nulonly ? nullstr : realifs;
6117 while (p < string + ifsp->endoff) {
6121 if (!strchr(ifs, *p)) {
6126 ifsspc = (strchr(defifs, *p) != NULL);
6127 /* Ignore IFS whitespace at start */
6128 if (q == start && ifsspc) {
6134 sp = stalloc(sizeof(*sp));
6136 *arglist->lastp = sp;
6137 arglist->lastp = &sp->next;
6141 if (p >= string + ifsp->endoff) {
6147 if (strchr(ifs, *p) == NULL ) {
6150 } else if (strchr(defifs, *p) == NULL) {
6165 } while (ifsp != NULL);
6174 sp = stalloc(sizeof(*sp));
6176 *arglist->lastp = sp;
6177 arglist->lastp = &sp->next;
6183 struct ifsregion *p;
6188 struct ifsregion *ifsp;
6194 ifsfirst.next = NULL;
6199 * Add a file name to the list.
6202 addfname(const char *name)
6206 sp = stalloc(sizeof(*sp));
6207 sp->text = ststrdup(name);
6209 exparg.lastp = &sp->next;
6212 static char *expdir;
6215 * Do metacharacter (i.e. *, ?, [...]) expansion.
6218 expmeta(char *enddir, char *name)
6233 for (p = name; *p; p++) {
6234 if (*p == '*' || *p == '?')
6236 else if (*p == '[') {
6243 if (*q == '/' || *q == '\0')
6250 } else if (*p == '\\')
6252 else if (*p == '/') {
6259 if (metaflag == 0) { /* we've reached the end of the file name */
6260 if (enddir != expdir)
6268 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6279 } while (p < start);
6281 if (enddir == expdir) {
6283 } else if (enddir == expdir + 1 && *expdir == '/') {
6292 if (enddir != expdir)
6294 if (*endname == 0) {
6306 while (!intpending && (dp = readdir(dirp)) != NULL) {
6307 if (dp->d_name[0] == '.' && ! matchdot)
6309 if (pmatch(start, dp->d_name)) {
6311 strcpy(enddir, dp->d_name);
6314 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6317 expmeta(p, endname);
6326 static struct strlist *
6327 msort(struct strlist *list, int len)
6329 struct strlist *p, *q = NULL;
6330 struct strlist **lpp;
6338 for (n = half; --n >= 0; ) {
6342 q->next = NULL; /* terminate first half of list */
6343 q = msort(list, half); /* sort first half of list */
6344 p = msort(p, len - half); /* sort second half */
6347 #if ENABLE_LOCALE_SUPPORT
6348 if (strcoll(p->text, q->text) < 0)
6350 if (strcmp(p->text, q->text) < 0)
6374 * Sort the results of file name expansion. It calculates the number of
6375 * strings to sort and then calls msort (short for merge sort) to do the
6378 static struct strlist *
6379 expsort(struct strlist *str)
6385 for (sp = str; sp; sp = sp->next)
6387 return msort(str, len);
6391 expandmeta(struct strlist *str, int flag)
6393 static const char metachars[] ALIGN1 = {
6396 /* TODO - EXP_REDIR */
6399 struct strlist **savelastp;
6405 if (!strpbrk(str->text, metachars))
6407 savelastp = exparg.lastp;
6410 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6412 int i = strlen(str->text);
6413 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6421 if (exparg.lastp == savelastp) {
6426 *exparg.lastp = str;
6427 rmescapes(str->text);
6428 exparg.lastp = &str->next;
6430 *exparg.lastp = NULL;
6431 *savelastp = sp = expsort(*savelastp);
6432 while (sp->next != NULL)
6434 exparg.lastp = &sp->next;
6441 * Perform variable substitution and command substitution on an argument,
6442 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6443 * perform splitting and file name expansion. When arglist is NULL, perform
6444 * here document expansion.
6447 expandarg(union node *arg, struct arglist *arglist, int flag)
6452 argbackq = arg->narg.backquote;
6453 STARTSTACKSTR(expdest);
6454 ifsfirst.next = NULL;
6456 argstr(arg->narg.text, flag,
6457 /* var_str_list: */ arglist ? arglist->list : NULL);
6458 p = _STPUTC('\0', expdest);
6460 if (arglist == NULL) {
6461 return; /* here document expanded */
6463 p = grabstackstr(p);
6464 exparg.lastp = &exparg.list;
6468 if (flag & EXP_FULL) {
6469 ifsbreakup(p, &exparg);
6470 *exparg.lastp = NULL;
6471 exparg.lastp = &exparg.list;
6472 expandmeta(exparg.list, flag);
6474 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6476 sp = stalloc(sizeof(*sp));
6479 exparg.lastp = &sp->next;
6483 *exparg.lastp = NULL;
6485 *arglist->lastp = exparg.list;
6486 arglist->lastp = exparg.lastp;
6491 * Expand shell variables and backquotes inside a here document.
6494 expandhere(union node *arg, int fd)
6497 expandarg(arg, (struct arglist *)NULL, 0);
6498 full_write(fd, stackblock(), expdest - (char *)stackblock());
6502 * Returns true if the pattern matches the string.
6505 patmatch(char *pattern, const char *string)
6507 return pmatch(preglob(pattern, 0, 0), string);
6511 * See if a pattern matches in a case statement.
6514 casematch(union node *pattern, char *val)
6516 struct stackmark smark;
6519 setstackmark(&smark);
6520 argbackq = pattern->narg.backquote;
6521 STARTSTACKSTR(expdest);
6523 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6524 /* var_str_list: */ NULL);
6525 STACKSTRNUL(expdest);
6526 result = patmatch(stackblock(), val);
6527 popstackmark(&smark);
6532 /* ============ find_command */
6536 int (*builtin)(int, char **);
6537 /* unsigned flags; */
6539 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
6540 /* "regular" builtins always take precedence over commands,
6541 * regardless of PATH=....%builtin... position */
6542 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
6543 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
6549 const struct builtincmd *cmd;
6550 struct funcnode *func;
6553 /* values of cmdtype */
6554 #define CMDUNKNOWN -1 /* no entry in table for command */
6555 #define CMDNORMAL 0 /* command is an executable program */
6556 #define CMDFUNCTION 1 /* command is a shell function */
6557 #define CMDBUILTIN 2 /* command is a shell builtin */
6559 /* action to find_command() */
6560 #define DO_ERR 0x01 /* prints errors */
6561 #define DO_ABS 0x02 /* checks absolute paths */
6562 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6563 #define DO_ALTPATH 0x08 /* using alternate path */
6564 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6566 static void find_command(char *, struct cmdentry *, int, const char *);
6569 /* ============ Hashing commands */
6572 * When commands are first encountered, they are entered in a hash table.
6573 * This ensures that a full path search will not have to be done for them
6574 * on each invocation.
6576 * We should investigate converting to a linear search, even though that
6577 * would make the command name "hash" a misnomer.
6580 #define ARB 1 /* actual size determined at run time */
6583 struct tblentry *next; /* next entry in hash chain */
6584 union param param; /* definition of builtin function */
6585 short cmdtype; /* index identifying command */
6586 char rehash; /* if set, cd done since entry created */
6587 char cmdname[ARB]; /* name of command */
6590 static struct tblentry **cmdtable;
6591 #define INIT_G_cmdtable() do { \
6592 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
6595 static int builtinloc = -1; /* index in path of %builtin, or -1 */
6599 tryexec(char *cmd, char **argv, char **envp)
6603 #if ENABLE_FEATURE_SH_STANDALONE
6604 if (strchr(cmd, '/') == NULL) {
6605 int a = find_applet_by_name(cmd);
6607 if (APPLET_IS_NOEXEC(a))
6608 run_applet_no_and_exit(a, argv);
6609 /* re-exec ourselves with the new arguments */
6610 execve(bb_busybox_exec_path, argv, envp);
6611 /* If they called chroot or otherwise made the binary no longer
6612 * executable, fall through */
6620 execve(cmd, argv, envp);
6621 } while (errno == EINTR);
6623 execve(cmd, argv, envp);
6627 } else if (errno == ENOEXEC) {
6631 for (ap = argv; *ap; ap++)
6633 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6635 ap[0] = cmd = (char *)DEFAULT_SHELL;
6638 while ((*ap++ = *argv++))
6646 * Exec a program. Never returns. If you change this routine, you may
6647 * have to change the find_command routine as well.
6649 #define environment() listvars(VEXPORT, VUNSET, 0)
6650 static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6652 shellexec(char **argv, const char *path, int idx)
6660 envp = environment();
6661 if (strchr(argv[0], '/')
6662 #if ENABLE_FEATURE_SH_STANDALONE
6663 || find_applet_by_name(argv[0]) >= 0
6666 tryexec(argv[0], argv, envp);
6670 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6671 if (--idx < 0 && pathopt == NULL) {
6672 tryexec(cmdname, argv, envp);
6673 if (errno != ENOENT && errno != ENOTDIR)
6680 /* Map to POSIX errors */
6692 exitstatus = exerrno;
6693 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6694 argv[0], e, suppressint ));
6695 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6700 printentry(struct tblentry *cmdp)
6706 idx = cmdp->param.index;
6709 name = padvance(&path, cmdp->cmdname);
6711 } while (--idx >= 0);
6712 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6716 * Clear out command entries. The argument specifies the first entry in
6717 * PATH which has changed.
6720 clearcmdentry(int firstchange)
6722 struct tblentry **tblp;
6723 struct tblentry **pp;
6724 struct tblentry *cmdp;
6727 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6729 while ((cmdp = *pp) != NULL) {
6730 if ((cmdp->cmdtype == CMDNORMAL &&
6731 cmdp->param.index >= firstchange)
6732 || (cmdp->cmdtype == CMDBUILTIN &&
6733 builtinloc >= firstchange)
6746 * Locate a command in the command hash table. If "add" is nonzero,
6747 * add the command to the table if it is not already present. The
6748 * variable "lastcmdentry" is set to point to the address of the link
6749 * pointing to the entry, so that delete_cmd_entry can delete the
6752 * Interrupts must be off if called with add != 0.
6754 static struct tblentry **lastcmdentry;
6756 static struct tblentry *
6757 cmdlookup(const char *name, int add)
6759 unsigned int hashval;
6761 struct tblentry *cmdp;
6762 struct tblentry **pp;
6765 hashval = (unsigned char)*p << 4;
6767 hashval += (unsigned char)*p++;
6769 pp = &cmdtable[hashval % CMDTABLESIZE];
6770 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6771 if (strcmp(cmdp->cmdname, name) == 0)
6775 if (add && cmdp == NULL) {
6776 cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
6777 + strlen(name) + 1);
6779 cmdp->cmdtype = CMDUNKNOWN;
6780 strcpy(cmdp->cmdname, name);
6787 * Delete the command entry returned on the last lookup.
6790 delete_cmd_entry(void)
6792 struct tblentry *cmdp;
6795 cmdp = *lastcmdentry;
6796 *lastcmdentry = cmdp->next;
6797 if (cmdp->cmdtype == CMDFUNCTION)
6798 freefunc(cmdp->param.func);
6804 * Add a new command entry, replacing any existing command entry for
6805 * the same name - except special builtins.
6808 addcmdentry(char *name, struct cmdentry *entry)
6810 struct tblentry *cmdp;
6812 cmdp = cmdlookup(name, 1);
6813 if (cmdp->cmdtype == CMDFUNCTION) {
6814 freefunc(cmdp->param.func);
6816 cmdp->cmdtype = entry->cmdtype;
6817 cmdp->param = entry->u;
6822 hashcmd(int argc, char **argv)
6824 struct tblentry **pp;
6825 struct tblentry *cmdp;
6827 struct cmdentry entry;
6830 if (nextopt("r") != '\0') {
6835 if (*argptr == NULL) {
6836 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6837 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6838 if (cmdp->cmdtype == CMDNORMAL)
6846 while ((name = *argptr) != NULL) {
6847 cmdp = cmdlookup(name, 0);
6849 && (cmdp->cmdtype == CMDNORMAL
6850 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
6854 find_command(name, &entry, DO_ERR, pathval());
6855 if (entry.cmdtype == CMDUNKNOWN)
6863 * Called when a cd is done. Marks all commands so the next time they
6864 * are executed they will be rehashed.
6869 struct tblentry **pp;
6870 struct tblentry *cmdp;
6872 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6873 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6874 if (cmdp->cmdtype == CMDNORMAL
6875 || (cmdp->cmdtype == CMDBUILTIN
6876 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
6886 * Fix command hash table when PATH changed.
6887 * Called before PATH is changed. The argument is the new value of PATH;
6888 * pathval() still returns the old value at this point.
6889 * Called with interrupts off.
6892 changepath(const char *new)
6900 firstchange = 9999; /* assume no change */
6906 if ((*old == '\0' && *new == ':')
6907 || (*old == ':' && *new == '\0'))
6909 old = new; /* ignore subsequent differences */
6913 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6919 if (builtinloc < 0 && idx_bltin >= 0)
6920 builtinloc = idx_bltin; /* zap builtins */
6921 if (builtinloc >= 0 && idx_bltin < 0)
6923 clearcmdentry(firstchange);
6924 builtinloc = idx_bltin;
6939 #define TENDBQUOTE 12
6957 /* first char is indicating which tokens mark the end of a list */
6958 static const char *const tokname_array[] = {
6972 #define KWDOFFSET 13
6973 /* the following are keywords */
6995 static char buf[16];
6998 //if (tok < TSEMI) return tokname_array[tok] + 1;
6999 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7004 sprintf(buf + (tok >= TSEMI), "%s%c",
7005 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7009 /* Wrapper around strcmp for qsort/bsearch/... */
7011 pstrcmp(const void *a, const void *b)
7013 return strcmp((char*) a, (*(char**) b) + 1);
7016 static const char *const *
7017 findkwd(const char *s)
7019 return bsearch(s, tokname_array + KWDOFFSET,
7020 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7021 sizeof(tokname_array[0]), pstrcmp);
7025 * Locate and print what a word is...
7028 describe_command(char *command, int describe_command_verbose)
7030 struct cmdentry entry;
7031 struct tblentry *cmdp;
7032 #if ENABLE_ASH_ALIAS
7033 const struct alias *ap;
7035 const char *path = pathval();
7037 if (describe_command_verbose) {
7041 /* First look at the keywords */
7042 if (findkwd(command)) {
7043 out1str(describe_command_verbose ? " is a shell keyword" : command);
7047 #if ENABLE_ASH_ALIAS
7048 /* Then look at the aliases */
7049 ap = lookupalias(command, 0);
7051 if (!describe_command_verbose) {
7056 out1fmt(" is an alias for %s", ap->val);
7060 /* Then check if it is a tracked alias */
7061 cmdp = cmdlookup(command, 0);
7063 entry.cmdtype = cmdp->cmdtype;
7064 entry.u = cmdp->param;
7066 /* Finally use brute force */
7067 find_command(command, &entry, DO_ABS, path);
7070 switch (entry.cmdtype) {
7072 int j = entry.u.index;
7078 p = padvance(&path, command);
7082 if (describe_command_verbose) {
7084 (cmdp ? " a tracked alias for" : nullstr), p
7093 if (describe_command_verbose) {
7094 out1str(" is a shell function");
7101 if (describe_command_verbose) {
7102 out1fmt(" is a %sshell builtin",
7103 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7104 "special " : nullstr
7112 if (describe_command_verbose) {
7113 out1str(": not found\n");
7118 outstr("\n", stdout);
7123 typecmd(int argc, char **argv)
7129 /* type -p ... ? (we don't bother checking for 'p') */
7130 if (argv[1] && argv[1][0] == '-') {
7135 err |= describe_command(argv[i++], verbose);
7140 #if ENABLE_ASH_CMDCMD
7142 commandcmd(int argc, char **argv)
7150 while ((c = nextopt("pvV")) != '\0')
7152 verify |= VERIFY_VERBOSE;
7154 verify |= VERIFY_BRIEF;
7160 return describe_command(*argptr, verify - VERIFY_BRIEF);
7167 /* ============ eval.c */
7169 static int funcblocksize; /* size of structures in function */
7170 static int funcstringsize; /* size of strings in node */
7171 static void *funcblock; /* block to allocate function from */
7172 static char *funcstring; /* block to allocate strings from */
7174 /* flags in argument to evaltree */
7175 #define EV_EXIT 01 /* exit after evaluating tree */
7176 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7177 #define EV_BACKCMD 04 /* command executing within back quotes */
7179 static const short nodesize[26] = {
7180 SHELL_ALIGN(sizeof(struct ncmd)),
7181 SHELL_ALIGN(sizeof(struct npipe)),
7182 SHELL_ALIGN(sizeof(struct nredir)),
7183 SHELL_ALIGN(sizeof(struct nredir)),
7184 SHELL_ALIGN(sizeof(struct nredir)),
7185 SHELL_ALIGN(sizeof(struct nbinary)),
7186 SHELL_ALIGN(sizeof(struct nbinary)),
7187 SHELL_ALIGN(sizeof(struct nbinary)),
7188 SHELL_ALIGN(sizeof(struct nif)),
7189 SHELL_ALIGN(sizeof(struct nbinary)),
7190 SHELL_ALIGN(sizeof(struct nbinary)),
7191 SHELL_ALIGN(sizeof(struct nfor)),
7192 SHELL_ALIGN(sizeof(struct ncase)),
7193 SHELL_ALIGN(sizeof(struct nclist)),
7194 SHELL_ALIGN(sizeof(struct narg)),
7195 SHELL_ALIGN(sizeof(struct narg)),
7196 SHELL_ALIGN(sizeof(struct nfile)),
7197 SHELL_ALIGN(sizeof(struct nfile)),
7198 SHELL_ALIGN(sizeof(struct nfile)),
7199 SHELL_ALIGN(sizeof(struct nfile)),
7200 SHELL_ALIGN(sizeof(struct nfile)),
7201 SHELL_ALIGN(sizeof(struct ndup)),
7202 SHELL_ALIGN(sizeof(struct ndup)),
7203 SHELL_ALIGN(sizeof(struct nhere)),
7204 SHELL_ALIGN(sizeof(struct nhere)),
7205 SHELL_ALIGN(sizeof(struct nnot)),
7208 static void calcsize(union node *n);
7211 sizenodelist(struct nodelist *lp)
7214 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7221 calcsize(union node *n)
7225 funcblocksize += nodesize[n->type];
7228 calcsize(n->ncmd.redirect);
7229 calcsize(n->ncmd.args);
7230 calcsize(n->ncmd.assign);
7233 sizenodelist(n->npipe.cmdlist);
7238 calcsize(n->nredir.redirect);
7239 calcsize(n->nredir.n);
7246 calcsize(n->nbinary.ch2);
7247 calcsize(n->nbinary.ch1);
7250 calcsize(n->nif.elsepart);
7251 calcsize(n->nif.ifpart);
7252 calcsize(n->nif.test);
7255 funcstringsize += strlen(n->nfor.var) + 1;
7256 calcsize(n->nfor.body);
7257 calcsize(n->nfor.args);
7260 calcsize(n->ncase.cases);
7261 calcsize(n->ncase.expr);
7264 calcsize(n->nclist.body);
7265 calcsize(n->nclist.pattern);
7266 calcsize(n->nclist.next);
7270 sizenodelist(n->narg.backquote);
7271 funcstringsize += strlen(n->narg.text) + 1;
7272 calcsize(n->narg.next);
7279 calcsize(n->nfile.fname);
7280 calcsize(n->nfile.next);
7284 calcsize(n->ndup.vname);
7285 calcsize(n->ndup.next);
7289 calcsize(n->nhere.doc);
7290 calcsize(n->nhere.next);
7293 calcsize(n->nnot.com);
7299 nodeckstrdup(char *s)
7301 char *rtn = funcstring;
7303 strcpy(funcstring, s);
7304 funcstring += strlen(s) + 1;
7308 static union node *copynode(union node *);
7310 static struct nodelist *
7311 copynodelist(struct nodelist *lp)
7313 struct nodelist *start;
7314 struct nodelist **lpp;
7319 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7320 (*lpp)->n = copynode(lp->n);
7322 lpp = &(*lpp)->next;
7329 copynode(union node *n)
7336 funcblock = (char *) funcblock + nodesize[n->type];
7340 new->ncmd.redirect = copynode(n->ncmd.redirect);
7341 new->ncmd.args = copynode(n->ncmd.args);
7342 new->ncmd.assign = copynode(n->ncmd.assign);
7345 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7346 new->npipe.backgnd = n->npipe.backgnd;
7351 new->nredir.redirect = copynode(n->nredir.redirect);
7352 new->nredir.n = copynode(n->nredir.n);
7359 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7360 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7363 new->nif.elsepart = copynode(n->nif.elsepart);
7364 new->nif.ifpart = copynode(n->nif.ifpart);
7365 new->nif.test = copynode(n->nif.test);
7368 new->nfor.var = nodeckstrdup(n->nfor.var);
7369 new->nfor.body = copynode(n->nfor.body);
7370 new->nfor.args = copynode(n->nfor.args);
7373 new->ncase.cases = copynode(n->ncase.cases);
7374 new->ncase.expr = copynode(n->ncase.expr);
7377 new->nclist.body = copynode(n->nclist.body);
7378 new->nclist.pattern = copynode(n->nclist.pattern);
7379 new->nclist.next = copynode(n->nclist.next);
7383 new->narg.backquote = copynodelist(n->narg.backquote);
7384 new->narg.text = nodeckstrdup(n->narg.text);
7385 new->narg.next = copynode(n->narg.next);
7392 new->nfile.fname = copynode(n->nfile.fname);
7393 new->nfile.fd = n->nfile.fd;
7394 new->nfile.next = copynode(n->nfile.next);
7398 new->ndup.vname = copynode(n->ndup.vname);
7399 new->ndup.dupfd = n->ndup.dupfd;
7400 new->ndup.fd = n->ndup.fd;
7401 new->ndup.next = copynode(n->ndup.next);
7405 new->nhere.doc = copynode(n->nhere.doc);
7406 new->nhere.fd = n->nhere.fd;
7407 new->nhere.next = copynode(n->nhere.next);
7410 new->nnot.com = copynode(n->nnot.com);
7413 new->type = n->type;
7418 * Make a copy of a parse tree.
7420 static struct funcnode *
7421 copyfunc(union node *n)
7426 funcblocksize = offsetof(struct funcnode, n);
7429 blocksize = funcblocksize;
7430 f = ckmalloc(blocksize + funcstringsize);
7431 funcblock = (char *) f + offsetof(struct funcnode, n);
7432 funcstring = (char *) f + blocksize;
7439 * Define a shell function.
7442 defun(char *name, union node *func)
7444 struct cmdentry entry;
7447 entry.cmdtype = CMDFUNCTION;
7448 entry.u.func = copyfunc(func);
7449 addcmdentry(name, &entry);
7453 static int evalskip; /* set if we are skipping commands */
7454 /* reasons for skipping commands (see comment on breakcmd routine) */
7455 #define SKIPBREAK (1 << 0)
7456 #define SKIPCONT (1 << 1)
7457 #define SKIPFUNC (1 << 2)
7458 #define SKIPFILE (1 << 3)
7459 #define SKIPEVAL (1 << 4)
7460 static int skipcount; /* number of levels to skip */
7461 static int funcnest; /* depth of function calls */
7463 /* forward decl way out to parsing code - dotrap needs it */
7464 static int evalstring(char *s, int mask);
7467 * Called to execute a trap. Perhaps we should avoid entering new trap
7468 * handlers while we are executing a trap handler.
7479 savestatus = exitstatus;
7483 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7491 skip = evalstring(p, SKIPEVAL);
7492 exitstatus = savestatus;
7500 /* forward declarations - evaluation is fairly recursive business... */
7501 static void evalloop(union node *, int);
7502 static void evalfor(union node *, int);
7503 static void evalcase(union node *, int);
7504 static void evalsubshell(union node *, int);
7505 static void expredir(union node *);
7506 static void evalpipe(union node *, int);
7507 static void evalcommand(union node *, int);
7508 static int evalbltin(const struct builtincmd *, int, char **);
7509 static void prehash(union node *);
7512 * Evaluate a parse tree. The value is left in the global variable
7516 evaltree(union node *n, int flags)
7519 void (*evalfn)(union node *, int);
7523 TRACE(("evaltree(NULL) called\n"));
7526 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
7527 getpid(), n, n->type, flags));
7531 out1fmt("Node type = %d\n", n->type);
7536 evaltree(n->nnot.com, EV_TESTED);
7537 status = !exitstatus;
7540 expredir(n->nredir.redirect);
7541 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7543 evaltree(n->nredir.n, flags & EV_TESTED);
7544 status = exitstatus;
7549 evalfn = evalcommand;
7551 if (eflag && !(flags & EV_TESTED))
7563 evalfn = evalsubshell;
7575 #error NAND + 1 != NOR
7577 #if NOR + 1 != NSEMI
7578 #error NOR + 1 != NSEMI
7580 isor = n->type - NAND;
7583 (flags | ((isor >> 1) - 1)) & EV_TESTED
7585 if (!exitstatus == isor)
7597 evaltree(n->nif.test, EV_TESTED);
7600 if (exitstatus == 0) {
7603 } else if (n->nif.elsepart) {
7604 n = n->nif.elsepart;
7609 defun(n->narg.text, n->narg.next);
7613 exitstatus = status;
7617 if ((checkexit & exitstatus))
7618 evalskip |= SKIPEVAL;
7619 else if (pendingsig && dotrap())
7622 if (flags & EV_EXIT) {
7624 raise_exception(EXEXIT);
7628 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7631 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7633 static int loopnest; /* current loop nesting level */
7636 evalloop(union node *n, int flags)
7646 evaltree(n->nbinary.ch1, EV_TESTED);
7649 if (evalskip == SKIPCONT && --skipcount <= 0) {
7653 if (evalskip == SKIPBREAK && --skipcount <= 0)
7658 if (n->type != NWHILE)
7662 evaltree(n->nbinary.ch2, flags);
7663 status = exitstatus;
7668 exitstatus = status;
7672 evalfor(union node *n, int flags)
7674 struct arglist arglist;
7677 struct stackmark smark;
7679 setstackmark(&smark);
7680 arglist.lastp = &arglist.list;
7681 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
7682 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
7687 *arglist.lastp = NULL;
7692 for (sp = arglist.list; sp; sp = sp->next) {
7693 setvar(n->nfor.var, sp->text, 0);
7694 evaltree(n->nfor.body, flags);
7696 if (evalskip == SKIPCONT && --skipcount <= 0) {
7700 if (evalskip == SKIPBREAK && --skipcount <= 0)
7707 popstackmark(&smark);
7711 evalcase(union node *n, int flags)
7715 struct arglist arglist;
7716 struct stackmark smark;
7718 setstackmark(&smark);
7719 arglist.lastp = &arglist.list;
7720 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
7722 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7723 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
7724 if (casematch(patp, arglist.list->text)) {
7725 if (evalskip == 0) {
7726 evaltree(cp->nclist.body, flags);
7733 popstackmark(&smark);
7737 * Kick off a subshell to evaluate a tree.
7740 evalsubshell(union node *n, int flags)
7743 int backgnd = (n->type == NBACKGND);
7746 expredir(n->nredir.redirect);
7747 if (!backgnd && flags & EV_EXIT && !trap[0])
7751 if (forkshell(jp, n, backgnd) == 0) {
7755 flags &=~ EV_TESTED;
7757 redirect(n->nredir.redirect, 0);
7758 evaltreenr(n->nredir.n, flags);
7763 status = waitforjob(jp);
7764 exitstatus = status;
7769 * Compute the names of the files in a redirection list.
7771 static void fixredir(union node *, const char *, int);
7773 expredir(union node *n)
7777 for (redir = n; redir; redir = redir->nfile.next) {
7780 memset(&fn, 0, sizeof(fn));
7781 fn.lastp = &fn.list;
7782 switch (redir->type) {
7788 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7789 redir->nfile.expfname = fn.list->text;
7793 if (redir->ndup.vname) {
7794 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
7795 if (fn.list == NULL)
7796 ash_msg_and_raise_error("redir error");
7797 fixredir(redir, fn.list->text, 1);
7805 * Evaluate a pipeline. All the processes in the pipeline are children
7806 * of the process creating the pipeline. (This differs from some versions
7807 * of the shell, which make the last process in a pipeline the parent
7811 evalpipe(union node *n, int flags)
7814 struct nodelist *lp;
7819 TRACE(("evalpipe(0x%lx) called\n", (long)n));
7821 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
7825 jp = makejob(n, pipelen);
7827 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7831 if (pipe(pip) < 0) {
7833 ash_msg_and_raise_error("pipe call failed");
7836 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
7849 evaltreenr(lp->n, flags);
7857 if (n->npipe.backgnd == 0) {
7858 exitstatus = waitforjob(jp);
7859 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
7865 * Controls whether the shell is interactive or not.
7868 setinteractive(int on)
7870 static int is_interactive;
7872 if (++on == is_interactive)
7874 is_interactive = on;
7878 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
7879 if (is_interactive > 1) {
7880 /* Looks like they want an interactive shell */
7881 static smallint did_banner;
7886 "%s built-in shell (ash)\n"
7887 "Enter 'help' for a list of built-in commands."
7896 #if ENABLE_FEATURE_EDITING_VI
7897 #define setvimode(on) do { \
7898 if (on) line_input_state->flags |= VI_MODE; \
7899 else line_input_state->flags &= ~VI_MODE; \
7902 #define setvimode(on) viflag = 0 /* forcibly keep the option off */
7911 setinteractive(iflag);
7916 static struct localvar *localvars;
7919 * Called after a function returns.
7920 * Interrupts must be off.
7925 struct localvar *lvp;
7928 while ((lvp = localvars) != NULL) {
7929 localvars = lvp->next;
7931 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7932 if (vp == NULL) { /* $- saved */
7933 memcpy(optlist, lvp->text, sizeof(optlist));
7934 free((char*)lvp->text);
7936 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7940 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7941 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7942 free((char*)vp->text);
7943 vp->flags = lvp->flags;
7944 vp->text = lvp->text;
7951 evalfun(struct funcnode *func, int argc, char **argv, int flags)
7953 volatile struct shparam saveparam;
7954 struct localvar *volatile savelocalvars;
7955 struct jmploc *volatile savehandler;
7956 struct jmploc jmploc;
7959 saveparam = shellparam;
7960 savelocalvars = localvars;
7961 e = setjmp(jmploc.loc);
7966 savehandler = exception_handler;
7967 exception_handler = &jmploc;
7969 shellparam.malloced = 0;
7973 shellparam.nparam = argc - 1;
7974 shellparam.p = argv + 1;
7975 #if ENABLE_ASH_GETOPTS
7976 shellparam.optind = 1;
7977 shellparam.optoff = -1;
7979 evaltree(&func->n, flags & EV_TESTED);
7985 localvars = savelocalvars;
7986 freeparam(&shellparam);
7987 shellparam = saveparam;
7988 exception_handler = savehandler;
7990 evalskip &= ~SKIPFUNC;
7994 #if ENABLE_ASH_CMDCMD
7996 parse_command_args(char **argv, const char **path)
8009 if (c == '-' && !*cp) {
8016 *path = bb_default_path;
8019 /* run 'typecmd' for other options */
8030 * Make a variable a local variable. When a variable is made local, it's
8031 * value and flags are saved in a localvar structure. The saved values
8032 * will be restored when the shell function returns. We handle the name
8033 * "-" as a special case.
8038 struct localvar *lvp;
8043 lvp = ckmalloc(sizeof(struct localvar));
8044 if (LONE_DASH(name)) {
8046 p = ckmalloc(sizeof(optlist));
8047 lvp->text = memcpy(p, optlist, sizeof(optlist));
8052 vpp = hashvar(name);
8053 vp = *findvar(vpp, name);
8054 eq = strchr(name, '=');
8057 setvareq(name, VSTRFIXED);
8059 setvar(name, NULL, VSTRFIXED);
8060 vp = *vpp; /* the new variable */
8061 lvp->flags = VUNSET;
8063 lvp->text = vp->text;
8064 lvp->flags = vp->flags;
8065 vp->flags |= VSTRFIXED|VTEXTFIXED;
8071 lvp->next = localvars;
8077 * The "local" command.
8080 localcmd(int argc, char **argv)
8085 while ((name = *argv++) != NULL) {
8092 falsecmd(int argc, char **argv)
8098 truecmd(int argc, char **argv)
8104 execcmd(int argc, char **argv)
8107 iflag = 0; /* exit on error */
8110 shellexec(argv + 1, pathval(), 0);
8116 * The return command.
8119 returncmd(int argc, char **argv)
8122 * If called outside a function, do what ksh does;
8123 * skip the rest of the file.
8125 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8126 return argv[1] ? number(argv[1]) : exitstatus;
8129 /* Forward declarations for builtintab[] */
8130 static int breakcmd(int, char **);
8131 static int dotcmd(int, char **);
8132 static int evalcmd(int, char **);
8133 #if ENABLE_ASH_BUILTIN_ECHO
8134 static int echocmd(int, char **);
8136 #if ENABLE_ASH_BUILTIN_TEST
8137 static int testcmd(int, char **);
8139 static int exitcmd(int, char **);
8140 static int exportcmd(int, char **);
8141 #if ENABLE_ASH_GETOPTS
8142 static int getoptscmd(int, char **);
8144 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8145 static int helpcmd(int argc, char **argv);
8147 #if ENABLE_ASH_MATH_SUPPORT
8148 static int letcmd(int, char **);
8150 static int readcmd(int, char **);
8151 static int setcmd(int, char **);
8152 static int shiftcmd(int, char **);
8153 static int timescmd(int, char **);
8154 static int trapcmd(int, char **);
8155 static int umaskcmd(int, char **);
8156 static int unsetcmd(int, char **);
8157 static int ulimitcmd(int, char **);
8159 #define BUILTIN_NOSPEC "0"
8160 #define BUILTIN_SPECIAL "1"
8161 #define BUILTIN_REGULAR "2"
8162 #define BUILTIN_SPEC_REG "3"
8163 #define BUILTIN_ASSIGN "4"
8164 #define BUILTIN_SPEC_ASSG "5"
8165 #define BUILTIN_REG_ASSG "6"
8166 #define BUILTIN_SPEC_REG_ASSG "7"
8168 /* make sure to keep these in proper order since it is searched via bsearch() */
8169 static const struct builtincmd builtintab[] = {
8170 { BUILTIN_SPEC_REG ".", dotcmd },
8171 { BUILTIN_SPEC_REG ":", truecmd },
8172 #if ENABLE_ASH_BUILTIN_TEST
8173 { BUILTIN_REGULAR "[", testcmd },
8174 { BUILTIN_REGULAR "[[", testcmd },
8176 #if ENABLE_ASH_ALIAS
8177 { BUILTIN_REG_ASSG "alias", aliascmd },
8180 { BUILTIN_REGULAR "bg", fg_bgcmd },
8182 { BUILTIN_SPEC_REG "break", breakcmd },
8183 { BUILTIN_REGULAR "cd", cdcmd },
8184 { BUILTIN_NOSPEC "chdir", cdcmd },
8185 #if ENABLE_ASH_CMDCMD
8186 { BUILTIN_REGULAR "command", commandcmd },
8188 { BUILTIN_SPEC_REG "continue", breakcmd },
8189 #if ENABLE_ASH_BUILTIN_ECHO
8190 { BUILTIN_REGULAR "echo", echocmd },
8192 { BUILTIN_SPEC_REG "eval", evalcmd },
8193 { BUILTIN_SPEC_REG "exec", execcmd },
8194 { BUILTIN_SPEC_REG "exit", exitcmd },
8195 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8196 { BUILTIN_REGULAR "false", falsecmd },
8198 { BUILTIN_REGULAR "fg", fg_bgcmd },
8200 #if ENABLE_ASH_GETOPTS
8201 { BUILTIN_REGULAR "getopts", getoptscmd },
8203 { BUILTIN_NOSPEC "hash", hashcmd },
8204 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8205 { BUILTIN_NOSPEC "help", helpcmd },
8208 { BUILTIN_REGULAR "jobs", jobscmd },
8209 { BUILTIN_REGULAR "kill", killcmd },
8211 #if ENABLE_ASH_MATH_SUPPORT
8212 { BUILTIN_NOSPEC "let", letcmd },
8214 { BUILTIN_ASSIGN "local", localcmd },
8215 { BUILTIN_NOSPEC "pwd", pwdcmd },
8216 { BUILTIN_REGULAR "read", readcmd },
8217 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8218 { BUILTIN_SPEC_REG "return", returncmd },
8219 { BUILTIN_SPEC_REG "set", setcmd },
8220 { BUILTIN_SPEC_REG "shift", shiftcmd },
8221 { BUILTIN_SPEC_REG "source", dotcmd },
8222 #if ENABLE_ASH_BUILTIN_TEST
8223 { BUILTIN_REGULAR "test", testcmd },
8225 { BUILTIN_SPEC_REG "times", timescmd },
8226 { BUILTIN_SPEC_REG "trap", trapcmd },
8227 { BUILTIN_REGULAR "true", truecmd },
8228 { BUILTIN_NOSPEC "type", typecmd },
8229 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8230 { BUILTIN_REGULAR "umask", umaskcmd },
8231 #if ENABLE_ASH_ALIAS
8232 { BUILTIN_REGULAR "unalias", unaliascmd },
8234 { BUILTIN_SPEC_REG "unset", unsetcmd },
8235 { BUILTIN_REGULAR "wait", waitcmd },
8239 #define COMMANDCMD (builtintab + 5 + \
8240 2 * ENABLE_ASH_BUILTIN_TEST + \
8241 ENABLE_ASH_ALIAS + \
8242 ENABLE_ASH_JOB_CONTROL)
8243 #define EXECCMD (builtintab + 7 + \
8244 2 * ENABLE_ASH_BUILTIN_TEST + \
8245 ENABLE_ASH_ALIAS + \
8246 ENABLE_ASH_JOB_CONTROL + \
8247 ENABLE_ASH_CMDCMD + \
8248 ENABLE_ASH_BUILTIN_ECHO)
8251 * Search the table of builtin commands.
8253 static struct builtincmd *
8254 find_builtin(const char *name)
8256 struct builtincmd *bp;
8259 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8266 * Execute a simple command.
8268 static int back_exitstatus; /* exit status of backquoted command */
8270 isassignment(const char *p)
8272 const char *q = endofname(p);
8278 bltincmd(int argc, char **argv)
8280 /* Preserve exitstatus of a previous possible redirection
8281 * as POSIX mandates */
8282 return back_exitstatus;
8285 evalcommand(union node *cmd, int flags)
8287 static const struct builtincmd null_bltin = {
8288 "\0\0", bltincmd /* why three NULs? */
8290 struct stackmark smark;
8292 struct arglist arglist;
8293 struct arglist varlist;
8296 const struct strlist *sp;
8297 struct cmdentry cmdentry;
8305 struct builtincmd *bcmd;
8306 int pseudovarflag = 0;
8308 /* First expand the arguments. */
8309 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8310 setstackmark(&smark);
8311 back_exitstatus = 0;
8313 cmdentry.cmdtype = CMDBUILTIN;
8314 cmdentry.u.cmd = &null_bltin;
8315 varlist.lastp = &varlist.list;
8316 *varlist.lastp = NULL;
8317 arglist.lastp = &arglist.list;
8318 *arglist.lastp = NULL;
8321 if (cmd->ncmd.args) {
8322 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8323 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8326 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8327 struct strlist **spp;
8329 spp = arglist.lastp;
8330 if (pseudovarflag && isassignment(argp->narg.text))
8331 expandarg(argp, &arglist, EXP_VARTILDE);
8333 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8335 for (sp = *spp; sp; sp = sp->next)
8339 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8340 for (sp = arglist.list; sp; sp = sp->next) {
8341 TRACE(("evalcommand arg: %s\n", sp->text));
8342 *nargv++ = sp->text;
8347 if (iflag && funcnest == 0 && argc > 0)
8348 lastarg = nargv[-1];
8351 expredir(cmd->ncmd.redirect);
8352 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8355 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8356 struct strlist **spp;
8359 spp = varlist.lastp;
8360 expandarg(argp, &varlist, EXP_VARTILDE);
8363 * Modify the command lookup path, if a PATH= assignment
8367 if (varequal(p, path))
8371 /* Print the command if xflag is set. */
8374 const char *p = " %s";
8377 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8380 for (n = 0; n < 2; n++) {
8382 fdprintf(preverrout_fd, p, sp->text);
8390 safe_write(preverrout_fd, "\n", 1);
8396 /* Now locate the command. */
8398 const char *oldpath;
8399 int cmd_flag = DO_ERR;
8404 find_command(argv[0], &cmdentry, cmd_flag, path);
8405 if (cmdentry.cmdtype == CMDUNKNOWN) {
8411 /* implement bltin and command here */
8412 if (cmdentry.cmdtype != CMDBUILTIN)
8415 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8416 if (cmdentry.u.cmd == EXECCMD)
8418 #if ENABLE_ASH_CMDCMD
8419 if (cmdentry.u.cmd == COMMANDCMD) {
8421 nargv = parse_command_args(argv, &path);
8424 argc -= nargv - argv;
8426 cmd_flag |= DO_NOFUNC;
8434 /* We have a redirection error. */
8436 raise_exception(EXERROR);
8438 exitstatus = status;
8442 /* Execute the command. */
8443 switch (cmdentry.cmdtype) {
8445 /* Fork off a child process if necessary. */
8446 if (!(flags & EV_EXIT) || trap[0]) {
8448 jp = makejob(cmd, 1);
8449 if (forkshell(jp, cmd, FORK_FG) != 0) {
8450 exitstatus = waitforjob(jp);
8456 listsetvar(varlist.list, VEXPORT|VSTACK);
8457 shellexec(argv, path, cmdentry.u.index);
8461 cmdenviron = varlist.list;
8463 struct strlist *list = cmdenviron;
8465 if (spclbltin > 0 || argc == 0) {
8467 if (cmd_is_exec && argc > 1)
8470 listsetvar(list, i);
8472 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8479 exit_status = 128 + SIGINT;
8481 exit_status = 128 + pendingsig;
8482 exitstatus = exit_status;
8483 if (i == EXINT || spclbltin > 0) {
8485 longjmp(exception_handler->loc, 1);
8492 listsetvar(varlist.list, 0);
8493 if (evalfun(cmdentry.u.func, argc, argv, flags))
8499 popredir(cmd_is_exec);
8501 /* dsl: I think this is intended to be used to support
8502 * '_' in 'vi' command mode during line editing...
8503 * However I implemented that within libedit itself.
8505 setvar("_", lastarg, 0);
8506 popstackmark(&smark);
8510 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8512 char *volatile savecmdname;
8513 struct jmploc *volatile savehandler;
8514 struct jmploc jmploc;
8517 savecmdname = commandname;
8518 i = setjmp(jmploc.loc);
8521 savehandler = exception_handler;
8522 exception_handler = &jmploc;
8523 commandname = argv[0];
8525 optptr = NULL; /* initialize nextopt */
8526 exitstatus = (*cmd->builtin)(argc, argv);
8527 flush_stdout_stderr();
8529 exitstatus |= ferror(stdout);
8531 commandname = savecmdname;
8533 exception_handler = savehandler;
8539 goodname(const char *p)
8541 return !*endofname(p);
8546 * Search for a command. This is called before we fork so that the
8547 * location of the command will be available in the parent as well as
8548 * the child. The check for "goodname" is an overly conservative
8549 * check that the name will not be subject to expansion.
8552 prehash(union node *n)
8554 struct cmdentry entry;
8556 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8557 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
8561 /* ============ Builtin commands
8563 * Builtin commands whose functions are closely tied to evaluation
8564 * are implemented here.
8568 * Handle break and continue commands. Break, continue, and return are
8569 * all handled by setting the evalskip flag. The evaluation routines
8570 * above all check this flag, and if it is set they start skipping
8571 * commands rather than executing them. The variable skipcount is
8572 * the number of loops to break/continue, or the number of function
8573 * levels to return. (The latter is always 1.) It should probably
8574 * be an error to break out of more loops than exist, but it isn't
8575 * in the standard shell so we don't make it one here.
8578 breakcmd(int argc, char **argv)
8580 int n = argc > 1 ? number(argv[1]) : 1;
8583 ash_msg_and_raise_error(illnum, argv[1]);
8587 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
8594 /* ============ input.c
8596 * This implements the input routines used by the parser.
8599 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
8602 INPUT_PUSH_FILE = 1,
8603 INPUT_NOFILE_OK = 2,
8606 static int plinno = 1; /* input line number */
8607 /* number of characters left in input buffer */
8608 static int parsenleft; /* copy of parsefile->nleft */
8609 static int parselleft; /* copy of parsefile->lleft */
8610 /* next character in input buffer */
8611 static char *parsenextc; /* copy of parsefile->nextc */
8613 static int checkkwd;
8614 /* values of checkkwd variable */
8615 #define CHKALIAS 0x1
8622 struct strpush *sp = parsefile->strpush;
8625 #if ENABLE_ASH_ALIAS
8627 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8628 checkkwd |= CHKALIAS;
8630 if (sp->string != sp->ap->val) {
8633 sp->ap->flag &= ~ALIASINUSE;
8634 if (sp->ap->flag & ALIASDEAD) {
8635 unalias(sp->ap->name);
8639 parsenextc = sp->prevstring;
8640 parsenleft = sp->prevnleft;
8641 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8642 parsefile->strpush = sp->prev;
8643 if (sp != &(parsefile->basestrpush))
8652 char *buf = parsefile->buf;
8656 #if ENABLE_FEATURE_EDITING
8657 if (!iflag || parsefile->fd)
8658 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8660 #if ENABLE_FEATURE_TAB_COMPLETION
8661 line_input_state->path_lookup = pathval();
8663 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8665 /* Ctrl+C pressed */
8674 if (nr < 0 && errno == 0) {
8675 /* Ctrl+D pressed */
8680 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8684 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
8685 int flags = fcntl(0, F_GETFL);
8686 if (flags >= 0 && (flags & O_NONBLOCK)) {
8687 flags &= ~O_NONBLOCK;
8688 if (fcntl(0, F_SETFL, flags) >= 0) {
8689 out2str("sh: turning off NDELAY mode\n");
8699 * Refill the input buffer and return the next input character:
8701 * 1) If a string was pushed back on the input, pop it;
8702 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8703 * from a string so we can't refill the buffer, return EOF.
8704 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8705 * 4) Process input up to the next newline, deleting nul characters.
8714 while (parsefile->strpush) {
8715 #if ENABLE_ASH_ALIAS
8716 if (parsenleft == -1 && parsefile->strpush->ap &&
8717 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
8722 if (--parsenleft >= 0)
8723 return signed_char2int(*parsenextc++);
8725 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8727 flush_stdout_stderr();
8734 parselleft = parsenleft = EOF_NLEFT;
8741 /* delete nul characters */
8749 memmove(q, q + 1, more);
8753 parsenleft = q - parsenextc - 1;
8759 parsenleft = q - parsenextc - 1;
8771 out2str(parsenextc);
8776 return signed_char2int(*parsenextc++);
8779 #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
8783 return pgetc_as_macro();
8786 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8787 #define pgetc_macro() pgetc()
8789 #define pgetc_macro() pgetc_as_macro()
8793 * Same as pgetc(), but ignores PEOA.
8795 #if ENABLE_ASH_ALIAS
8803 } while (c == PEOA);
8810 return pgetc_macro();
8815 * Read a line from the script.
8818 pfgets(char *line, int len)
8824 while (--nleft > 0) {
8840 * Undo the last call to pgetc. Only one character may be pushed back.
8841 * PEOF may be pushed back.
8851 * Push a string back onto the input at this current parsefile level.
8852 * We handle aliases this way.
8855 pushstring(char *s, void *ap)
8862 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8863 if (parsefile->strpush) {
8864 sp = ckmalloc(sizeof(struct strpush));
8865 sp->prev = parsefile->strpush;
8866 parsefile->strpush = sp;
8868 sp = parsefile->strpush = &(parsefile->basestrpush);
8869 sp->prevstring = parsenextc;
8870 sp->prevnleft = parsenleft;
8871 #if ENABLE_ASH_ALIAS
8872 sp->ap = (struct alias *)ap;
8874 ((struct alias *)ap)->flag |= ALIASINUSE;
8884 * To handle the "." command, a stack of input files is used. Pushfile
8885 * adds a new entry to the stack and popfile restores the previous level.
8890 struct parsefile *pf;
8892 parsefile->nleft = parsenleft;
8893 parsefile->lleft = parselleft;
8894 parsefile->nextc = parsenextc;
8895 parsefile->linno = plinno;
8896 pf = ckmalloc(sizeof(*pf));
8897 pf->prev = parsefile;
8900 pf->basestrpush.prev = NULL;
8907 struct parsefile *pf = parsefile;
8915 parsefile = pf->prev;
8917 parsenleft = parsefile->nleft;
8918 parselleft = parsefile->lleft;
8919 parsenextc = parsefile->nextc;
8920 plinno = parsefile->linno;
8925 * Return to top level.
8930 while (parsefile != &basepf)
8935 * Close the file(s) that the shell is reading commands from. Called
8936 * after a fork is done.
8942 if (parsefile->fd > 0) {
8943 close(parsefile->fd);
8949 * Like setinputfile, but takes an open file descriptor. Call this with
8953 setinputfd(int fd, int push)
8955 close_on_exec_on(fd);
8961 if (parsefile->buf == NULL)
8962 parsefile->buf = ckmalloc(IBUFSIZ);
8963 parselleft = parsenleft = 0;
8968 * Set the input to take input from a file. If push is set, push the
8969 * old input onto the stack first.
8972 setinputfile(const char *fname, int flags)
8978 fd = open(fname, O_RDONLY);
8980 if (flags & INPUT_NOFILE_OK)
8982 ash_msg_and_raise_error("can't open %s", fname);
8985 fd2 = copyfd(fd, 10);
8988 ash_msg_and_raise_error("out of file descriptors");
8991 setinputfd(fd, flags & INPUT_PUSH_FILE);
8998 * Like setinputfile, but takes input from a string.
9001 setinputstring(char *string)
9005 parsenextc = string;
9006 parsenleft = strlen(string);
9007 parsefile->buf = NULL;
9013 /* ============ mail.c
9015 * Routines to check for mail.
9020 #define MAXMBOXES 10
9022 /* times of mailboxes */
9023 static time_t mailtime[MAXMBOXES];
9024 /* Set if MAIL or MAILPATH is changed. */
9025 static smallint mail_var_path_changed;
9028 * Print appropriate message(s) if mail has arrived.
9029 * If mail_var_path_changed is set,
9030 * then the value of MAIL has mail_var_path_changed,
9031 * so we just update the values.
9040 struct stackmark smark;
9043 setstackmark(&smark);
9044 mpath = mpathset() ? mpathval() : mailval();
9045 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9046 p = padvance(&mpath, nullstr);
9051 for (q = p; *q; q++);
9056 q[-1] = '\0'; /* delete trailing '/' */
9057 if (stat(p, &statb) < 0) {
9061 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9064 pathopt ? pathopt : "you have mail"
9067 *mtp = statb.st_mtime;
9069 mail_var_path_changed = 0;
9070 popstackmark(&smark);
9074 changemail(const char *val)
9076 mail_var_path_changed = 1;
9079 #endif /* ASH_MAIL */
9082 /* ============ ??? */
9085 * Set the shell parameters.
9088 setparam(char **argv)
9094 for (nparam = 0; argv[nparam]; nparam++);
9095 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9097 *ap++ = ckstrdup(*argv++);
9100 freeparam(&shellparam);
9101 shellparam.malloced = 1;
9102 shellparam.nparam = nparam;
9103 shellparam.p = newparam;
9104 #if ENABLE_ASH_GETOPTS
9105 shellparam.optind = 1;
9106 shellparam.optoff = -1;
9111 * Process shell options. The global variable argptr contains a pointer
9112 * to the argument list; we advance it past the options.
9114 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9115 * For a non-interactive shell, an error condition encountered
9116 * by a special built-in ... shall cause the shell to write a diagnostic message
9117 * to standard error and exit as shown in the following table:
9118 * Error Special Built-In
9120 * Utility syntax error (option or operand error) Shall exit
9122 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9123 * we see that bash does not do that (set "finishes" with error code 1 instead,
9124 * and shell continues), and people rely on this behavior!
9126 * set -o barfoo 2>/dev/null
9129 * Oh well. Let's mimic that.
9132 minus_o(char *name, int val)
9137 for (i = 0; i < NOPTS; i++) {
9138 if (strcmp(name, optnames(i)) == 0) {
9143 ash_msg("illegal option -o %s", name);
9146 out1str("Current option settings\n");
9147 for (i = 0; i < NOPTS; i++)
9148 out1fmt("%-16s%s\n", optnames(i),
9149 optlist[i] ? "on" : "off");
9153 setoption(int flag, int val)
9157 for (i = 0; i < NOPTS; i++) {
9158 if (optletters(i) == flag) {
9163 ash_msg_and_raise_error("illegal option -%c", flag);
9167 options(int cmdline)
9175 while ((p = *argptr) != NULL) {
9177 if (c != '-' && c != '+')
9180 val = 0; /* val = 0 if c == '+' */
9183 if (p[0] == '\0' || LONE_DASH(p)) {
9185 /* "-" means turn off -x and -v */
9188 /* "--" means reset params */
9189 else if (*argptr == NULL)
9192 break; /* "-" or "--" terminates options */
9195 /* first char was + or - */
9196 while ((c = *p++) != '\0') {
9197 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9198 if (c == 'c' && cmdline) {
9199 minusc = p; /* command is after shell args */
9200 } else if (c == 'o') {
9201 if (minus_o(*argptr, val)) {
9202 /* it already printed err message */
9203 return 1; /* error */
9207 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9209 /* bash does not accept +-login, we also won't */
9210 } else if (cmdline && val && (c == '-')) { /* long options */
9211 if (strcmp(p, "login") == 0)
9223 * The shift builtin command.
9226 shiftcmd(int argc, char **argv)
9233 n = number(argv[1]);
9234 if (n > shellparam.nparam)
9235 ash_msg_and_raise_error("can't shift that many");
9237 shellparam.nparam -= n;
9238 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9239 if (shellparam.malloced)
9243 while ((*ap2++ = *ap1++) != NULL);
9244 #if ENABLE_ASH_GETOPTS
9245 shellparam.optind = 1;
9246 shellparam.optoff = -1;
9253 * POSIX requires that 'set' (but not export or readonly) output the
9254 * variables in lexicographic order - by the locale's collating order (sigh).
9255 * Maybe we could keep them in an ordered balanced binary tree
9256 * instead of hashed lists.
9257 * For now just roll 'em through qsort for printing...
9260 showvars(const char *sep_prefix, int on, int off)
9265 ep = listvars(on, off, &epend);
9266 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9268 sep = *sep_prefix ? " " : sep_prefix;
9270 for (; ep < epend; ep++) {
9274 p = strchrnul(*ep, '=');
9277 q = single_quote(++p);
9278 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9284 * The set command builtin.
9287 setcmd(int argc, char **argv)
9292 return showvars(nullstr, 0, VUNSET);
9295 if (!options(0)) { /* if no parse error... */
9298 if (*argptr != NULL) {
9306 #if ENABLE_ASH_RANDOM_SUPPORT
9307 /* Roughly copied from bash.. */
9309 change_random(const char *value)
9311 if (value == NULL) {
9312 /* "get", generate */
9315 rseed = rseed * 1103515245 + 12345;
9316 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9317 /* set without recursion */
9318 setvar(vrandom.text, buf, VNOFUNC);
9319 vrandom.flags &= ~VNOFUNC;
9322 rseed = strtoul(value, (char **)NULL, 10);
9327 #if ENABLE_ASH_GETOPTS
9329 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9338 if (*param_optind < 1)
9340 optnext = optfirst + *param_optind - 1;
9342 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9345 p = optnext[-1] + *optoff;
9346 if (p == NULL || *p == '\0') {
9347 /* Current word is done, advance */
9349 if (p == NULL || *p != '-' || *++p == '\0') {
9356 if (LONE_DASH(p)) /* check for "--" */
9361 for (q = optstr; *q != c; ) {
9363 if (optstr[0] == ':') {
9366 err |= setvarsafe("OPTARG", s, 0);
9368 fprintf(stderr, "Illegal option -%c\n", c);
9379 if (*p == '\0' && (p = *optnext) == NULL) {
9380 if (optstr[0] == ':') {
9383 err |= setvarsafe("OPTARG", s, 0);
9386 fprintf(stderr, "No arg for -%c option\n", c);
9395 err |= setvarsafe("OPTARG", p, 0);
9398 err |= setvarsafe("OPTARG", nullstr, 0);
9400 *optoff = p ? p - *(optnext - 1) : -1;
9401 *param_optind = optnext - optfirst + 1;
9402 fmtstr(s, sizeof(s), "%d", *param_optind);
9403 err |= setvarsafe("OPTIND", s, VNOFUNC);
9406 err |= setvarsafe(optvar, s, 0);
9410 flush_stdout_stderr();
9411 raise_exception(EXERROR);
9417 * The getopts builtin. Shellparam.optnext points to the next argument
9418 * to be processed. Shellparam.optptr points to the next character to
9419 * be processed in the current argument. If shellparam.optnext is NULL,
9420 * then it's the first time getopts has been called.
9423 getoptscmd(int argc, char **argv)
9428 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
9430 optbase = shellparam.p;
9431 if (shellparam.optind > shellparam.nparam + 1) {
9432 shellparam.optind = 1;
9433 shellparam.optoff = -1;
9437 if (shellparam.optind > argc - 2) {
9438 shellparam.optind = 1;
9439 shellparam.optoff = -1;
9443 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9444 &shellparam.optoff);
9446 #endif /* ASH_GETOPTS */
9449 /* ============ Shell parser */
9452 * NEOF is returned by parsecmd when it encounters an end of file. It
9453 * must be distinct from NULL, so we use the address of a variable that
9454 * happens to be handy.
9456 static smallint tokpushback; /* last token pushed back */
9457 #define NEOF ((union node *)&tokpushback)
9458 static smallint parsebackquote; /* nonzero if we are inside backquotes */
9459 static int lasttoken; /* last token read */
9460 static char *wordtext; /* text of last word returned by readtoken */
9461 static struct nodelist *backquotelist;
9462 static union node *redirnode;
9463 static struct heredoc *heredoc;
9464 static smallint quoteflag; /* set if (part of) last token was quoted */
9466 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9468 raise_error_syntax(const char *msg)
9470 ash_msg_and_raise_error("syntax error: %s", msg);
9475 * Called when an unexpected token is read during the parse. The argument
9476 * is the token that is expected, or -1 if more than one type of token can
9477 * occur at this point.
9479 static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9481 raise_error_unexpected_syntax(int token)
9486 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9488 sprintf(msg + l, " (expecting %s)", tokname(token));
9489 raise_error_syntax(msg);
9493 #define EOFMARKLEN 79
9496 struct heredoc *next; /* next here document in list */
9497 union node *here; /* redirection node */
9498 char *eofmark; /* string indicating end of input */
9499 int striptabs; /* if set, strip leading tabs */
9502 static struct heredoc *heredoclist; /* list of here documents to read */
9504 /* parsing is heavily cross-recursive, need these forward decls */
9505 static union node *andor(void);
9506 static union node *pipeline(void);
9507 static union node *parse_command(void);
9508 static void parseheredoc(void);
9509 static char peektoken(void);
9510 static int readtoken(void);
9515 union node *n1, *n2, *n3;
9518 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9519 if (nlflag == 2 && peektoken())
9525 if (tok == TBACKGND) {
9526 if (n2->type == NPIPE) {
9527 n2->npipe.backgnd = 1;
9529 if (n2->type != NREDIR) {
9530 n3 = stalloc(sizeof(struct nredir));
9532 n3->nredir.redirect = NULL;
9535 n2->type = NBACKGND;
9541 n3 = stalloc(sizeof(struct nbinary));
9543 n3->nbinary.ch1 = n1;
9544 n3->nbinary.ch2 = n2;
9560 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9568 pungetc(); /* push back EOF on input */
9572 raise_error_unexpected_syntax(-1);
9582 union node *n1, *n2, *n3;
9590 } else if (t == TOR) {
9596 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9598 n3 = stalloc(sizeof(struct nbinary));
9600 n3->nbinary.ch1 = n1;
9601 n3->nbinary.ch2 = n2;
9609 union node *n1, *n2, *pipenode;
9610 struct nodelist *lp, *prev;
9614 TRACE(("pipeline: entered\n"));
9615 if (readtoken() == TNOT) {
9617 checkkwd = CHKKWD | CHKALIAS;
9620 n1 = parse_command();
9621 if (readtoken() == TPIPE) {
9622 pipenode = stalloc(sizeof(struct npipe));
9623 pipenode->type = NPIPE;
9624 pipenode->npipe.backgnd = 0;
9625 lp = stalloc(sizeof(struct nodelist));
9626 pipenode->npipe.cmdlist = lp;
9630 lp = stalloc(sizeof(struct nodelist));
9631 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9632 lp->n = parse_command();
9634 } while (readtoken() == TPIPE);
9640 n2 = stalloc(sizeof(struct nnot));
9653 n = stalloc(sizeof(struct narg));
9655 n->narg.next = NULL;
9656 n->narg.text = wordtext;
9657 n->narg.backquote = backquotelist;
9662 fixredir(union node *n, const char *text, int err)
9664 TRACE(("Fix redir %s %d\n", text, err));
9666 n->ndup.vname = NULL;
9668 if (isdigit(text[0]) && text[1] == '\0')
9669 n->ndup.dupfd = text[0] - '0';
9670 else if (LONE_DASH(text))
9674 raise_error_syntax("Bad fd number");
9675 n->ndup.vname = makename();
9680 * Returns true if the text contains nothing to expand (no dollar signs
9684 noexpand(char *text)
9690 while ((c = *p++) != '\0') {
9691 if (c == CTLQUOTEMARK)
9695 else if (SIT(c, BASESYNTAX) == CCTL)
9704 union node *n = redirnode;
9706 if (readtoken() != TWORD)
9707 raise_error_unexpected_syntax(-1);
9708 if (n->type == NHERE) {
9709 struct heredoc *here = heredoc;
9715 TRACE(("Here document %d\n", n->type));
9716 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9717 raise_error_syntax("Illegal eof marker for << redirection");
9718 rmescapes(wordtext);
9719 here->eofmark = wordtext;
9721 if (heredoclist == NULL)
9724 for (p = heredoclist; p->next; p = p->next);
9727 } else if (n->type == NTOFD || n->type == NFROMFD) {
9728 fixredir(n, wordtext, 0);
9730 n->nfile.fname = makename();
9737 union node *args, **app;
9738 union node *n = NULL;
9739 union node *vars, **vpp;
9740 union node **rpp, *redir;
9750 savecheckkwd = CHKALIAS;
9752 checkkwd = savecheckkwd;
9753 switch (readtoken()) {
9755 n = stalloc(sizeof(struct narg));
9757 n->narg.text = wordtext;
9758 n->narg.backquote = backquotelist;
9759 if (savecheckkwd && isassignment(wordtext)) {
9761 vpp = &n->narg.next;
9764 app = &n->narg.next;
9769 *rpp = n = redirnode;
9770 rpp = &n->nfile.next;
9771 parsefname(); /* read name of redirection file */
9774 if (args && app == &args->narg.next
9777 struct builtincmd *bcmd;
9780 /* We have a function */
9781 if (readtoken() != TRP)
9782 raise_error_unexpected_syntax(TRP);
9783 name = n->narg.text;
9785 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9787 raise_error_syntax("Bad function name");
9790 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9791 n->narg.next = parse_command();
9804 n = stalloc(sizeof(struct ncmd));
9806 n->ncmd.args = args;
9807 n->ncmd.assign = vars;
9808 n->ncmd.redirect = redir;
9815 union node *n1, *n2;
9816 union node *ap, **app;
9817 union node *cp, **cpp;
9818 union node *redir, **rpp;
9825 switch (readtoken()) {
9827 raise_error_unexpected_syntax(-1);
9830 n1 = stalloc(sizeof(struct nif));
9832 n1->nif.test = list(0);
9833 if (readtoken() != TTHEN)
9834 raise_error_unexpected_syntax(TTHEN);
9835 n1->nif.ifpart = list(0);
9837 while (readtoken() == TELIF) {
9838 n2->nif.elsepart = stalloc(sizeof(struct nif));
9839 n2 = n2->nif.elsepart;
9841 n2->nif.test = list(0);
9842 if (readtoken() != TTHEN)
9843 raise_error_unexpected_syntax(TTHEN);
9844 n2->nif.ifpart = list(0);
9846 if (lasttoken == TELSE)
9847 n2->nif.elsepart = list(0);
9849 n2->nif.elsepart = NULL;
9857 n1 = stalloc(sizeof(struct nbinary));
9858 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9859 n1->nbinary.ch1 = list(0);
9862 TRACE(("expecting DO got %s %s\n", tokname(got),
9863 got == TWORD ? wordtext : ""));
9864 raise_error_unexpected_syntax(TDO);
9866 n1->nbinary.ch2 = list(0);
9871 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9872 raise_error_syntax("Bad for loop variable");
9873 n1 = stalloc(sizeof(struct nfor));
9875 n1->nfor.var = wordtext;
9876 checkkwd = CHKKWD | CHKALIAS;
9877 if (readtoken() == TIN) {
9879 while (readtoken() == TWORD) {
9880 n2 = stalloc(sizeof(struct narg));
9882 n2->narg.text = wordtext;
9883 n2->narg.backquote = backquotelist;
9885 app = &n2->narg.next;
9889 if (lasttoken != TNL && lasttoken != TSEMI)
9890 raise_error_unexpected_syntax(-1);
9892 n2 = stalloc(sizeof(struct narg));
9894 n2->narg.text = (char *)dolatstr;
9895 n2->narg.backquote = NULL;
9896 n2->narg.next = NULL;
9899 * Newline or semicolon here is optional (but note
9900 * that the original Bourne shell only allowed NL).
9902 if (lasttoken != TNL && lasttoken != TSEMI)
9905 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9906 if (readtoken() != TDO)
9907 raise_error_unexpected_syntax(TDO);
9908 n1->nfor.body = list(0);
9912 n1 = stalloc(sizeof(struct ncase));
9914 if (readtoken() != TWORD)
9915 raise_error_unexpected_syntax(TWORD);
9916 n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
9918 n2->narg.text = wordtext;
9919 n2->narg.backquote = backquotelist;
9920 n2->narg.next = NULL;
9922 checkkwd = CHKKWD | CHKALIAS;
9923 } while (readtoken() == TNL);
9924 if (lasttoken != TIN)
9925 raise_error_unexpected_syntax(TIN);
9926 cpp = &n1->ncase.cases;
9928 checkkwd = CHKNL | CHKKWD;
9930 while (t != TESAC) {
9931 if (lasttoken == TLP)
9933 *cpp = cp = stalloc(sizeof(struct nclist));
9935 app = &cp->nclist.pattern;
9937 *app = ap = stalloc(sizeof(struct narg));
9939 ap->narg.text = wordtext;
9940 ap->narg.backquote = backquotelist;
9941 if (readtoken() != TPIPE)
9943 app = &ap->narg.next;
9946 ap->narg.next = NULL;
9947 if (lasttoken != TRP)
9948 raise_error_unexpected_syntax(TRP);
9949 cp->nclist.body = list(2);
9951 cpp = &cp->nclist.next;
9953 checkkwd = CHKNL | CHKKWD;
9957 raise_error_unexpected_syntax(TENDCASE);
9964 n1 = stalloc(sizeof(struct nredir));
9965 n1->type = NSUBSHELL;
9966 n1->nredir.n = list(0);
9967 n1->nredir.redirect = NULL;
9980 if (readtoken() != t)
9981 raise_error_unexpected_syntax(t);
9984 /* Now check for redirection which may follow command */
9985 checkkwd = CHKKWD | CHKALIAS;
9987 while (readtoken() == TREDIR) {
9988 *rpp = n2 = redirnode;
9989 rpp = &n2->nfile.next;
9995 if (n1->type != NSUBSHELL) {
9996 n2 = stalloc(sizeof(struct nredir));
10001 n1->nredir.redirect = redir;
10007 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10008 * is not NULL, read a here document. In the latter case, eofmark is the
10009 * word which marks the end of the document and striptabs is true if
10010 * leading tabs should be stripped from the document. The argument firstc
10011 * is the first character of the input token or document.
10013 * Because C does not have internal subroutines, I have simulated them
10014 * using goto's to implement the subroutine linkage. The following macros
10015 * will run code that appears at the end of readtoken1.
10018 #define CHECKEND() {goto checkend; checkend_return:;}
10019 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10020 #define PARSESUB() {goto parsesub; parsesub_return:;}
10021 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10022 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10023 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10026 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10028 /* NB: syntax parameter fits into smallint */
10032 char line[EOFMARKLEN + 1];
10033 struct nodelist *bqlist;
10037 smallint prevsyntax; /* syntax before arithmetic */
10038 #if ENABLE_ASH_EXPAND_PRMT
10039 smallint pssyntax; /* we are expanding a prompt string */
10041 int varnest; /* levels of variables expansion */
10042 int arinest; /* levels of arithmetic expansion */
10043 int parenlevel; /* levels of parens in arithmetic */
10044 int dqvarnest; /* levels of variables expansion within double quotes */
10047 /* Avoid longjmp clobbering */
10053 (void) &parenlevel;
10056 (void) &prevsyntax;
10059 startlinno = plinno;
10064 #if ENABLE_ASH_EXPAND_PRMT
10065 pssyntax = (syntax == PSSYNTAX);
10069 dblquote = (syntax == DQSYNTAX);
10075 STARTSTACKSTR(out);
10076 loop: { /* for each line, until end of word */
10077 CHECKEND(); /* set c to PEOF if at end of here document */
10078 for (;;) { /* until end of line or end of word */
10079 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10080 switch (SIT(c, syntax)) {
10081 case CNL: /* '\n' */
10082 if (syntax == BASESYNTAX)
10083 goto endword; /* exit outer loop */
10089 goto loop; /* continue outer loop */
10094 if (eofmark == NULL || dblquote)
10095 USTPUTC(CTLESC, out);
10098 case CBACK: /* backslash */
10101 USTPUTC(CTLESC, out);
10102 USTPUTC('\\', out);
10104 } else if (c == '\n') {
10108 #if ENABLE_ASH_EXPAND_PRMT
10109 if (c == '$' && pssyntax) {
10110 USTPUTC(CTLESC, out);
10111 USTPUTC('\\', out);
10115 c != '\\' && c != '`' &&
10120 USTPUTC(CTLESC, out);
10121 USTPUTC('\\', out);
10123 if (SIT(c, SQSYNTAX) == CCTL)
10124 USTPUTC(CTLESC, out);
10132 if (eofmark == NULL) {
10133 USTPUTC(CTLQUOTEMARK, out);
10141 if (eofmark != NULL && arinest == 0
10146 if (dqvarnest == 0) {
10147 syntax = BASESYNTAX;
10154 case CVAR: /* '$' */
10155 PARSESUB(); /* parse substitution */
10157 case CENDVAR: /* '}' */
10160 if (dqvarnest > 0) {
10163 USTPUTC(CTLENDVAR, out);
10168 #if ENABLE_ASH_MATH_SUPPORT
10169 case CLP: /* '(' in arithmetic */
10173 case CRP: /* ')' in arithmetic */
10174 if (parenlevel > 0) {
10178 if (pgetc() == ')') {
10179 if (--arinest == 0) {
10180 USTPUTC(CTLENDARI, out);
10181 syntax = prevsyntax;
10182 dblquote = (syntax == DQSYNTAX);
10187 * unbalanced parens
10188 * (don't 2nd guess - no error)
10196 case CBQUOTE: /* '`' */
10200 goto endword; /* exit outer loop */
10205 goto endword; /* exit outer loop */
10206 #if ENABLE_ASH_ALIAS
10216 #if ENABLE_ASH_MATH_SUPPORT
10217 if (syntax == ARISYNTAX)
10218 raise_error_syntax("Missing '))'");
10220 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10221 raise_error_syntax("Unterminated quoted string");
10222 if (varnest != 0) {
10223 startlinno = plinno;
10225 raise_error_syntax("Missing '}'");
10227 USTPUTC('\0', out);
10228 len = out - (char *)stackblock();
10229 out = stackblock();
10230 if (eofmark == NULL) {
10231 if ((c == '>' || c == '<')
10234 && (*out == '\0' || isdigit(*out))) {
10236 return lasttoken = TREDIR;
10241 quoteflag = quotef;
10242 backquotelist = bqlist;
10243 grabstackblock(len);
10247 /* end of readtoken routine */
10250 * Check to see whether we are at the end of the here document. When this
10251 * is called, c is set to the first character of the next input line. If
10252 * we are at the end of the here document, this routine sets the c to PEOF.
10256 #if ENABLE_ASH_ALIAS
10262 while (c == '\t') {
10266 if (c == *eofmark) {
10267 if (pfgets(line, sizeof(line)) != NULL) {
10271 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10272 if (*p == '\n' && *q == '\0') {
10275 needprompt = doprompt;
10277 pushstring(line, NULL);
10282 goto checkend_return;
10286 * Parse a redirection operator. The variable "out" points to a string
10287 * specifying the fd to be redirected. The variable "c" contains the
10288 * first character of the redirection operator.
10294 np = stalloc(sizeof(struct nfile));
10299 np->type = NAPPEND;
10301 np->type = NCLOBBER;
10308 } else { /* c == '<' */
10313 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10314 np = stalloc(sizeof(struct nhere));
10318 heredoc = stalloc(sizeof(struct heredoc));
10319 heredoc->here = np;
10322 heredoc->striptabs = 1;
10324 heredoc->striptabs = 0;
10330 np->type = NFROMFD;
10334 np->type = NFROMTO;
10344 np->nfile.fd = fd - '0';
10346 goto parseredir_return;
10350 * Parse a substitution. At this point, we have read the dollar sign
10351 * and nothing else.
10354 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10355 * (assuming ascii char codes, as the original implementation did) */
10356 #define is_special(c) \
10357 ((((unsigned int)c) - 33 < 32) \
10358 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
10364 static const char types[] ALIGN1 = "}-+?=";
10368 c <= PEOA_OR_PEOF ||
10369 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10373 } else if (c == '(') { /* $(command) or $((arith)) */
10374 if (pgetc() == '(') {
10375 #if ENABLE_ASH_MATH_SUPPORT
10378 raise_error_syntax("We unsupport $((arith))");
10385 USTPUTC(CTLVAR, out);
10386 typeloc = out - (char *)stackblock();
10387 USTPUTC(VSNORMAL, out);
10388 subtype = VSNORMAL;
10396 subtype = VSLENGTH;
10400 if (c > PEOA_OR_PEOF && is_name(c)) {
10404 } while (c > PEOA_OR_PEOF && is_in_name(c));
10405 } else if (isdigit(c)) {
10409 } while (isdigit(c));
10410 } else if (is_special(c)) {
10414 badsub: raise_error_syntax("Bad substitution");
10418 if (subtype == 0) {
10425 p = strchr(types, c);
10428 subtype = p - types + VSNORMAL;
10434 subtype = c == '#' ? VSTRIMLEFT :
10447 if (dblquote || arinest)
10449 *((char *)stackblock() + typeloc) = subtype | flags;
10450 if (subtype != VSNORMAL) {
10452 if (dblquote || arinest) {
10457 goto parsesub_return;
10461 * Called to parse command substitutions. Newstyle is set if the command
10462 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10463 * list of commands (passed by reference), and savelen is the number of
10464 * characters on the top of the stack which must be preserved.
10467 struct nodelist **nlpp;
10470 char *volatile str;
10471 struct jmploc jmploc;
10472 struct jmploc *volatile savehandler;
10474 smallint saveprompt = 0;
10477 (void) &saveprompt;
10479 savepbq = parsebackquote;
10480 if (setjmp(jmploc.loc)) {
10482 parsebackquote = 0;
10483 exception_handler = savehandler;
10484 longjmp(exception_handler->loc, 1);
10488 savelen = out - (char *)stackblock();
10490 str = ckmalloc(savelen);
10491 memcpy(str, stackblock(), savelen);
10493 savehandler = exception_handler;
10494 exception_handler = &jmploc;
10497 /* We must read until the closing backquote, giving special
10498 treatment to some slashes, and then push the string and
10499 reread it as input, interpreting it normally. */
10506 STARTSTACKSTR(pout);
10523 * If eating a newline, avoid putting
10524 * the newline into the new character
10525 * stream (via the STPUTC after the
10530 if (pc != '\\' && pc != '`' && pc != '$'
10531 && (!dblquote || pc != '"'))
10532 STPUTC('\\', pout);
10533 if (pc > PEOA_OR_PEOF) {
10539 #if ENABLE_ASH_ALIAS
10542 startlinno = plinno;
10543 raise_error_syntax("EOF in backquote substitution");
10547 needprompt = doprompt;
10556 STPUTC('\0', pout);
10557 psavelen = pout - (char *)stackblock();
10558 if (psavelen > 0) {
10559 pstr = grabstackstr(pout);
10560 setinputstring(pstr);
10565 nlpp = &(*nlpp)->next;
10566 *nlpp = stalloc(sizeof(**nlpp));
10567 (*nlpp)->next = NULL;
10568 parsebackquote = oldstyle;
10571 saveprompt = doprompt;
10578 doprompt = saveprompt;
10579 else if (readtoken() != TRP)
10580 raise_error_unexpected_syntax(TRP);
10585 * Start reading from old file again, ignoring any pushed back
10586 * tokens left from the backquote parsing
10591 while (stackblocksize() <= savelen)
10593 STARTSTACKSTR(out);
10595 memcpy(out, str, savelen);
10596 STADJUST(savelen, out);
10602 parsebackquote = savepbq;
10603 exception_handler = savehandler;
10604 if (arinest || dblquote)
10605 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10607 USTPUTC(CTLBACKQ, out);
10609 goto parsebackq_oldreturn;
10610 goto parsebackq_newreturn;
10613 #if ENABLE_ASH_MATH_SUPPORT
10615 * Parse an arithmetic expansion (indicate start of one and set state)
10618 if (++arinest == 1) {
10619 prevsyntax = syntax;
10620 syntax = ARISYNTAX;
10621 USTPUTC(CTLARI, out);
10628 * we collapse embedded arithmetic expansion to
10629 * parenthesis, which should be equivalent
10633 goto parsearith_return;
10637 } /* end of readtoken */
10640 * Read the next input token.
10641 * If the token is a word, we set backquotelist to the list of cmds in
10642 * backquotes. We set quoteflag to true if any part of the word was
10644 * If the token is TREDIR, then we set redirnode to a structure containing
10646 * In all cases, the variable startlinno is set to the number of the line
10647 * on which the token starts.
10649 * [Change comment: here documents and internal procedures]
10650 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10651 * word parsing code into a separate routine. In this case, readtoken
10652 * doesn't need to have any internal procedures, but parseword does.
10653 * We could also make parseoperator in essence the main routine, and
10654 * have parseword (readtoken1?) handle both words and redirection.]
10656 #define NEW_xxreadtoken
10657 #ifdef NEW_xxreadtoken
10658 /* singles must be first! */
10659 static const char xxreadtoken_chars[7] ALIGN1 = {
10660 '\n', '(', ')', '&', '|', ';', 0
10663 static const char xxreadtoken_tokens[] ALIGN1 = {
10664 TNL, TLP, TRP, /* only single occurrence allowed */
10665 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10666 TEOF, /* corresponds to trailing nul */
10667 TAND, TOR, TENDCASE /* if double occurrence */
10670 #define xxreadtoken_doubles \
10671 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10672 #define xxreadtoken_singles \
10673 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10687 startlinno = plinno;
10688 for (;;) { /* until token or start of word found */
10691 if ((c != ' ') && (c != '\t')
10692 #if ENABLE_ASH_ALIAS
10697 while ((c = pgetc()) != '\n' && c != PEOF);
10699 } else if (c == '\\') {
10700 if (pgetc() != '\n') {
10704 startlinno = ++plinno;
10709 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10714 needprompt = doprompt;
10717 p = strchr(xxreadtoken_chars, c);
10720 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10723 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10724 if (pgetc() == *p) { /* double occurrence? */
10725 p += xxreadtoken_doubles + 1;
10731 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10737 #define RETURN(token) return lasttoken = token
10750 startlinno = plinno;
10751 for (;;) { /* until token or start of word found */
10754 case ' ': case '\t':
10755 #if ENABLE_ASH_ALIAS
10760 while ((c = pgetc()) != '\n' && c != PEOF);
10764 if (pgetc() == '\n') {
10765 startlinno = ++plinno;
10774 needprompt = doprompt;
10779 if (pgetc() == '&')
10784 if (pgetc() == '|')
10789 if (pgetc() == ';')
10802 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10805 #endif /* NEW_xxreadtoken */
10812 smallint alreadyseen = tokpushback;
10815 #if ENABLE_ASH_ALIAS
10824 if (checkkwd & CHKNL) {
10831 if (t != TWORD || quoteflag) {
10836 * check for keywords
10838 if (checkkwd & CHKKWD) {
10839 const char *const *pp;
10841 pp = findkwd(wordtext);
10843 lasttoken = t = pp - tokname_array;
10844 TRACE(("keyword %s recognized\n", tokname(t)));
10849 if (checkkwd & CHKALIAS) {
10850 #if ENABLE_ASH_ALIAS
10852 ap = lookupalias(wordtext, 1);
10855 pushstring(ap->val, ap);
10865 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10867 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10879 return tokname_array[t][0];
10883 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10884 * valid parse tree indicating a blank line.)
10886 static union node *
10887 parsecmd(int interact)
10892 doprompt = interact;
10894 setprompt(doprompt);
10906 * Input any here documents.
10911 struct heredoc *here;
10914 here = heredoclist;
10921 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10922 here->eofmark, here->striptabs);
10923 n = stalloc(sizeof(struct narg));
10924 n->narg.type = NARG;
10925 n->narg.next = NULL;
10926 n->narg.text = wordtext;
10927 n->narg.backquote = backquotelist;
10928 here->here->nhere.doc = n;
10935 * called by editline -- any expansions to the prompt should be added here.
10937 #if ENABLE_ASH_EXPAND_PRMT
10938 static const char *
10939 expandstr(const char *ps)
10943 /* XXX Fix (char *) cast. */
10944 setinputstring((char *)ps);
10945 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
10948 n.narg.type = NARG;
10949 n.narg.next = NULL;
10950 n.narg.text = wordtext;
10951 n.narg.backquote = backquotelist;
10953 expandarg(&n, NULL, 0);
10954 return stackblock();
10959 * Execute a command or commands contained in a string.
10962 evalstring(char *s, int mask)
10965 struct stackmark smark;
10969 setstackmark(&smark);
10972 while ((n = parsecmd(0)) != NEOF) {
10974 popstackmark(&smark);
10987 * The eval command.
10990 evalcmd(int argc, char **argv)
10999 STARTSTACKSTR(concat);
11002 concat = stack_putstr(p, concat);
11006 STPUTC(' ', concat);
11008 STPUTC('\0', concat);
11009 p = grabstackstr(concat);
11011 evalstring(p, ~SKIPEVAL);
11018 * Read and execute commands. "Top" is nonzero for the top level command
11019 * loop; it turns on prompting if the shell is interactive.
11025 struct stackmark smark;
11029 TRACE(("cmdloop(%d) called\n", top));
11033 setstackmark(&smark);
11036 showjobs(stderr, SHOW_CHANGED);
11039 if (iflag && top) {
11041 #if ENABLE_ASH_MAIL
11045 n = parsecmd(inter);
11046 /* showtree(n); DEBUG */
11048 if (!top || numeof >= 50)
11050 if (!stoppedjobs()) {
11053 out2str("\nUse \"exit\" to leave shell.\n");
11056 } else if (nflag == 0) {
11057 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11062 popstackmark(&smark);
11067 return skip & SKIPEVAL;
11074 * Take commands from a file. To be compatible we should do a path
11075 * search for the file, which is necessary to find sub-commands.
11078 find_dot_file(char *name)
11081 const char *path = pathval();
11084 /* don't try this for absolute or relative paths */
11085 if (strchr(name, '/'))
11088 while ((fullname = padvance(&path, name)) != NULL) {
11089 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11091 * Don't bother freeing here, since it will
11092 * be freed by the caller.
11096 stunalloc(fullname);
11099 /* not found in the PATH */
11100 ash_msg_and_raise_error("%s: not found", name);
11105 dotcmd(int argc, char **argv)
11107 struct strlist *sp;
11108 volatile struct shparam saveparam;
11111 for (sp = cmdenviron; sp; sp = sp->next)
11112 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11114 if (argc >= 2) { /* That's what SVR2 does */
11117 fullname = find_dot_file(argv[1]);
11120 saveparam = shellparam;
11121 shellparam.malloced = 0;
11122 shellparam.nparam = argc - 2;
11123 shellparam.p = argv + 2;
11126 setinputfile(fullname, INPUT_PUSH_FILE);
11127 commandname = fullname;
11132 freeparam(&shellparam);
11133 shellparam = saveparam;
11135 status = exitstatus;
11141 exitcmd(int argc, char **argv)
11146 exitstatus = number(argv[1]);
11147 raise_exception(EXEXIT);
11151 #if ENABLE_ASH_BUILTIN_ECHO
11153 echocmd(int argc, char **argv)
11155 return echo_main(argc, argv);
11159 #if ENABLE_ASH_BUILTIN_TEST
11161 testcmd(int argc, char **argv)
11163 return test_main(argc, argv);
11168 * Read a file containing shell functions.
11171 readcmdfile(char *name)
11173 setinputfile(name, INPUT_PUSH_FILE);
11179 /* ============ find_command inplementation */
11182 * Resolve a command name. If you change this routine, you may have to
11183 * change the shellexec routine as well.
11186 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11188 struct tblentry *cmdp;
11195 struct builtincmd *bcmd;
11197 /* If name contains a slash, don't use PATH or hash table */
11198 if (strchr(name, '/') != NULL) {
11199 entry->u.index = -1;
11200 if (act & DO_ABS) {
11201 while (stat(name, &statb) < 0) {
11203 if (errno == EINTR)
11206 entry->cmdtype = CMDUNKNOWN;
11210 entry->cmdtype = CMDNORMAL;
11214 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
11216 updatetbl = (path == pathval());
11219 if (strstr(path, "%builtin") != NULL)
11220 act |= DO_ALTBLTIN;
11223 /* If name is in the table, check answer will be ok */
11224 cmdp = cmdlookup(name, 0);
11225 if (cmdp != NULL) {
11228 switch (cmdp->cmdtype) {
11246 } else if (cmdp->rehash == 0)
11247 /* if not invalidated by cd, we're done */
11251 /* If %builtin not in path, check for builtin next */
11252 bcmd = find_builtin(name);
11254 if (IS_BUILTIN_REGULAR(bcmd))
11255 goto builtin_success;
11256 if (act & DO_ALTPATH) {
11257 if (!(act & DO_ALTBLTIN))
11258 goto builtin_success;
11259 } else if (builtinloc <= 0) {
11260 goto builtin_success;
11264 #if ENABLE_FEATURE_SH_STANDALONE
11265 if (find_applet_by_name(name) >= 0) {
11266 entry->cmdtype = CMDNORMAL;
11267 entry->u.index = -1;
11272 /* We have to search path. */
11273 prev = -1; /* where to start */
11274 if (cmdp && cmdp->rehash) { /* doing a rehash */
11275 if (cmdp->cmdtype == CMDBUILTIN)
11278 prev = cmdp->param.index;
11284 while ((fullname = padvance(&path, name)) != NULL) {
11285 stunalloc(fullname);
11286 /* NB: code below will still use fullname
11287 * despite it being "unallocated" */
11290 if (prefix(pathopt, "builtin")) {
11292 goto builtin_success;
11294 } else if (!(act & DO_NOFUNC)
11295 && prefix(pathopt, "func")) {
11296 /* handled below */
11298 /* ignore unimplemented options */
11302 /* if rehash, don't redo absolute path names */
11303 if (fullname[0] == '/' && idx <= prev) {
11306 TRACE(("searchexec \"%s\": no change\n", name));
11309 while (stat(fullname, &statb) < 0) {
11311 if (errno == EINTR)
11314 if (errno != ENOENT && errno != ENOTDIR)
11318 e = EACCES; /* if we fail, this will be the error */
11319 if (!S_ISREG(statb.st_mode))
11321 if (pathopt) { /* this is a %func directory */
11322 stalloc(strlen(fullname) + 1);
11323 /* NB: stalloc will return space pointed by fullname
11324 * (because we don't have any intervening allocations
11325 * between stunalloc above and this stalloc) */
11326 readcmdfile(fullname);
11327 cmdp = cmdlookup(name, 0);
11328 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11329 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11330 stunalloc(fullname);
11333 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11335 entry->cmdtype = CMDNORMAL;
11336 entry->u.index = idx;
11340 cmdp = cmdlookup(name, 1);
11341 cmdp->cmdtype = CMDNORMAL;
11342 cmdp->param.index = idx;
11347 /* We failed. If there was an entry for this command, delete it */
11348 if (cmdp && updatetbl)
11349 delete_cmd_entry();
11351 ash_msg("%s: %s", name, errmsg(e, "not found"));
11352 entry->cmdtype = CMDUNKNOWN;
11357 entry->cmdtype = CMDBUILTIN;
11358 entry->u.cmd = bcmd;
11362 cmdp = cmdlookup(name, 1);
11363 cmdp->cmdtype = CMDBUILTIN;
11364 cmdp->param.cmd = bcmd;
11368 entry->cmdtype = cmdp->cmdtype;
11369 entry->u = cmdp->param;
11373 /* ============ trap.c */
11376 * The trap builtin.
11379 trapcmd(int argc, char **argv)
11388 for (signo = 0; signo < NSIG; signo++) {
11389 if (trap[signo] != NULL) {
11392 sn = get_signame(signo);
11393 out1fmt("trap -- %s %s\n",
11394 single_quote(trap[signo]), sn);
11404 signo = get_signum(*ap);
11406 ash_msg_and_raise_error("%s: bad trap", *ap);
11409 if (LONE_DASH(action))
11412 action = ckstrdup(action);
11415 trap[signo] = action;
11425 /* ============ Builtins */
11427 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
11429 * Lists available builtins
11432 helpcmd(int argc, char **argv)
11436 out1fmt("\nBuilt-in commands:\n-------------------\n");
11437 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
11438 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11439 builtintab[i].name + 1);
11445 #if ENABLE_FEATURE_SH_STANDALONE
11447 const char *a = applet_names;
11449 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11454 a += strlen(a) + 1;
11459 return EXIT_SUCCESS;
11461 #endif /* FEATURE_SH_EXTRA_QUIET */
11464 * The export and readonly commands.
11467 exportcmd(int argc, char **argv)
11473 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
11475 if (nextopt("p") != 'p') {
11480 p = strchr(name, '=');
11484 vp = *findvar(hashvar(name), name);
11490 setvar(name, p, flag);
11491 } while ((name = *++aptr) != NULL);
11495 showvars(argv[0], flag, 0);
11500 * Delete a function if it exists.
11503 unsetfunc(const char *name)
11505 struct tblentry *cmdp;
11507 cmdp = cmdlookup(name, 0);
11508 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11509 delete_cmd_entry();
11513 * The unset builtin command. We unset the function before we unset the
11514 * variable to allow a function to be unset when there is a readonly variable
11515 * with the same name.
11518 unsetcmd(int argc, char **argv)
11525 while ((i = nextopt("vf")) != '\0') {
11529 for (ap = argptr; *ap; ap++) {
11545 #include <sys/times.h>
11547 static const unsigned char timescmd_str[] ALIGN1 = {
11548 ' ', offsetof(struct tms, tms_utime),
11549 '\n', offsetof(struct tms, tms_stime),
11550 ' ', offsetof(struct tms, tms_cutime),
11551 '\n', offsetof(struct tms, tms_cstime),
11556 timescmd(int ac, char **av)
11558 long clk_tck, s, t;
11559 const unsigned char *p;
11562 clk_tck = sysconf(_SC_CLK_TCK);
11567 t = *(clock_t *)(((char *) &buf) + p[1]);
11569 out1fmt("%ldm%ld.%.3lds%c",
11571 ((t - s * clk_tck) * 1000) / clk_tck,
11573 } while (*(p += 2));
11578 #if ENABLE_ASH_MATH_SUPPORT
11580 dash_arith(const char *s)
11586 result = arith(s, &errcode);
11589 ash_msg_and_raise_error("exponent less than 0");
11591 ash_msg_and_raise_error("divide by zero");
11593 ash_msg_and_raise_error("expression recursion loop detected");
11594 raise_error_syntax(s);
11602 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11603 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11605 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
11608 letcmd(int argc, char **argv)
11615 ash_msg_and_raise_error("expression expected");
11616 for (ap = argv + 1; *ap; ap++) {
11617 i = dash_arith(*ap);
11622 #endif /* ASH_MATH_SUPPORT */
11625 /* ============ miscbltin.c
11627 * Miscellaneous builtins.
11632 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
11633 typedef enum __rlimit_resource rlim_t;
11637 * The read builtin. The -e option causes backslashes to escape the
11638 * following character.
11640 * This uses unbuffered input, which may be avoidable in some cases.
11643 readcmd(int argc, char **argv)
11655 #if ENABLE_ASH_READ_NCHARS
11659 struct termios tty, old_tty;
11661 #if ENABLE_ASH_READ_TIMEOUT
11665 ts.tv_sec = ts.tv_usec = 0;
11670 #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
11671 while ((i = nextopt("p:rt:n:s")) != '\0')
11672 #elif ENABLE_ASH_READ_NCHARS
11673 while ((i = nextopt("p:rn:s")) != '\0')
11674 #elif ENABLE_ASH_READ_TIMEOUT
11675 while ((i = nextopt("p:rt:")) != '\0')
11677 while ((i = nextopt("p:r")) != '\0')
11682 prompt = optionarg;
11684 #if ENABLE_ASH_READ_NCHARS
11686 nchars = bb_strtou(optionarg, NULL, 10);
11687 if (nchars < 0 || errno)
11688 ash_msg_and_raise_error("invalid count");
11689 n_flag = nchars; /* just a flag "nchars is nonzero" */
11695 #if ENABLE_ASH_READ_TIMEOUT
11697 ts.tv_sec = bb_strtou(optionarg, &p, 10);
11699 /* EINVAL means number is ok, but not terminated by NUL */
11700 if (*p == '.' && errno == EINVAL) {
11704 ts.tv_usec = bb_strtou(p, &p2, 10);
11706 ash_msg_and_raise_error("invalid timeout");
11708 /* normalize to usec */
11710 ash_msg_and_raise_error("invalid timeout");
11711 while (scale++ < 6)
11714 } else if (ts.tv_sec < 0 || errno) {
11715 ash_msg_and_raise_error("invalid timeout");
11717 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
11718 ash_msg_and_raise_error("invalid timeout");
11729 if (prompt && isatty(0)) {
11734 ash_msg_and_raise_error("arg count");
11735 ifs = bltinlookup("IFS");
11738 #if ENABLE_ASH_READ_NCHARS
11739 if (n_flag || silent) {
11740 if (tcgetattr(0, &tty) != 0) {
11747 tty.c_lflag &= ~ICANON;
11748 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
11751 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
11753 tcsetattr(0, TCSANOW, &tty);
11757 #if ENABLE_ASH_READ_TIMEOUT
11758 if (ts.tv_sec || ts.tv_usec) {
11762 /* poll-based wait produces bigger code, using select */
11763 i = select(1, &set, NULL, NULL, &ts);
11764 if (!i) { /* timed out! */
11765 #if ENABLE_ASH_READ_NCHARS
11767 tcsetattr(0, TCSANOW, &old_tty);
11778 if (read(0, &c, 1) != 1) {
11790 if (!rflag && c == '\\') {
11796 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11800 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11802 setvar(*ap, stackblock(), 0);
11811 /* end of do {} while: */
11812 #if ENABLE_ASH_READ_NCHARS
11813 while (!n_flag || --nchars);
11818 #if ENABLE_ASH_READ_NCHARS
11819 if (n_flag || silent)
11820 tcsetattr(0, TCSANOW, &old_tty);
11824 /* Remove trailing blanks */
11825 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11827 setvar(*ap, stackblock(), 0);
11828 while (*++ap != NULL)
11829 setvar(*ap, nullstr, 0);
11834 umaskcmd(int argc, char **argv)
11836 static const char permuser[3] ALIGN1 = "ugo";
11837 static const char permmode[3] ALIGN1 = "rwx";
11838 static const short permmask[] ALIGN2 = {
11839 S_IRUSR, S_IWUSR, S_IXUSR,
11840 S_IRGRP, S_IWGRP, S_IXGRP,
11841 S_IROTH, S_IWOTH, S_IXOTH
11847 int symbolic_mode = 0;
11849 while (nextopt("S") != '\0') {
11860 if (symbolic_mode) {
11864 for (i = 0; i < 3; i++) {
11867 *p++ = permuser[i];
11869 for (j = 0; j < 3; j++) {
11870 if ((mask & permmask[3 * i + j]) == 0) {
11871 *p++ = permmode[j];
11879 out1fmt("%.4o\n", mask);
11882 if (isdigit((unsigned char) *ap)) {
11885 if (*ap >= '8' || *ap < '0')
11886 ash_msg_and_raise_error(illnum, argv[1]);
11887 mask = (mask << 3) + (*ap - '0');
11888 } while (*++ap != '\0');
11891 mask = ~mask & 0777;
11892 if (!bb_parse_mode(ap, &mask)) {
11893 ash_msg_and_raise_error("illegal mode: %s", ap);
11895 umask(~mask & 0777);
11904 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11905 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11906 * ash by J.T. Conklin.
11912 uint8_t cmd; /* RLIMIT_xxx fit into it */
11913 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
11917 static const struct limits limits_tbl[] = {
11919 { RLIMIT_CPU, 0, 't' },
11921 #ifdef RLIMIT_FSIZE
11922 { RLIMIT_FSIZE, 9, 'f' },
11925 { RLIMIT_DATA, 10, 'd' },
11927 #ifdef RLIMIT_STACK
11928 { RLIMIT_STACK, 10, 's' },
11931 { RLIMIT_CORE, 9, 'c' },
11934 { RLIMIT_RSS, 10, 'm' },
11936 #ifdef RLIMIT_MEMLOCK
11937 { RLIMIT_MEMLOCK, 10, 'l' },
11939 #ifdef RLIMIT_NPROC
11940 { RLIMIT_NPROC, 0, 'p' },
11942 #ifdef RLIMIT_NOFILE
11943 { RLIMIT_NOFILE, 0, 'n' },
11946 { RLIMIT_AS, 10, 'v' },
11948 #ifdef RLIMIT_LOCKS
11949 { RLIMIT_LOCKS, 0, 'w' },
11952 static const char limits_name[] =
11954 "time(seconds)" "\0"
11956 #ifdef RLIMIT_FSIZE
11957 "file(blocks)" "\0"
11962 #ifdef RLIMIT_STACK
11966 "coredump(blocks)" "\0"
11971 #ifdef RLIMIT_MEMLOCK
11972 "locked memory(kb)" "\0"
11974 #ifdef RLIMIT_NPROC
11977 #ifdef RLIMIT_NOFILE
11983 #ifdef RLIMIT_LOCKS
11988 enum limtype { SOFT = 0x1, HARD = 0x2 };
11991 printlim(enum limtype how, const struct rlimit *limit,
11992 const struct limits *l)
11996 val = limit->rlim_max;
11998 val = limit->rlim_cur;
12000 if (val == RLIM_INFINITY)
12001 out1fmt("unlimited\n");
12003 val >>= l->factor_shift;
12004 out1fmt("%lld\n", (long long) val);
12009 ulimitcmd(int argc, char **argv)
12013 enum limtype how = SOFT | HARD;
12014 const struct limits *l;
12017 struct rlimit limit;
12020 while ((optc = nextopt("HSa"
12024 #ifdef RLIMIT_FSIZE
12030 #ifdef RLIMIT_STACK
12039 #ifdef RLIMIT_MEMLOCK
12042 #ifdef RLIMIT_NPROC
12045 #ifdef RLIMIT_NOFILE
12051 #ifdef RLIMIT_LOCKS
12069 for (l = limits_tbl; l->option != what; l++)
12072 set = *argptr ? 1 : 0;
12076 if (all || argptr[1])
12077 ash_msg_and_raise_error("too many arguments");
12078 if (strncmp(p, "unlimited\n", 9) == 0)
12079 val = RLIM_INFINITY;
12083 while ((c = *p++) >= '0' && c <= '9') {
12084 val = (val * 10) + (long)(c - '0');
12085 if (val < (rlim_t) 0)
12089 ash_msg_and_raise_error("bad number");
12090 val <<= l->factor_shift;
12094 const char *lname = limits_name;
12095 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12096 getrlimit(l->cmd, &limit);
12097 out1fmt("%-20s ", lname);
12098 lname += strlen(lname) + 1;
12099 printlim(how, &limit, l);
12104 getrlimit(l->cmd, &limit);
12107 limit.rlim_max = val;
12109 limit.rlim_cur = val;
12110 if (setrlimit(l->cmd, &limit) < 0)
12111 ash_msg_and_raise_error("error setting limit (%m)");
12113 printlim(how, &limit, l);
12119 /* ============ Math support */
12121 #if ENABLE_ASH_MATH_SUPPORT
12123 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12125 Permission is hereby granted, free of charge, to any person obtaining
12126 a copy of this software and associated documentation files (the
12127 "Software"), to deal in the Software without restriction, including
12128 without limitation the rights to use, copy, modify, merge, publish,
12129 distribute, sublicense, and/or sell copies of the Software, and to
12130 permit persons to whom the Software is furnished to do so, subject to
12131 the following conditions:
12133 The above copyright notice and this permission notice shall be
12134 included in all copies or substantial portions of the Software.
12136 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12137 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12138 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12139 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12140 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12141 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12142 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12145 /* This is my infix parser/evaluator. It is optimized for size, intended
12146 * as a replacement for yacc-based parsers. However, it may well be faster
12147 * than a comparable parser written in yacc. The supported operators are
12148 * listed in #defines below. Parens, order of operations, and error handling
12149 * are supported. This code is thread safe. The exact expression format should
12150 * be that which POSIX specifies for shells. */
12152 /* The code uses a simple two-stack algorithm. See
12153 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12154 * for a detailed explanation of the infix-to-postfix algorithm on which
12155 * this is based (this code differs in that it applies operators immediately
12156 * to the stack instead of adding them to a queue to end up with an
12159 /* To use the routine, call it with an expression string and error return
12163 * Aug 24, 2001 Manuel Novoa III
12165 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12167 * 1) In arith_apply():
12168 * a) Cached values of *numptr and &(numptr[-1]).
12169 * b) Removed redundant test for zero denominator.
12172 * a) Eliminated redundant code for processing operator tokens by moving
12173 * to a table-based implementation. Also folded handling of parens
12175 * b) Combined all 3 loops which called arith_apply to reduce generated
12176 * code size at the cost of speed.
12178 * 3) The following expressions were treated as valid by the original code:
12179 * 1() , 0! , 1 ( *3 ) .
12180 * These bugs have been fixed by internally enclosing the expression in
12181 * parens and then checking that all binary ops and right parens are
12182 * preceded by a valid expression (NUM_TOKEN).
12184 * Note: It may be desirable to replace Aaron's test for whitespace with
12185 * ctype's isspace() if it is used by another busybox applet or if additional
12186 * whitespace chars should be considered. Look below the "#include"s for a
12187 * precompiler test.
12191 * Aug 26, 2001 Manuel Novoa III
12193 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12195 * Merge in Aaron's comments previously posted to the busybox list,
12196 * modified slightly to take account of my changes to the code.
12201 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12203 * - allow access to variable,
12204 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12205 * - realize assign syntax (VAR=expr, +=, *= etc)
12206 * - realize exponentiation (** operator)
12207 * - realize comma separated - expr, expr
12208 * - realise ++expr --expr expr++ expr--
12209 * - realise expr ? expr : expr (but, second expr calculate always)
12210 * - allow hexadecimal and octal numbers
12211 * - was restored loses XOR operator
12212 * - remove one goto label, added three ;-)
12213 * - protect $((num num)) as true zero expr (Manuel`s error)
12214 * - always use special isspace(), see comment from bash ;-)
12217 #define arith_isspace(arithval) \
12218 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12220 typedef unsigned char operator;
12222 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12223 * precedence, and 3 high bits are an ID unique across operators of that
12224 * precedence. The ID portion is so that multiple operators can have the
12225 * same precedence, ensuring that the leftmost one is evaluated first.
12226 * Consider * and /. */
12228 #define tok_decl(prec,id) (((id)<<5)|(prec))
12229 #define PREC(op) ((op) & 0x1F)
12231 #define TOK_LPAREN tok_decl(0,0)
12233 #define TOK_COMMA tok_decl(1,0)
12235 #define TOK_ASSIGN tok_decl(2,0)
12236 #define TOK_AND_ASSIGN tok_decl(2,1)
12237 #define TOK_OR_ASSIGN tok_decl(2,2)
12238 #define TOK_XOR_ASSIGN tok_decl(2,3)
12239 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12240 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12241 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12242 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12244 #define TOK_MUL_ASSIGN tok_decl(3,0)
12245 #define TOK_DIV_ASSIGN tok_decl(3,1)
12246 #define TOK_REM_ASSIGN tok_decl(3,2)
12248 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12249 #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
12251 /* conditional is right associativity too */
12252 #define TOK_CONDITIONAL tok_decl(4,0)
12253 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12255 #define TOK_OR tok_decl(5,0)
12257 #define TOK_AND tok_decl(6,0)
12259 #define TOK_BOR tok_decl(7,0)
12261 #define TOK_BXOR tok_decl(8,0)
12263 #define TOK_BAND tok_decl(9,0)
12265 #define TOK_EQ tok_decl(10,0)
12266 #define TOK_NE tok_decl(10,1)
12268 #define TOK_LT tok_decl(11,0)
12269 #define TOK_GT tok_decl(11,1)
12270 #define TOK_GE tok_decl(11,2)
12271 #define TOK_LE tok_decl(11,3)
12273 #define TOK_LSHIFT tok_decl(12,0)
12274 #define TOK_RSHIFT tok_decl(12,1)
12276 #define TOK_ADD tok_decl(13,0)
12277 #define TOK_SUB tok_decl(13,1)
12279 #define TOK_MUL tok_decl(14,0)
12280 #define TOK_DIV tok_decl(14,1)
12281 #define TOK_REM tok_decl(14,2)
12283 /* exponent is right associativity */
12284 #define TOK_EXPONENT tok_decl(15,1)
12286 /* For now unary operators. */
12287 #define UNARYPREC 16
12288 #define TOK_BNOT tok_decl(UNARYPREC,0)
12289 #define TOK_NOT tok_decl(UNARYPREC,1)
12291 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12292 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12294 #define PREC_PRE (UNARYPREC+2)
12296 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12297 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12299 #define PREC_POST (UNARYPREC+3)
12301 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12302 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12304 #define SPEC_PREC (UNARYPREC+4)
12306 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12307 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12309 #define NUMPTR (*numstackptr)
12312 tok_have_assign(operator op)
12314 operator prec = PREC(op);
12316 convert_prec_is_assing(prec);
12317 return (prec == PREC(TOK_ASSIGN) ||
12318 prec == PREC_PRE || prec == PREC_POST);
12322 is_right_associativity(operator prec)
12324 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12325 || prec == PREC(TOK_CONDITIONAL));
12328 typedef struct ARITCH_VAR_NUM {
12330 arith_t contidional_second_val;
12331 char contidional_second_val_initialized;
12332 char *var; /* if NULL then is regular number,
12333 else is variable name */
12336 typedef struct CHK_VAR_RECURSIVE_LOOPED {
12338 struct CHK_VAR_RECURSIVE_LOOPED *next;
12339 } chk_var_recursive_looped_t;
12341 static chk_var_recursive_looped_t *prev_chk_var_recursive;
12344 arith_lookup_val(v_n_t *t)
12347 const char * p = lookupvar(t->var);
12352 /* recursive try as expression */
12353 chk_var_recursive_looped_t *cur;
12354 chk_var_recursive_looped_t cur_save;
12356 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12357 if (strcmp(cur->var, t->var) == 0) {
12358 /* expression recursion loop detected */
12362 /* save current lookuped var name */
12363 cur = prev_chk_var_recursive;
12364 cur_save.var = t->var;
12365 cur_save.next = cur;
12366 prev_chk_var_recursive = &cur_save;
12368 t->val = arith (p, &errcode);
12369 /* restore previous ptr after recursiving */
12370 prev_chk_var_recursive = cur;
12373 /* allow undefined var as 0 */
12379 /* "applying" a token means performing it on the top elements on the integer
12380 * stack. For a unary operator it will only change the top element, but a
12381 * binary operator will pop two arguments and push a result */
12383 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
12386 arith_t numptr_val, rez;
12387 int ret_arith_lookup_val;
12389 /* There is no operator that can work without arguments */
12390 if (NUMPTR == numstack) goto err;
12391 numptr_m1 = NUMPTR - 1;
12393 /* check operand is var with noninteger value */
12394 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12395 if (ret_arith_lookup_val)
12396 return ret_arith_lookup_val;
12398 rez = numptr_m1->val;
12399 if (op == TOK_UMINUS)
12401 else if (op == TOK_NOT)
12403 else if (op == TOK_BNOT)
12405 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12407 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12409 else if (op != TOK_UPLUS) {
12410 /* Binary operators */
12412 /* check and binary operators need two arguments */
12413 if (numptr_m1 == numstack) goto err;
12415 /* ... and they pop one */
12418 if (op == TOK_CONDITIONAL) {
12419 if (! numptr_m1->contidional_second_val_initialized) {
12420 /* protect $((expr1 ? expr2)) without ": expr" */
12423 rez = numptr_m1->contidional_second_val;
12424 } else if (numptr_m1->contidional_second_val_initialized) {
12425 /* protect $((expr1 : expr2)) without "expr ? " */
12428 numptr_m1 = NUMPTR - 1;
12429 if (op != TOK_ASSIGN) {
12430 /* check operand is var with noninteger value for not '=' */
12431 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12432 if (ret_arith_lookup_val)
12433 return ret_arith_lookup_val;
12435 if (op == TOK_CONDITIONAL) {
12436 numptr_m1->contidional_second_val = rez;
12438 rez = numptr_m1->val;
12439 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
12441 else if (op == TOK_OR)
12442 rez = numptr_val || rez;
12443 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
12445 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
12447 else if (op == TOK_AND)
12448 rez = rez && numptr_val;
12449 else if (op == TOK_EQ)
12450 rez = (rez == numptr_val);
12451 else if (op == TOK_NE)
12452 rez = (rez != numptr_val);
12453 else if (op == TOK_GE)
12454 rez = (rez >= numptr_val);
12455 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
12456 rez >>= numptr_val;
12457 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
12458 rez <<= numptr_val;
12459 else if (op == TOK_GT)
12460 rez = (rez > numptr_val);
12461 else if (op == TOK_LT)
12462 rez = (rez < numptr_val);
12463 else if (op == TOK_LE)
12464 rez = (rez <= numptr_val);
12465 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
12467 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
12469 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
12471 else if (op == TOK_ASSIGN || op == TOK_COMMA)
12473 else if (op == TOK_CONDITIONAL_SEP) {
12474 if (numptr_m1 == numstack) {
12475 /* protect $((expr : expr)) without "expr ? " */
12478 numptr_m1->contidional_second_val_initialized = op;
12479 numptr_m1->contidional_second_val = numptr_val;
12480 } else if (op == TOK_CONDITIONAL) {
12482 numptr_val : numptr_m1->contidional_second_val;
12483 } else if (op == TOK_EXPONENT) {
12484 if (numptr_val < 0)
12485 return -3; /* exponent less than 0 */
12490 while (numptr_val--)
12494 } else if (numptr_val==0) /* zero divisor check */
12496 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
12498 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
12501 if (tok_have_assign(op)) {
12502 char buf[sizeof(arith_t_type)*3 + 2];
12504 if (numptr_m1->var == NULL) {
12508 /* save to shell variable */
12509 #if ENABLE_ASH_MATH_SUPPORT_64
12510 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
12512 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
12514 setvar(numptr_m1->var, buf, 0);
12515 /* after saving, make previous value for v++ or v-- */
12516 if (op == TOK_POST_INC)
12518 else if (op == TOK_POST_DEC)
12521 numptr_m1->val = rez;
12522 /* protect geting var value, is number now */
12523 numptr_m1->var = NULL;
12529 /* longest must be first */
12530 static const char op_tokens[] ALIGN1 = {
12531 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12532 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12533 '<','<', 0, TOK_LSHIFT,
12534 '>','>', 0, TOK_RSHIFT,
12535 '|','|', 0, TOK_OR,
12536 '&','&', 0, TOK_AND,
12537 '!','=', 0, TOK_NE,
12538 '<','=', 0, TOK_LE,
12539 '>','=', 0, TOK_GE,
12540 '=','=', 0, TOK_EQ,
12541 '|','=', 0, TOK_OR_ASSIGN,
12542 '&','=', 0, TOK_AND_ASSIGN,
12543 '*','=', 0, TOK_MUL_ASSIGN,
12544 '/','=', 0, TOK_DIV_ASSIGN,
12545 '%','=', 0, TOK_REM_ASSIGN,
12546 '+','=', 0, TOK_PLUS_ASSIGN,
12547 '-','=', 0, TOK_MINUS_ASSIGN,
12548 '-','-', 0, TOK_POST_DEC,
12549 '^','=', 0, TOK_XOR_ASSIGN,
12550 '+','+', 0, TOK_POST_INC,
12551 '*','*', 0, TOK_EXPONENT,
12555 '=', 0, TOK_ASSIGN,
12567 '?', 0, TOK_CONDITIONAL,
12568 ':', 0, TOK_CONDITIONAL_SEP,
12569 ')', 0, TOK_RPAREN,
12570 '(', 0, TOK_LPAREN,
12574 #define endexpression &op_tokens[sizeof(op_tokens)-7]
12577 arith(const char *expr, int *perrcode)
12579 char arithval; /* Current character under analysis */
12580 operator lasttok, op;
12583 const char *p = endexpression;
12586 size_t datasizes = strlen(expr) + 2;
12588 /* Stack of integers */
12589 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12590 * in any given correct or incorrect expression is left as an exercise to
12592 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12593 *numstackptr = numstack;
12594 /* Stack of operator tokens */
12595 operator *stack = alloca((datasizes) * sizeof(operator)),
12598 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12599 *perrcode = errcode = 0;
12603 if (arithval == 0) {
12604 if (p == endexpression) {
12605 /* Null expression. */
12609 /* This is only reached after all tokens have been extracted from the
12610 * input stream. If there are still tokens on the operator stack, they
12611 * are to be applied in order. At the end, there should be a final
12612 * result on the integer stack */
12614 if (expr != endexpression + 1) {
12615 /* If we haven't done so already, */
12616 /* append a closing right paren */
12617 expr = endexpression;
12618 /* and let the loop process it. */
12621 /* At this point, we're done with the expression. */
12622 if (numstackptr != numstack+1) {
12623 /* ... but if there isn't, it's bad */
12625 return (*perrcode = -1);
12627 if (numstack->var) {
12628 /* expression is $((var)) only, lookup now */
12629 errcode = arith_lookup_val(numstack);
12632 *perrcode = errcode;
12633 return numstack->val;
12636 /* Continue processing the expression. */
12637 if (arith_isspace(arithval)) {
12638 /* Skip whitespace */
12641 p = endofname(expr);
12643 size_t var_name_size = (p-expr) + 1; /* trailing zero */
12645 numstackptr->var = alloca(var_name_size);
12646 safe_strncpy(numstackptr->var, expr, var_name_size);
12649 numstackptr->contidional_second_val_initialized = 0;
12654 if (isdigit(arithval)) {
12655 numstackptr->var = NULL;
12656 #if ENABLE_ASH_MATH_SUPPORT_64
12657 numstackptr->val = strtoll(expr, (char **) &expr, 0);
12659 numstackptr->val = strtol(expr, (char **) &expr, 0);
12663 for (p = op_tokens; ; p++) {
12667 /* strange operator not found */
12670 for (o = expr; *p && *o == *p; p++)
12677 /* skip tail uncompared token */
12680 /* skip zero delim */
12685 /* post grammar: a++ reduce to num */
12686 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12689 /* Plus and minus are binary (not unary) _only_ if the last
12690 * token was as number, or a right paren (which pretends to be
12691 * a number, since it evaluates to one). Think about it.
12692 * It makes sense. */
12693 if (lasttok != TOK_NUM) {
12709 /* We don't want a unary operator to cause recursive descent on the
12710 * stack, because there can be many in a row and it could cause an
12711 * operator to be evaluated before its argument is pushed onto the
12712 * integer stack. */
12713 /* But for binary operators, "apply" everything on the operator
12714 * stack until we find an operator with a lesser priority than the
12715 * one we have just extracted. */
12716 /* Left paren is given the lowest priority so it will never be
12717 * "applied" in this way.
12718 * if associativity is right and priority eq, applied also skip
12721 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12722 /* not left paren or unary */
12723 if (lasttok != TOK_NUM) {
12724 /* binary op must be preceded by a num */
12727 while (stackptr != stack) {
12728 if (op == TOK_RPAREN) {
12729 /* The algorithm employed here is simple: while we don't
12730 * hit an open paren nor the bottom of the stack, pop
12731 * tokens and apply them */
12732 if (stackptr[-1] == TOK_LPAREN) {
12734 /* Any operator directly after a */
12736 /* close paren should consider itself binary */
12740 operator prev_prec = PREC(stackptr[-1]);
12742 convert_prec_is_assing(prec);
12743 convert_prec_is_assing(prev_prec);
12744 if (prev_prec < prec)
12746 /* check right assoc */
12747 if (prev_prec == prec && is_right_associativity(prec))
12750 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12751 if (errcode) goto ret;
12753 if (op == TOK_RPAREN) {
12758 /* Push this operator to the stack and remember it. */
12759 *stackptr++ = lasttok = op;
12764 #endif /* ASH_MATH_SUPPORT */
12767 /* ============ main() and helpers */
12770 * Called to exit the shell.
12772 static void exitshell(void) ATTRIBUTE_NORETURN;
12780 status = exitstatus;
12781 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12782 if (setjmp(loc.loc)) {
12783 if (exception == EXEXIT)
12784 /* dash bug: it just does _exit(exitstatus) here
12785 * but we have to do setjobctl(0) first!
12786 * (bug is still not fixed in dash-0.5.3 - if you run dash
12787 * under Midnight Commander, on exit from dash MC is backgrounded) */
12788 status = exitstatus;
12791 exception_handler = &loc;
12797 flush_stdout_stderr();
12807 /* from input.c: */
12808 basepf.nextc = basepf.buf = basebuf;
12811 signal(SIGCHLD, SIG_DFL);
12816 char ppid[sizeof(int)*3 + 1];
12818 struct stat st1, st2;
12821 for (envp = environ; envp && *envp; envp++) {
12822 if (strchr(*envp, '=')) {
12823 setvareq(*envp, VEXPORT|VTEXTFIXED);
12827 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12828 setvar("PPID", ppid, 0);
12830 p = lookupvar("PWD");
12832 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12833 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12840 * Process the shell command line arguments.
12843 procargs(int argc, char **argv)
12846 const char *xminusc;
12853 for (i = 0; i < NOPTS; i++)
12857 /* it already printed err message */
12858 raise_exception(EXERROR);
12862 if (*xargv == NULL) {
12864 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12867 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12871 for (i = 0; i < NOPTS; i++)
12872 if (optlist[i] == 2)
12877 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12882 } else if (!sflag) {
12883 setinputfile(*xargv, 0);
12886 commandname = arg0;
12889 shellparam.p = xargv;
12890 #if ENABLE_ASH_GETOPTS
12891 shellparam.optind = 1;
12892 shellparam.optoff = -1;
12894 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12896 shellparam.nparam++;
12903 * Read /etc/profile or .profile.
12906 read_profile(const char *name)
12910 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12919 * This routine is called when an error or an interrupt occurs in an
12920 * interactive shell and control is returned to the main command loop.
12928 /* from input.c: */
12929 parselleft = parsenleft = 0; /* clear input buffer */
12931 /* from parser.c: */
12934 /* from redir.c: */
12939 static short profile_buf[16384];
12940 extern int etext();
12944 * Main routine. We initialize things, parse the arguments, execute
12945 * profiles if we're a login shell, and then call cmdloop to execute
12946 * commands. The setjmp call sets up the location to jump to when an
12947 * exception occurs. When an exception occurs the variable "state"
12948 * is used to figure out how far we had gotten.
12950 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12951 int ash_main(int argc, char **argv)
12954 volatile int state;
12955 struct jmploc jmploc;
12956 struct stackmark smark;
12958 /* Initialize global data */
12962 #if ENABLE_ASH_ALIAS
12968 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12971 #if ENABLE_FEATURE_EDITING
12972 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12975 if (setjmp(jmploc.loc)) {
12985 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12989 outcslow('\n', stderr);
12991 popstackmark(&smark);
12992 FORCE_INT_ON; /* enable interrupts */
13001 exception_handler = &jmploc;
13004 trace_puts("Shell args: ");
13005 trace_puts_args(argv);
13007 rootpid = getpid();
13009 #if ENABLE_ASH_RANDOM_SUPPORT
13010 rseed = rootpid + time(NULL);
13013 setstackmark(&smark);
13014 procargs(argc, argv);
13015 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13017 const char *hp = lookupvar("HISTFILE");
13020 hp = lookupvar("HOME");
13022 char *defhp = concat_path_file(hp, ".ash_history");
13023 setvar("HISTFILE", defhp, 0);
13029 if (argv[0] && argv[0][0] == '-')
13033 read_profile("/etc/profile");
13036 read_profile(".profile");
13042 getuid() == geteuid() && getgid() == getegid() &&
13046 shinit = lookupvar("ENV");
13047 if (shinit != NULL && *shinit != '\0') {
13048 read_profile(shinit);
13054 evalstring(minusc, 0);
13056 if (sflag || minusc == NULL) {
13057 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13059 const char *hp = lookupvar("HISTFILE");
13062 line_input_state->hist_file = hp;
13065 state4: /* XXX ??? - why isn't this before the "if" statement */
13073 extern void _mcleanup(void);
13082 const char *applet_name = "debug stuff usage";
13083 int main(int argc, char **argv)
13085 return ash_main(argc, argv);
13091 * Copyright (c) 1989, 1991, 1993, 1994
13092 * The Regents of the University of California. All rights reserved.
13094 * This code is derived from software contributed to Berkeley by
13095 * Kenneth Almquist.
13097 * Redistribution and use in source and binary forms, with or without
13098 * modification, are permitted provided that the following conditions
13100 * 1. Redistributions of source code must retain the above copyright
13101 * notice, this list of conditions and the following disclaimer.
13102 * 2. Redistributions in binary form must reproduce the above copyright
13103 * notice, this list of conditions and the following disclaimer in the
13104 * documentation and/or other materials provided with the distribution.
13105 * 3. Neither the name of the University nor the names of its contributors
13106 * may be used to endorse or promote products derived from this software
13107 * without specific prior written permission.
13109 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13110 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13111 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13112 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13113 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13114 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13115 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13116 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13117 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13118 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF