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