xref: /netbsd-src/bin/sh/exec.c (revision fdecd6a253f999ae92b139670d9e15cc9df4497c)
1 /*	$NetBSD: exec.c,v 1.23 1997/07/04 21:01:59 christos 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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)exec.c	8.4 (Berkeley) 6/8/95";
43 #else
44 __RCSID("$NetBSD: exec.c,v 1.23 1997/07/04 21:01:59 christos Exp $");
45 #endif
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <errno.h>
53 #include <stdlib.h>
54 
55 /*
56  * When commands are first encountered, they are entered in a hash table.
57  * This ensures that a full path search will not have to be done for them
58  * on each invocation.
59  *
60  * We should investigate converting to a linear search, even though that
61  * would make the command name "hash" a misnomer.
62  */
63 
64 #include "shell.h"
65 #include "main.h"
66 #include "nodes.h"
67 #include "parser.h"
68 #include "redir.h"
69 #include "eval.h"
70 #include "exec.h"
71 #include "builtins.h"
72 #include "var.h"
73 #include "options.h"
74 #include "input.h"
75 #include "output.h"
76 #include "syntax.h"
77 #include "memalloc.h"
78 #include "error.h"
79 #include "init.h"
80 #include "mystring.h"
81 #include "show.h"
82 #include "jobs.h"
83 #include "alias.h"
84 
85 
86 #define CMDTABLESIZE 31		/* should be prime */
87 #define ARB 1			/* actual size determined at run time */
88 
89 
90 
91 struct tblentry {
92 	struct tblentry *next;	/* next entry in hash chain */
93 	union param param;	/* definition of builtin function */
94 	short cmdtype;		/* index identifying command */
95 	char rehash;		/* if set, cd done since entry created */
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 __P((char *, char **, char **));
106 STATIC void execinterp __P((char **, char **));
107 STATIC void printentry __P((struct tblentry *, int));
108 STATIC void clearcmdentry __P((int));
109 STATIC struct tblentry *cmdlookup __P((char *, int));
110 STATIC void delete_cmd_entry __P((void));
111 
112 
113 
114 /*
115  * Exec a program.  Never returns.  If you change this routine, you may
116  * have to change the find_command routine as well.
117  */
118 
119 void
120 shellexec(argv, envp, path, index)
121 	char **argv, **envp;
122 	char *path;
123 	int index;
124 {
125 	char *cmdname;
126 	int e;
127 
128 	if (strchr(argv[0], '/') != NULL) {
129 		tryexec(argv[0], argv, envp);
130 		e = errno;
131 	} else {
132 		e = ENOENT;
133 		while ((cmdname = padvance(&path, argv[0])) != NULL) {
134 			if (--index < 0 && pathopt == NULL) {
135 				tryexec(cmdname, argv, envp);
136 				if (errno != ENOENT && errno != ENOTDIR)
137 					e = errno;
138 			}
139 			stunalloc(cmdname);
140 		}
141 	}
142 
143 	/* Map to POSIX errors */
144 	switch (e) {
145 	case EACCES:
146 		exerrno = 126;
147 		break;
148 	case ENOENT:
149 		exerrno = 127;
150 		break;
151 	default:
152 		exerrno = 2;
153 		break;
154 	}
155 	exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
156 }
157 
158 
159 STATIC void
160 tryexec(cmd, argv, envp)
161 	char *cmd;
162 	char **argv;
163 	char **envp;
164 	{
165 	int e;
166 #ifndef BSD
167 	char *p;
168 #endif
169 
170 #ifdef SYSV
171 	do {
172 		execve(cmd, argv, envp);
173 	} while (errno == EINTR);
174 #else
175 	execve(cmd, argv, envp);
176 #endif
177 	e = errno;
178 	if (e == ENOEXEC) {
179 		initshellproc();
180 		setinputfile(cmd, 0);
181 		commandname = arg0 = savestr(argv[0]);
182 #ifndef BSD
183 		pgetc(); pungetc();		/* fill up input buffer */
184 		p = parsenextc;
185 		if (parsenleft > 2 && p[0] == '#' && p[1] == '!') {
186 			argv[0] = cmd;
187 			execinterp(argv, envp);
188 		}
189 #endif
190 		setparam(argv + 1);
191 		exraise(EXSHELLPROC);
192 		/*NOTREACHED*/
193 	}
194 	errno = e;
195 }
196 
197 
198 #ifndef BSD
199 /*
200  * Execute an interpreter introduced by "#!", for systems where this
201  * feature has not been built into the kernel.  If the interpreter is
202  * the shell, return (effectively ignoring the "#!").  If the execution
203  * of the interpreter fails, exit.
204  *
205  * This code peeks inside the input buffer in order to avoid actually
206  * reading any input.  It would benefit from a rewrite.
207  */
208 
209 #define NEWARGS 5
210 
211 STATIC void
212 execinterp(argv, envp)
213 	char **argv, **envp;
214 	{
215 	int n;
216 	char *inp;
217 	char *outp;
218 	char c;
219 	char *p;
220 	char **ap;
221 	char *newargs[NEWARGS];
222 	int i;
223 	char **ap2;
224 	char **new;
225 
226 	n = parsenleft - 2;
227 	inp = parsenextc + 2;
228 	ap = newargs;
229 	for (;;) {
230 		while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
231 			inp++;
232 		if (n < 0)
233 			goto bad;
234 		if ((c = *inp++) == '\n')
235 			break;
236 		if (ap == &newargs[NEWARGS])
237 bad:		  error("Bad #! line");
238 		STARTSTACKSTR(outp);
239 		do {
240 			STPUTC(c, outp);
241 		} while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
242 		STPUTC('\0', outp);
243 		n++, inp--;
244 		*ap++ = grabstackstr(outp);
245 	}
246 	if (ap == newargs + 1) {	/* if no args, maybe no exec is needed */
247 		p = newargs[0];
248 		for (;;) {
249 			if (equal(p, "sh") || equal(p, "ash")) {
250 				return;
251 			}
252 			while (*p != '/') {
253 				if (*p == '\0')
254 					goto break2;
255 				p++;
256 			}
257 			p++;
258 		}
259 break2:;
260 	}
261 	i = (char *)ap - (char *)newargs;		/* size in bytes */
262 	if (i == 0)
263 		error("Bad #! line");
264 	for (ap2 = argv ; *ap2++ != NULL ; );
265 	new = ckmalloc(i + ((char *)ap2 - (char *)argv));
266 	ap = newargs, ap2 = new;
267 	while ((i -= sizeof (char **)) >= 0)
268 		*ap2++ = *ap++;
269 	ap = argv;
270 	while (*ap2++ = *ap++);
271 	shellexec(new, envp, pathval(), 0);
272 }
273 #endif
274 
275 
276 
277 /*
278  * Do a path search.  The variable path (passed by reference) should be
279  * set to the start of the path before the first call; padvance will update
280  * this value as it proceeds.  Successive calls to padvance will return
281  * the possible path expansions in sequence.  If an option (indicated by
282  * a percent sign) appears in the path entry then the global variable
283  * pathopt will be set to point to it; otherwise pathopt will be set to
284  * NULL.
285  */
286 
287 char *pathopt;
288 
289 char *
290 padvance(path, name)
291 	char **path;
292 	char *name;
293 	{
294 	char *p, *q;
295 	char *start;
296 	int len;
297 
298 	if (*path == NULL)
299 		return NULL;
300 	start = *path;
301 	for (p = start ; *p && *p != ':' && *p != '%' ; p++);
302 	len = p - start + strlen(name) + 2;	/* "2" is for '/' and '\0' */
303 	while (stackblocksize() < len)
304 		growstackblock();
305 	q = stackblock();
306 	if (p != start) {
307 		memcpy(q, start, p - start);
308 		q += p - start;
309 		*q++ = '/';
310 	}
311 	strcpy(q, name);
312 	pathopt = NULL;
313 	if (*p == '%') {
314 		pathopt = ++p;
315 		while (*p && *p != ':')  p++;
316 	}
317 	if (*p == ':')
318 		*path = p + 1;
319 	else
320 		*path = NULL;
321 	return stalloc(len);
322 }
323 
324 
325 
326 /*** Command hashing code ***/
327 
328 
329 int
330 hashcmd(argc, argv)
331 	int argc;
332 	char **argv;
333 {
334 	struct tblentry **pp;
335 	struct tblentry *cmdp;
336 	int c;
337 	int verbose;
338 	struct cmdentry entry;
339 	char *name;
340 
341 	verbose = 0;
342 	while ((c = nextopt("rv")) != '\0') {
343 		if (c == 'r') {
344 			clearcmdentry(0);
345 		} else if (c == 'v') {
346 			verbose++;
347 		}
348 	}
349 	if (*argptr == NULL) {
350 		for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
351 			for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
352 				printentry(cmdp, verbose);
353 			}
354 		}
355 		return 0;
356 	}
357 	while ((name = *argptr) != NULL) {
358 		if ((cmdp = cmdlookup(name, 0)) != NULL
359 		 && (cmdp->cmdtype == CMDNORMAL
360 		     || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
361 			delete_cmd_entry();
362 		find_command(name, &entry, 1, pathval());
363 		if (verbose) {
364 			if (entry.cmdtype != CMDUNKNOWN) {	/* if no error msg */
365 				cmdp = cmdlookup(name, 0);
366 				printentry(cmdp, verbose);
367 			}
368 			flushall();
369 		}
370 		argptr++;
371 	}
372 	return 0;
373 }
374 
375 
376 STATIC void
377 printentry(cmdp, verbose)
378 	struct tblentry *cmdp;
379 	int verbose;
380 	{
381 	int index;
382 	char *path;
383 	char *name;
384 
385 	if (cmdp->cmdtype == CMDNORMAL) {
386 		index = cmdp->param.index;
387 		path = pathval();
388 		do {
389 			name = padvance(&path, cmdp->cmdname);
390 			stunalloc(name);
391 		} while (--index >= 0);
392 		out1str(name);
393 	} else if (cmdp->cmdtype == CMDBUILTIN) {
394 		out1fmt("builtin %s", cmdp->cmdname);
395 	} else if (cmdp->cmdtype == CMDFUNCTION) {
396 		out1fmt("function %s", cmdp->cmdname);
397 		if (verbose) {
398 			INTOFF;
399 			name = commandtext(cmdp->param.func);
400 			out1c(' ');
401 			out1str(name);
402 			ckfree(name);
403 			INTON;
404 		}
405 #ifdef DEBUG
406 	} else {
407 		error("internal error: cmdtype %d", cmdp->cmdtype);
408 #endif
409 	}
410 	if (cmdp->rehash)
411 		out1c('*');
412 	out1c('\n');
413 }
414 
415 
416 
417 /*
418  * Resolve a command name.  If you change this routine, you may have to
419  * change the shellexec routine as well.
420  */
421 
422 void
423 find_command(name, entry, printerr, path)
424 	char *name;
425 	struct cmdentry *entry;
426 	int printerr;
427 	char *path;
428 {
429 	struct tblentry *cmdp;
430 	int index;
431 	int prev;
432 	char *fullname;
433 	struct stat statb;
434 	int e;
435 	int i;
436 
437 	/* If name contains a slash, don't use the hash table */
438 	if (strchr(name, '/') != NULL) {
439 		entry->cmdtype = CMDNORMAL;
440 		entry->u.index = 0;
441 		return;
442 	}
443 
444 	/* If name is in the table, and not invalidated by cd, we're done */
445 	if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0)
446 		goto success;
447 
448 	/* If %builtin not in path, check for builtin next */
449 	if (builtinloc < 0 && (i = find_builtin(name)) >= 0) {
450 		INTOFF;
451 		cmdp = cmdlookup(name, 1);
452 		cmdp->cmdtype = CMDBUILTIN;
453 		cmdp->param.index = i;
454 		INTON;
455 		goto success;
456 	}
457 
458 	/* We have to search path. */
459 	prev = -1;		/* where to start */
460 	if (cmdp) {		/* doing a rehash */
461 		if (cmdp->cmdtype == CMDBUILTIN)
462 			prev = builtinloc;
463 		else
464 			prev = cmdp->param.index;
465 	}
466 
467 	e = ENOENT;
468 	index = -1;
469 loop:
470 	while ((fullname = padvance(&path, name)) != NULL) {
471 		stunalloc(fullname);
472 		index++;
473 		if (pathopt) {
474 			if (prefix("builtin", pathopt)) {
475 				if ((i = find_builtin(name)) < 0)
476 					goto loop;
477 				INTOFF;
478 				cmdp = cmdlookup(name, 1);
479 				cmdp->cmdtype = CMDBUILTIN;
480 				cmdp->param.index = i;
481 				INTON;
482 				goto success;
483 			} else if (prefix("func", pathopt)) {
484 				/* handled below */
485 			} else {
486 				goto loop;	/* ignore unimplemented options */
487 			}
488 		}
489 		/* if rehash, don't redo absolute path names */
490 		if (fullname[0] == '/' && index <= prev) {
491 			if (index < prev)
492 				goto loop;
493 			TRACE(("searchexec \"%s\": no change\n", name));
494 			goto success;
495 		}
496 		while (stat(fullname, &statb) < 0) {
497 #ifdef SYSV
498 			if (errno == EINTR)
499 				continue;
500 #endif
501 			if (errno != ENOENT && errno != ENOTDIR)
502 				e = errno;
503 			goto loop;
504 		}
505 		e = EACCES;	/* if we fail, this will be the error */
506 		if (!S_ISREG(statb.st_mode))
507 			goto loop;
508 		if (pathopt) {		/* this is a %func directory */
509 			stalloc(strlen(fullname) + 1);
510 			readcmdfile(fullname);
511 			if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
512 				error("%s not defined in %s", name, fullname);
513 			stunalloc(fullname);
514 			goto success;
515 		}
516 #ifdef notdef
517 		if (statb.st_uid == geteuid()) {
518 			if ((statb.st_mode & 0100) == 0)
519 				goto loop;
520 		} else if (statb.st_gid == getegid()) {
521 			if ((statb.st_mode & 010) == 0)
522 				goto loop;
523 		} else {
524 			if ((statb.st_mode & 01) == 0)
525 				goto loop;
526 		}
527 #endif
528 		TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
529 		INTOFF;
530 		cmdp = cmdlookup(name, 1);
531 		cmdp->cmdtype = CMDNORMAL;
532 		cmdp->param.index = index;
533 		INTON;
534 		goto success;
535 	}
536 
537 	/* We failed.  If there was an entry for this command, delete it */
538 	if (cmdp)
539 		delete_cmd_entry();
540 	if (printerr)
541 		outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
542 	entry->cmdtype = CMDUNKNOWN;
543 	return;
544 
545 success:
546 	cmdp->rehash = 0;
547 	entry->cmdtype = cmdp->cmdtype;
548 	entry->u = cmdp->param;
549 }
550 
551 
552 
553 /*
554  * Search the table of builtin commands.
555  */
556 
557 int
558 find_builtin(name)
559 	char *name;
560 {
561 	const struct builtincmd *bp;
562 
563 	for (bp = builtincmd ; bp->name ; bp++) {
564 		if (*bp->name == *name && equal(bp->name, name))
565 			return bp->code;
566 	}
567 	return -1;
568 }
569 
570 
571 
572 /*
573  * Called when a cd is done.  Marks all commands so the next time they
574  * are executed they will be rehashed.
575  */
576 
577 void
578 hashcd() {
579 	struct tblentry **pp;
580 	struct tblentry *cmdp;
581 
582 	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
583 		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
584 			if (cmdp->cmdtype == CMDNORMAL
585 			 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
586 				cmdp->rehash = 1;
587 		}
588 	}
589 }
590 
591 
592 
593 /*
594  * Called before PATH is changed.  The argument is the new value of PATH;
595  * pathval() still returns the old value at this point.  Called with
596  * interrupts off.
597  */
598 
599 void
600 changepath(newval)
601 	const char *newval;
602 {
603 	const char *old, *new;
604 	int index;
605 	int firstchange;
606 	int bltin;
607 
608 	old = pathval();
609 	new = newval;
610 	firstchange = 9999;	/* assume no change */
611 	index = 0;
612 	bltin = -1;
613 	for (;;) {
614 		if (*old != *new) {
615 			firstchange = index;
616 			if ((*old == '\0' && *new == ':')
617 			 || (*old == ':' && *new == '\0'))
618 				firstchange++;
619 			old = new;	/* ignore subsequent differences */
620 		}
621 		if (*new == '\0')
622 			break;
623 		if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
624 			bltin = index;
625 		if (*new == ':') {
626 			index++;
627 		}
628 		new++, old++;
629 	}
630 	if (builtinloc < 0 && bltin >= 0)
631 		builtinloc = bltin;		/* zap builtins */
632 	if (builtinloc >= 0 && bltin < 0)
633 		firstchange = 0;
634 	clearcmdentry(firstchange);
635 	builtinloc = bltin;
636 }
637 
638 
639 /*
640  * Clear out command entries.  The argument specifies the first entry in
641  * PATH which has changed.
642  */
643 
644 STATIC void
645 clearcmdentry(firstchange)
646 	int firstchange;
647 {
648 	struct tblentry **tblp;
649 	struct tblentry **pp;
650 	struct tblentry *cmdp;
651 
652 	INTOFF;
653 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
654 		pp = tblp;
655 		while ((cmdp = *pp) != NULL) {
656 			if ((cmdp->cmdtype == CMDNORMAL &&
657 			     cmdp->param.index >= firstchange)
658 			 || (cmdp->cmdtype == CMDBUILTIN &&
659 			     builtinloc >= firstchange)) {
660 				*pp = cmdp->next;
661 				ckfree(cmdp);
662 			} else {
663 				pp = &cmdp->next;
664 			}
665 		}
666 	}
667 	INTON;
668 }
669 
670 
671 /*
672  * Delete all functions.
673  */
674 
675 #ifdef mkinit
676 MKINIT void deletefuncs __P((void));
677 
678 SHELLPROC {
679 	deletefuncs();
680 }
681 #endif
682 
683 void
684 deletefuncs() {
685 	struct tblentry **tblp;
686 	struct tblentry **pp;
687 	struct tblentry *cmdp;
688 
689 	INTOFF;
690 	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
691 		pp = tblp;
692 		while ((cmdp = *pp) != NULL) {
693 			if (cmdp->cmdtype == CMDFUNCTION) {
694 				*pp = cmdp->next;
695 				freefunc(cmdp->param.func);
696 				ckfree(cmdp);
697 			} else {
698 				pp = &cmdp->next;
699 			}
700 		}
701 	}
702 	INTON;
703 }
704 
705 
706 
707 /*
708  * Locate a command in the command hash table.  If "add" is nonzero,
709  * add the command to the table if it is not already present.  The
710  * variable "lastcmdentry" is set to point to the address of the link
711  * pointing to the entry, so that delete_cmd_entry can delete the
712  * entry.
713  */
714 
715 struct tblentry **lastcmdentry;
716 
717 
718 STATIC struct tblentry *
719 cmdlookup(name, add)
720 	char *name;
721 	int add;
722 {
723 	int hashval;
724 	char *p;
725 	struct tblentry *cmdp;
726 	struct tblentry **pp;
727 
728 	p = name;
729 	hashval = *p << 4;
730 	while (*p)
731 		hashval += *p++;
732 	hashval &= 0x7FFF;
733 	pp = &cmdtable[hashval % CMDTABLESIZE];
734 	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
735 		if (equal(cmdp->cmdname, name))
736 			break;
737 		pp = &cmdp->next;
738 	}
739 	if (add && cmdp == NULL) {
740 		INTOFF;
741 		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
742 					+ strlen(name) + 1);
743 		cmdp->next = NULL;
744 		cmdp->cmdtype = CMDUNKNOWN;
745 		cmdp->rehash = 0;
746 		strcpy(cmdp->cmdname, name);
747 		INTON;
748 	}
749 	lastcmdentry = pp;
750 	return cmdp;
751 }
752 
753 /*
754  * Delete the command entry returned on the last lookup.
755  */
756 
757 STATIC void
758 delete_cmd_entry() {
759 	struct tblentry *cmdp;
760 
761 	INTOFF;
762 	cmdp = *lastcmdentry;
763 	*lastcmdentry = cmdp->next;
764 	ckfree(cmdp);
765 	INTON;
766 }
767 
768 
769 
770 #ifdef notdef
771 void
772 getcmdentry(name, entry)
773 	char *name;
774 	struct cmdentry *entry;
775 	{
776 	struct tblentry *cmdp = cmdlookup(name, 0);
777 
778 	if (cmdp) {
779 		entry->u = cmdp->param;
780 		entry->cmdtype = cmdp->cmdtype;
781 	} else {
782 		entry->cmdtype = CMDUNKNOWN;
783 		entry->u.index = 0;
784 	}
785 }
786 #endif
787 
788 
789 /*
790  * Add a new command entry, replacing any existing command entry for
791  * the same name.
792  */
793 
794 void
795 addcmdentry(name, entry)
796 	char *name;
797 	struct cmdentry *entry;
798 	{
799 	struct tblentry *cmdp;
800 
801 	INTOFF;
802 	cmdp = cmdlookup(name, 1);
803 	if (cmdp->cmdtype == CMDFUNCTION) {
804 		freefunc(cmdp->param.func);
805 	}
806 	cmdp->cmdtype = entry->cmdtype;
807 	cmdp->param = entry->u;
808 	INTON;
809 }
810 
811 
812 /*
813  * Define a shell function.
814  */
815 
816 void
817 defun(name, func)
818 	char *name;
819 	union node *func;
820 	{
821 	struct cmdentry entry;
822 
823 	INTOFF;
824 	entry.cmdtype = CMDFUNCTION;
825 	entry.u.func = copyfunc(func);
826 	addcmdentry(name, &entry);
827 	INTON;
828 }
829 
830 
831 /*
832  * Delete a function if it exists.
833  */
834 
835 int
836 unsetfunc(name)
837 	char *name;
838 	{
839 	struct tblentry *cmdp;
840 
841 	if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
842 		freefunc(cmdp->param.func);
843 		delete_cmd_entry();
844 		return (0);
845 	}
846 	return (1);
847 }
848 
849 /*
850  * Locate and print what a word is...
851  */
852 
853 int
854 typecmd(argc, argv)
855 	int argc;
856 	char **argv;
857 {
858 	struct cmdentry entry;
859 	struct tblentry *cmdp;
860 	char **pp;
861 	struct alias *ap;
862 	int i;
863 	int error = 0;
864 	extern char *const parsekwd[];
865 
866 	for (i = 1; i < argc; i++) {
867 		out1str(argv[i]);
868 		/* First look at the keywords */
869 		for (pp = (char **)parsekwd; *pp; pp++)
870 			if (**pp == *argv[i] && equal(*pp, argv[i]))
871 				break;
872 
873 		if (*pp) {
874 			out1str(" is a shell keyword\n");
875 			continue;
876 		}
877 
878 		/* Then look at the aliases */
879 		if ((ap = lookupalias(argv[i], 1)) != NULL) {
880 			out1fmt(" is an alias for %s\n", ap->val);
881 			continue;
882 		}
883 
884 		/* Then check if it is a tracked alias */
885 		if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
886 			entry.cmdtype = cmdp->cmdtype;
887 			entry.u = cmdp->param;
888 		}
889 		else {
890 			/* Finally use brute force */
891 			find_command(argv[i], &entry, 0, pathval());
892 		}
893 
894 		switch (entry.cmdtype) {
895 		case CMDNORMAL: {
896 			int j = entry.u.index;
897 			char *path = pathval(), *name;
898 			do {
899 				name = padvance(&path, argv[i]);
900 				stunalloc(name);
901 			} while (--j >= 0);
902 			out1fmt(" is%s %s\n",
903 			    cmdp ? " a tracked alias for" : "", name);
904 			break;
905 		}
906 		case CMDFUNCTION:
907 			out1str(" is a shell function\n");
908 			break;
909 
910 		case CMDBUILTIN:
911 			out1str(" is a shell builtin\n");
912 			break;
913 
914 		default:
915 			out1str(" not found\n");
916 			error |= 127;
917 			break;
918 		}
919 	}
920 	return error;
921 }
922