xref: /netbsd-src/bin/sh/exec.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: exec.c,v 1.51 2017/07/05 19:58:10 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.51 2017/07/05 19:58:10 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 			INTOFF;
485 			commandtext(&ps, cmdp->param.func);
486 			INTON;
487 			out1str("() { ");
488 			out1str(ps.cmd);
489 			out1str("; }");
490 		}
491 		break;
492 	default:
493 		error("internal error: %s cmdtype %d",
494 		    cmdp->cmdname, cmdp->cmdtype);
495 	}
496 	if (cmdp->rehash)
497 		out1c('*');
498 	out1c('\n');
499 }
500 
501 
502 
503 /*
504  * Resolve a command name.  If you change this routine, you may have to
505  * change the shellexec routine as well.
506  */
507 
508 void
509 find_command(char *name, struct cmdentry *entry, int act, const char *path)
510 {
511 	struct tblentry *cmdp, loc_cmd;
512 	int idx;
513 	int prev;
514 	char *fullname;
515 	struct stat statb;
516 	int e;
517 	int (*bltin)(int,char **);
518 
519 	/* If name contains a slash, don't use PATH or hash table */
520 	if (strchr(name, '/') != NULL) {
521 		if (act & DO_ABS) {
522 			while (stat(name, &statb) < 0) {
523 #ifdef SYSV
524 				if (errno == EINTR)
525 					continue;
526 #endif
527 				if (errno != ENOENT && errno != ENOTDIR)
528 					e = errno;
529 				entry->cmdtype = CMDUNKNOWN;
530 				entry->u.index = -1;
531 				return;
532 			}
533 			entry->cmdtype = CMDNORMAL;
534 			entry->u.index = -1;
535 			return;
536 		}
537 		entry->cmdtype = CMDNORMAL;
538 		entry->u.index = 0;
539 		return;
540 	}
541 
542 	if (path != pathval())
543 		act |= DO_ALTPATH;
544 
545 	if (act & DO_ALTPATH && strstr(path, "%builtin") != NULL)
546 		act |= DO_ALTBLTIN;
547 
548 	/* If name is in the table, check answer will be ok */
549 	if ((cmdp = cmdlookup(name, 0)) != NULL) {
550 		do {
551 			switch (cmdp->cmdtype) {
552 			case CMDNORMAL:
553 				if (act & DO_ALTPATH) {
554 					cmdp = NULL;
555 					continue;
556 				}
557 				break;
558 			case CMDFUNCTION:
559 				if (act & DO_NOFUNC) {
560 					cmdp = NULL;
561 					continue;
562 				}
563 				break;
564 			case CMDBUILTIN:
565 				if ((act & DO_ALTBLTIN) || builtinloc >= 0) {
566 					cmdp = NULL;
567 					continue;
568 				}
569 				break;
570 			}
571 			/* if not invalidated by cd, we're done */
572 			if (cmdp->rehash == 0)
573 				goto success;
574 		} while (0);
575 	}
576 
577 	/* If %builtin not in path, check for builtin next */
578 	if ((act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc < 0) &&
579 	    (bltin = find_builtin(name)) != 0)
580 		goto builtin_success;
581 
582 	/* We have to search path. */
583 	prev = -1;		/* where to start */
584 	if (cmdp) {		/* doing a rehash */
585 		if (cmdp->cmdtype == CMDBUILTIN)
586 			prev = builtinloc;
587 		else
588 			prev = cmdp->param.index;
589 	}
590 
591 	e = ENOENT;
592 	idx = -1;
593 loop:
594 	while ((fullname = padvance(&path, name, 1)) != NULL) {
595 		stunalloc(fullname);
596 		idx++;
597 		if (pathopt) {
598 			if (prefix("builtin", pathopt)) {
599 				if ((bltin = find_builtin(name)) == 0)
600 					goto loop;
601 				goto builtin_success;
602 			} else if (prefix("func", pathopt)) {
603 				/* handled below */
604 			} else {
605 				/* ignore unimplemented options */
606 				goto loop;
607 			}
608 		}
609 		/* if rehash, don't redo absolute path names */
610 		if (fullname[0] == '/' && idx <= prev) {
611 			if (idx < prev)
612 				goto loop;
613 			VTRACE(DBG_CMDS, ("searchexec \"%s\": no change\n",
614 			    name));
615 			goto success;
616 		}
617 		while (stat(fullname, &statb) < 0) {
618 #ifdef SYSV
619 			if (errno == EINTR)
620 				continue;
621 #endif
622 			if (errno != ENOENT && errno != ENOTDIR)
623 				e = errno;
624 			goto loop;
625 		}
626 		e = EACCES;	/* if we fail, this will be the error */
627 		if (!S_ISREG(statb.st_mode))
628 			goto loop;
629 		if (pathopt) {		/* this is a %func directory */
630 			char *endname;
631 
632 			if (act & DO_NOFUNC)
633 				goto loop;
634 			endname = fullname + strlen(fullname) + 1;
635 			grabstackstr(endname);
636 			readcmdfile(fullname);
637 			if ((cmdp = cmdlookup(name, 0)) == NULL ||
638 			    cmdp->cmdtype != CMDFUNCTION)
639 				error("%s not defined in %s", name, fullname);
640 			ungrabstackstr(fullname, endname);
641 			goto success;
642 		}
643 #ifdef notdef
644 		/* XXX this code stops root executing stuff, and is buggy
645 		   if you need a group from the group list. */
646 		if (statb.st_uid == geteuid()) {
647 			if ((statb.st_mode & 0100) == 0)
648 				goto loop;
649 		} else if (statb.st_gid == getegid()) {
650 			if ((statb.st_mode & 010) == 0)
651 				goto loop;
652 		} else {
653 			if ((statb.st_mode & 01) == 0)
654 				goto loop;
655 		}
656 #endif
657 		VTRACE(DBG_CMDS, ("searchexec \"%s\" returns \"%s\"\n", name,
658 		    fullname));
659 		INTOFF;
660 		if (act & DO_ALTPATH) {
661 		/*
662 		 * this should be a grabstackstr() but is not needed:
663 		 * fullname is no longer needed for anything
664 			stalloc(strlen(fullname) + 1);
665 		 */
666 			cmdp = &loc_cmd;
667 		} else
668 			cmdp = cmdlookup(name, 1);
669 		cmdp->cmdtype = CMDNORMAL;
670 		cmdp->param.index = idx;
671 		INTON;
672 		goto success;
673 	}
674 
675 	/* We failed.  If there was an entry for this command, delete it */
676 	if (cmdp)
677 		delete_cmd_entry();
678 	if (act & DO_ERR)
679 		outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
680 	entry->cmdtype = CMDUNKNOWN;
681 	return;
682 
683 builtin_success:
684 	INTOFF;
685 	if (act & DO_ALTPATH)
686 		cmdp = &loc_cmd;
687 	else
688 		cmdp = cmdlookup(name, 1);
689 	if (cmdp->cmdtype == CMDFUNCTION)
690 		/* DO_NOFUNC must have been set */
691 		cmdp = &loc_cmd;
692 	cmdp->cmdtype = CMDBUILTIN;
693 	cmdp->param.bltin = bltin;
694 	INTON;
695 success:
696 	if (cmdp) {
697 		cmdp->rehash = 0;
698 		entry->cmdtype = cmdp->cmdtype;
699 		entry->lineno = cmdp->lineno;
700 		entry->lno_frel = cmdp->fn_ln1;
701 		entry->u = cmdp->param;
702 	} else
703 		entry->cmdtype = CMDUNKNOWN;
704 }
705 
706 
707 
708 /*
709  * Search the table of builtin commands.
710  */
711 
712 int
713 (*find_builtin(char *name))(int, char **)
714 {
715 	const struct builtincmd *bp;
716 
717 	for (bp = builtincmd ; bp->name ; bp++) {
718 		if (*bp->name == *name
719 		    && (*name == '%' || equal(bp->name, name)))
720 			return bp->builtin;
721 	}
722 	return 0;
723 }
724 
725 int
726 (*find_splbltin(char *name))(int, char **)
727 {
728 	const struct builtincmd *bp;
729 
730 	for (bp = splbltincmd ; bp->name ; bp++) {
731 		if (*bp->name == *name && equal(bp->name, name))
732 			return bp->builtin;
733 	}
734 	return 0;
735 }
736 
737 /*
738  * At shell startup put special builtins into hash table.
739  * ensures they are executed first (see posix).
740  * We stop functions being added with the same name
741  * (as they are impossible to call)
742  */
743 
744 void
745 hash_special_builtins(void)
746 {
747 	const struct builtincmd *bp;
748 	struct tblentry *cmdp;
749 
750 	for (bp = splbltincmd ; bp->name ; bp++) {
751 		cmdp = cmdlookup(bp->name, 1);
752 		cmdp->cmdtype = CMDSPLBLTIN;
753 		cmdp->param.bltin = bp->builtin;
754 	}
755 }
756 
757 
758 
759 /*
760  * Called when a cd is done.  Marks all commands so the next time they
761  * are executed they will be rehashed.
762  */
763 
764 void
765 hashcd(void)
766 {
767 	struct tblentry **pp;
768 	struct tblentry *cmdp;
769 
770 	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
771 		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
772 			if (cmdp->cmdtype == CMDNORMAL
773 			 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
774 				cmdp->rehash = 1;
775 		}
776 	}
777 }
778 
779 
780 
781 /*
782  * Fix command hash table when PATH changed.
783  * Called before PATH is changed.  The argument is the new value of PATH;
784  * pathval() still returns the old value at this point.
785  * Called with interrupts off.
786  */
787 
788 void
789 changepath(const char *newval)
790 {
791 	const char *old, *new;
792 	int idx;
793 	int firstchange;
794 	int bltin;
795 
796 	old = pathval();
797 	new = newval;
798 	firstchange = 9999;	/* assume no change */
799 	idx = 0;
800 	bltin = -1;
801 	for (;;) {
802 		if (*old != *new) {
803 			firstchange = idx;
804 			if ((*old == '\0' && *new == ':')
805 			 || (*old == ':' && *new == '\0'))
806 				firstchange++;
807 			old = new;	/* ignore subsequent differences */
808 		}
809 		if (*new == '\0')
810 			break;
811 		if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
812 			bltin = idx;
813 		if (*new == ':') {
814 			idx++;
815 		}
816 		new++, old++;
817 	}
818 	if (builtinloc < 0 && bltin >= 0)
819 		builtinloc = bltin;		/* zap builtins */
820 	if (builtinloc >= 0 && bltin < 0)
821 		firstchange = 0;
822 	clearcmdentry(firstchange);
823 	builtinloc = bltin;
824 }
825 
826 
827 /*
828  * Clear out command entries.  The argument specifies the first entry in
829  * PATH which has changed.
830  */
831 
832 STATIC void
833 clearcmdentry(int firstchange)
834 {
835 	struct tblentry **tblp;
836 	struct tblentry **pp;
837 	struct tblentry *cmdp;
838 
839 	INTOFF;
840 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
841 		pp = tblp;
842 		while ((cmdp = *pp) != NULL) {
843 			if ((cmdp->cmdtype == CMDNORMAL &&
844 			     cmdp->param.index >= firstchange)
845 			 || (cmdp->cmdtype == CMDBUILTIN &&
846 			     builtinloc >= firstchange)) {
847 				*pp = cmdp->next;
848 				ckfree(cmdp);
849 			} else {
850 				pp = &cmdp->next;
851 			}
852 		}
853 	}
854 	INTON;
855 }
856 
857 
858 /*
859  * Delete all functions.
860  */
861 
862 #ifdef mkinit
863 MKINIT void deletefuncs(void);
864 MKINIT void hash_special_builtins(void);
865 
866 INIT {
867 	hash_special_builtins();
868 }
869 
870 SHELLPROC {
871 	deletefuncs();
872 }
873 #endif
874 
875 void
876 deletefuncs(void)
877 {
878 	struct tblentry **tblp;
879 	struct tblentry **pp;
880 	struct tblentry *cmdp;
881 
882 	INTOFF;
883 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
884 		pp = tblp;
885 		while ((cmdp = *pp) != NULL) {
886 			if (cmdp->cmdtype == CMDFUNCTION) {
887 				*pp = cmdp->next;
888 				freefunc(cmdp->param.func);
889 				ckfree(cmdp);
890 			} else {
891 				pp = &cmdp->next;
892 			}
893 		}
894 	}
895 	INTON;
896 }
897 
898 
899 
900 /*
901  * Locate a command in the command hash table.  If "add" is nonzero,
902  * add the command to the table if it is not already present.  The
903  * variable "lastcmdentry" is set to point to the address of the link
904  * pointing to the entry, so that delete_cmd_entry can delete the
905  * entry.
906  */
907 
908 struct tblentry **lastcmdentry;
909 
910 
911 STATIC struct tblentry *
912 cmdlookup(const char *name, int add)
913 {
914 	int hashval;
915 	const char *p;
916 	struct tblentry *cmdp;
917 	struct tblentry **pp;
918 
919 	p = name;
920 	hashval = *p << 4;
921 	while (*p)
922 		hashval += *p++;
923 	hashval &= 0x7FFF;
924 	pp = &cmdtable[hashval % CMDTABLESIZE];
925 	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
926 		if (equal(cmdp->cmdname, name))
927 			break;
928 		pp = &cmdp->next;
929 	}
930 	if (add && cmdp == NULL) {
931 		INTOFF;
932 		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
933 					+ strlen(name) + 1);
934 		cmdp->next = NULL;
935 		cmdp->cmdtype = CMDUNKNOWN;
936 		cmdp->rehash = 0;
937 		strcpy(cmdp->cmdname, name);
938 		INTON;
939 	}
940 	lastcmdentry = pp;
941 	return cmdp;
942 }
943 
944 /*
945  * Delete the command entry returned on the last lookup.
946  */
947 
948 STATIC void
949 delete_cmd_entry(void)
950 {
951 	struct tblentry *cmdp;
952 
953 	INTOFF;
954 	cmdp = *lastcmdentry;
955 	*lastcmdentry = cmdp->next;
956 	ckfree(cmdp);
957 	INTON;
958 }
959 
960 
961 
962 #ifdef notdef
963 void
964 getcmdentry(char *name, struct cmdentry *entry)
965 {
966 	struct tblentry *cmdp = cmdlookup(name, 0);
967 
968 	if (cmdp) {
969 		entry->u = cmdp->param;
970 		entry->cmdtype = cmdp->cmdtype;
971 	} else {
972 		entry->cmdtype = CMDUNKNOWN;
973 		entry->u.index = 0;
974 	}
975 }
976 #endif
977 
978 
979 /*
980  * Add a new command entry, replacing any existing command entry for
981  * the same name - except special builtins.
982  */
983 
984 STATIC void
985 addcmdentry(char *name, struct cmdentry *entry)
986 {
987 	struct tblentry *cmdp;
988 
989 	INTOFF;
990 	cmdp = cmdlookup(name, 1);
991 	if (cmdp->cmdtype != CMDSPLBLTIN) {
992 		if (cmdp->cmdtype == CMDFUNCTION) {
993 			freefunc(cmdp->param.func);
994 		}
995 		cmdp->cmdtype = entry->cmdtype;
996 		cmdp->lineno = entry->lineno;
997 		cmdp->fn_ln1 = entry->lno_frel;
998 		cmdp->param = entry->u;
999 	}
1000 	INTON;
1001 }
1002 
1003 
1004 /*
1005  * Define a shell function.
1006  */
1007 
1008 void
1009 defun(char *name, union node *func, int lineno)
1010 {
1011 	struct cmdentry entry;
1012 
1013 	INTOFF;
1014 	entry.cmdtype = CMDFUNCTION;
1015 	entry.lineno = lineno;
1016 	entry.lno_frel = fnline1;
1017 	entry.u.func = copyfunc(func);
1018 	addcmdentry(name, &entry);
1019 	INTON;
1020 }
1021 
1022 
1023 /*
1024  * Delete a function if it exists.
1025  */
1026 
1027 int
1028 unsetfunc(char *name)
1029 {
1030 	struct tblentry *cmdp;
1031 
1032 	if ((cmdp = cmdlookup(name, 0)) != NULL &&
1033 	    cmdp->cmdtype == CMDFUNCTION) {
1034 		freefunc(cmdp->param.func);
1035 		delete_cmd_entry();
1036 	}
1037 	return 0;
1038 }
1039 
1040 /*
1041  * Locate and print what a word is...
1042  * also used for 'command -[v|V]'
1043  */
1044 
1045 int
1046 typecmd(int argc, char **argv)
1047 {
1048 	struct cmdentry entry;
1049 	struct tblentry *cmdp;
1050 	const char * const *pp;
1051 	struct alias *ap;
1052 	int err = 0;
1053 	char *arg;
1054 	int c;
1055 	int V_flag = 0;
1056 	int v_flag = 0;
1057 	int p_flag = 0;
1058 
1059 	while ((c = nextopt("vVp")) != 0) {
1060 		switch (c) {
1061 		case 'v': v_flag = 1; break;
1062 		case 'V': V_flag = 1; break;
1063 		case 'p': p_flag = 1; break;
1064 		}
1065 	}
1066 
1067 	if (p_flag && (v_flag || V_flag))
1068 		error("cannot specify -p with -v or -V");
1069 
1070 	while ((arg = *argptr++)) {
1071 		if (!v_flag)
1072 			out1str(arg);
1073 		/* First look at the keywords */
1074 		for (pp = parsekwd; *pp; pp++)
1075 			if (**pp == *arg && equal(*pp, arg))
1076 				break;
1077 
1078 		if (*pp) {
1079 			if (v_flag)
1080 				err = 1;
1081 			else
1082 				out1str(" is a shell keyword\n");
1083 			continue;
1084 		}
1085 
1086 		/* Then look at the aliases */
1087 		if ((ap = lookupalias(arg, 1)) != NULL) {
1088 			if (!v_flag)
1089 				out1fmt(" is an alias for \n");
1090 			out1fmt("%s\n", ap->val);
1091 			continue;
1092 		}
1093 
1094 		/* Then check if it is a tracked alias */
1095 		if ((cmdp = cmdlookup(arg, 0)) != NULL) {
1096 			entry.cmdtype = cmdp->cmdtype;
1097 			entry.u = cmdp->param;
1098 		} else {
1099 			/* Finally use brute force */
1100 			find_command(arg, &entry, DO_ABS, pathval());
1101 		}
1102 
1103 		switch (entry.cmdtype) {
1104 		case CMDNORMAL: {
1105 			if (strchr(arg, '/') == NULL) {
1106 				const char *path = pathval();
1107 				char *name;
1108 				int j = entry.u.index;
1109 				do {
1110 					name = padvance(&path, arg, 1);
1111 					stunalloc(name);
1112 				} while (--j >= 0);
1113 				if (!v_flag)
1114 					out1fmt(" is%s ",
1115 					    cmdp ? " a tracked alias for" : "");
1116 				out1fmt("%s\n", name);
1117 			} else {
1118 				if (access(arg, X_OK) == 0) {
1119 					if (!v_flag)
1120 						out1fmt(" is ");
1121 					out1fmt("%s\n", arg);
1122 				} else {
1123 					if (!v_flag)
1124 						out1fmt(": %s\n",
1125 						    strerror(errno));
1126 					else
1127 						err = 126;
1128 				}
1129 			}
1130  			break;
1131 		}
1132 		case CMDFUNCTION:
1133 			if (!v_flag)
1134 				out1str(" is a shell function\n");
1135 			else
1136 				out1fmt("%s\n", arg);
1137 			break;
1138 
1139 		case CMDBUILTIN:
1140 			if (!v_flag)
1141 				out1str(" is a shell builtin\n");
1142 			else
1143 				out1fmt("%s\n", arg);
1144 			break;
1145 
1146 		case CMDSPLBLTIN:
1147 			if (!v_flag)
1148 				out1str(" is a special shell builtin\n");
1149 			else
1150 				out1fmt("%s\n", arg);
1151 			break;
1152 
1153 		default:
1154 			if (!v_flag)
1155 				out1str(": not found\n");
1156 			err = 127;
1157 			break;
1158 		}
1159 	}
1160 	return err;
1161 }
1162