Skip to content

Commit 7d11802

Browse files
tmlemankv2019i
authored andcommitted
zephyr: fix overflow and overlap checks in memcpy_s
This patch addresses an issue in the `memcpy_s` function within the Zephyr RTOS string header. The issue was identified during IPC3 fuzz testing with UndefinedBehaviorSanitizer enabled. Changes include: - Adding `stdint.h` for `uintptr_t` type. - Adding checks to prevent overflow in pointer arithmetic. - Adjusting overlap checks to avoid overflow. These changes ensure that the `memcpy_s` function correctly handles edge cases, preventing undefined behavior due to pointer arithmetic overflow and memory overlap. Fixes thesofproject#9768 Signed-off-by: Tomasz Leman <tomasz.m.leman@intel.com>
1 parent ce3315b commit 7d11802

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

zephyr/include/rtos/string.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
/* Zephyr uses a C library so lets use it */
1010
#include <string.h>
11+
#include <stdint.h>
1112
#include <stddef.h>
1213
#include <errno.h>
1314

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

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

47-
if (count > dest_size)
47+
uintptr_t dest_addr = (uintptr_t)dest;
48+
uintptr_t src_addr = (uintptr_t)src;
49+
50+
/* Check for overflow in pointer arithmetic */
51+
if ((dest_addr + dest_size < dest_addr) || (src_addr + count < src_addr))
52+
return -EINVAL;
53+
54+
/* Check for overlap without causing overflow */
55+
if ((dest_addr >= src_addr && dest_addr < src_addr + count) ||
56+
(src_addr >= dest_addr && src_addr < dest_addr + dest_size))
4857
return -EINVAL;
4958

5059
memcpy(dest, src, count);

0 commit comments

Comments
 (0)