From dbdda355d0add3f7d96e3279321d3a63abfc4b32 Mon Sep 17 00:00:00 2001 From: Johannes Berg Date: Tue, 7 Mar 2017 10:17:23 +0100 Subject: [PATCH] Introduce os_memdup() This can be used to clean the code and reduce size by converting os_malloc() followed by os_memcpy() cases to use a single function call. Signed-off-by: Johannes Berg --- src/utils/os.h | 12 ++++++++++++ src/utils/os_none.c | 6 ++++++ src/utils/os_unix.c | 12 ++++++++++++ src/utils/os_win32.c | 10 ++++++++++ 4 files changed, 40 insertions(+) diff --git a/src/utils/os.h b/src/utils/os.h index e8f0b7927..21ba5c3ff 100644 --- a/src/utils/os.h +++ b/src/utils/os.h @@ -614,6 +614,18 @@ size_t os_strlcpy(char *dest, const char *src, size_t siz); */ int os_memcmp_const(const void *a, const void *b, size_t len); + +/** + * os_memdup - Allocate duplicate of passed memory chunk + * @src: Source buffer to duplicate + * @len: Length of source buffer + * Returns: %NULL if allocation failed, copy of src buffer otherwise + * + * This function allocates a memory block like os_malloc() would, and + * copies the given source buffer into it. + */ +void * os_memdup(const void *src, size_t len); + /** * os_exec - Execute an external program * @program: Path to the program diff --git a/src/utils/os_none.c b/src/utils/os_none.c index 0c3214d32..e74f206a2 100644 --- a/src/utils/os_none.c +++ b/src/utils/os_none.c @@ -114,6 +114,12 @@ void * os_zalloc(size_t size) } +void * os_memdup(const void *src, size_t n) +{ + return NULL; +} + + #ifdef OS_NO_C_LIB_DEFINES void * os_malloc(size_t size) { diff --git a/src/utils/os_unix.c b/src/utils/os_unix.c index 26fd172b7..1894fcdb0 100644 --- a/src/utils/os_unix.c +++ b/src/utils/os_unix.c @@ -508,6 +508,16 @@ int os_memcmp_const(const void *a, const void *b, size_t len) } +void * os_memdup(const void *src, size_t len) +{ + void *r = os_malloc(len); + + if (r) + os_memcpy(r, src, len); + return r; +} + + #ifdef WPA_TRACE #if defined(WPA_TRACE_BFD) && defined(CONFIG_TESTING_OPTIONS) @@ -540,6 +550,8 @@ static int testing_fail_alloc(void) i++; if (i < res && os_strcmp(func[i], "os_strdup") == 0) i++; + if (i < res && os_strcmp(func[i], "os_memdup") == 0) + i++; pos = wpa_trace_fail_func; diff --git a/src/utils/os_win32.c b/src/utils/os_win32.c index dea27b9f2..f9e4b308e 100644 --- a/src/utils/os_win32.c +++ b/src/utils/os_win32.c @@ -283,3 +283,13 @@ int os_exec(const char *program, const char *arg, int wait_completion) { return -1; } + + +void * os_memdup(const void *src, size_t len) +{ + void *r = os_malloc(len); + + if (r) + os_memcpy(r, src, len); + return r; +}