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 <demiobenour@gmail.com>
This commit is contained in:
Demi Marie Obenour 2026-05-30 16:00:09 -04:00
parent d44205284f
commit 6fe291e2e9
2 changed files with 17 additions and 2 deletions

View file

@ -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);
}

View file

@ -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