exec.c revision 242620
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 242620 2012-11-05 17:52:18Z 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
82
83
84struct tblentry {
85	struct tblentry *next;	/* next entry in hash chain */
86	union param param;	/* definition of builtin function */
87	int special;		/* flag for special builtin commands */
88	signed char cmdtype;	/* index identifying command */
89	char rehash;		/* if set, cd done since entry created */
90	char cmdname[];		/* name of command */
91};
92
93
94static struct tblentry *cmdtable[CMDTABLESIZE];
95int exerrno = 0;			/* Last exec error */
96
97
98static void tryexec(char *, char **, char **);
99static void printentry(struct tblentry *, int);
100static struct tblentry *cmdlookup(const char *, int);
101static void delete_cmd_entry(void);
102static void addcmdentry(const char *, struct cmdentry *);
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				if (e == ENOEXEC)
130					break;
131			}
132			stunalloc(cmdname);
133		}
134	}
135
136	/* Map to POSIX errors */
137	if (e == ENOENT || e == ENOTDIR) {
138		exerrno = 127;
139		exerror(EXEXEC, "%s: not found", argv[0]);
140	} else {
141		exerrno = 126;
142		exerror(EXEXEC, "%s: %s", argv[0], strerror(e));
143	}
144}
145
146
147static void
148tryexec(char *cmd, char **argv, char **envp)
149{
150	int e, in;
151	ssize_t n;
152	char buf[256];
153
154	execve(cmd, argv, envp);
155	e = errno;
156	if (e == ENOEXEC) {
157		INTOFF;
158		in = open(cmd, O_RDONLY | O_NONBLOCK);
159		if (in != -1) {
160			n = pread(in, buf, sizeof buf, 0);
161			close(in);
162			if (n > 0 && memchr(buf, '\0', n) != NULL) {
163				errno = ENOEXEC;
164				return;
165			}
166		}
167		*argv = cmd;
168		*--argv = _PATH_BSHELL;
169		execve(_PATH_BSHELL, argv, envp);
170	}
171	errno = e;
172}
173
174/*
175 * Do a path search.  The variable path (passed by reference) should be
176 * set to the start of the path before the first call; padvance will update
177 * this value as it proceeds.  Successive calls to padvance will return
178 * the possible path expansions in sequence.  If an option (indicated by
179 * a percent sign) appears in the path entry then the global variable
180 * pathopt will be set to point to it; otherwise pathopt will be set to
181 * NULL.
182 */
183
184const char *pathopt;
185
186char *
187padvance(const char **path, const char *name)
188{
189	const char *p, *start;
190	char *q;
191	int len;
192
193	if (*path == NULL)
194		return NULL;
195	start = *path;
196	for (p = start; *p && *p != ':' && *p != '%'; p++)
197		; /* nothing */
198	len = p - start + strlen(name) + 2;	/* "2" is for '/' and '\0' */
199	STARTSTACKSTR(q);
200	CHECKSTRSPACE(len, q);
201	if (p != start) {
202		memcpy(q, start, p - start);
203		q += p - start;
204		*q++ = '/';
205	}
206	strcpy(q, name);
207	pathopt = NULL;
208	if (*p == '%') {
209		pathopt = ++p;
210		while (*p && *p != ':')  p++;
211	}
212	if (*p == ':')
213		*path = p + 1;
214	else
215		*path = NULL;
216	return stalloc(len);
217}
218
219
220
221/*** Command hashing code ***/
222
223
224int
225hashcmd(int argc __unused, char **argv __unused)
226{
227	struct tblentry **pp;
228	struct tblentry *cmdp;
229	int c;
230	int verbose;
231	struct cmdentry entry;
232	char *name;
233	int errors;
234
235	errors = 0;
236	verbose = 0;
237	while ((c = nextopt("rv")) != '\0') {
238		if (c == 'r') {
239			clearcmdentry();
240		} else if (c == 'v') {
241			verbose++;
242		}
243	}
244	if (*argptr == NULL) {
245		for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
246			for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
247				if (cmdp->cmdtype == CMDNORMAL)
248					printentry(cmdp, verbose);
249			}
250		}
251		return 0;
252	}
253	while ((name = *argptr) != NULL) {
254		if ((cmdp = cmdlookup(name, 0)) != NULL
255		 && cmdp->cmdtype == CMDNORMAL)
256			delete_cmd_entry();
257		find_command(name, &entry, DO_ERR, pathval());
258		if (entry.cmdtype == CMDUNKNOWN)
259			errors = 1;
260		else if (verbose) {
261			cmdp = cmdlookup(name, 0);
262			if (cmdp != NULL)
263				printentry(cmdp, verbose);
264			else {
265				outfmt(out2, "%s: not found\n", name);
266				errors = 1;
267			}
268			flushall();
269		}
270		argptr++;
271	}
272	return errors;
273}
274
275
276static void
277printentry(struct tblentry *cmdp, int verbose)
278{
279	int idx;
280	const char *path;
281	char *name;
282
283	if (cmdp->cmdtype == CMDNORMAL) {
284		idx = cmdp->param.index;
285		path = pathval();
286		do {
287			name = padvance(&path, cmdp->cmdname);
288			stunalloc(name);
289		} while (--idx >= 0);
290		out1str(name);
291	} else if (cmdp->cmdtype == CMDBUILTIN) {
292		out1fmt("builtin %s", cmdp->cmdname);
293	} else if (cmdp->cmdtype == CMDFUNCTION) {
294		out1fmt("function %s", cmdp->cmdname);
295		if (verbose) {
296			INTOFF;
297			name = commandtext(getfuncnode(cmdp->param.func));
298			out1c(' ');
299			out1str(name);
300			ckfree(name);
301			INTON;
302		}
303#ifdef DEBUG
304	} else {
305		error("internal error: cmdtype %d", cmdp->cmdtype);
306#endif
307	}
308	if (cmdp->rehash)
309		out1c('*');
310	out1c('\n');
311}
312
313
314
315/*
316 * Resolve a command name.  If you change this routine, you may have to
317 * change the shellexec routine as well.
318 */
319
320void
321find_command(const char *name, struct cmdentry *entry, int act,
322    const char *path)
323{
324	struct tblentry *cmdp, loc_cmd;
325	int idx;
326	int prev;
327	char *fullname;
328	struct stat statb;
329	int e;
330	int i;
331	int spec;
332
333	/* If name contains a slash, don't use the hash table */
334	if (strchr(name, '/') != NULL) {
335		entry->cmdtype = CMDNORMAL;
336		entry->u.index = 0;
337		return;
338	}
339
340	/* If name is in the table, and not invalidated by cd, we're done */
341	if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
342		if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC)
343			cmdp = NULL;
344		else
345			goto success;
346	}
347
348	/* Check for builtin next */
349	if ((i = find_builtin(name, &spec)) >= 0) {
350		INTOFF;
351		cmdp = cmdlookup(name, 1);
352		if (cmdp->cmdtype == CMDFUNCTION)
353			cmdp = &loc_cmd;
354		cmdp->cmdtype = CMDBUILTIN;
355		cmdp->param.index = i;
356		cmdp->special = spec;
357		INTON;
358		goto success;
359	}
360
361	/* We have to search path. */
362	prev = -1;		/* where to start */
363	if (cmdp) {		/* doing a rehash */
364		if (cmdp->cmdtype == CMDBUILTIN)
365			prev = -1;
366		else
367			prev = cmdp->param.index;
368	}
369
370	e = ENOENT;
371	idx = -1;
372loop:
373	while ((fullname = padvance(&path, name)) != NULL) {
374		stunalloc(fullname);
375		idx++;
376		if (pathopt) {
377			if (prefix("func", pathopt)) {
378				/* handled below */
379			} else {
380				goto loop;	/* ignore unimplemented options */
381			}
382		}
383		/* if rehash, don't redo absolute path names */
384		if (fullname[0] == '/' && idx <= prev) {
385			if (idx < prev)
386				goto loop;
387			TRACE(("searchexec \"%s\": no change\n", name));
388			goto success;
389		}
390		if (stat(fullname, &statb) < 0) {
391			if (errno != ENOENT && errno != ENOTDIR)
392				e = errno;
393			goto loop;
394		}
395		e = EACCES;	/* if we fail, this will be the error */
396		if (!S_ISREG(statb.st_mode))
397			goto loop;
398		if (pathopt) {		/* this is a %func directory */
399			stalloc(strlen(fullname) + 1);
400			readcmdfile(fullname);
401			if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
402				error("%s not defined in %s", name, fullname);
403			stunalloc(fullname);
404			goto success;
405		}
406#ifdef notdef
407		if (statb.st_uid == geteuid()) {
408			if ((statb.st_mode & 0100) == 0)
409				goto loop;
410		} else if (statb.st_gid == getegid()) {
411			if ((statb.st_mode & 010) == 0)
412				goto loop;
413		} else {
414			if ((statb.st_mode & 01) == 0)
415				goto loop;
416		}
417#endif
418		TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
419		INTOFF;
420		cmdp = cmdlookup(name, 1);
421		if (cmdp->cmdtype == CMDFUNCTION)
422			cmdp = &loc_cmd;
423		cmdp->cmdtype = CMDNORMAL;
424		cmdp->param.index = idx;
425		INTON;
426		goto success;
427	}
428
429	/* We failed.  If there was an entry for this command, delete it */
430	if (cmdp && cmdp->cmdtype != CMDFUNCTION)
431		delete_cmd_entry();
432	if (act & DO_ERR) {
433		if (e == ENOENT || e == ENOTDIR)
434			outfmt(out2, "%s: not found\n", name);
435		else
436			outfmt(out2, "%s: %s\n", name, strerror(e));
437	}
438	entry->cmdtype = CMDUNKNOWN;
439	entry->u.index = 0;
440	return;
441
442success:
443	cmdp->rehash = 0;
444	entry->cmdtype = cmdp->cmdtype;
445	entry->u = cmdp->param;
446	entry->special = cmdp->special;
447}
448
449
450
451/*
452 * Search the table of builtin commands.
453 */
454
455int
456find_builtin(const char *name, int *special)
457{
458	const struct builtincmd *bp;
459
460	for (bp = builtincmd ; bp->name ; bp++) {
461		if (*bp->name == *name && equal(bp->name, name)) {
462			*special = bp->special;
463			return bp->code;
464		}
465	}
466	return -1;
467}
468
469
470
471/*
472 * Called when a cd is done.  Marks all commands so the next time they
473 * are executed they will be rehashed.
474 */
475
476void
477hashcd(void)
478{
479	struct tblentry **pp;
480	struct tblentry *cmdp;
481
482	for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
483		for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
484			if (cmdp->cmdtype == CMDNORMAL)
485				cmdp->rehash = 1;
486		}
487	}
488}
489
490
491
492/*
493 * Called before PATH is changed.  The argument is the new value of PATH;
494 * pathval() still returns the old value at this point.  Called with
495 * interrupts off.
496 */
497
498void
499changepath(const char *newval __unused)
500{
501	clearcmdentry();
502}
503
504
505/*
506 * Clear out command entries.  The argument specifies the first entry in
507 * PATH which has changed.
508 */
509
510void
511clearcmdentry(void)
512{
513	struct tblentry **tblp;
514	struct tblentry **pp;
515	struct tblentry *cmdp;
516
517	INTOFF;
518	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
519		pp = tblp;
520		while ((cmdp = *pp) != NULL) {
521			if (cmdp->cmdtype == CMDNORMAL) {
522				*pp = cmdp->next;
523				ckfree(cmdp);
524			} else {
525				pp = &cmdp->next;
526			}
527		}
528	}
529	INTON;
530}
531
532
533/*
534 * Locate a command in the command hash table.  If "add" is nonzero,
535 * add the command to the table if it is not already present.  The
536 * variable "lastcmdentry" is set to point to the address of the link
537 * pointing to the entry, so that delete_cmd_entry can delete the
538 * entry.
539 */
540
541static struct tblentry **lastcmdentry;
542
543
544static struct tblentry *
545cmdlookup(const char *name, int add)
546{
547	int hashval;
548	const char *p;
549	struct tblentry *cmdp;
550	struct tblentry **pp;
551
552	p = name;
553	hashval = *p << 4;
554	while (*p)
555		hashval += *p++;
556	hashval &= 0x7FFF;
557	pp = &cmdtable[hashval % CMDTABLESIZE];
558	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
559		if (equal(cmdp->cmdname, name))
560			break;
561		pp = &cmdp->next;
562	}
563	if (add && cmdp == NULL) {
564		INTOFF;
565		cmdp = *pp = ckmalloc(sizeof (struct tblentry)
566					+ strlen(name) + 1);
567		cmdp->next = NULL;
568		cmdp->cmdtype = CMDUNKNOWN;
569		cmdp->rehash = 0;
570		strcpy(cmdp->cmdname, name);
571		INTON;
572	}
573	lastcmdentry = pp;
574	return cmdp;
575}
576
577/*
578 * Delete the command entry returned on the last lookup.
579 */
580
581static void
582delete_cmd_entry(void)
583{
584	struct tblentry *cmdp;
585
586	INTOFF;
587	cmdp = *lastcmdentry;
588	*lastcmdentry = cmdp->next;
589	ckfree(cmdp);
590	INTON;
591}
592
593
594
595/*
596 * Add a new command entry, replacing any existing command entry for
597 * the same name.
598 */
599
600static void
601addcmdentry(const char *name, struct cmdentry *entry)
602{
603	struct tblentry *cmdp;
604
605	INTOFF;
606	cmdp = cmdlookup(name, 1);
607	if (cmdp->cmdtype == CMDFUNCTION) {
608		unreffunc(cmdp->param.func);
609	}
610	cmdp->cmdtype = entry->cmdtype;
611	cmdp->param = entry->u;
612	INTON;
613}
614
615
616/*
617 * Define a shell function.
618 */
619
620void
621defun(const char *name, union node *func)
622{
623	struct cmdentry entry;
624
625	INTOFF;
626	entry.cmdtype = CMDFUNCTION;
627	entry.u.func = copyfunc(func);
628	addcmdentry(name, &entry);
629	INTON;
630}
631
632
633/*
634 * Delete a function if it exists.
635 */
636
637int
638unsetfunc(const char *name)
639{
640	struct tblentry *cmdp;
641
642	if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
643		unreffunc(cmdp->param.func);
644		delete_cmd_entry();
645		return (0);
646	}
647	return (0);
648}
649
650
651/*
652 * Check if a function by a certain name exists.
653 */
654int
655isfunc(const char *name)
656{
657	struct tblentry *cmdp;
658	cmdp = cmdlookup(name, 0);
659	return (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION);
660}
661
662
663/*
664 * Shared code for the following builtin commands:
665 *    type, command -v, command -V
666 */
667
668int
669typecmd_impl(int argc, char **argv, int cmd, const char *path)
670{
671	struct cmdentry entry;
672	struct tblentry *cmdp;
673	const char *const *pp;
674	struct alias *ap;
675	int i;
676	int error1 = 0;
677
678	if (path != pathval())
679		clearcmdentry();
680
681	for (i = 1; i < argc; i++) {
682		/* First look at the keywords */
683		for (pp = parsekwd; *pp; pp++)
684			if (**pp == *argv[i] && equal(*pp, argv[i]))
685				break;
686
687		if (*pp) {
688			if (cmd == TYPECMD_SMALLV)
689				out1fmt("%s\n", argv[i]);
690			else
691				out1fmt("%s is a shell keyword\n", argv[i]);
692			continue;
693		}
694
695		/* Then look at the aliases */
696		if ((ap = lookupalias(argv[i], 1)) != NULL) {
697			if (cmd == TYPECMD_SMALLV)
698				out1fmt("alias %s='%s'\n", argv[i], ap->val);
699			else
700				out1fmt("%s is an alias for %s\n", argv[i],
701				    ap->val);
702			continue;
703		}
704
705		/* Then check if it is a tracked alias */
706		if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
707			entry.cmdtype = cmdp->cmdtype;
708			entry.u = cmdp->param;
709			entry.special = cmdp->special;
710		}
711		else {
712			/* Finally use brute force */
713			find_command(argv[i], &entry, 0, path);
714		}
715
716		switch (entry.cmdtype) {
717		case CMDNORMAL: {
718			if (strchr(argv[i], '/') == NULL) {
719				const char *path2 = path;
720				char *name;
721				int j = entry.u.index;
722				do {
723					name = padvance(&path2, argv[i]);
724					stunalloc(name);
725				} while (--j >= 0);
726				if (cmd == TYPECMD_SMALLV)
727					out1fmt("%s\n", name);
728				else
729					out1fmt("%s is%s %s\n", argv[i],
730					    (cmdp && cmd == TYPECMD_TYPE) ?
731						" a tracked alias for" : "",
732					    name);
733			} else {
734				if (eaccess(argv[i], X_OK) == 0) {
735					if (cmd == TYPECMD_SMALLV)
736						out1fmt("%s\n", argv[i]);
737					else
738						out1fmt("%s is %s\n", argv[i],
739						    argv[i]);
740				} else {
741					if (cmd != TYPECMD_SMALLV)
742						outfmt(out2, "%s: %s\n",
743						    argv[i], strerror(errno));
744					error1 |= 127;
745				}
746			}
747			break;
748		}
749		case CMDFUNCTION:
750			if (cmd == TYPECMD_SMALLV)
751				out1fmt("%s\n", argv[i]);
752			else
753				out1fmt("%s is a shell function\n", argv[i]);
754			break;
755
756		case CMDBUILTIN:
757			if (cmd == TYPECMD_SMALLV)
758				out1fmt("%s\n", argv[i]);
759			else if (entry.special)
760				out1fmt("%s is a special shell builtin\n",
761				    argv[i]);
762			else
763				out1fmt("%s is a shell builtin\n", argv[i]);
764			break;
765
766		default:
767			if (cmd != TYPECMD_SMALLV)
768				outfmt(out2, "%s: not found\n", argv[i]);
769			error1 |= 127;
770			break;
771		}
772	}
773
774	if (path != pathval())
775		clearcmdentry();
776
777	return error1;
778}
779
780/*
781 * Locate and print what a word is...
782 */
783
784int
785typecmd(int argc, char **argv)
786{
787	return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1));
788}
789