Skip to content

Commit a082d39

Browse files
committed
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 <tomasz.m.leman@intel.com>
1 parent d6a2a4d commit a082d39

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

zephyr/include/rtos/string.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,14 @@ static inline int memset_s(void *dest, size_t dest_size, int data, size_t count)
6969
if (count > dest_size)
7070
return -EINVAL;
7171

72-
if (!memset(dest, data, count))
73-
return -ENOMEM;
72+
memset(dest, data, count);
73+
/*
74+
* Prevent compiler from optimizing away the memset.
75+
* Memory barrier prevents dead store elimination.
76+
*/
77+
#if defined(CONFIG_XTENSA)
78+
__asm__ __volatile__("memw" ::: "memory");
79+
#endif
7480

7581
return 0;
7682
}

0 commit comments

Comments
 (0)