xref: /netbsd-src/bin/sh/exec.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: exec.c,v 1.54 2020/08/01 17:51:18 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.54 2020/08/01 17:51:18 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 	return;
687 
688 builtin_success:
689 	INTOFF;
690 	if (act & DO_ALTPATH)
691 		cmdp = &loc_cmd;
692 	else
693 		cmdp = cmdlookup(name, 1);
694 	if (cmdp->cmdtype == CMDFUNCTION)
695 		/* DO_NOFUNC must have been set */
696 		cmdp = &loc_cmd;
697 	cmdp->cmdtype = CMDBUILTIN;
698 	cmdp->param.bltin = bltin;
699 	INTON;
700 success:
701 	if (cmdp) {
702 		cmdp->rehash = 0;
703 		entry->cmdtype = cmdp->cmdtype;
704 		entry->lineno = cmdp->lineno;
705 		entry->lno_frel = cmdp->fn_ln1;
706 		entry->u = cmdp->param;
707 	} else
708 		entry->cmdtype = CMDUNKNOWN;
709 }
710 
711 
712 
713 /*
714  * Search the table of builtin commands.
715  */
716 
717 int
718 (*find_builtin(char *name))(int, char **)
719 {
720 	const struct builtincmd *bp;
721 
722 	for (bp = builtincmd ; bp->name ; bp++) {
723 		if (*bp->name == *name
724 		    && (*name == '%' || equal(bp->name, name)))
725 			return bp->builtin;
726 	}
727 	return 0;
728 }
729 
730 int
731 (*find_splbltin(char *name))(int, char **)
732 {
733 	const struct builtincmd *bp;
734 
735 	for (bp = splbltincmd ; bp->name ; bp++) {
736 		if (*bp->name == *name && equal(bp->name, name))
737 			return bp->builtin;
738 	}
739 	return 0;
740 }
741 
742 /*
743  * At shell startup put special builtins into hash table.
744  * ensures they are executed first (see posix).
745  * We stop functions being added with the same name
746  * (as they are impossible to call)
747  */
748 
749 void
750 hash_special_builtins(void)
751 {
752 	const struct builtincmd *bp;
753 	struct tblentry *cmdp;
754 
755 	for (bp = splbltincmd ; bp->name ; bp++) {
756 		cmdp = cmdlookup(bp->name, 1);
757 		cmdp->cmdtype = CMDSPLBLTIN;
758 		cmdp->param.bltin = bp->builtin;
759 	}
760 }
761 
762 
763 
764 /*
765  * Called when a cd is done.  Marks all commands so the next time they
766  * are executed they will be rehashed.
767  */
768 
769 void
770 hashcd(void)
771 {
772 	struct tblentry **pp;
773 	struct tblentry *cmdp;
774 
775 	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
776 		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
777 			if (cmdp->cmdtype == CMDNORMAL
778 			 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
779 				cmdp->rehash = 1;
780 		}
781 	}
782 }
783 
784 
785 
786 /*
787  * Fix command hash table when PATH changed.
788  * Called before PATH is changed.  The argument is the new value of PATH;
789  * pathval() still returns the old value at this point.
790  * Called with interrupts off.
791  */
792 
793 void
794 changepath(const char *newval)
795 {
796 	const char *old, *new;
797 	int idx;
798 	int firstchange;
799 	int bltin;
800 
801 	old = pathval();
802 	new = newval;
803 	firstchange = 9999;	/* assume no change */
804 	idx = 0;
805 	bltin = -1;
806 	for (;;) {
807 		if (*old != *new) {
808 			firstchange = idx;
809 			if ((*old == '\0' && *new == ':')
810 			 || (*old == ':' && *new == '\0'))
811 				firstchange++;
812 			old = new;	/* ignore subsequent differences */
813 		}
814 		if (*new == '\0')
815 			break;
816 		if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
817 			bltin = idx;
818 		if (*new == ':') {
819 			idx++;
820 		}
821 		new++, old++;
822 	}
823 	if (builtinloc < 0 && bltin >= 0)
824 		builtinloc = bltin;		/* zap builtins */
825 	if (builtinloc >= 0 && bltin < 0)
826 		firstchange = 0;
827 	clearcmdentry(firstchange);
828 	builtinloc = bltin;
829 }
830 
831 
832 /*
833  * Clear out command entries.  The argument specifies the first entry in
834  * PATH which has changed.
835  */
836 
837 STATIC void
838 clearcmdentry(int firstchange)
839 {
840 	struct tblentry **tblp;
841 	struct tblentry **pp;
842 	struct tblentry *cmdp;
843 
844 	INTOFF;
845 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
846 		pp = tblp;
847 		while ((cmdp = *pp) != NULL) {
848 			if ((cmdp->cmdtype == CMDNORMAL &&
849 			     cmdp->param.index >= firstchange)
850 			 || (cmdp->cmdtype == CMDBUILTIN &&
851 			     builtinloc >= firstchange)) {
852 				*pp = cmdp->next;
853 				ckfree(cmdp);
854 			} else {
855 				pp = &cmdp->next;
856 			}
857 		}
858 	}
859 	INTON;
860 }
861 
862 
863 /*
864  * Delete all functions.
865  */
866 
867 #ifdef mkinit
868 MKINIT void deletefuncs(void);
869 MKINIT void hash_special_builtins(void);
870 
871 INIT {
872 	hash_special_builtins();
873 }
874 
875 SHELLPROC {
876 	deletefuncs();
877 }
878 #endif
879 
880 void
881 deletefuncs(void)
882 {
883 	struct tblentry **tblp;
884 	struct tblentry **pp;
885 	struct tblentry *cmdp;
886 
887 	INTOFF;
888 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
889 		pp = tblp;
890 		while ((cmdp = *pp) != NULL) {
891 			if (cmdp->cmdtype == CMDFUNCTION) {
892 				*pp = cmdp->next;
893 				freefunc(cmdp->param.func);
894 				ckfree(cmdp);
895 			} else {
896 				pp = &cmdp->next;
897 			}
898 		}
899 	}
900 	INTON;
901 }
902 
903 
904 
905 /*
906  * Locate a command in the command hash table.  If "add" is nonzero,
907  * add the command to the table if it is not already present.  The
908  * variable "lastcmdentry" is set to point to the address of the link
909  * pointing to the entry, so that delete_cmd_entry can delete the
910  * entry.
911  */
912 
913 struct tblentry **lastcmdentry;
914 
915 
916 STATIC struct tblentry *
917 cmdlookup(const char *name, int add)
918 {
919 	int hashval;
920 	const char *p;
921 	struct tblentry *cmdp;
922 	struct tblentry **pp;
923 
924 	p = name;
925 	hashval = *p << 4;
926 	while (*p)
927 		hashval += *p++;
928 	hashval &= 0x7FFF;
929 	pp = &cmdtable[hashval % CMDTABLESIZE];
930 	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
931 		if (equal(cmdp->cmdname, name))
932 			break;
933 		pp = &cmdp->next;
934 	}
935 	if (add && cmdp == NULL) {
936 		INTOFF;
937 		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
938 					+ strlen(name) + 1);
939 		cmdp->next = NULL;
940 		cmdp->cmdtype = CMDUNKNOWN;
941 		cmdp->rehash = 0;
942 		strcpy(cmdp->cmdname, name);
943 		INTON;
944 	}
945 	lastcmdentry = pp;
946 	return cmdp;
947 }
948 
949 /*
950  * Delete the command entry returned on the last lookup.
951  */
952 
953 STATIC void
954 delete_cmd_entry(void)
955 {
956 	struct tblentry *cmdp;
957 
958 	INTOFF;
959 	cmdp = *lastcmdentry;
960 	*lastcmdentry = cmdp->next;
961 	ckfree(cmdp);
962 	INTON;
963 }
964 
965 
966 
967 #ifdef notdef
968 void
969 getcmdentry(char *name, struct cmdentry *entry)
970 {
971 	struct tblentry *cmdp = cmdlookup(name, 0);
972 
973 	if (cmdp) {
974 		entry->u = cmdp->param;
975 		entry->cmdtype = cmdp->cmdtype;
976 	} else {
977 		entry->cmdtype = CMDUNKNOWN;
978 		entry->u.index = 0;
979 	}
980 }
981 #endif
982 
983 
984 /*
985  * Add a new command entry, replacing any existing command entry for
986  * the same name - except special builtins.
987  */
988 
989 STATIC void
990 addcmdentry(char *name, struct cmdentry *entry)
991 {
992 	struct tblentry *cmdp;
993 
994 	INTOFF;
995 	cmdp = cmdlookup(name, 1);
996 	if (cmdp->cmdtype != CMDSPLBLTIN) {
997 		if (cmdp->cmdtype == CMDFUNCTION)
998 			unreffunc(cmdp->param.func);
999 		cmdp->cmdtype = entry->cmdtype;
1000 		cmdp->lineno = entry->lineno;
1001 		cmdp->fn_ln1 = entry->lno_frel;
1002 		cmdp->param = entry->u;
1003 	}
1004 	INTON;
1005 }
1006 
1007 
1008 /*
1009  * Define a shell function.
1010  */
1011 
1012 void
1013 defun(char *name, union node *func, int lineno)
1014 {
1015 	struct cmdentry entry;
1016 
1017 	INTOFF;
1018 	entry.cmdtype = CMDFUNCTION;
1019 	entry.lineno = lineno;
1020 	entry.lno_frel = fnline1;
1021 	entry.u.func = copyfunc(func);
1022 	addcmdentry(name, &entry);
1023 	INTON;
1024 }
1025 
1026 
1027 /*
1028  * Delete a function if it exists.
1029  */
1030 
1031 int
1032 unsetfunc(char *name)
1033 {
1034 	struct tblentry *cmdp;
1035 
1036 	if ((cmdp = cmdlookup(name, 0)) != NULL &&
1037 	    cmdp->cmdtype == CMDFUNCTION) {
1038 		unreffunc(cmdp->param.func);
1039 		delete_cmd_entry();
1040 	}
1041 	return 0;
1042 }
1043 
1044 /*
1045  * Locate and print what a word is...
1046  * also used for 'command -[v|V]'
1047  */
1048 
1049 int
1050 typecmd(int argc, char **argv)
1051 {
1052 	struct cmdentry entry;
1053 	struct tblentry *cmdp;
1054 	const char * const *pp;
1055 	struct alias *ap;
1056 	int err = 0;
1057 	char *arg;
1058 	int c;
1059 	int V_flag = 0;
1060 	int v_flag = 0;
1061 	int p_flag = 0;
1062 
1063 	while ((c = nextopt("vVp")) != 0) {
1064 		switch (c) {
1065 		case 'v': v_flag = 1; break;
1066 		case 'V': V_flag = 1; break;
1067 		case 'p': p_flag = 1; break;
1068 		}
1069 	}
1070 
1071 	if (argv[0][0] != 'c' && v_flag | V_flag | p_flag)
1072 		error("usage: %s name...", argv[0]);
1073 
1074 	if (v_flag && V_flag)
1075 		error("-v and -V cannot both be specified");
1076 
1077 	if (*argptr == NULL)
1078 		error("usage: %s%s name ...", argv[0],
1079 		    argv[0][0] == 'c' ? " [-p] [-v|-V]" : "");
1080 
1081 	while ((arg = *argptr++)) {
1082 		if (!v_flag)
1083 			out1str(arg);
1084 		/* First look at the keywords */
1085 		for (pp = parsekwd; *pp; pp++)
1086 			if (**pp == *arg && equal(*pp, arg))
1087 				break;
1088 
1089 		if (*pp) {
1090 			if (v_flag)
1091 				out1fmt("%s\n", arg);
1092 			else
1093 				out1str(" is a shell keyword\n");
1094 			continue;
1095 		}
1096 
1097 		/* Then look at the aliases */
1098 		if ((ap = lookupalias(arg, 1)) != NULL) {
1099 			int ml = 0;
1100 
1101 			if (!v_flag) {
1102 				out1str(" is an alias ");
1103 				if (strchr(ap->val, '\n')) {
1104 					out1str("(multiline)...\n");
1105 					ml = 1;
1106 				} else
1107 					out1str("for: ");
1108 			}
1109 			out1fmt("%s\n", ap->val);
1110 			if (ml && *argptr != NULL)
1111 				out1c('\n');
1112 			continue;
1113 		}
1114 
1115 		/* Then check if it is a tracked alias */
1116 		if (!p_flag && (cmdp = cmdlookup(arg, 0)) != NULL) {
1117 			entry.cmdtype = cmdp->cmdtype;
1118 			entry.u = cmdp->param;
1119 		} else {
1120 			cmdp = NULL;
1121 			/* Finally use brute force */
1122 			find_command(arg, &entry, DO_ABS,
1123 			     p_flag ? syspath() + 5 : pathval());
1124 		}
1125 
1126 		switch (entry.cmdtype) {
1127 		case CMDNORMAL: {
1128 			if (strchr(arg, '/') == NULL) {
1129 				const char *path;
1130 				char *name;
1131 				int j = entry.u.index;
1132 
1133 				path = p_flag ? syspath() + 5 : pathval();
1134 
1135 				do {
1136 					name = padvance(&path, arg, 1);
1137 					stunalloc(name);
1138 				} while (--j >= 0);
1139 				if (!v_flag)
1140 					out1fmt(" is%s ",
1141 					    cmdp ? " a tracked alias for" : "");
1142 				out1fmt("%s\n", name);
1143 			} else {
1144 				if (access(arg, X_OK) == 0) {
1145 					if (!v_flag)
1146 						out1fmt(" is ");
1147 					out1fmt("%s\n", arg);
1148 				} else {
1149 					if (!v_flag)
1150 						out1fmt(": %s\n",
1151 						    strerror(errno));
1152 					else
1153 						err = 126;
1154 				}
1155 			}
1156  			break;
1157 		}
1158 		case CMDFUNCTION:
1159 			if (!v_flag)
1160 				out1str(" is a shell function\n");
1161 			else
1162 				out1fmt("%s\n", arg);
1163 			break;
1164 
1165 		case CMDBUILTIN:
1166 			if (!v_flag)
1167 				out1str(" is a shell builtin\n");
1168 			else
1169 				out1fmt("%s\n", arg);
1170 			break;
1171 
1172 		case CMDSPLBLTIN:
1173 			if (!v_flag)
1174 				out1str(" is a special shell builtin\n");
1175 			else
1176 				out1fmt("%s\n", arg);
1177 			break;
1178 
1179 		default:
1180 			if (!v_flag)
1181 				out1str(": not found\n");
1182 			err = 127;
1183 			break;
1184 		}
1185 	}
1186 	return err;
1187 }
1188