Skip to content

Commit 798a98b

Browse files
committed
stdlib: Use lots of uintptr_t casts to avoid sanitizer in malloc
Much of mallocs work confuses the address sanitizer as the pointers don't appear to point into the same object, even though they all come from sbrk. Spam the code with enough uintptr_t casts to avoid the sanitizer's wrath. Signed-off-by: Keith Packard <[email protected]>
1 parent 84252fc commit 798a98b

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

newlib/libc/picolib/picosbrk.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
#include <unistd.h>
3737
#include <errno.h>
38+
#include <stdint.h>
3839

3940
extern char __heap_start[];
4041
extern char __heap_end[];
@@ -44,17 +45,17 @@ static char *__brk = __heap_start;
4445
void *sbrk(ptrdiff_t incr)
4546
{
4647
if (incr < 0) {
47-
if ((size_t) (__brk - __heap_start) < (size_t) (-incr)) {
48+
if ((size_t) ((uintptr_t)__brk - (uintptr_t)__heap_start) < (size_t) (-incr)) {
4849
errno = ENOMEM;
4950
return (void *) -1;
5051
}
5152
} else {
52-
if ((size_t) (__heap_end - __brk) < (size_t) incr) {
53+
if ((size_t) ((uintptr_t)__heap_end - (uintptr_t)__brk) < (size_t) incr) {
5354
errno = ENOMEM;
5455
return (void *) -1;
5556
}
5657
}
5758
void *ret = __brk;
58-
__brk += incr;
59+
__brk = (char *) ((uintptr_t) __brk + incr);
5960
return ret;
6061
}

newlib/libc/stdlib/nano-malloc.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,13 @@ __malloc_sbrk_aligned(size_t s)
6666
if (p == (void *)-1)
6767
return p;
6868

69-
__malloc_sbrk_top = p + s;
69+
__malloc_sbrk_top = (char *) ((uintptr_t) p + s);
7070

7171
/* Adjust returned space so that the storage area
7272
* is MALLOC_CHUNK_ALIGN aligned and the head is
7373
* MALLOC_HEAD_ALIGN aligned.
7474
*/
75-
align_p = __align_up(p + MALLOC_HEAD, MALLOC_CHUNK_ALIGN) - MALLOC_HEAD;
75+
align_p = (char *) (__align_up((uintptr_t) p + MALLOC_HEAD, MALLOC_CHUNK_ALIGN) - MALLOC_HEAD);
7676

7777
if (align_p != p)
7878
{
@@ -84,7 +84,7 @@ __malloc_sbrk_aligned(size_t s)
8484
*/
8585
intptr_t adjust = align_p - p;
8686
char *extra = sbrk(adjust);
87-
if (extra != p + s)
87+
if (extra != (char *) ((uintptr_t) p + s))
8888
return (void *) -1;
8989
__malloc_sbrk_top = extra + adjust;
9090
}

0 commit comments

Comments
 (0)