From 6fe291e2e94b04206e8d5603d95bf618451d47e6 Mon Sep 17 00:00:00 2001 From: Demi Marie Obenour Date: Sat, 30 May 2026 16:00:09 -0400 Subject: [PATCH] Core: Make ngx_memcpy and ngx_copymem safe with null pointers In many C standards versions, memcpy() with a NULL pointer argument is undefined behavior, even if the size is 0. Avoid the memcpy on zero-length arguments. Signed-off-by: Demi Marie Obenour --- src/core/ngx_string.c | 4 ++++ src/core/ngx_string.h | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/core/ngx_string.c b/src/core/ngx_string.c index 10fe764c3..901f5d335 100644 --- a/src/core/ngx_string.c +++ b/src/core/ngx_string.c @@ -2124,6 +2124,10 @@ ngx_memcpy(void *dst, const void *src, size_t n) ngx_debug_point(); } + if (n == 0) { + return dst; + } + return memcpy(dst, src, n); } diff --git a/src/core/ngx_string.h b/src/core/ngx_string.h index 183a20521..b9c695356 100644 --- a/src/core/ngx_string.h +++ b/src/core/ngx_string.h @@ -103,8 +103,19 @@ void *ngx_memcpy(void *dst, const void *src, size_t n); * gcc3 compiles memcpy(d, s, 4) to the inline "mov"es. * icc8 compile memcpy(d, s, 4) to the inline "mov"es or XMM moves. */ -#define ngx_memcpy(dst, src, n) (void) memcpy(dst, src, n) -#define ngx_cpymem(dst, src, n) (((u_char *) memcpy(dst, src, n)) + (n)) +static inline void +ngx_memcpy(void *restrict dst, const void *restrict src, size_t n) +{ + if (n != 0) { + (void) memcpy(dst, src, n); + } +} + +static inline u_char * +ngx_cpymem(void *restrict dst, const void *restrict src, size_t n) +{ + return n != 0 ? (u_char *) memcpy(dst, src, n) + n : (u_char *) dst; +} #endif