xref: /netbsd-src/bin/sh/exec.c (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 /*	$NetBSD: exec.c,v 1.55 2021/02/16 15:30:12 kre 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.55 2021/02/16 15:30:12 kre 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 fn_ln1;		/* for functions, LINENO from 1 */
95 	int lineno;		/* for functions abs LINENO of definition */
96 	char cmdname[ARB];	/* name of command */
97 };
98 
99 
100 STATIC struct tblentry *cmdtable[CMDTABLESIZE];
101 STATIC int builtinloc = -1;		/* index in path of %builtin, or -1 */
102 int exerrno = 0;			/* Last exec error */
103 
104 
105 STATIC void tryexec(char *, char **, char **, int);
106 STATIC void printentry(struct tblentry *, int);
107 STATIC void addcmdentry(char *, struct cmdentry *);
108 STATIC void clearcmdentry(int);
109 STATIC struct tblentry *cmdlookup(const char *, int);
110 STATIC void delete_cmd_entry(void);
111 
112 #ifndef BSD
113 STATIC void execinterp(char **, char **);
114 #endif
115 
116 
117 extern const char *const parsekwd[];
118 
119 /*
120  * Exec a program.  Never returns.  If you change this routine, you may
121  * have to change the find_command routine as well.
122  */
123 
124 void
125 shellexec(char **argv, char **envp, const char *path, int idx, int vforked)
126 {
127 	char *cmdname;
128 	int e;
129 
130 	if (strchr(argv[0], '/') != NULL) {
131 		tryexec(argv[0], argv, envp, vforked);
132 		e = errno;
133 	} else {
134 		e = ENOENT;
135 		while ((cmdname = padvance(&path, argv[0], 1)) != NULL) {
136 			if (--idx < 0 && pathopt == NULL) {
137 				tryexec(cmdname, argv, envp, vforked);
138 				if (errno != ENOENT && errno != ENOTDIR)
139 					e = errno;
140 			}
141 			stunalloc(cmdname);
142 		}
143 	}
144 
145 	/* Map to POSIX errors */
146 	switch (e) {
147 	case EACCES:	/* particularly this (unless no search perm) */
148 		/*
149 		 * should perhaps check if this EACCES is an exec()
150 		 * EACESS or a namei() EACESS - the latter should be 127
151 		 * - but not today
152 		 */
153 	case EINVAL:	/* also explicitly these */
154 	case ENOEXEC:
155 	default:	/* and anything else */
156 		exerrno = 126;
157 		break;
158 
159 	case ENOENT:	/* these are the "pathname lookup failed" errors */
160 	case ELOOP:
161 	case ENOTDIR:
162 	case ENAMETOOLONG:
163 		exerrno = 127;
164 		break;
165 	}
166 	CTRACE(DBG_ERRS|DBG_CMDS|DBG_EVAL,
167 	    ("shellexec failed for %s, errno %d, vforked %d, suppressint %d\n",
168 		argv[0], e, vforked, suppressint));
169 	exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
170 	/* NOTREACHED */
171 }
172 
173 
174 STATIC void
175 tryexec(char *cmd, char **argv, char **envp, int vforked)
176 {
177 	int e;
178 #ifndef BSD
179 	char *p;
180 #endif
181 
182 #ifdef SYSV
183 	do {
184 		execve(cmd, argv, envp);
185 	} while (errno == EINTR);
186 #else
187 	execve(cmd, argv, envp);
188 #endif
189 	e = errno;
190 	if (e == ENOEXEC) {
191 		if (vforked) {
192 			/* We are currently vfork(2)ed, so raise an
193 			 * exception, and evalcommand will try again
194 			 * with a normal fork(2).
195 			 */
196 			exraise(EXSHELLPROC);
197 		}
198 #ifdef DEBUG
199 		VTRACE(DBG_CMDS, ("execve(cmd=%s) returned ENOEXEC\n", cmd));
200 #endif
201 		initshellproc();
202 		setinputfile(cmd, 0);
203 		commandname = arg0 = savestr(argv[0]);
204 #ifndef BSD
205 		pgetc(); pungetc();		/* fill up input buffer */
206 		p = parsenextc;
207 		if (parsenleft > 2 && p[0] == '#' && p[1] == '!') {
208 			argv[0] = cmd;
209 			execinterp(argv, envp);
210 		}
211 #endif
212 		setparam(argv + 1);
213 		exraise(EXSHELLPROC);
214 	}
215 	errno = e;
216 }
217 
218 
219 #ifndef BSD
220 /*
221  * Execute an interpreter introduced by "#!", for systems where this
222  * feature has not been built into the kernel.  If the interpreter is
223  * the shell, return (effectively ignoring the "#!").  If the execution
224  * of the interpreter fails, exit.
225  *
226  * This code peeks inside the input buffer in order to avoid actually
227  * reading any input.  It would benefit from a rewrite.
228  */
229 
230 #define NEWARGS 5
231 
232 STATIC void
233 execinterp(char **argv, char **envp)
234 {
235 	int n;
236 	char *inp;
237 	char *outp;
238 	char c;
239 	char *p;
240 	char **ap;
241 	char *newargs[NEWARGS];
242 	int i;
243 	char **ap2;
244 	char **new;
245 
246 	n = parsenleft - 2;
247 	inp = parsenextc + 2;
248 	ap = newargs;
249 	for (;;) {
250 		while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
251 			inp++;
252 		if (n < 0)
253 			goto bad;
254 		if ((c = *inp++) == '\n')
255 			break;
256 		if (ap == &newargs[NEWARGS])
257 bad:		  error("Bad #! line");
258 		STARTSTACKSTR(outp);
259 		do {
260 			STPUTC(c, outp);
261 		} while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
262 		STPUTC('\0', outp);
263 		n++, inp--;
264 		*ap++ = grabstackstr(outp);
265 	}
266 	if (ap == newargs + 1) {	/* if no args, maybe no exec is needed */
267 		p = newargs[0];
268 		for (;;) {
269 			if (equal(p, "sh") || equal(p, "ash")) {
270 				return;
271 			}
272 			while (*p != '/') {
273 				if (*p == '\0')
274 					goto break2;
275 				p++;
276 			}
277 			p++;
278 		}
279 break2:;
280 	}
281 	i = (char *)ap - (char *)newargs;		/* size in bytes */
282 	if (i == 0)
283 		error("Bad #! line");
284 	for (ap2 = argv ; *ap2++ != NULL ; );
285 	new = ckmalloc(i + ((char *)ap2 - (char *)argv));
286 	ap = newargs, ap2 = new;
287 	while ((i -= sizeof (char **)) >= 0)
288 		*ap2++ = *ap++;
289 	ap = argv;
290 	while (*ap2++ = *ap++);
291 	shellexec(new, envp, pathval(), 0);
292 	/* NOTREACHED */
293 }
294 #endif
295 
296 
297 
298 /*
299  * Do a path search.  The variable path (passed by reference) should be
300  * set to the start of the path before the first call; padvance will update
301  * this value as it proceeds.  Successive calls to padvance will return
302  * the possible path expansions in sequence.  If an option (indicated by
303  * a percent sign) appears in the path entry then the global variable
304  * pathopt will be set to point to it; otherwise pathopt will be set to
305  * NULL.
306  */
307 
308 const char *pathopt;
309 
310 char *
311 padvance(const char **path, const char *name, int magic_percent)
312 {
313 	const char *p;
314 	char *q;
315 	const char *start;
316 	int len;
317 
318 	if (*path == NULL)
319 		return NULL;
320 	if (magic_percent)
321 		magic_percent = '%';
322 
323 	start = *path;
324 	for (p = start ; *p && *p != ':' && *p != magic_percent ; p++)
325 		;
326 	len = p - start + strlen(name) + 2;	/* "2" is for '/' and '\0' */
327 	while (stackblocksize() < len)
328 		growstackblock();
329 	q = stackblock();
330 	if (p != start) {
331 		memcpy(q, start, p - start);
332 		q += p - start;
333 		if (q[-1] != '/')
334 			*q++ = '/';
335 	}
336 	strcpy(q, name);
337 	pathopt = NULL;
338 	if (*p == magic_percent) {
339 		pathopt = ++p;
340 		while (*p && *p != ':')
341 			p++;
342 	}
343 	if (*p == ':')
344 		*path = p + 1;
345 	else
346 		*path = NULL;
347 	return grabstackstr(q + strlen(name) + 1);
348 }
349 
350 
351 /*** Command hashing code ***/
352 
353 
354 int
355 hashcmd(int argc, char **argv)
356 {
357 	struct tblentry **pp;
358 	struct tblentry *cmdp;
359 	int c;
360 	struct cmdentry entry;
361 	char *name;
362 	int allopt=0, bopt=0, fopt=0, ropt=0, sopt=0, uopt=0, verbose=0;
363 
364 	while ((c = nextopt("bcfrsuv")) != '\0')
365 		switch (c) {
366 		case 'b':	bopt = 1;	break;
367 		case 'c':	uopt = 1;	break;	/* c == u */
368 		case 'f':	fopt = 1;	break;
369 		case 'r':	ropt = 1;	break;
370 		case 's':	sopt = 1;	break;
371 		case 'u':	uopt = 1;	break;
372 		case 'v':	verbose = 1;	break;
373 		}
374 
375 	if (ropt)
376 		clearcmdentry(0);
377 
378 	if (bopt == 0 && fopt == 0 && sopt == 0 && uopt == 0)
379 		allopt = bopt = fopt = sopt = uopt = 1;
380 
381 	if (*argptr == NULL) {
382 		for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
383 			for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
384 				switch (cmdp->cmdtype) {
385 				case CMDNORMAL:
386 					if (!uopt)
387 						continue;
388 					break;
389 				case CMDBUILTIN:
390 					if (!bopt)
391 						continue;
392 					break;
393 				case CMDSPLBLTIN:
394 					if (!sopt)
395 						continue;
396 					break;
397 				case CMDFUNCTION:
398 					if (!fopt)
399 						continue;
400 					break;
401 				default:	/* never happens */
402 					continue;
403 				}
404 				if (!allopt || verbose ||
405 				    cmdp->cmdtype == CMDNORMAL)
406 					printentry(cmdp, verbose);
407 			}
408 		}
409 		return 0;
410 	}
411 
412 	while ((name = *argptr++) != NULL) {
413 		if ((cmdp = cmdlookup(name, 0)) != NULL) {
414 			switch (cmdp->cmdtype) {
415 			case CMDNORMAL:
416 				if (!uopt)
417 					continue;
418 				delete_cmd_entry();
419 				break;
420 			case CMDBUILTIN:
421 				if (!bopt)
422 					continue;
423 				if (builtinloc >= 0)
424 					delete_cmd_entry();
425 				break;
426 			case CMDSPLBLTIN:
427 				if (!sopt)
428 					continue;
429 				break;
430 			case CMDFUNCTION:
431 				if (!fopt)
432 					continue;
433 				break;
434 			}
435 		}
436 		find_command(name, &entry, DO_ERR, pathval());
437 		if (verbose) {
438 			if (entry.cmdtype != CMDUNKNOWN) {	/* if no error msg */
439 				cmdp = cmdlookup(name, 0);
440 				if (cmdp != NULL)
441 					printentry(cmdp, verbose);
442 			}
443 			flushall();
444 		}
445 	}
446 	return 0;
447 }
448 
449 STATIC void
450 printentry(struct tblentry *cmdp, int verbose)
451 {
452 	int idx;
453 	const char *path;
454 	char *name;
455 
456 	switch (cmdp->cmdtype) {
457 	case CMDNORMAL:
458 		idx = cmdp->param.index;
459 		path = pathval();
460 		do {
461 			name = padvance(&path, cmdp->cmdname, 1);
462 			stunalloc(name);
463 		} while (--idx >= 0);
464 		if (verbose)
465 			out1fmt("Command from PATH[%d]: ",
466 			    cmdp->param.index);
467 		out1str(name);
468 		break;
469 	case CMDSPLBLTIN:
470 		if (verbose)
471 			out1str("special ");
472 		/* FALLTHROUGH */
473 	case CMDBUILTIN:
474 		if (verbose)
475 			out1str("builtin ");
476 		out1fmt("%s", cmdp->cmdname);
477 		break;
478 	case CMDFUNCTION:
479 		if (verbose)
480 			out1str("function ");
481 		out1fmt("%s", cmdp->cmdname);
482 		if (verbose) {
483 			struct procstat ps;
484 
485 			INTOFF;
486 			commandtext(&ps, getfuncnode(cmdp->param.func));
487 			INTON;
488 			out1str("() { ");
489 			out1str(ps.cmd);
490 			out1str("; }");
491 		}
492 		break;
493 	default:
494 		error("internal error: %s cmdtype %d",
495 		    cmdp->cmdname, cmdp->cmdtype);
496 	}
497 	if (cmdp->rehash)
498 		out1c('*');
499 	out1c('\n');
500 }
501 
502 
503 
504 /*
505  * Resolve a command name.  If you change this routine, you may have to
506  * change the shellexec routine as well.
507  */
508 
509 void
510 find_command(char *name, struct cmdentry *entry, int act, const char *path)
511 {
512 	struct tblentry *cmdp, loc_cmd;
513 	int idx;
514 	int prev;
515 	char *fullname;
516 	struct stat statb;
517 	int e;
518 	int (*bltin)(int,char **);
519 
520 	/* If name contains a slash, don't use PATH or hash table */
521 	if (strchr(name, '/') != NULL) {
522 		if (act & DO_ABS) {
523 			while (stat(name, &statb) < 0) {
524 #ifdef SYSV
525 				if (errno == EINTR)
526 					continue;
527 #endif
528 				if (errno != ENOENT && errno != ENOTDIR)
529 					e = errno;
530 				entry->cmdtype = CMDUNKNOWN;
531 				entry->u.index = -1;
532 				return;
533 			}
534 			entry->cmdtype = CMDNORMAL;
535 			entry->u.index = -1;
536 			return;
537 		}
538 		entry->cmdtype = CMDNORMAL;
539 		entry->u.index = 0;
540 		return;
541 	}
542 
543 	if (path != pathval())
544 		act |= DO_ALTPATH;
545 
546 	if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
547 		act |= DO_ALTBLTIN;
548 
549 	/* If name is in the table, check answer will be ok */
550 	if ((cmdp = cmdlookup(name, 0)) != NULL) {
551 		do {
552 			switch (cmdp->cmdtype) {
553 			case CMDNORMAL:
554 				if (act & DO_ALTPATH) {
555 					cmdp = NULL;
556 					continue;
557 				}
558 				break;
559 			case CMDFUNCTION:
560 				if (act & DO_NOFUNC) {
561 					cmdp = NULL;
562 					continue;
563 				}
564 				break;
565 			case CMDBUILTIN:
566 				if ((act & DO_ALTBLTIN) || builtinloc >= 0) {
567 					cmdp = NULL;
568 					continue;
569 				}
570 				break;
571 			}
572 			/* if not invalidated by cd, we're done */
573 			if (cmdp->rehash == 0)
574 				goto success;
575 		} while (0);
576 	}
577 
578 	/* If %builtin not in path, check for builtin next */
579 	if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc < 0) &&
580 	    (bltin = find_builtin(name)) != 0)
581 		goto builtin_success;
582 
583 	/* We have to search path. */
584 	prev = -1;		/* where to start */
585 	if (cmdp) {		/* doing a rehash */
586 		if (cmdp->cmdtype == CMDBUILTIN)
587 			prev = builtinloc;
588 		else
589 			prev = cmdp->param.index;
590 	}
591 
592 	e = ENOENT;
593 	idx = -1;
594 loop:
595 	while ((fullname = padvance(&path, name, 1)) != NULL) {
596 		stunalloc(fullname);
597 		idx++;
598 		if (pathopt) {
599 			if (prefix("builtin", pathopt)) {
600 				if ((bltin = find_builtin(name)) == 0)
601 					goto loop;
602 				goto builtin_success;
603 			} else if (prefix("func", pathopt)) {
604 				/* handled below */
605 			} else {
606 				/* ignore unimplemented options */
607 				goto loop;
608 			}
609 		}
610 		/* if rehash, don't redo absolute path names */
611 		if (fullname[0] == '/' && idx <= prev) {
612 			if (idx < prev)
613 				goto loop;
614 			VTRACE(DBG_CMDS, ("searchexec \"%s\": no change\n",
615 			    name));
616 			goto success;
617 		}
618 		while (stat(fullname, &statb) < 0) {
619 #ifdef SYSV
620 			if (errno == EINTR)
621 				continue;
622 #endif
623 			if (errno != ENOENT && errno != ENOTDIR)
624 				e = errno;
625 			goto loop;
626 		}
627 		e = EACCES;	/* if we fail, this will be the error */
628 		if (!S_ISREG(statb.st_mode))
629 			goto loop;
630 		if (pathopt) {		/* this is a %func directory */
631 			char *endname;
632 
633 			if (act & DO_NOFUNC)
634 				goto loop;
635 			endname = fullname + strlen(fullname) + 1;
636 			grabstackstr(endname);
637 			readcmdfile(fullname);
638 			if ((cmdp = cmdlookup(name, 0)) == NULL ||
639 			    cmdp->cmdtype != CMDFUNCTION)
640 				error("%s not defined in %s", name, fullname);
641 			ungrabstackstr(fullname, endname);
642 			goto success;
643 		}
644 #ifdef notdef
645 		/* XXX this code stops root executing stuff, and is buggy
646 		   if you need a group from the group list. */
647 		if (statb.st_uid == geteuid()) {
648 			if ((statb.st_mode & 0100) == 0)
649 				goto loop;
650 		} else if (statb.st_gid == getegid()) {
651 			if ((statb.st_mode & 010) == 0)
652 				goto loop;
653 		} else {
654 			if ((statb.st_mode & 01) == 0)
655 				goto loop;
656 		}
657 #endif
658 		VTRACE(DBG_CMDS, ("searchexec \"%s\" returns \"%s\"\n", name,
659 		    fullname));
660 		INTOFF;
661 		if (act & DO_ALTPATH) {
662 		/*
663 		 * this should be a grabstackstr() but is not needed:
664 		 * fullname is no longer needed for anything
665 			stalloc(strlen(fullname) + 1);
666 		 */
667 			cmdp = &loc_cmd;
668 		} else
669 			cmdp = cmdlookup(name, 1);
670 
671 		if (cmdp->cmdtype == CMDFUNCTION)
672 			cmdp = &loc_cmd;
673 
674 		cmdp->cmdtype = CMDNORMAL;
675 		cmdp->param.index = idx;
676 		INTON;
677 		goto success;
678 	}
679 
680 	/* We failed.  If there was an entry for this command, delete it */
681 	if (cmdp)
682 		delete_cmd_entry();
683 	if (act & DO_ERR)
684 		outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
685 	entry->cmdtype = CMDUNKNOWN;
686 	entry->u.index = idx + 1;
687 	return;
688 
689 builtin_success:
690 	INTOFF;
691 	if (act & DO_ALTPATH)
692 		cmdp = &loc_cmd;
693 	else
694 		cmdp = cmdlookup(name, 1);
695 	if (cmdp->cmdtype == CMDFUNCTION)
696 		/* DO_NOFUNC must have been set */
697 		cmdp = &loc_cmd;
698 	cmdp->cmdtype = CMDBUILTIN;
699 	cmdp->param.bltin = bltin;
700 	INTON;
701 success:
702 	if (cmdp) {
703 		cmdp->rehash = 0;
704 		entry->cmdtype = cmdp->cmdtype;
705 		entry->lineno = cmdp->lineno;
706 		entry->lno_frel = cmdp->fn_ln1;
707 		entry->u = cmdp->param;
708 	} else {
709 		entry->cmdtype = CMDUNKNOWN;
710 		entry->u.index = -1;
711 	}
712 }
713 
714 
715 
716 /*
717  * Search the table of builtin commands.
718  */
719 
720 int
721 (*find_builtin(char *name))(int, char **)
722 {
723 	const struct builtincmd *bp;
724 
725 	for (bp = builtincmd ; bp->name ; bp++) {
726 		if (*bp->name == *name
727 		    && (*name == '%' || equal(bp->name, name)))
728 			return bp->builtin;
729 	}
730 	return 0;
731 }
732 
733 int
734 (*find_splbltin(char *name))(int, char **)
735 {
736 	const struct builtincmd *bp;
737 
738 	for (bp = splbltincmd ; bp->name ; bp++) {
739 		if (*bp->name == *name && equal(bp->name, name))
740 			return bp->builtin;
741 	}
742 	return 0;
743 }
744 
745 /*
746  * At shell startup put special builtins into hash table.
747  * ensures they are executed first (see posix).
748  * We stop functions being added with the same name
749  * (as they are impossible to call)
750  */
751 
752 void
753 hash_special_builtins(void)
754 {
755 	const struct builtincmd *bp;
756 	struct tblentry *cmdp;
757 
758 	for (bp = splbltincmd ; bp->name ; bp++) {
759 		cmdp = cmdlookup(bp->name, 1);
760 		cmdp->cmdtype = CMDSPLBLTIN;
761 		cmdp->param.bltin = bp->builtin;
762 	}
763 }
764 
765 
766 
767 /*
768  * Called when a cd is done.  Marks all commands so the next time they
769  * are executed they will be rehashed.
770  */
771 
772 void
773 hashcd(void)
774 {
775 	struct tblentry **pp;
776 	struct tblentry *cmdp;
777 
778 	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
779 		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
780 			if (cmdp->cmdtype == CMDNORMAL
781 			 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
782 				cmdp->rehash = 1;
783 		}
784 	}
785 }
786 
787 
788 
789 /*
790  * Fix command hash table when PATH changed.
791  * Called before PATH is changed.  The argument is the new value of PATH;
792  * pathval() still returns the old value at this point.
793  * Called with interrupts off.
794  */
795 
796 void
797 changepath(const char *newval)
798 {
799 	const char *old, *new;
800 	int idx;
801 	int firstchange;
802 	int bltin;
803 
804 	old = pathval();
805 	new = newval;
806 	firstchange = 9999;	/* assume no change */
807 	idx = 0;
808 	bltin = -1;
809 	for (;;) {
810 		if (*old != *new) {
811 			firstchange = idx;
812 			if ((*old == '\0' && *new == ':')
813 			 || (*old == ':' && *new == '\0'))
814 				firstchange++;
815 			old = new;	/* ignore subsequent differences */
816 		}
817 		if (*new == '\0')
818 			break;
819 		if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
820 			bltin = idx;
821 		if (*new == ':') {
822 			idx++;
823 		}
824 		new++, old++;
825 	}
826 	if (builtinloc < 0 && bltin >= 0)
827 		builtinloc = bltin;		/* zap builtins */
828 	if (builtinloc >= 0 && bltin < 0)
829 		firstchange = 0;
830 	clearcmdentry(firstchange);
831 	builtinloc = bltin;
832 }
833 
834 
835 /*
836  * Clear out command entries.  The argument specifies the first entry in
837  * PATH which has changed.
838  */
839 
840 STATIC void
841 clearcmdentry(int firstchange)
842 {
843 	struct tblentry **tblp;
844 	struct tblentry **pp;
845 	struct tblentry *cmdp;
846 
847 	INTOFF;
848 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
849 		pp = tblp;
850 		while ((cmdp = *pp) != NULL) {
851 			if ((cmdp->cmdtype == CMDNORMAL &&
852 			     cmdp->param.index >= firstchange)
853 			 || (cmdp->cmdtype == CMDBUILTIN &&
854 			     builtinloc >= firstchange)) {
855 				*pp = cmdp->next;
856 				ckfree(cmdp);
857 			} else {
858 				pp = &cmdp->next;
859 			}
860 		}
861 	}
862 	INTON;
863 }
864 
865 
866 /*
867  * Delete all functions.
868  */
869 
870 #ifdef mkinit
871 MKINIT void deletefuncs(void);
872 MKINIT void hash_special_builtins(void);
873 
874 INIT {
875 	hash_special_builtins();
876 }
877 
878 SHELLPROC {
879 	deletefuncs();
880 }
881 #endif
882 
883 void
884 deletefuncs(void)
885 {
886 	struct tblentry **tblp;
887 	struct tblentry **pp;
888 	struct tblentry *cmdp;
889 
890 	INTOFF;
891 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
892 		pp = tblp;
893 		while ((cmdp = *pp) != NULL) {
894 			if (cmdp->cmdtype == CMDFUNCTION) {
895 				*pp = cmdp->next;
896 				freefunc(cmdp->param.func);
897 				ckfree(cmdp);
898 			} else {
899 				pp = &cmdp->next;
900 			}
901 		}
902 	}
903 	INTON;
904 }
905 
906 
907 
908 /*
909  * Locate a command in the command hash table.  If "add" is nonzero,
910  * add the command to the table if it is not already present.  The
911  * variable "lastcmdentry" is set to point to the address of the link
912  * pointing to the entry, so that delete_cmd_entry can delete the
913  * entry.
914  */
915 
916 struct tblentry **lastcmdentry;
917 
918 
919 STATIC struct tblentry *
920 cmdlookup(const char *name, int add)
921 {
922 	int hashval;
923 	const char *p;
924 	struct tblentry *cmdp;
925 	struct tblentry **pp;
926 
927 	p = name;
928 	hashval = *p << 4;
929 	while (*p)
930 		hashval += *p++;
931 	hashval &= 0x7FFF;
932 	pp = &cmdtable[hashval % CMDTABLESIZE];
933 	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
934 		if (equal(cmdp->cmdname, name))
935 			break;
936 		pp = &cmdp->next;
937 	}
938 	if (add && cmdp == NULL) {
939 		INTOFF;
940 		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
941 					+ strlen(name) + 1);
942 		cmdp->next = NULL;
943 		cmdp->cmdtype = CMDUNKNOWN;
944 		cmdp->rehash = 0;
945 		strcpy(cmdp->cmdname, name);
946 		INTON;
947 	}
948 	lastcmdentry = pp;
949 	return cmdp;
950 }
951 
952 /*
953  * Delete the command entry returned on the last lookup.
954  */
955 
956 STATIC void
957 delete_cmd_entry(void)
958 {
959 	struct tblentry *cmdp;
960 
961 	INTOFF;
962 	cmdp = *lastcmdentry;
963 	*lastcmdentry = cmdp->next;
964 	ckfree(cmdp);
965 	INTON;
966 }
967 
968 
969 
970 #ifdef notdef
971 void
972 getcmdentry(char *name, struct cmdentry *entry)
973 {
974 	struct tblentry *cmdp = cmdlookup(name, 0);
975 
976 	if (cmdp) {
977 		entry->u = cmdp->param;
978 		entry->cmdtype = cmdp->cmdtype;
979 	} else {
980 		entry->cmdtype = CMDUNKNOWN;
981 		entry->u.index = 0;
982 	}
983 }
984 #endif
985 
986 
987 /*
988  * Add a new command entry, replacing any existing command entry for
989  * the same name - except special builtins.
990  */
991 
992 STATIC void
993 addcmdentry(char *name, struct cmdentry *entry)
994 {
995 	struct tblentry *cmdp;
996 
997 	INTOFF;
998 	cmdp = cmdlookup(name, 1);
999 	if (cmdp->cmdtype != CMDSPLBLTIN) {
1000 		if (cmdp->cmdtype == CMDFUNCTION)
1001 			unreffunc(cmdp->param.func);
1002 		cmdp->cmdtype = entry->cmdtype;
1003 		cmdp->lineno = entry->lineno;
1004 		cmdp->fn_ln1 = entry->lno_frel;
1005 		cmdp->param = entry->u;
1006 	}
1007 	INTON;
1008 }
1009 
1010 
1011 /*
1012  * Define a shell function.
1013  */
1014 
1015 void
1016 defun(char *name, union node *func, int lineno)
1017 {
1018 	struct cmdentry entry;
1019 
1020 	INTOFF;
1021 	entry.cmdtype = CMDFUNCTION;
1022 	entry.lineno = lineno;
1023 	entry.lno_frel = fnline1;
1024 	entry.u.func = copyfunc(func);
1025 	addcmdentry(name, &entry);
1026 	INTON;
1027 }
1028 
1029 
1030 /*
1031  * Delete a function if it exists.
1032  */
1033 
1034 int
1035 unsetfunc(char *name)
1036 {
1037 	struct tblentry *cmdp;
1038 
1039 	if ((cmdp = cmdlookup(name, 0)) != NULL &&
1040 	    cmdp->cmdtype == CMDFUNCTION) {
1041 		unreffunc(cmdp->param.func);
1042 		delete_cmd_entry();
1043 	}
1044 	return 0;
1045 }
1046 
1047 /*
1048  * Locate and print what a word is...
1049  * also used for 'command -[v|V]'
1050  */
1051 
1052 int
1053 typecmd(int argc, char **argv)
1054 {
1055 	struct cmdentry entry;
1056 	struct tblentry *cmdp;
1057 	const char * const *pp;
1058 	struct alias *ap;
1059 	int err = 0;
1060 	char *arg;
1061 	int c;
1062 	int V_flag = 0;
1063 	int v_flag = 0;
1064 	int p_flag = 0;
1065 
1066 	while ((c = nextopt("vVp")) != 0) {
1067 		switch (c) {
1068 		case 'v': v_flag = 1; break;
1069 		case 'V': V_flag = 1; break;
1070 		case 'p': p_flag = 1; break;
1071 		}
1072 	}
1073 
1074 	if (argv[0][0] != 'c' && v_flag | V_flag | p_flag)
1075 		error("usage: %s name...", argv[0]);
1076 
1077 	if (v_flag && V_flag)
1078 		error("-v and -V cannot both be specified");
1079 
1080 	if (*argptr == NULL)
1081 		error("usage: %s%s name ...", argv[0],
1082 		    argv[0][0] == 'c' ? " [-p] [-v|-V]" : "");
1083 
1084 	while ((arg = *argptr++)) {
1085 		if (!v_flag)
1086 			out1str(arg);
1087 		/* First look at the keywords */
1088 		for (pp = parsekwd; *pp; pp++)
1089 			if (**pp == *arg && equal(*pp, arg))
1090 				break;
1091 
1092 		if (*pp) {
1093 			if (v_flag)
1094 				out1fmt("%s\n", arg);
1095 			else
1096 				out1str(" is a shell keyword\n");
1097 			continue;
1098 		}
1099 
1100 		/* Then look at the aliases */
1101 		if ((ap = lookupalias(arg, 1)) != NULL) {
1102 			int ml = 0;
1103 
1104 			if (!v_flag) {
1105 				out1str(" is an alias ");
1106 				if (strchr(ap->val, '\n')) {
1107 					out1str("(multiline)...\n");
1108 					ml = 1;
1109 				} else
1110 					out1str("for: ");
1111 			}
1112 			out1fmt("%s\n", ap->val);
1113 			if (ml && *argptr != NULL)
1114 				out1c('\n');
1115 			continue;
1116 		}
1117 
1118 		/* Then check if it is a tracked alias */
1119 		if (!p_flag && (cmdp = cmdlookup(arg, 0)) != NULL) {
1120 			entry.cmdtype = cmdp->cmdtype;
1121 			entry.u = cmdp->param;
1122 		} else {
1123 			cmdp = NULL;
1124 			/* Finally use brute force */
1125 			find_command(arg, &entry, DO_ABS,
1126 			     p_flag ? syspath() + 5 : pathval());
1127 		}
1128 
1129 		switch (entry.cmdtype) {
1130 		case CMDNORMAL: {
1131 			if (strchr(arg, '/') == NULL) {
1132 				const char *path;
1133 				char *name;
1134 				int j = entry.u.index;
1135 
1136 				path = p_flag ? syspath() + 5 : pathval();
1137 
1138 				do {
1139 					name = padvance(&path, arg, 1);
1140 					stunalloc(name);
1141 				} while (--j >= 0);
1142 				if (!v_flag)
1143 					out1fmt(" is%s ",
1144 					    cmdp ? " a tracked alias for" : "");
1145 				out1fmt("%s\n", name);
1146 			} else {
1147 				if (access(arg, X_OK) == 0) {
1148 					if (!v_flag)
1149 						out1fmt(" is ");
1150 					out1fmt("%s\n", arg);
1151 				} else {
1152 					if (!v_flag)
1153 						out1fmt(": %s\n",
1154 						    strerror(errno));
1155 					else
1156 						err = 126;
1157 				}
1158 			}
1159  			break;
1160 		}
1161 		case CMDFUNCTION:
1162 			if (!v_flag)
1163 				out1str(" is a shell function\n");
1164 			else
1165 				out1fmt("%s\n", arg);
1166 			break;
1167 
1168 		case CMDBUILTIN:
1169 			if (!v_flag)
1170 				out1str(" is a shell builtin\n");
1171 			else
1172 				out1fmt("%s\n", arg);
1173 			break;
1174 
1175 		case CMDSPLBLTIN:
1176 			if (!v_flag)
1177 				out1str(" is a special shell builtin\n");
1178 			else
1179 				out1fmt("%s\n", arg);
1180 			break;
1181 
1182 		default:
1183 			if (!v_flag)
1184 				out1str(": not found\n");
1185 			err = 127;
1186 			break;
1187 		}
1188 	}
1189 	return err;
1190 }
1191