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