fix various bugs in path and error handling in execvp/fexecve

This commit is contained in:
Rich Felker 2011-09-29 00:48:04 -04:00
parent 5f814682b4
commit 4b87736998
2 changed files with 31 additions and 20 deletions

View File

@ -2,33 +2,41 @@
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <errno.h> #include <errno.h>
#include <limits.h>
extern char **__environ;
int execvp(const char *file, char *const argv[]) int execvp(const char *file, char *const argv[])
{ {
const char *p, *z, *path = getenv("PATH"); const char *p, *z, *path = getenv("PATH");
int l; size_t l, k;
errno = ENOENT;
if (!*file) return -1;
if (strchr(file, '/')) if (strchr(file, '/'))
return execve(file, argv, __environ); return execv(file, argv);
/* FIXME: integer overflows */
if (!path) path = "/usr/local/bin:/bin:/usr/bin"; if (!path) path = "/usr/local/bin:/bin:/usr/bin";
l = strlen(file) + strlen(path) + 2; k = strnlen(file, NAME_MAX+1);
if (k > NAME_MAX) {
for(p=path; p && *p; p=z) { errno = ENAMETOOLONG;
char b[l]; return -1;
z = strchr(p, ':'); }
if (z) { l = strnlen(path, PATH_MAX-1)+1;
memcpy(b, p, z-p);
b[z++-p] = 0; for(p=path; ; p=z) {
} else strcpy(b, p); char b[l+k+1];
strcat(b, "/"); z = strchr(p, ':');
strcat(b, file); if (!z) z = p+strlen(p);
if (!access(b, X_OK)) if (z-p >= l) {
return execve(b, argv, __environ); if (!*z++) break;
} continue;
errno = ENOENT; }
memcpy(b, p, z-p);
b[z-p] = '/';
memcpy(b+(z-p)+(z>p), file, k+1);
execv(b, argv);
if (errno != ENOENT) return -1;
if (!*z++) break;
}
return -1; return -1;
} }

View File

@ -1,10 +1,13 @@
#include <unistd.h> #include <unistd.h>
#include <stdio.h> #include <stdio.h>
#include <errno.h>
int fexecve(int fd, char *const argv[], char *const envp[]) int fexecve(int fd, char *const argv[], char *const envp[])
{ {
static const char proc[] = "/proc/self/fd/%d"; static const char proc[] = "/proc/self/fd/%d";
char buf[sizeof proc + 3*sizeof(int)]; char buf[sizeof proc + 3*sizeof(int)];
snprintf(buf, sizeof buf, proc, fd); snprintf(buf, sizeof buf, proc, fd);
return execve(buf, argv, envp); execve(buf, argv, envp);
if (errno == ENOENT) errno = EBADF;
return -1;
} }