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