1 /* $NetBSD: exec.c,v 1.41 2008/02/15 17:26:06 matt Exp $ */
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
38 static char sccsid
[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95";
40 __RCSID("$NetBSD: exec.c,v 1.41 2008/02/15 17:26:06 matt Exp $");
44 #include <sys/types.h>
54 * When commands are first encountered, they are entered in a hash table.
55 * This ensures that a full path search will not have to be done for them
58 * We should investigate converting to a linear search, even though that
59 * would make the command name "hash" a misnomer.
84 #define CMDTABLESIZE 31 /* should be prime */
85 #define ARB 1 /* actual size determined at run time */
90 struct tblentry
*next
; /* next entry in hash chain */
91 union param param
; /* definition of builtin function */
92 short cmdtype
; /* index identifying command */
93 char rehash
; /* if set, cd done since entry created */
94 char cmdname
[ARB
]; /* name of command */
98 STATIC
struct tblentry
*cmdtable
[CMDTABLESIZE
];
99 STATIC
int builtinloc
= -1; /* index in path of %builtin, or -1 */
100 int exerrno
= 0; /* Last exec error */
103 STATIC
void tryexec(char *, char **, char **, int);
104 STATIC
void printentry(struct tblentry
*, int);
105 STATIC
void clearcmdentry(int);
106 STATIC
struct tblentry
*cmdlookup(const char *, int);
107 STATIC
void delete_cmd_entry(void);
110 STATIC
void execinterp(char **, char **);
114 extern const char *const parsekwd
[];
117 * Exec a program. Never returns. If you change this routine, you may
118 * have to change the find_command routine as well.
122 shellexec(char **argv
, char **envp
, const char *path
, int idx
, int vforked
)
127 if (strchr(argv
[0], '/') != NULL
) {
128 tryexec(argv
[0], argv
, envp
, vforked
);
132 while ((cmdname
= padvance(&path
, argv
[0])) != NULL
) {
133 if (--idx
< 0 && pathopt
== NULL
) {
134 tryexec(cmdname
, argv
, envp
, vforked
);
135 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
142 /* Map to POSIX errors */
154 TRACE(("shellexec failed for %s, errno %d, vforked %d, suppressint %d\n",
155 argv
[0], e
, vforked
, suppressint
));
156 exerror(EXEXEC
, "%s: %s", argv
[0], errmsg(e
, E_EXEC
));
162 tryexec(char *cmd
, char **argv
, char **envp
, int vforked
)
171 execve(cmd
, argv
, envp
);
172 } while (errno
== EINTR
);
174 execve(cmd
, argv
, envp
);
179 /* We are currently vfork(2)ed, so raise an
180 * exception, and evalcommand will try again
181 * with a normal fork(2).
183 exraise(EXSHELLPROC
);
186 TRACE(("execve(cmd=%s) returned ENOEXEC\n", cmd
));
189 setinputfile(cmd
, 0);
190 commandname
= arg0
= savestr(argv
[0]);
192 pgetc(); pungetc(); /* fill up input buffer */
194 if (parsenleft
> 2 && p
[0] == '#' && p
[1] == '!') {
196 execinterp(argv
, envp
);
200 exraise(EXSHELLPROC
);
208 * Execute an interpreter introduced by "#!", for systems where this
209 * feature has not been built into the kernel. If the interpreter is
210 * the shell, return (effectively ignoring the "#!"). If the execution
211 * of the interpreter fails, exit.
213 * This code peeks inside the input buffer in order to avoid actually
214 * reading any input. It would benefit from a rewrite.
220 execinterp(char **argv
, char **envp
)
228 char *newargs
[NEWARGS
];
234 inp
= parsenextc
+ 2;
237 while (--n
>= 0 && (*inp
== ' ' || *inp
== '\t'))
241 if ((c
= *inp
++) == '\n')
243 if (ap
== &newargs
[NEWARGS
])
244 bad
: error("Bad #! line");
248 } while (--n
>= 0 && (c
= *inp
++) != ' ' && c
!= '\t' && c
!= '\n');
251 *ap
++ = grabstackstr(outp
);
253 if (ap
== newargs
+ 1) { /* if no args, maybe no exec is needed */
256 if (equal(p
, "sh") || equal(p
, "ash")) {
268 i
= (char *)ap
- (char *)newargs
; /* size in bytes */
270 error("Bad #! line");
271 for (ap2
= argv
; *ap2
++ != NULL
; );
272 new = ckmalloc(i
+ ((char *)ap2
- (char *)argv
));
273 ap
= newargs
, ap2
= new;
274 while ((i
-= sizeof (char **)) >= 0)
277 while (*ap2
++ = *ap
++);
278 shellexec(new, envp
, pathval(), 0);
286 * Do a path search. The variable path (passed by reference) should be
287 * set to the start of the path before the first call; padvance will update
288 * this value as it proceeds. Successive calls to padvance will return
289 * the possible path expansions in sequence. If an option (indicated by
290 * a percent sign) appears in the path entry then the global variable
291 * pathopt will be set to point to it; otherwise pathopt will be set to
298 padvance(const char **path
, const char *name
)
308 for (p
= start
; *p
&& *p
!= ':' && *p
!= '%' ; p
++);
309 len
= p
- start
+ strlen(name
) + 2; /* "2" is for '/' and '\0' */
310 while (stackblocksize() < len
)
314 memcpy(q
, start
, p
- start
);
322 while (*p
&& *p
!= ':') p
++;
333 /*** Command hashing code ***/
337 hashcmd(int argc
, char **argv
)
339 struct tblentry
**pp
;
340 struct tblentry
*cmdp
;
343 struct cmdentry entry
;
347 while ((c
= nextopt("rv")) != '\0') {
350 } else if (c
== 'v') {
354 if (*argptr
== NULL
) {
355 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
] ; pp
++) {
356 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
357 if (verbose
|| cmdp
->cmdtype
== CMDNORMAL
)
358 printentry(cmdp
, verbose
);
363 while ((name
= *argptr
) != NULL
) {
364 if ((cmdp
= cmdlookup(name
, 0)) != NULL
365 && (cmdp
->cmdtype
== CMDNORMAL
366 || (cmdp
->cmdtype
== CMDBUILTIN
&& builtinloc
>= 0)))
368 find_command(name
, &entry
, DO_ERR
, pathval());
370 if (entry
.cmdtype
!= CMDUNKNOWN
) { /* if no error msg */
371 cmdp
= cmdlookup(name
, 0);
373 printentry(cmdp
, verbose
);
384 printentry(struct tblentry
*cmdp
, int verbose
)
390 switch (cmdp
->cmdtype
) {
392 idx
= cmdp
->param
.index
;
395 name
= padvance(&path
, cmdp
->cmdname
);
397 } while (--idx
>= 0);
401 out1fmt("special builtin %s", cmdp
->cmdname
);
404 out1fmt("builtin %s", cmdp
->cmdname
);
407 out1fmt("function %s", cmdp
->cmdname
);
411 commandtext(&ps
, cmdp
->param
.func
);
419 error("internal error: %s cmdtype %d", cmdp
->cmdname
, cmdp
->cmdtype
);
429 * Resolve a command name. If you change this routine, you may have to
430 * change the shellexec routine as well.
434 find_command(char *name
, struct cmdentry
*entry
, int act
, const char *path
)
436 struct tblentry
*cmdp
, loc_cmd
;
442 int (*bltin
)(int,char **);
444 /* If name contains a slash, don't use PATH or hash table */
445 if (strchr(name
, '/') != NULL
) {
447 while (stat(name
, &statb
) < 0) {
452 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
454 entry
->cmdtype
= CMDUNKNOWN
;
458 entry
->cmdtype
= CMDNORMAL
;
462 entry
->cmdtype
= CMDNORMAL
;
467 if (path
!= pathval())
470 if (act
& DO_ALTPATH
&& strstr(path
, "%builtin") != NULL
)
473 /* If name is in the table, check answer will be ok */
474 if ((cmdp
= cmdlookup(name
, 0)) != NULL
) {
476 switch (cmdp
->cmdtype
) {
478 if (act
& DO_ALTPATH
) {
484 if (act
& DO_NOFUNC
) {
490 if ((act
& DO_ALTBLTIN
) || builtinloc
>= 0) {
496 /* if not invalidated by cd, we're done */
497 if (cmdp
->rehash
== 0)
502 /* If %builtin not in path, check for builtin next */
503 if ((act
& DO_ALTPATH
? !(act
& DO_ALTBLTIN
) : builtinloc
< 0) &&
504 (bltin
= find_builtin(name
)) != 0)
505 goto builtin_success
;
507 /* We have to search path. */
508 prev
= -1; /* where to start */
509 if (cmdp
) { /* doing a rehash */
510 if (cmdp
->cmdtype
== CMDBUILTIN
)
513 prev
= cmdp
->param
.index
;
519 while ((fullname
= padvance(&path
, name
)) != NULL
) {
523 if (prefix("builtin", pathopt
)) {
524 if ((bltin
= find_builtin(name
)) == 0)
526 goto builtin_success
;
527 } else if (prefix("func", pathopt
)) {
530 /* ignore unimplemented options */
534 /* if rehash, don't redo absolute path names */
535 if (fullname
[0] == '/' && idx
<= prev
) {
538 TRACE(("searchexec \"%s\": no change\n", name
));
541 while (stat(fullname
, &statb
) < 0) {
546 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
550 e
= EACCES
; /* if we fail, this will be the error */
551 if (!S_ISREG(statb
.st_mode
))
553 if (pathopt
) { /* this is a %func directory */
556 stalloc(strlen(fullname
) + 1);
557 readcmdfile(fullname
);
558 if ((cmdp
= cmdlookup(name
, 0)) == NULL
||
559 cmdp
->cmdtype
!= CMDFUNCTION
)
560 error("%s not defined in %s", name
, fullname
);
565 /* XXX this code stops root executing stuff, and is buggy
566 if you need a group from the group list. */
567 if (statb
.st_uid
== geteuid()) {
568 if ((statb
.st_mode
& 0100) == 0)
570 } else if (statb
.st_gid
== getegid()) {
571 if ((statb
.st_mode
& 010) == 0)
574 if ((statb
.st_mode
& 01) == 0)
578 TRACE(("searchexec \"%s\" returns \"%s\"\n", name
, fullname
));
580 if (act
& DO_ALTPATH
) {
581 stalloc(strlen(fullname
) + 1);
584 cmdp
= cmdlookup(name
, 1);
585 cmdp
->cmdtype
= CMDNORMAL
;
586 cmdp
->param
.index
= idx
;
591 /* We failed. If there was an entry for this command, delete it */
595 outfmt(out2
, "%s: %s\n", name
, errmsg(e
, E_EXEC
));
596 entry
->cmdtype
= CMDUNKNOWN
;
601 if (act
& DO_ALTPATH
)
604 cmdp
= cmdlookup(name
, 1);
605 if (cmdp
->cmdtype
== CMDFUNCTION
)
606 /* DO_NOFUNC must have been set */
608 cmdp
->cmdtype
= CMDBUILTIN
;
609 cmdp
->param
.bltin
= bltin
;
614 entry
->cmdtype
= cmdp
->cmdtype
;
615 entry
->u
= cmdp
->param
;
617 entry
->cmdtype
= CMDUNKNOWN
;
623 * Search the table of builtin commands.
627 (*find_builtin(name
))(int, char **)
630 const struct builtincmd
*bp
;
632 for (bp
= builtincmd
; bp
->name
; bp
++) {
633 if (*bp
->name
== *name
&& equal(bp
->name
, name
))
640 (*find_splbltin(name
))(int, char **)
643 const struct builtincmd
*bp
;
645 for (bp
= splbltincmd
; bp
->name
; bp
++) {
646 if (*bp
->name
== *name
&& equal(bp
->name
, name
))
653 * At shell startup put special builtins into hash table.
654 * ensures they are executed first (see posix).
655 * We stop functions being added with the same name
656 * (as they are impossible to call)
660 hash_special_builtins(void)
662 const struct builtincmd
*bp
;
663 struct tblentry
*cmdp
;
665 for (bp
= splbltincmd
; bp
->name
; bp
++) {
666 cmdp
= cmdlookup(bp
->name
, 1);
667 cmdp
->cmdtype
= CMDSPLBLTIN
;
668 cmdp
->param
.bltin
= bp
->builtin
;
675 * Called when a cd is done. Marks all commands so the next time they
676 * are executed they will be rehashed.
682 struct tblentry
**pp
;
683 struct tblentry
*cmdp
;
685 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
] ; pp
++) {
686 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
687 if (cmdp
->cmdtype
== CMDNORMAL
688 || (cmdp
->cmdtype
== CMDBUILTIN
&& builtinloc
>= 0))
697 * Fix command hash table when PATH changed.
698 * Called before PATH is changed. The argument is the new value of PATH;
699 * pathval() still returns the old value at this point.
700 * Called with interrupts off.
704 changepath(const char *newval
)
706 const char *old
, *new;
713 firstchange
= 9999; /* assume no change */
719 if ((*old
== '\0' && *new == ':')
720 || (*old
== ':' && *new == '\0'))
722 old
= new; /* ignore subsequent differences */
726 if (*new == '%' && bltin
< 0 && prefix("builtin", new + 1))
733 if (builtinloc
< 0 && bltin
>= 0)
734 builtinloc
= bltin
; /* zap builtins */
735 if (builtinloc
>= 0 && bltin
< 0)
737 clearcmdentry(firstchange
);
743 * Clear out command entries. The argument specifies the first entry in
744 * PATH which has changed.
748 clearcmdentry(int firstchange
)
750 struct tblentry
**tblp
;
751 struct tblentry
**pp
;
752 struct tblentry
*cmdp
;
755 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
] ; tblp
++) {
757 while ((cmdp
= *pp
) != NULL
) {
758 if ((cmdp
->cmdtype
== CMDNORMAL
&&
759 cmdp
->param
.index
>= firstchange
)
760 || (cmdp
->cmdtype
== CMDBUILTIN
&&
761 builtinloc
>= firstchange
)) {
774 * Delete all functions.
778 MKINIT
void deletefuncs(void);
779 MKINIT
void hash_special_builtins(void);
782 hash_special_builtins();
793 struct tblentry
**tblp
;
794 struct tblentry
**pp
;
795 struct tblentry
*cmdp
;
798 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
] ; tblp
++) {
800 while ((cmdp
= *pp
) != NULL
) {
801 if (cmdp
->cmdtype
== CMDFUNCTION
) {
803 freefunc(cmdp
->param
.func
);
816 * Locate a command in the command hash table. If "add" is nonzero,
817 * add the command to the table if it is not already present. The
818 * variable "lastcmdentry" is set to point to the address of the link
819 * pointing to the entry, so that delete_cmd_entry can delete the
823 struct tblentry
**lastcmdentry
;
826 STATIC
struct tblentry
*
827 cmdlookup(const char *name
, int add
)
831 struct tblentry
*cmdp
;
832 struct tblentry
**pp
;
839 pp
= &cmdtable
[hashval
% CMDTABLESIZE
];
840 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
841 if (equal(cmdp
->cmdname
, name
))
845 if (add
&& cmdp
== NULL
) {
847 cmdp
= *pp
= ckmalloc(sizeof (struct tblentry
) - ARB
850 cmdp
->cmdtype
= CMDUNKNOWN
;
852 strcpy(cmdp
->cmdname
, name
);
860 * Delete the command entry returned on the last lookup.
864 delete_cmd_entry(void)
866 struct tblentry
*cmdp
;
869 cmdp
= *lastcmdentry
;
870 *lastcmdentry
= cmdp
->next
;
879 getcmdentry(char *name
, struct cmdentry
*entry
)
881 struct tblentry
*cmdp
= cmdlookup(name
, 0);
884 entry
->u
= cmdp
->param
;
885 entry
->cmdtype
= cmdp
->cmdtype
;
887 entry
->cmdtype
= CMDUNKNOWN
;
895 * Add a new command entry, replacing any existing command entry for
896 * the same name - except special builtins.
900 addcmdentry(char *name
, struct cmdentry
*entry
)
902 struct tblentry
*cmdp
;
905 cmdp
= cmdlookup(name
, 1);
906 if (cmdp
->cmdtype
!= CMDSPLBLTIN
) {
907 if (cmdp
->cmdtype
== CMDFUNCTION
) {
908 freefunc(cmdp
->param
.func
);
910 cmdp
->cmdtype
= entry
->cmdtype
;
911 cmdp
->param
= entry
->u
;
918 * Define a shell function.
922 defun(char *name
, union node
*func
)
924 struct cmdentry entry
;
927 entry
.cmdtype
= CMDFUNCTION
;
928 entry
.u
.func
= copyfunc(func
);
929 addcmdentry(name
, &entry
);
935 * Delete a function if it exists.
939 unsetfunc(char *name
)
941 struct tblentry
*cmdp
;
943 if ((cmdp
= cmdlookup(name
, 0)) != NULL
&&
944 cmdp
->cmdtype
== CMDFUNCTION
) {
945 freefunc(cmdp
->param
.func
);
953 * Locate and print what a word is...
954 * also used for 'command -[v|V]'
958 typecmd(int argc
, char **argv
)
960 struct cmdentry entry
;
961 struct tblentry
*cmdp
;
962 const char * const *pp
;
971 while ((c
= nextopt("vVp")) != 0) {
973 case 'v': v_flag
= 1; break;
974 case 'V': V_flag
= 1; break;
975 case 'p': p_flag
= 1; break;
979 if (p_flag
&& (v_flag
|| V_flag
))
980 error("cannot specify -p with -v or -V");
982 while ((arg
= *argptr
++)) {
985 /* First look at the keywords */
986 for (pp
= parsekwd
; *pp
; pp
++)
987 if (**pp
== *arg
&& equal(*pp
, arg
))
994 out1str(" is a shell keyword\n");
998 /* Then look at the aliases */
999 if ((ap
= lookupalias(arg
, 1)) != NULL
) {
1001 out1fmt(" is an alias for \n");
1002 out1fmt("%s\n", ap
->val
);
1006 /* Then check if it is a tracked alias */
1007 if ((cmdp
= cmdlookup(arg
, 0)) != NULL
) {
1008 entry
.cmdtype
= cmdp
->cmdtype
;
1009 entry
.u
= cmdp
->param
;
1011 /* Finally use brute force */
1012 find_command(arg
, &entry
, DO_ABS
, pathval());
1015 switch (entry
.cmdtype
) {
1017 if (strchr(arg
, '/') == NULL
) {
1018 const char *path
= pathval();
1020 int j
= entry
.u
.index
;
1022 name
= padvance(&path
, arg
);
1027 cmdp
? " a tracked alias for" : "");
1028 out1fmt("%s\n", name
);
1030 if (access(arg
, X_OK
) == 0) {
1033 out1fmt("%s\n", arg
);
1046 out1str(" is a shell function\n");
1048 out1fmt("%s\n", arg
);
1053 out1str(" is a shell builtin\n");
1055 out1fmt("%s\n", arg
);
1060 out1str(" is a special shell builtin\n");
1062 out1fmt("%s\n", arg
);
1067 out1str(": not found\n");