Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions zephyr/include/rtos/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +77 to +79
Copy link

Copilot AI Jan 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The memory barrier implementation creates architecture-specific code paths in a security function. Consider extracting this into a macro (e.g., SECURE_MEMORY_BARRIER()) defined in an architecture header file. This would improve maintainability and make it easier to add barriers for other architectures in the future.

Copilot uses AI. Check for mistakes.

Comment on lines +72 to 80
Copy link

Copilot AI Jan 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The memory barrier is only applied for Xtensa architecture, leaving other architectures vulnerable to dead store elimination. For security-critical memset_s() function, consider using a portable solution like a volatile function pointer or compiler builtins (e.g., memset_explicit() in C23, or explicit_bzero()) that work across all architectures to prevent compiler optimizations from removing the memory clearing operation.

Suggested change
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
/*
* Prevent compiler from optimizing away the memset.
* Use a volatile function pointer so the call has
* observable side effects on all architectures.
*/
void *(*volatile memset_ptr)(void *, int, size_t) = memset;
memset_ptr(dest, data, count);

Copilot uses AI. Check for mistakes.
return 0;
}
Expand Down