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