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