1 /* $NetBSD: exec.c,v 1.45 2013/11/01 16:49:02 christos 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.45 2013/11/01 16:49:02 christos 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(char *name
))(int, char **)
629 const struct builtincmd
*bp
;
631 for (bp
= builtincmd
; bp
->name
; bp
++) {
632 if (*bp
->name
== *name
633 && (*name
== '%' || equal(bp
->name
, name
)))
640 (*find_splbltin(char *name
))(int, char **)
642 const struct builtincmd
*bp
;
644 for (bp
= splbltincmd
; bp
->name
; bp
++) {
645 if (*bp
->name
== *name
&& equal(bp
->name
, name
))
652 * At shell startup put special builtins into hash table.
653 * ensures they are executed first (see posix).
654 * We stop functions being added with the same name
655 * (as they are impossible to call)
659 hash_special_builtins(void)
661 const struct builtincmd
*bp
;
662 struct tblentry
*cmdp
;
664 for (bp
= splbltincmd
; bp
->name
; bp
++) {
665 cmdp
= cmdlookup(bp
->name
, 1);
666 cmdp
->cmdtype
= CMDSPLBLTIN
;
667 cmdp
->param
.bltin
= bp
->builtin
;
674 * Called when a cd is done. Marks all commands so the next time they
675 * are executed they will be rehashed.
681 struct tblentry
**pp
;
682 struct tblentry
*cmdp
;
684 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
] ; pp
++) {
685 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
686 if (cmdp
->cmdtype
== CMDNORMAL
687 || (cmdp
->cmdtype
== CMDBUILTIN
&& builtinloc
>= 0))
696 * Fix command hash table when PATH changed.
697 * Called before PATH is changed. The argument is the new value of PATH;
698 * pathval() still returns the old value at this point.
699 * Called with interrupts off.
703 changepath(const char *newval
)
705 const char *old
, *new;
712 firstchange
= 9999; /* assume no change */
718 if ((*old
== '\0' && *new == ':')
719 || (*old
== ':' && *new == '\0'))
721 old
= new; /* ignore subsequent differences */
725 if (*new == '%' && bltin
< 0 && prefix("builtin", new + 1))
732 if (builtinloc
< 0 && bltin
>= 0)
733 builtinloc
= bltin
; /* zap builtins */
734 if (builtinloc
>= 0 && bltin
< 0)
736 clearcmdentry(firstchange
);
742 * Clear out command entries. The argument specifies the first entry in
743 * PATH which has changed.
747 clearcmdentry(int firstchange
)
749 struct tblentry
**tblp
;
750 struct tblentry
**pp
;
751 struct tblentry
*cmdp
;
754 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
] ; tblp
++) {
756 while ((cmdp
= *pp
) != NULL
) {
757 if ((cmdp
->cmdtype
== CMDNORMAL
&&
758 cmdp
->param
.index
>= firstchange
)
759 || (cmdp
->cmdtype
== CMDBUILTIN
&&
760 builtinloc
>= firstchange
)) {
773 * Delete all functions.
777 MKINIT
void deletefuncs(void);
778 MKINIT
void hash_special_builtins(void);
781 hash_special_builtins();
792 struct tblentry
**tblp
;
793 struct tblentry
**pp
;
794 struct tblentry
*cmdp
;
797 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
] ; tblp
++) {
799 while ((cmdp
= *pp
) != NULL
) {
800 if (cmdp
->cmdtype
== CMDFUNCTION
) {
802 freefunc(cmdp
->param
.func
);
815 * Locate a command in the command hash table. If "add" is nonzero,
816 * add the command to the table if it is not already present. The
817 * variable "lastcmdentry" is set to point to the address of the link
818 * pointing to the entry, so that delete_cmd_entry can delete the
822 struct tblentry
**lastcmdentry
;
825 STATIC
struct tblentry
*
826 cmdlookup(const char *name
, int add
)
830 struct tblentry
*cmdp
;
831 struct tblentry
**pp
;
838 pp
= &cmdtable
[hashval
% CMDTABLESIZE
];
839 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
840 if (equal(cmdp
->cmdname
, name
))
844 if (add
&& cmdp
== NULL
) {
846 cmdp
= *pp
= ckmalloc(sizeof (struct tblentry
) - ARB
849 cmdp
->cmdtype
= CMDUNKNOWN
;
851 strcpy(cmdp
->cmdname
, name
);
859 * Delete the command entry returned on the last lookup.
863 delete_cmd_entry(void)
865 struct tblentry
*cmdp
;
868 cmdp
= *lastcmdentry
;
869 *lastcmdentry
= cmdp
->next
;
878 getcmdentry(char *name
, struct cmdentry
*entry
)
880 struct tblentry
*cmdp
= cmdlookup(name
, 0);
883 entry
->u
= cmdp
->param
;
884 entry
->cmdtype
= cmdp
->cmdtype
;
886 entry
->cmdtype
= CMDUNKNOWN
;
894 * Add a new command entry, replacing any existing command entry for
895 * the same name - except special builtins.
899 addcmdentry(char *name
, struct cmdentry
*entry
)
901 struct tblentry
*cmdp
;
904 cmdp
= cmdlookup(name
, 1);
905 if (cmdp
->cmdtype
!= CMDSPLBLTIN
) {
906 if (cmdp
->cmdtype
== CMDFUNCTION
) {
907 freefunc(cmdp
->param
.func
);
909 cmdp
->cmdtype
= entry
->cmdtype
;
910 cmdp
->param
= entry
->u
;
917 * Define a shell function.
921 defun(char *name
, union node
*func
)
923 struct cmdentry entry
;
926 entry
.cmdtype
= CMDFUNCTION
;
927 entry
.u
.func
= copyfunc(func
);
928 addcmdentry(name
, &entry
);
934 * Delete a function if it exists.
938 unsetfunc(char *name
)
940 struct tblentry
*cmdp
;
942 if ((cmdp
= cmdlookup(name
, 0)) != NULL
&&
943 cmdp
->cmdtype
== CMDFUNCTION
) {
944 freefunc(cmdp
->param
.func
);
951 * Locate and print what a word is...
952 * also used for 'command -[v|V]'
956 typecmd(int argc
, char **argv
)
958 struct cmdentry entry
;
959 struct tblentry
*cmdp
;
960 const char * const *pp
;
969 while ((c
= nextopt("vVp")) != 0) {
971 case 'v': v_flag
= 1; break;
972 case 'V': V_flag
= 1; break;
973 case 'p': p_flag
= 1; break;
977 if (p_flag
&& (v_flag
|| V_flag
))
978 error("cannot specify -p with -v or -V");
980 while ((arg
= *argptr
++)) {
983 /* First look at the keywords */
984 for (pp
= parsekwd
; *pp
; pp
++)
985 if (**pp
== *arg
&& equal(*pp
, arg
))
992 out1str(" is a shell keyword\n");
996 /* Then look at the aliases */
997 if ((ap
= lookupalias(arg
, 1)) != NULL
) {
999 out1fmt(" is an alias for \n");
1000 out1fmt("%s\n", ap
->val
);
1004 /* Then check if it is a tracked alias */
1005 if ((cmdp
= cmdlookup(arg
, 0)) != NULL
) {
1006 entry
.cmdtype
= cmdp
->cmdtype
;
1007 entry
.u
= cmdp
->param
;
1009 /* Finally use brute force */
1010 find_command(arg
, &entry
, DO_ABS
, pathval());
1013 switch (entry
.cmdtype
) {
1015 if (strchr(arg
, '/') == NULL
) {
1016 const char *path
= pathval();
1018 int j
= entry
.u
.index
;
1020 name
= padvance(&path
, arg
);
1025 cmdp
? " a tracked alias for" : "");
1026 out1fmt("%s\n", name
);
1028 if (access(arg
, X_OK
) == 0) {
1031 out1fmt("%s\n", arg
);
1044 out1str(" is a shell function\n");
1046 out1fmt("%s\n", arg
);
1051 out1str(" is a shell builtin\n");
1053 out1fmt("%s\n", arg
);
1058 out1str(" is a special shell builtin\n");
1060 out1fmt("%s\n", arg
);
1065 out1str(": not found\n");