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