xref: /netbsd/bin/sh/exec.c (revision 6550d01e)
1 /*	$NetBSD: exec.c,v 1.42 2008/10/16 15:31:05 dholland Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)exec.c	8.4 (Berkeley) 6/8/95";
39 #else
40 __RCSID("$NetBSD: exec.c,v 1.42 2008/10/16 15:31:05 dholland Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/wait.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <errno.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 
53 /*
54  * When commands are first encountered, they are entered in a hash table.
55  * This ensures that a full path search will not have to be done for them
56  * on each invocation.
57  *
58  * We should investigate converting to a linear search, even though that
59  * would make the command name "hash" a misnomer.
60  */
61 
62 #include "shell.h"
63 #include "main.h"
64 #include "nodes.h"
65 #include "parser.h"
66 #include "redir.h"
67 #include "eval.h"
68 #include "exec.h"
69 #include "builtins.h"
70 #include "var.h"
71 #include "options.h"
72 #include "input.h"
73 #include "output.h"
74 #include "syntax.h"
75 #include "memalloc.h"
76 #include "error.h"
77 #include "init.h"
78 #include "mystring.h"
79 #include "show.h"
80 #include "jobs.h"
81 #include "alias.h"
82 
83 
84 #define CMDTABLESIZE 31		/* should be prime */
85 #define ARB 1			/* actual size determined at run time */
86 
87 
88 
89 struct tblentry {
90 	struct tblentry *next;	/* next entry in hash chain */
91 	union param param;	/* definition of builtin function */
92 	short cmdtype;		/* index identifying command */
93 	char rehash;		/* if set, cd done since entry created */
94 	char cmdname[ARB];	/* name of command */
95 };
96 
97 
98 STATIC struct tblentry *cmdtable[CMDTABLESIZE];
99 STATIC int builtinloc = -1;		/* index in path of %builtin, or -1 */
100 int exerrno = 0;			/* Last exec error */
101 
102 
103 STATIC void tryexec(char *, char **, char **, int);
104 STATIC void printentry(struct tblentry *, int);
105 STATIC void clearcmdentry(int);
106 STATIC struct tblentry *cmdlookup(const char *, int);
107 STATIC void delete_cmd_entry(void);
108 
109 #ifndef BSD
110 STATIC void execinterp(char **, char **);
111 #endif
112 
113 
114 extern const char *const parsekwd[];
115 
116 /*
117  * Exec a program.  Never returns.  If you change this routine, you may
118  * have to change the find_command routine as well.
119  */
120 
121 void
122 shellexec(char **argv, char **envp, const char *path, int idx, int vforked)
123 {
124 	char *cmdname;
125 	int e;
126 
127 	if (strchr(argv[0], '/') != NULL) {
128 		tryexec(argv[0], argv, envp, vforked);
129 		e = errno;
130 	} else {
131 		e = ENOENT;
132 		while ((cmdname = padvance(&path, argv[0])) != NULL) {
133 			if (--idx < 0 && pathopt == NULL) {
134 				tryexec(cmdname, argv, envp, vforked);
135 				if (errno != ENOENT && errno != ENOTDIR)
136 					e = errno;
137 			}
138 			stunalloc(cmdname);
139 		}
140 	}
141 
142 	/* Map to POSIX errors */
143 	switch (e) {
144 	case EACCES:
145 		exerrno = 126;
146 		break;
147 	case ENOENT:
148 		exerrno = 127;
149 		break;
150 	default:
151 		exerrno = 2;
152 		break;
153 	}
154 	TRACE(("shellexec failed for %s, errno %d, vforked %d, suppressint %d\n",
155 		argv[0], e, vforked, suppressint ));
156 	exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
157 	/* NOTREACHED */
158 }
159 
160 
161 STATIC void
162 tryexec(char *cmd, char **argv, char **envp, int vforked)
163 {
164 	int e;
165 #ifndef BSD
166 	char *p;
167 #endif
168 
169 #ifdef SYSV
170 	do {
171 		execve(cmd, argv, envp);
172 	} while (errno == EINTR);
173 #else
174 	execve(cmd, argv, envp);
175 #endif
176 	e = errno;
177 	if (e == ENOEXEC) {
178 		if (vforked) {
179 			/* We are currently vfork(2)ed, so raise an
180 			 * exception, and evalcommand will try again
181 			 * with a normal fork(2).
182 			 */
183 			exraise(EXSHELLPROC);
184 		}
185 #ifdef DEBUG
186 		TRACE(("execve(cmd=%s) returned ENOEXEC\n", cmd));
187 #endif
188 		initshellproc();
189 		setinputfile(cmd, 0);
190 		commandname = arg0 = savestr(argv[0]);
191 #ifndef BSD
192 		pgetc(); pungetc();		/* fill up input buffer */
193 		p = parsenextc;
194 		if (parsenleft > 2 && p[0] == '#' && p[1] == '!') {
195 			argv[0] = cmd;
196 			execinterp(argv, envp);
197 		}
198 #endif
199 		setparam(argv + 1);
200 		exraise(EXSHELLPROC);
201 	}
202 	errno = e;
203 }
204 
205 
206 #ifndef BSD
207 /*
208  * Execute an interpreter introduced by "#!", for systems where this
209  * feature has not been built into the kernel.  If the interpreter is
210  * the shell, return (effectively ignoring the "#!").  If the execution
211  * of the interpreter fails, exit.
212  *
213  * This code peeks inside the input buffer in order to avoid actually
214  * reading any input.  It would benefit from a rewrite.
215  */
216 
217 #define NEWARGS 5
218 
219 STATIC void
220 execinterp(char **argv, char **envp)
221 {
222 	int n;
223 	char *inp;
224 	char *outp;
225 	char c;
226 	char *p;
227 	char **ap;
228 	char *newargs[NEWARGS];
229 	int i;
230 	char **ap2;
231 	char **new;
232 
233 	n = parsenleft - 2;
234 	inp = parsenextc + 2;
235 	ap = newargs;
236 	for (;;) {
237 		while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
238 			inp++;
239 		if (n < 0)
240 			goto bad;
241 		if ((c = *inp++) == '\n')
242 			break;
243 		if (ap == &newargs[NEWARGS])
244 bad:		  error("Bad #! line");
245 		STARTSTACKSTR(outp);
246 		do {
247 			STPUTC(c, outp);
248 		} while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
249 		STPUTC('\0', outp);
250 		n++, inp--;
251 		*ap++ = grabstackstr(outp);
252 	}
253 	if (ap == newargs + 1) {	/* if no args, maybe no exec is needed */
254 		p = newargs[0];
255 		for (;;) {
256 			if (equal(p, "sh") || equal(p, "ash")) {
257 				return;
258 			}
259 			while (*p != '/') {
260 				if (*p == '\0')
261 					goto break2;
262 				p++;
263 			}
264 			p++;
265 		}
266 break2:;
267 	}
268 	i = (char *)ap - (char *)newargs;		/* size in bytes */
269 	if (i == 0)
270 		error("Bad #! line");
271 	for (ap2 = argv ; *ap2++ != NULL ; );
272 	new = ckmalloc(i + ((char *)ap2 - (char *)argv));
273 	ap = newargs, ap2 = new;
274 	while ((i -= sizeof (char **)) >= 0)
275 		*ap2++ = *ap++;
276 	ap = argv;
277 	while (*ap2++ = *ap++);
278 	shellexec(new, envp, pathval(), 0);
279 	/* NOTREACHED */
280 }
281 #endif
282 
283 
284 
285 /*
286  * Do a path search.  The variable path (passed by reference) should be
287  * set to the start of the path before the first call; padvance will update
288  * this value as it proceeds.  Successive calls to padvance will return
289  * the possible path expansions in sequence.  If an option (indicated by
290  * a percent sign) appears in the path entry then the global variable
291  * pathopt will be set to point to it; otherwise pathopt will be set to
292  * NULL.
293  */
294 
295 const char *pathopt;
296 
297 char *
298 padvance(const char **path, const char *name)
299 {
300 	const char *p;
301 	char *q;
302 	const char *start;
303 	int len;
304 
305 	if (*path == NULL)
306 		return NULL;
307 	start = *path;
308 	for (p = start ; *p && *p != ':' && *p != '%' ; p++);
309 	len = p - start + strlen(name) + 2;	/* "2" is for '/' and '\0' */
310 	while (stackblocksize() < len)
311 		growstackblock();
312 	q = stackblock();
313 	if (p != start) {
314 		memcpy(q, start, p - start);
315 		q += p - start;
316 		*q++ = '/';
317 	}
318 	strcpy(q, name);
319 	pathopt = NULL;
320 	if (*p == '%') {
321 		pathopt = ++p;
322 		while (*p && *p != ':')  p++;
323 	}
324 	if (*p == ':')
325 		*path = p + 1;
326 	else
327 		*path = NULL;
328 	return stalloc(len);
329 }
330 
331 
332 
333 /*** Command hashing code ***/
334 
335 
336 int
337 hashcmd(int argc, char **argv)
338 {
339 	struct tblentry **pp;
340 	struct tblentry *cmdp;
341 	int c;
342 	int verbose;
343 	struct cmdentry entry;
344 	char *name;
345 
346 	verbose = 0;
347 	while ((c = nextopt("rv")) != '\0') {
348 		if (c == 'r') {
349 			clearcmdentry(0);
350 		} else if (c == 'v') {
351 			verbose++;
352 		}
353 	}
354 	if (*argptr == NULL) {
355 		for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
356 			for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
357 				if (verbose || cmdp->cmdtype == CMDNORMAL)
358 					printentry(cmdp, verbose);
359 			}
360 		}
361 		return 0;
362 	}
363 	while ((name = *argptr) != NULL) {
364 		if ((cmdp = cmdlookup(name, 0)) != NULL
365 		 && (cmdp->cmdtype == CMDNORMAL
366 		     || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
367 			delete_cmd_entry();
368 		find_command(name, &entry, DO_ERR, pathval());
369 		if (verbose) {
370 			if (entry.cmdtype != CMDUNKNOWN) {	/* if no error msg */
371 				cmdp = cmdlookup(name, 0);
372 				if (cmdp != NULL)
373 					printentry(cmdp, verbose);
374 			}
375 			flushall();
376 		}
377 		argptr++;
378 	}
379 	return 0;
380 }
381 
382 
383 STATIC void
384 printentry(struct tblentry *cmdp, int verbose)
385 {
386 	int idx;
387 	const char *path;
388 	char *name;
389 
390 	switch (cmdp->cmdtype) {
391 	case CMDNORMAL:
392 		idx = cmdp->param.index;
393 		path = pathval();
394 		do {
395 			name = padvance(&path, cmdp->cmdname);
396 			stunalloc(name);
397 		} while (--idx >= 0);
398 		out1str(name);
399 		break;
400 	case CMDSPLBLTIN:
401 		out1fmt("special builtin %s", cmdp->cmdname);
402 		break;
403 	case CMDBUILTIN:
404 		out1fmt("builtin %s", cmdp->cmdname);
405 		break;
406 	case CMDFUNCTION:
407 		out1fmt("function %s", cmdp->cmdname);
408 		if (verbose) {
409 			struct procstat ps;
410 			INTOFF;
411 			commandtext(&ps, cmdp->param.func);
412 			INTON;
413 			out1str("() { ");
414 			out1str(ps.cmd);
415 			out1str("; }");
416 		}
417 		break;
418 	default:
419 		error("internal error: %s cmdtype %d", cmdp->cmdname, cmdp->cmdtype);
420 	}
421 	if (cmdp->rehash)
422 		out1c('*');
423 	out1c('\n');
424 }
425 
426 
427 
428 /*
429  * Resolve a command name.  If you change this routine, you may have to
430  * change the shellexec routine as well.
431  */
432 
433 void
434 find_command(char *name, struct cmdentry *entry, int act, const char *path)
435 {
436 	struct tblentry *cmdp, loc_cmd;
437 	int idx;
438 	int prev;
439 	char *fullname;
440 	struct stat statb;
441 	int e;
442 	int (*bltin)(int,char **);
443 
444 	/* If name contains a slash, don't use PATH or hash table */
445 	if (strchr(name, '/') != NULL) {
446 		if (act & DO_ABS) {
447 			while (stat(name, &statb) < 0) {
448 #ifdef SYSV
449 				if (errno == EINTR)
450 					continue;
451 #endif
452 				if (errno != ENOENT && errno != ENOTDIR)
453 					e = errno;
454 				entry->cmdtype = CMDUNKNOWN;
455 				entry->u.index = -1;
456 				return;
457 			}
458 			entry->cmdtype = CMDNORMAL;
459 			entry->u.index = -1;
460 			return;
461 		}
462 		entry->cmdtype = CMDNORMAL;
463 		entry->u.index = 0;
464 		return;
465 	}
466 
467 	if (path != pathval())
468 		act |= DO_ALTPATH;
469 
470 	if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
471 		act |= DO_ALTBLTIN;
472 
473 	/* If name is in the table, check answer will be ok */
474 	if ((cmdp = cmdlookup(name, 0)) != NULL) {
475 		do {
476 			switch (cmdp->cmdtype) {
477 			case CMDNORMAL:
478 				if (act & DO_ALTPATH) {
479 					cmdp = NULL;
480 					continue;
481 				}
482 				break;
483 			case CMDFUNCTION:
484 				if (act & DO_NOFUNC) {
485 					cmdp = NULL;
486 					continue;
487 				}
488 				break;
489 			case CMDBUILTIN:
490 				if ((act & DO_ALTBLTIN) || builtinloc >= 0) {
491 					cmdp = NULL;
492 					continue;
493 				}
494 				break;
495 			}
496 			/* if not invalidated by cd, we're done */
497 			if (cmdp->rehash == 0)
498 				goto success;
499 		} while (0);
500 	}
501 
502 	/* If %builtin not in path, check for builtin next */
503 	if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc < 0) &&
504 	    (bltin = find_builtin(name)) != 0)
505 		goto builtin_success;
506 
507 	/* We have to search path. */
508 	prev = -1;		/* where to start */
509 	if (cmdp) {		/* doing a rehash */
510 		if (cmdp->cmdtype == CMDBUILTIN)
511 			prev = builtinloc;
512 		else
513 			prev = cmdp->param.index;
514 	}
515 
516 	e = ENOENT;
517 	idx = -1;
518 loop:
519 	while ((fullname = padvance(&path, name)) != NULL) {
520 		stunalloc(fullname);
521 		idx++;
522 		if (pathopt) {
523 			if (prefix("builtin", pathopt)) {
524 				if ((bltin = find_builtin(name)) == 0)
525 					goto loop;
526 				goto builtin_success;
527 			} else if (prefix("func", pathopt)) {
528 				/* handled below */
529 			} else {
530 				/* ignore unimplemented options */
531 				goto loop;
532 			}
533 		}
534 		/* if rehash, don't redo absolute path names */
535 		if (fullname[0] == '/' && idx <= prev) {
536 			if (idx < prev)
537 				goto loop;
538 			TRACE(("searchexec \"%s\": no change\n", name));
539 			goto success;
540 		}
541 		while (stat(fullname, &statb) < 0) {
542 #ifdef SYSV
543 			if (errno == EINTR)
544 				continue;
545 #endif
546 			if (errno != ENOENT && errno != ENOTDIR)
547 				e = errno;
548 			goto loop;
549 		}
550 		e = EACCES;	/* if we fail, this will be the error */
551 		if (!S_ISREG(statb.st_mode))
552 			goto loop;
553 		if (pathopt) {		/* this is a %func directory */
554 			if (act & DO_NOFUNC)
555 				goto loop;
556 			stalloc(strlen(fullname) + 1);
557 			readcmdfile(fullname);
558 			if ((cmdp = cmdlookup(name, 0)) == NULL ||
559 			    cmdp->cmdtype != CMDFUNCTION)
560 				error("%s not defined in %s", name, fullname);
561 			stunalloc(fullname);
562 			goto success;
563 		}
564 #ifdef notdef
565 		/* XXX this code stops root executing stuff, and is buggy
566 		   if you need a group from the group list. */
567 		if (statb.st_uid == geteuid()) {
568 			if ((statb.st_mode & 0100) == 0)
569 				goto loop;
570 		} else if (statb.st_gid == getegid()) {
571 			if ((statb.st_mode & 010) == 0)
572 				goto loop;
573 		} else {
574 			if ((statb.st_mode & 01) == 0)
575 				goto loop;
576 		}
577 #endif
578 		TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
579 		INTOFF;
580 		if (act & DO_ALTPATH) {
581 			stalloc(strlen(fullname) + 1);
582 			cmdp = &loc_cmd;
583 		} else
584 			cmdp = cmdlookup(name, 1);
585 		cmdp->cmdtype = CMDNORMAL;
586 		cmdp->param.index = idx;
587 		INTON;
588 		goto success;
589 	}
590 
591 	/* We failed.  If there was an entry for this command, delete it */
592 	if (cmdp)
593 		delete_cmd_entry();
594 	if (act & DO_ERR)
595 		outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
596 	entry->cmdtype = CMDUNKNOWN;
597 	return;
598 
599 builtin_success:
600 	INTOFF;
601 	if (act & DO_ALTPATH)
602 		cmdp = &loc_cmd;
603 	else
604 		cmdp = cmdlookup(name, 1);
605 	if (cmdp->cmdtype == CMDFUNCTION)
606 		/* DO_NOFUNC must have been set */
607 		cmdp = &loc_cmd;
608 	cmdp->cmdtype = CMDBUILTIN;
609 	cmdp->param.bltin = bltin;
610 	INTON;
611 success:
612 	if (cmdp) {
613 		cmdp->rehash = 0;
614 		entry->cmdtype = cmdp->cmdtype;
615 		entry->u = cmdp->param;
616 	} else
617 		entry->cmdtype = CMDUNKNOWN;
618 }
619 
620 
621 
622 /*
623  * Search the table of builtin commands.
624  */
625 
626 int
627 (*find_builtin(name))(int, char **)
628 	char *name;
629 {
630 	const struct builtincmd *bp;
631 
632 	for (bp = builtincmd ; bp->name ; bp++) {
633 		if (*bp->name == *name && equal(bp->name, name))
634 			return bp->builtin;
635 	}
636 	return 0;
637 }
638 
639 int
640 (*find_splbltin(name))(int, char **)
641 	char *name;
642 {
643 	const struct builtincmd *bp;
644 
645 	for (bp = splbltincmd ; bp->name ; bp++) {
646 		if (*bp->name == *name && equal(bp->name, name))
647 			return bp->builtin;
648 	}
649 	return 0;
650 }
651 
652 /*
653  * At shell startup put special builtins into hash table.
654  * ensures they are executed first (see posix).
655  * We stop functions being added with the same name
656  * (as they are impossible to call)
657  */
658 
659 void
660 hash_special_builtins(void)
661 {
662 	const struct builtincmd *bp;
663 	struct tblentry *cmdp;
664 
665 	for (bp = splbltincmd ; bp->name ; bp++) {
666 		cmdp = cmdlookup(bp->name, 1);
667 		cmdp->cmdtype = CMDSPLBLTIN;
668 		cmdp->param.bltin = bp->builtin;
669 	}
670 }
671 
672 
673 
674 /*
675  * Called when a cd is done.  Marks all commands so the next time they
676  * are executed they will be rehashed.
677  */
678 
679 void
680 hashcd(void)
681 {
682 	struct tblentry **pp;
683 	struct tblentry *cmdp;
684 
685 	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
686 		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
687 			if (cmdp->cmdtype == CMDNORMAL
688 			 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
689 				cmdp->rehash = 1;
690 		}
691 	}
692 }
693 
694 
695 
696 /*
697  * Fix command hash table when PATH changed.
698  * Called before PATH is changed.  The argument is the new value of PATH;
699  * pathval() still returns the old value at this point.
700  * Called with interrupts off.
701  */
702 
703 void
704 changepath(const char *newval)
705 {
706 	const char *old, *new;
707 	int idx;
708 	int firstchange;
709 	int bltin;
710 
711 	old = pathval();
712 	new = newval;
713 	firstchange = 9999;	/* assume no change */
714 	idx = 0;
715 	bltin = -1;
716 	for (;;) {
717 		if (*old != *new) {
718 			firstchange = idx;
719 			if ((*old == '\0' && *new == ':')
720 			 || (*old == ':' && *new == '\0'))
721 				firstchange++;
722 			old = new;	/* ignore subsequent differences */
723 		}
724 		if (*new == '\0')
725 			break;
726 		if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
727 			bltin = idx;
728 		if (*new == ':') {
729 			idx++;
730 		}
731 		new++, old++;
732 	}
733 	if (builtinloc < 0 && bltin >= 0)
734 		builtinloc = bltin;		/* zap builtins */
735 	if (builtinloc >= 0 && bltin < 0)
736 		firstchange = 0;
737 	clearcmdentry(firstchange);
738 	builtinloc = bltin;
739 }
740 
741 
742 /*
743  * Clear out command entries.  The argument specifies the first entry in
744  * PATH which has changed.
745  */
746 
747 STATIC void
748 clearcmdentry(int firstchange)
749 {
750 	struct tblentry **tblp;
751 	struct tblentry **pp;
752 	struct tblentry *cmdp;
753 
754 	INTOFF;
755 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
756 		pp = tblp;
757 		while ((cmdp = *pp) != NULL) {
758 			if ((cmdp->cmdtype == CMDNORMAL &&
759 			     cmdp->param.index >= firstchange)
760 			 || (cmdp->cmdtype == CMDBUILTIN &&
761 			     builtinloc >= firstchange)) {
762 				*pp = cmdp->next;
763 				ckfree(cmdp);
764 			} else {
765 				pp = &cmdp->next;
766 			}
767 		}
768 	}
769 	INTON;
770 }
771 
772 
773 /*
774  * Delete all functions.
775  */
776 
777 #ifdef mkinit
778 MKINIT void deletefuncs(void);
779 MKINIT void hash_special_builtins(void);
780 
781 INIT {
782 	hash_special_builtins();
783 }
784 
785 SHELLPROC {
786 	deletefuncs();
787 }
788 #endif
789 
790 void
791 deletefuncs(void)
792 {
793 	struct tblentry **tblp;
794 	struct tblentry **pp;
795 	struct tblentry *cmdp;
796 
797 	INTOFF;
798 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
799 		pp = tblp;
800 		while ((cmdp = *pp) != NULL) {
801 			if (cmdp->cmdtype == CMDFUNCTION) {
802 				*pp = cmdp->next;
803 				freefunc(cmdp->param.func);
804 				ckfree(cmdp);
805 			} else {
806 				pp = &cmdp->next;
807 			}
808 		}
809 	}
810 	INTON;
811 }
812 
813 
814 
815 /*
816  * Locate a command in the command hash table.  If "add" is nonzero,
817  * add the command to the table if it is not already present.  The
818  * variable "lastcmdentry" is set to point to the address of the link
819  * pointing to the entry, so that delete_cmd_entry can delete the
820  * entry.
821  */
822 
823 struct tblentry **lastcmdentry;
824 
825 
826 STATIC struct tblentry *
827 cmdlookup(const char *name, int add)
828 {
829 	int hashval;
830 	const char *p;
831 	struct tblentry *cmdp;
832 	struct tblentry **pp;
833 
834 	p = name;
835 	hashval = *p << 4;
836 	while (*p)
837 		hashval += *p++;
838 	hashval &= 0x7FFF;
839 	pp = &cmdtable[hashval % CMDTABLESIZE];
840 	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
841 		if (equal(cmdp->cmdname, name))
842 			break;
843 		pp = &cmdp->next;
844 	}
845 	if (add && cmdp == NULL) {
846 		INTOFF;
847 		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
848 					+ strlen(name) + 1);
849 		cmdp->next = NULL;
850 		cmdp->cmdtype = CMDUNKNOWN;
851 		cmdp->rehash = 0;
852 		strcpy(cmdp->cmdname, name);
853 		INTON;
854 	}
855 	lastcmdentry = pp;
856 	return cmdp;
857 }
858 
859 /*
860  * Delete the command entry returned on the last lookup.
861  */
862 
863 STATIC void
864 delete_cmd_entry(void)
865 {
866 	struct tblentry *cmdp;
867 
868 	INTOFF;
869 	cmdp = *lastcmdentry;
870 	*lastcmdentry = cmdp->next;
871 	ckfree(cmdp);
872 	INTON;
873 }
874 
875 
876 
877 #ifdef notdef
878 void
879 getcmdentry(char *name, struct cmdentry *entry)
880 {
881 	struct tblentry *cmdp = cmdlookup(name, 0);
882 
883 	if (cmdp) {
884 		entry->u = cmdp->param;
885 		entry->cmdtype = cmdp->cmdtype;
886 	} else {
887 		entry->cmdtype = CMDUNKNOWN;
888 		entry->u.index = 0;
889 	}
890 }
891 #endif
892 
893 
894 /*
895  * Add a new command entry, replacing any existing command entry for
896  * the same name - except special builtins.
897  */
898 
899 STATIC void
900 addcmdentry(char *name, struct cmdentry *entry)
901 {
902 	struct tblentry *cmdp;
903 
904 	INTOFF;
905 	cmdp = cmdlookup(name, 1);
906 	if (cmdp->cmdtype != CMDSPLBLTIN) {
907 		if (cmdp->cmdtype == CMDFUNCTION) {
908 			freefunc(cmdp->param.func);
909 		}
910 		cmdp->cmdtype = entry->cmdtype;
911 		cmdp->param = entry->u;
912 	}
913 	INTON;
914 }
915 
916 
917 /*
918  * Define a shell function.
919  */
920 
921 void
922 defun(char *name, union node *func)
923 {
924 	struct cmdentry entry;
925 
926 	INTOFF;
927 	entry.cmdtype = CMDFUNCTION;
928 	entry.u.func = copyfunc(func);
929 	addcmdentry(name, &entry);
930 	INTON;
931 }
932 
933 
934 /*
935  * Delete a function if it exists.
936  */
937 
938 int
939 unsetfunc(char *name)
940 {
941 	struct tblentry *cmdp;
942 
943 	if ((cmdp = cmdlookup(name, 0)) != NULL &&
944 	    cmdp->cmdtype == CMDFUNCTION) {
945 		freefunc(cmdp->param.func);
946 		delete_cmd_entry();
947 		return (0);
948 	}
949 	return (1);
950 }
951 
952 /*
953  * Locate and print what a word is...
954  * also used for 'command -[v|V]'
955  */
956 
957 int
958 typecmd(int argc, char **argv)
959 {
960 	struct cmdentry entry;
961 	struct tblentry *cmdp;
962 	const char * const *pp;
963 	struct alias *ap;
964 	int err = 0;
965 	char *arg;
966 	int c;
967 	int V_flag = 0;
968 	int v_flag = 0;
969 	int p_flag = 0;
970 
971 	while ((c = nextopt("vVp")) != 0) {
972 		switch (c) {
973 		case 'v': v_flag = 1; break;
974 		case 'V': V_flag = 1; break;
975 		case 'p': p_flag = 1; break;
976 		}
977 	}
978 
979 	if (p_flag && (v_flag || V_flag))
980 		error("cannot specify -p with -v or -V");
981 
982 	while ((arg = *argptr++)) {
983 		if (!v_flag)
984 			out1str(arg);
985 		/* First look at the keywords */
986 		for (pp = parsekwd; *pp; pp++)
987 			if (**pp == *arg && equal(*pp, arg))
988 				break;
989 
990 		if (*pp) {
991 			if (v_flag)
992 				err = 1;
993 			else
994 				out1str(" is a shell keyword\n");
995 			continue;
996 		}
997 
998 		/* Then look at the aliases */
999 		if ((ap = lookupalias(arg, 1)) != NULL) {
1000 			if (!v_flag)
1001 				out1fmt(" is an alias for \n");
1002 			out1fmt("%s\n", ap->val);
1003 			continue;
1004 		}
1005 
1006 		/* Then check if it is a tracked alias */
1007 		if ((cmdp = cmdlookup(arg, 0)) != NULL) {
1008 			entry.cmdtype = cmdp->cmdtype;
1009 			entry.u = cmdp->param;
1010 		} else {
1011 			/* Finally use brute force */
1012 			find_command(arg, &entry, DO_ABS, pathval());
1013 		}
1014 
1015 		switch (entry.cmdtype) {
1016 		case CMDNORMAL: {
1017 			if (strchr(arg, '/') == NULL) {
1018 				const char *path = pathval();
1019 				char *name;
1020 				int j = entry.u.index;
1021 				do {
1022 					name = padvance(&path, arg);
1023 					stunalloc(name);
1024 				} while (--j >= 0);
1025 				if (!v_flag)
1026 					out1fmt(" is%s ",
1027 					    cmdp ? " a tracked alias for" : "");
1028 				out1fmt("%s\n", name);
1029 			} else {
1030 				if (access(arg, X_OK) == 0) {
1031 					if (!v_flag)
1032 						out1fmt(" is ");
1033 					out1fmt("%s\n", arg);
1034 				} else {
1035 					if (!v_flag)
1036 						out1fmt(": %s\n",
1037 						    strerror(errno));
1038 					else
1039 						err = 126;
1040 				}
1041 			}
1042  			break;
1043 		}
1044 		case CMDFUNCTION:
1045 			if (!v_flag)
1046 				out1str(" is a shell function\n");
1047 			else
1048 				out1fmt("%s\n", arg);
1049 			break;
1050 
1051 		case CMDBUILTIN:
1052 			if (!v_flag)
1053 				out1str(" is a shell builtin\n");
1054 			else
1055 				out1fmt("%s\n", arg);
1056 			break;
1057 
1058 		case CMDSPLBLTIN:
1059 			if (!v_flag)
1060 				out1str(" is a special shell builtin\n");
1061 			else
1062 				out1fmt("%s\n", arg);
1063 			break;
1064 
1065 		default:
1066 			if (!v_flag)
1067 				out1str(": not found\n");
1068 			err = 127;
1069 			break;
1070 		}
1071 	}
1072 	return err;
1073 }
1074