From b27aa3fb5ae55ac2223cd880f7e17bb8abc14e22 Mon Sep 17 00:00:00 2001 From: Emil Velikov Date: Thu, 22 Aug 2024 17:04:21 +0100 Subject: [PATCH] shared: use memdup over stdndupa The stdndupa has a couple of gotchas: - allocates memory on stack via alloca(3)... where we pass it a user-provided string in at least one instance - it's a GNU extension missing on musl and bionic The mkdir_p() function is not a hot path, so using heap allocation is perfectly fine. Swap the stdndupa for our local helper memdup. Signed-off-by: Emil Velikov Link: https://github.com/kmod-project/kmod/pull/92 Signed-off-by: Lucas De Marchi --- configure.ac | 3 +-- shared/missing.h | 12 ------------ shared/util.c | 9 +++++++-- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/configure.ac b/configure.ac index 5396436d..d179159a 100644 --- a/configure.ac +++ b/configure.ac @@ -50,10 +50,9 @@ CC_CHECK_FUNC_BUILTIN([__builtin_uaddll_overflow], [ ], [ ]) # dietlibc doesn't have st.st_mtim struct member AC_CHECK_MEMBERS([struct stat.st_mtim], [], [], [#include ]) -# musl 1.0 and bionic 4.4 don't have strndupa # basename may be only available in libgen.h with the POSIX behavior, # not desired here -AC_CHECK_DECLS_ONCE([[strndupa], [basename]], [], [], [[#include ]]) +AC_CHECK_DECLS_ONCE([[basename]], [], [], [[#include ]]) AC_MSG_CHECKING([whether _Static_assert() is supported]) AC_COMPILE_IFELSE( diff --git a/shared/missing.h b/shared/missing.h index 86caf80a..9dbbd707 100644 --- a/shared/missing.h +++ b/shared/missing.h @@ -34,18 +34,6 @@ static inline int finit_module(int fd, const char *uargs, int flags) } #endif -#if !HAVE_DECL_STRNDUPA -#include -#define strndupa(s, n) \ - ({ \ - const char *__old = (s); \ - size_t __len = strnlen(__old, (n)); \ - char *__new = alloca(__len + 1); \ - __new[__len] = '\0'; \ - memcpy(__new, __old, __len); \ - }) -#endif - #if !HAVE_DECL_BASENAME #include static inline const char *basename(const char *s) diff --git a/shared/util.c b/shared/util.c index d7db5d4f..1dfb218f 100644 --- a/shared/util.c +++ b/shared/util.c @@ -387,9 +387,14 @@ static inline int is_dir(const char *path) int mkdir_p(const char *path, int len, mode_t mode) { - char *start, *end; + _cleanup_free_ char *start; + char *end; - start = strndupa(path, len); + start = memdup(path, len + 1); + if (!start) + return -ENOMEM; + + start[len] = '\0'; end = start + len; /*