summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorManuel Stoeckl <code@mstoeckl.com>2022-08-07 16:15:26 -0400
committerManuel Stoeckl <code@mstoeckl.com>2022-08-07 16:28:14 -0400
commit0113af39bc6daf0e40870bb142ae803ad2712371 (patch)
tree36ae1918d17f7b195b2dbf20362fa9070ad822d5
parentfc7fe93a299fa9fe9b1b01c044113e0fb53fa700 (diff)
Fix use-after-free in zeroed_aligned_realloc
-rw-r--r--src/platform.c13
1 files changed, 9 insertions, 4 deletions
diff --git a/src/platform.c b/src/platform.c
index aa2d1c0..845e45f 100644
--- a/src/platform.c
+++ b/src/platform.c
@@ -121,16 +121,21 @@ void *zeroed_aligned_realloc(size_t old_size_bytes, size_t new_size_bytes,
{
/* warning: this might copy a lot of data */
if (new_size_bytes <= 2 * old_size_bytes) {
+ void *old_handle = *handle;
+ ptrdiff_t old_offset = (uint8_t *)data - (uint8_t *)old_handle;
+
void *new_handle = realloc(
- *handle, new_size_bytes + alignment - 1);
+ old_handle, new_size_bytes + alignment - 1);
if (!new_handle) {
return NULL;
}
void *new_data = align_ptr(new_handle, alignment);
- if (((uint8_t *)data - (uint8_t *)*handle) !=
- ((uint8_t *)new_data - (uint8_t *)new_handle)) {
+ ptrdiff_t new_offset =
+ (uint8_t *)new_data - (uint8_t *)new_handle;
+ if (old_offset != new_offset) {
/* realloc broke alignment offset */
- memmove(new_data, data,
+ memmove((uint8_t *)new_data + new_offset,
+ (uint8_t *)new_data + old_offset,
new_size_bytes > old_size_bytes
? old_size_bytes
: new_size_bytes);