Fixed memory leak when using execvpe() with vfork().

This commit is contained in:
Gunnar Beutner 2013-02-11 14:42:08 +01:00
parent 2304256b41
commit 72c46deca9
1 changed files with 10 additions and 11 deletions

View File

@ -20,6 +20,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <errno.h> #include <errno.h>
#include <alloca.h>
/* /*
* We want the search semantics of execvp, but we want to provide our * We want the search semantics of execvp, but we want to provide our
@ -77,20 +78,23 @@ execvpe(char *name, char *const argv[], char **envp)
if (!(path = getenv("PATH"))) { if (!(path = getenv("PATH"))) {
#ifdef HAVE_CONFSTR #ifdef HAVE_CONFSTR
ln = confstr(_CS_PATH, NULL, 0); ln = confstr(_CS_PATH, NULL, 0);
if ((cur = path = malloc(ln + 1)) != NULL) { if ((cur = path = alloca(ln + 1)) != NULL) {
path[0] = ':'; path[0] = ':';
(void) confstr (_CS_PATH, path + 1, ln); (void) confstr (_CS_PATH, path + 1, ln);
} }
#else #else
if ((cur = path = malloc(1 + 1)) != NULL) { if ((cur = path = alloca(1 + 1)) != NULL) {
path[0] = ':'; path[0] = ':';
path[1] = '\0'; path[1] = '\0';
} }
#endif #endif
} else } else {
cur = path = strdup(path); cur = alloca(strlen(path) + 1);
strcpy(cur, path);
path = cur;
}
if (path == NULL || (bp = buf = malloc(strlen(path)+strlen(name)+2)) == NULL) if (path == NULL || (bp = buf = alloca(strlen(path)+strlen(name)+2)) == NULL)
goto done; goto done;
while (cur != NULL) { while (cur != NULL) {
@ -129,13 +133,12 @@ execvpe(char *name, char *const argv[], char **envp)
for (cnt = 0, ap = (char **) argv; *ap; ++ap, ++cnt) for (cnt = 0, ap = (char **) argv; *ap; ++ap, ++cnt)
; ;
if ((ap = malloc((cnt + 2) * sizeof(char *))) != NULL) { if ((ap = alloca((cnt + 2) * sizeof(char *))) != NULL) {
memcpy(ap + 2, argv + 1, cnt * sizeof(char *)); memcpy(ap + 2, argv + 1, cnt * sizeof(char *));
ap[0] = "sh"; ap[0] = "sh";
ap[1] = bp; ap[1] = bp;
(void) execve("/bin/sh", ap, envp); (void) execve("/bin/sh", ap, envp);
free(ap);
} }
goto done; goto done;
} }
@ -152,10 +155,6 @@ execvpe(char *name, char *const argv[], char **envp)
else if (!errno) else if (!errno)
errno = ENOENT; errno = ENOENT;
done: done:
if (path)
free(path);
if (buf)
free(buf);
return (-1); return (-1);
} }
#endif #endif