exec.c revision 218242
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 218242 2011-02-03 23:38:11Z 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 <stdlib.h>
47
48/*
49 * When commands are first encountered, they are entered in a hash table.
50 * This ensures that a full path search will not have to be done for them
51 * on each invocation.
52 *
53 * We should investigate converting to a linear search, even though that
54 * would make the command name "hash" a misnomer.
55 */
56
57#include "shell.h"
58#include "main.h"
59#include "nodes.h"
60#include "parser.h"
61#include "redir.h"
62#include "eval.h"
63#include "exec.h"
64#include "builtins.h"
65#include "var.h"
66#include "options.h"
67#include "input.h"
68#include "output.h"
69#include "syntax.h"
70#include "memalloc.h"
71#include "error.h"
72#include "init.h"
73#include "mystring.h"
74#include "show.h"
75#include "jobs.h"
76#include "alias.h"
77
78
79#define CMDTABLESIZE 31		/* should be prime */
80#define ARB 1			/* actual size determined at run time */
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	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];
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);
102
103
104
105/*
106 * Exec a program.  Never returns.  If you change this routine, you may
107 * have to change the find_command routine as well.
108 */
109
110void
111shellexec(char **argv, char **envp, const char *path, int idx)
112{
113	char *cmdname;
114	int e;
115
116	if (strchr(argv[0], '/') != NULL) {
117		tryexec(argv[0], argv, envp);
118		e = errno;
119	} else {
120		e = ENOENT;
121		while ((cmdname = padvance(&path, argv[0])) != NULL) {
122			if (--idx < 0 && pathopt == NULL) {
123				tryexec(cmdname, argv, envp);
124				if (errno != ENOENT && errno != ENOTDIR)
125					e = errno;
126			}
127			stunalloc(cmdname);
128		}
129	}
130
131	/* Map to POSIX errors */
132	if (e == ENOENT || e == ENOTDIR) {
133		exerrno = 127;
134		exerror(EXEXEC, "%s: not found", argv[0]);
135	} else {
136		exerrno = 126;
137		exerror(EXEXEC, "%s: %s", argv[0], strerror(e));
138	}
139}
140
141
142static void
143tryexec(char *cmd, char **argv, char **envp)
144{
145	int e;
146
147	execve(cmd, argv, envp);
148	e = errno;
149	if (e == ENOEXEC) {
150		initshellproc();
151		setinputfile(cmd, 0);
152		commandname = arg0 = savestr(argv[0]);
153		setparam(argv + 1);
154		exraise(EXSHELLPROC);
155		/*NOTREACHED*/
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 * Delete all functions.
541 */
542
543#ifdef mkinit
544MKINIT void deletefuncs(void);
545
546SHELLPROC {
547	deletefuncs();
548}
549#endif
550
551void
552deletefuncs(void)
553{
554	struct tblentry **tblp;
555	struct tblentry **pp;
556	struct tblentry *cmdp;
557
558	INTOFF;
559	for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
560		pp = tblp;
561		while ((cmdp = *pp) != NULL) {
562			if (cmdp->cmdtype == CMDFUNCTION) {
563				*pp = cmdp->next;
564				unreffunc(cmdp->param.func);
565				ckfree(cmdp);
566			} else {
567				pp = &cmdp->next;
568			}
569		}
570	}
571	INTON;
572}
573
574
575
576/*
577 * Locate a command in the command hash table.  If "add" is nonzero,
578 * add the command to the table if it is not already present.  The
579 * variable "lastcmdentry" is set to point to the address of the link
580 * pointing to the entry, so that delete_cmd_entry can delete the
581 * entry.
582 */
583
584static struct tblentry **lastcmdentry;
585
586
587static struct tblentry *
588cmdlookup(const char *name, int add)
589{
590	int hashval;
591	const char *p;
592	struct tblentry *cmdp;
593	struct tblentry **pp;
594
595	p = name;
596	hashval = *p << 4;
597	while (*p)
598		hashval += *p++;
599	hashval &= 0x7FFF;
600	pp = &cmdtable[hashval % CMDTABLESIZE];
601	for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
602		if (equal(cmdp->cmdname, name))
603			break;
604		pp = &cmdp->next;
605	}
606	if (add && cmdp == NULL) {
607		INTOFF;
608		cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
609					+ strlen(name) + 1);
610		cmdp->next = NULL;
611		cmdp->cmdtype = CMDUNKNOWN;
612		cmdp->rehash = 0;
613		strcpy(cmdp->cmdname, name);
614		INTON;
615	}
616	lastcmdentry = pp;
617	return cmdp;
618}
619
620/*
621 * Delete the command entry returned on the last lookup.
622 */
623
624static void
625delete_cmd_entry(void)
626{
627	struct tblentry *cmdp;
628
629	INTOFF;
630	cmdp = *lastcmdentry;
631	*lastcmdentry = cmdp->next;
632	ckfree(cmdp);
633	INTON;
634}
635
636
637
638/*
639 * Add a new command entry, replacing any existing command entry for
640 * the same name.
641 */
642
643void
644addcmdentry(const char *name, struct cmdentry *entry)
645{
646	struct tblentry *cmdp;
647
648	INTOFF;
649	cmdp = cmdlookup(name, 1);
650	if (cmdp->cmdtype == CMDFUNCTION) {
651		unreffunc(cmdp->param.func);
652	}
653	cmdp->cmdtype = entry->cmdtype;
654	cmdp->param = entry->u;
655	INTON;
656}
657
658
659/*
660 * Define a shell function.
661 */
662
663void
664defun(const char *name, union node *func)
665{
666	struct cmdentry entry;
667
668	INTOFF;
669	entry.cmdtype = CMDFUNCTION;
670	entry.u.func = copyfunc(func);
671	addcmdentry(name, &entry);
672	INTON;
673}
674
675
676/*
677 * Delete a function if it exists.
678 */
679
680int
681unsetfunc(const char *name)
682{
683	struct tblentry *cmdp;
684
685	if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
686		unreffunc(cmdp->param.func);
687		delete_cmd_entry();
688		return (0);
689	}
690	return (0);
691}
692
693/*
694 * Shared code for the following builtin commands:
695 *    type, command -v, command -V
696 */
697
698int
699typecmd_impl(int argc, char **argv, int cmd, const char *path)
700{
701	struct cmdentry entry;
702	struct tblentry *cmdp;
703	const char *const *pp;
704	struct alias *ap;
705	int i;
706	int error1 = 0;
707
708	if (path != pathval())
709		clearcmdentry(0);
710
711	for (i = 1; i < argc; i++) {
712		/* First look at the keywords */
713		for (pp = parsekwd; *pp; pp++)
714			if (**pp == *argv[i] && equal(*pp, argv[i]))
715				break;
716
717		if (*pp) {
718			if (cmd == TYPECMD_SMALLV)
719				out1fmt("%s\n", argv[i]);
720			else
721				out1fmt("%s is a shell keyword\n", argv[i]);
722			continue;
723		}
724
725		/* Then look at the aliases */
726		if ((ap = lookupalias(argv[i], 1)) != NULL) {
727			if (cmd == TYPECMD_SMALLV)
728				out1fmt("alias %s='%s'\n", argv[i], ap->val);
729			else
730				out1fmt("%s is an alias for %s\n", argv[i],
731				    ap->val);
732			continue;
733		}
734
735		/* Then check if it is a tracked alias */
736		if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
737			entry.cmdtype = cmdp->cmdtype;
738			entry.u = cmdp->param;
739			entry.special = cmdp->special;
740		}
741		else {
742			/* Finally use brute force */
743			find_command(argv[i], &entry, 0, path);
744		}
745
746		switch (entry.cmdtype) {
747		case CMDNORMAL: {
748			if (strchr(argv[i], '/') == NULL) {
749				const char *path2 = path;
750				char *name;
751				int j = entry.u.index;
752				do {
753					name = padvance(&path2, argv[i]);
754					stunalloc(name);
755				} while (--j >= 0);
756				if (cmd == TYPECMD_SMALLV)
757					out1fmt("%s\n", name);
758				else
759					out1fmt("%s is%s %s\n", argv[i],
760					    (cmdp && cmd == TYPECMD_TYPE) ?
761						" a tracked alias for" : "",
762					    name);
763			} else {
764				if (eaccess(argv[i], X_OK) == 0) {
765					if (cmd == TYPECMD_SMALLV)
766						out1fmt("%s\n", argv[i]);
767					else
768						out1fmt("%s is %s\n", argv[i],
769						    argv[i]);
770				} else {
771					if (cmd != TYPECMD_SMALLV)
772						outfmt(out2, "%s: %s\n",
773						    argv[i], strerror(errno));
774					error1 |= 127;
775				}
776			}
777			break;
778		}
779		case CMDFUNCTION:
780			if (cmd == TYPECMD_SMALLV)
781				out1fmt("%s\n", argv[i]);
782			else
783				out1fmt("%s is a shell function\n", argv[i]);
784			break;
785
786		case CMDBUILTIN:
787			if (cmd == TYPECMD_SMALLV)
788				out1fmt("%s\n", argv[i]);
789			else if (entry.special)
790				out1fmt("%s is a special shell builtin\n",
791				    argv[i]);
792			else
793				out1fmt("%s is a shell builtin\n", argv[i]);
794			break;
795
796		default:
797			if (cmd != TYPECMD_SMALLV)
798				outfmt(out2, "%s: not found\n", argv[i]);
799			error1 |= 127;
800			break;
801		}
802	}
803
804	if (path != pathval())
805		clearcmdentry(0);
806
807	return error1;
808}
809
810/*
811 * Locate and print what a word is...
812 */
813
814int
815typecmd(int argc, char **argv)
816{
817	return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1));
818}
819