Skip to content

Commit

Permalink
free_aligned: validate passed in pointer
Browse files Browse the repository at this point in the history
Especially when replacing zlib with zlib-ng in old binaries, it is possible that the binary is mixing allocation and
deallocation functions from different libraries. As not all old binaries can be rebuild, we should validate the passed
in pointer and if the pointer doesn't seem to be allocated with alloc_aligned of zlib-ng, we should not try to adjust
the pointer.
  • Loading branch information
mtl1979 committed Apr 9, 2024
1 parent 8026095 commit 71c2e15
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions zutil.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#include "zutil_p.h"
#include "zutil.h"

#include <stdio.h>

z_const char * const PREFIX(z_errmsg)[10] = {
(z_const char *)"need dictionary", /* Z_NEED_DICT 2 */
(z_const char *)"stream end", /* Z_STREAM_END 1 */
Expand Down Expand Up @@ -154,6 +156,14 @@ void Z_INTERNAL PREFIX3(free_aligned)(zng_cfree_func zfree, void *opaque, void *
void *original_ptr = (void *)((uintptr_t)ptr - sizeof(void *));
void *free_ptr = *(void **)original_ptr;

/* Validate original_ptr, the distance to ptr should be less than double the maximum alignment of 64 bytes */
ptrdiff_t dist = (ptrdiff_t)original_ptr - (ptrdiff_t)free_ptr;
if (dist < 0 || dist > 127) {
Tracev((stderr, "free_aligned: Allocation/deallocation mismatch\n"));
zfree(opaque, ptr);
return;
}

/* Free original memory allocation */
zfree(opaque, free_ptr);
}

0 comments on commit 71c2e15

Please sign in to comment.