Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stable-v2.12] zephyr: fix overflow and overlap checks in memcpy_s #9771

Merged
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
15 changes: 12 additions & 3 deletions zephyr/include/rtos/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

/* Zephyr uses a C library so lets use it */
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>

Expand Down Expand Up @@ -40,11 +41,19 @@ static inline int memcpy_s(void *dest, size_t dest_size,
if (!dest || !src)
return -EINVAL;

if ((dest >= src && (char *)dest < ((char *)src + count)) ||
(src >= dest && (char *)src < ((char *)dest + dest_size)))
if (count > dest_size)
return -EINVAL;

if (count > dest_size)
uintptr_t dest_addr = (uintptr_t)dest;
uintptr_t src_addr = (uintptr_t)src;

/* Check for overflow in pointer arithmetic */
if ((dest_addr + dest_size < dest_addr) || (src_addr + count < src_addr))
return -EINVAL;

/* Check for overlap without causing overflow */
if ((dest_addr >= src_addr && dest_addr < src_addr + count) ||
(src_addr >= dest_addr && src_addr < dest_addr + dest_size))
return -EINVAL;

memcpy(dest, src, count);
Expand Down
Loading