From a082d39c1e8fc6f84042e7bff1999f6f2080558b Mon Sep 17 00:00:00 2001 From: Tomasz Leman Date: Fri, 16 Jan 2026 15:27:48 +0100 Subject: [PATCH] rtos: string: Add memory barrier to memset_s for security Add Xtensa memory barrier (memw) instruction after memset() in memset_s() implementation to prevent compiler dead store elimination (DSE) optimization from removing the memory clearing operation. When optimization flags like -O2 are enabled, compilers may perform dead store elimination and incorrectly remove memset() calls used for security purposes to scrub sensitive data from memory. This is critical for confidential data handling where memory must be reliably cleared after use. The memory barrier ensures the memset operation completes and cannot be optimized away, satisfying secure memory scrubbing requirements for cryptographic operations and sensitive data processing. Additionally, the patch removes the check for the return value of memset. The standard C library memset always returns the pointer passed as its first argument and does not indicate errors through its return value. Error handling for a NULL destination is already performed earlier in the function, so the return value check is unnecessary and can be safely omitted. Signed-off-by: Tomasz Leman --- zephyr/include/rtos/string.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/zephyr/include/rtos/string.h b/zephyr/include/rtos/string.h index 49c26acd17da..37bd657ff91d 100644 --- a/zephyr/include/rtos/string.h +++ b/zephyr/include/rtos/string.h @@ -69,8 +69,14 @@ static inline int memset_s(void *dest, size_t dest_size, int data, size_t count) if (count > dest_size) return -EINVAL; - if (!memset(dest, data, count)) - return -ENOMEM; + memset(dest, data, count); + /* + * Prevent compiler from optimizing away the memset. + * Memory barrier prevents dead store elimination. + */ +#if defined(CONFIG_XTENSA) + __asm__ __volatile__("memw" ::: "memory"); +#endif return 0; }