2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
39 static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
41 static const char rcsid[] =
45 #include <sys/types.h>
53 * When commands are first encountered, they are entered in a hash table.
54 * This ensures that a full path search will not have to be done for them
57 * We should investigate converting to a linear search, even though that
58 * would make the command name "hash" a misnomer.
83 #define CMDTABLESIZE 31 /* should be prime */
84 #define ARB 1 /* actual size determined at run time */
89 struct tblentry *next; /* next entry in hash chain */
90 union param param; /* definition of builtin function */
91 short cmdtype; /* index identifying command */
92 char rehash; /* if set, cd done since entry created */
93 char cmdname[ARB]; /* name of command */
97 STATIC struct tblentry *cmdtable[CMDTABLESIZE];
98 STATIC int builtinloc = -1; /* index in path of %builtin, or -1 */
99 int exerrno = 0; /* Last exec error */
102 STATIC void tryexec __P((char *, char **, char **));
104 STATIC void execinterp __P((char **, char **));
106 STATIC void printentry __P((struct tblentry *, int));
107 STATIC void clearcmdentry __P((int));
108 STATIC struct tblentry *cmdlookup __P((char *, int));
109 STATIC void delete_cmd_entry __P((void));
114 * Exec a program. Never returns. If you change this routine, you may
115 * have to change the find_command routine as well.
119 shellexec(argv, envp, path, index)
127 if (strchr(argv[0], '/') != NULL) {
128 tryexec(argv[0], argv, envp);
132 while ((cmdname = padvance(&path, argv[0])) != NULL) {
133 if (--index < 0 && pathopt == NULL) {
134 tryexec(cmdname, argv, envp);
135 if (errno != ENOENT && errno != ENOTDIR)
142 /* Map to POSIX errors */
154 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
159 tryexec(cmd, argv, envp)
171 execve(cmd, argv, envp);
172 } while (errno == EINTR);
174 execve(cmd, argv, envp);
179 setinputfile(cmd, 0);
180 commandname = arg0 = savestr(argv[0]);
182 pgetc(); pungetc(); /* fill up input buffer */
184 if (parsenleft > 2 && p[0] == '#' && p[1] == '!') {
186 execinterp(argv, envp);
190 exraise(EXSHELLPROC);
199 * Execute an interpreter introduced by "#!", for systems where this
200 * feature has not been built into the kernel. If the interpreter is
201 * the shell, return (effectively ignoring the "#!"). If the execution
202 * of the interpreter fails, exit.
204 * This code peeks inside the input buffer in order to avoid actually
205 * reading any input. It would benefit from a rewrite.
211 execinterp(argv, envp)
220 char *newargs[NEWARGS];
226 inp = parsenextc + 2;
229 while (--n >= 0 && (*inp == ' ' || *inp == '\t'))
233 if ((c = *inp++) == '\n')
235 if (ap == &newargs[NEWARGS])
236 bad: error("Bad #! line");
240 } while (--n >= 0 && (c = *inp++) != ' ' && c != '\t' && c != '\n');
243 *ap++ = grabstackstr(outp);
245 if (ap == newargs + 1) { /* if no args, maybe no exec is needed */
248 if (equal(p, "sh") || equal(p, "ash")) {
260 i = (char *)ap - (char *)newargs; /* size in bytes */
262 error("Bad #! line");
263 for (ap2 = argv ; *ap2++ != NULL ; );
264 new = ckmalloc(i + ((char *)ap2 - (char *)argv));
265 ap = newargs, ap2 = new;
266 while ((i -= sizeof (char **)) >= 0)
269 while (*ap2++ = *ap++);
270 shellexec(new, envp, pathval(), 0);
277 * Do a path search. The variable path (passed by reference) should be
278 * set to the start of the path before the first call; padvance will update
279 * this value as it proceeds. Successive calls to padvance will return
280 * the possible path expansions in sequence. If an option (indicated by
281 * a percent sign) appears in the path entry then the global variable
282 * pathopt will be set to point to it; otherwise pathopt will be set to
300 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
301 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
302 while (stackblocksize() < len)
306 memcpy(q, start, p - start);
314 while (*p && *p != ':') p++;
325 /*** Command hashing code ***/
331 char **argv __unused;
333 struct tblentry **pp;
334 struct tblentry *cmdp;
337 struct cmdentry entry;
341 while ((c = nextopt("rv")) != '\0') {
344 } else if (c == 'v') {
348 if (*argptr == NULL) {
349 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
350 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
351 printentry(cmdp, verbose);
356 while ((name = *argptr) != NULL) {
357 if ((cmdp = cmdlookup(name, 0)) != NULL
358 && (cmdp->cmdtype == CMDNORMAL
359 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
361 find_command(name, &entry, 1, pathval());
363 if (entry.cmdtype != CMDUNKNOWN) { /* if no error msg */
364 cmdp = cmdlookup(name, 0);
365 printentry(cmdp, verbose);
376 printentry(cmdp, verbose)
377 struct tblentry *cmdp;
384 if (cmdp->cmdtype == CMDNORMAL) {
385 index = cmdp->param.index;
388 name = padvance(&path, cmdp->cmdname);
390 } while (--index >= 0);
392 } else if (cmdp->cmdtype == CMDBUILTIN) {
393 out1fmt("builtin %s", cmdp->cmdname);
394 } else if (cmdp->cmdtype == CMDFUNCTION) {
395 out1fmt("function %s", cmdp->cmdname);
398 name = commandtext(cmdp->param.func);
406 error("internal error: cmdtype %d", cmdp->cmdtype);
417 * Resolve a command name. If you change this routine, you may have to
418 * change the shellexec routine as well.
422 find_command(name, entry, printerr, path)
424 struct cmdentry *entry;
428 struct tblentry *cmdp;
436 /* If name contains a slash, don't use the hash table */
437 if (strchr(name, '/') != NULL) {
438 entry->cmdtype = CMDNORMAL;
443 /* If name is in the table, and not invalidated by cd, we're done */
444 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0)
447 /* If %builtin not in path, check for builtin next */
448 if (builtinloc < 0 && (i = find_builtin(name)) >= 0) {
450 cmdp = cmdlookup(name, 1);
451 cmdp->cmdtype = CMDBUILTIN;
452 cmdp->param.index = i;
457 /* We have to search path. */
458 prev = -1; /* where to start */
459 if (cmdp) { /* doing a rehash */
460 if (cmdp->cmdtype == CMDBUILTIN)
463 prev = cmdp->param.index;
469 while ((fullname = padvance(&path, name)) != NULL) {
473 if (prefix("builtin", pathopt)) {
474 if ((i = find_builtin(name)) < 0)
477 cmdp = cmdlookup(name, 1);
478 cmdp->cmdtype = CMDBUILTIN;
479 cmdp->param.index = i;
482 } else if (prefix("func", pathopt)) {
485 goto loop; /* ignore unimplemented options */
488 /* if rehash, don't redo absolute path names */
489 if (fullname[0] == '/' && index <= prev) {
492 TRACE(("searchexec \"%s\": no change\n", name));
495 while (stat(fullname, &statb) < 0) {
500 if (errno != ENOENT && errno != ENOTDIR)
504 e = EACCES; /* if we fail, this will be the error */
505 if (!S_ISREG(statb.st_mode))
507 if (pathopt) { /* this is a %func directory */
508 stalloc(strlen(fullname) + 1);
509 readcmdfile(fullname);
510 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
511 error("%s not defined in %s", name, fullname);
516 if (statb.st_uid == geteuid()) {
517 if ((statb.st_mode & 0100) == 0)
519 } else if (statb.st_gid == getegid()) {
520 if ((statb.st_mode & 010) == 0)
523 if ((statb.st_mode & 01) == 0)
527 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
529 cmdp = cmdlookup(name, 1);
530 cmdp->cmdtype = CMDNORMAL;
531 cmdp->param.index = index;
536 /* We failed. If there was an entry for this command, delete it */
540 outfmt(out2, "%s: %s\n", name, errmsg(e, E_EXEC));
541 entry->cmdtype = CMDUNKNOWN;
546 entry->cmdtype = cmdp->cmdtype;
547 entry->u = cmdp->param;
553 * Search the table of builtin commands.
560 const struct builtincmd *bp;
562 for (bp = builtincmd ; bp->name ; bp++) {
563 if (*bp->name == *name && equal(bp->name, name))
572 * Called when a cd is done. Marks all commands so the next time they
573 * are executed they will be rehashed.
578 struct tblentry **pp;
579 struct tblentry *cmdp;
581 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
582 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
583 if (cmdp->cmdtype == CMDNORMAL
584 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
593 * Called before PATH is changed. The argument is the new value of PATH;
594 * pathval() still returns the old value at this point. Called with
602 const char *old, *new;
609 firstchange = 9999; /* assume no change */
615 if ((*old == '\0' && *new == ':')
616 || (*old == ':' && *new == '\0'))
618 old = new; /* ignore subsequent differences */
622 if (*new == '%' && bltin < 0 && prefix("builtin", new + 1))
629 if (builtinloc < 0 && bltin >= 0)
630 builtinloc = bltin; /* zap builtins */
631 if (builtinloc >= 0 && bltin < 0)
633 clearcmdentry(firstchange);
639 * Clear out command entries. The argument specifies the first entry in
640 * PATH which has changed.
644 clearcmdentry(firstchange)
647 struct tblentry **tblp;
648 struct tblentry **pp;
649 struct tblentry *cmdp;
652 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
654 while ((cmdp = *pp) != NULL) {
655 if ((cmdp->cmdtype == CMDNORMAL &&
656 cmdp->param.index >= firstchange)
657 || (cmdp->cmdtype == CMDBUILTIN &&
658 builtinloc >= firstchange)) {
671 * Delete all functions.
675 MKINIT void deletefuncs();
684 struct tblentry **tblp;
685 struct tblentry **pp;
686 struct tblentry *cmdp;
689 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
691 while ((cmdp = *pp) != NULL) {
692 if (cmdp->cmdtype == CMDFUNCTION) {
694 freefunc(cmdp->param.func);
707 * Locate a command in the command hash table. If "add" is nonzero,
708 * add the command to the table if it is not already present. The
709 * variable "lastcmdentry" is set to point to the address of the link
710 * pointing to the entry, so that delete_cmd_entry can delete the
714 struct tblentry **lastcmdentry;
717 STATIC struct tblentry *
724 struct tblentry *cmdp;
725 struct tblentry **pp;
732 pp = &cmdtable[hashval % CMDTABLESIZE];
733 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
734 if (equal(cmdp->cmdname, name))
738 if (add && cmdp == NULL) {
740 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
743 cmdp->cmdtype = CMDUNKNOWN;
745 strcpy(cmdp->cmdname, name);
753 * Delete the command entry returned on the last lookup.
758 struct tblentry *cmdp;
761 cmdp = *lastcmdentry;
762 *lastcmdentry = cmdp->next;
771 getcmdentry(name, entry)
773 struct cmdentry *entry;
775 struct tblentry *cmdp = cmdlookup(name, 0);
778 entry->u = cmdp->param;
779 entry->cmdtype = cmdp->cmdtype;
781 entry->cmdtype = CMDUNKNOWN;
789 * Add a new command entry, replacing any existing command entry for
794 addcmdentry(name, entry)
796 struct cmdentry *entry;
798 struct tblentry *cmdp;
801 cmdp = cmdlookup(name, 1);
802 if (cmdp->cmdtype == CMDFUNCTION) {
803 freefunc(cmdp->param.func);
805 cmdp->cmdtype = entry->cmdtype;
806 cmdp->param = entry->u;
812 * Define a shell function.
820 struct cmdentry entry;
823 entry.cmdtype = CMDFUNCTION;
824 entry.u.func = copyfunc(func);
825 addcmdentry(name, &entry);
831 * Delete a function if it exists.
838 struct tblentry *cmdp;
840 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
841 freefunc(cmdp->param.func);
849 * Locate and print what a word is...
857 struct cmdentry entry;
858 struct tblentry *cmdp;
863 extern char *const parsekwd[];
865 for (i = 1; i < argc; i++) {
867 /* First look at the keywords */
868 for (pp = (char **)parsekwd; *pp; pp++)
869 if (**pp == *argv[i] && equal(*pp, argv[i]))
873 out1str(" is a shell keyword\n");
877 /* Then look at the aliases */
878 if ((ap = lookupalias(argv[i], 1)) != NULL) {
879 out1fmt(" is an alias for %s\n", ap->val);
883 /* Then check if it is a tracked alias */
884 if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
885 entry.cmdtype = cmdp->cmdtype;
886 entry.u = cmdp->param;
889 /* Finally use brute force */
890 find_command(argv[i], &entry, 0, pathval());
893 switch (entry.cmdtype) {
895 int j = entry.u.index;
896 char *path = pathval(), *name;
898 name = padvance(&path, argv[i]);
901 out1fmt(" is%s %s\n",
902 cmdp ? " a tracked alias for" : "", name);
906 out1str(" is a shell function\n");
910 out1str(" is a shell builtin\n");
914 out1str(" not found\n");