From 8f8c0ba615a88de9c78d6b24f3ce0470c7015cbd Mon Sep 17 00:00:00 2001 From: Karol Lewandowski Date: Wed, 7 Nov 2018 00:21:26 +0100 Subject: [PATCH] util: Fix and replace nullvec2str utility function with concatenate() MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Multiple issues were found and fixed in previously-unused nullvec2str function, including major problem with possible stack corruption via long parameters. This commit completely rewrites the function to dynamically resize the buffer while appending new parameters to avoid previous problems. Additionally, name is changed to somewhat more developer friendly name. Influenced-by: Mateusz Mościcki and Michał Bloch Change-Id: Ia97e3851bb4b5779a14704098752e3644c487f0b --- src/shared/util.c | 31 ++++++++++++++++++++++++------- src/shared/util.h | 2 +- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/shared/util.c b/src/shared/util.c index 775d6be..bdb8259 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -828,17 +828,34 @@ char* get_exe_path(pid_t pid) return result; } -char *nullvec2str(char *const vec[]) +/* This function is supposed to accept same data as passed to execve + * (argv and envp), which can be arrays of strings as well as NULL + * pointer. + */ +char* concatenate(char *const vec[]) { - char command[PATH_MAX] = {0, }; + size_t length = 0; + for (char *const *p = vec; p && *p; p++) + length += strlen(*p) + 1; + + if (length == 0) + return strdup(""); + + char *str = (char *)malloc(length); + if (!str) + return NULL; - for (char *const *p = vec; *p; ++p) { - strncat(command, *p, sizeof(command)-1); - strncat(command, " ", sizeof(command)-1); + char *destp = str; + char *const *vecp = vec; + while (*vecp) { + destp = stpcpy(destp, *(vecp++)); + if (*vecp) + destp = stpcpy(destp, " "); } - command[sizeof(command)-1] = 0; - return strdup(command); + + return str; } + /** * @} */ diff --git a/src/shared/util.h b/src/shared/util.h index dfe40bf..53e0c7d 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -67,7 +67,7 @@ char* get_exe_path(pid_t pid); char* get_cmd_line(pid_t pid); -char *nullvec2str(char *const vec[]); +char* concatenate(char *const vec[]); #ifdef __cplusplus } -- 2.7.4