From fe98a513bc11e2934e4ca1e39a5d204d2d3ad77a Mon Sep 17 00:00:00 2001 From: Bill Currie Date: Thu, 29 Jul 2021 15:27:48 +0900 Subject: [PATCH] [util] Add a function to check hunk pointers Its only real utility is to check that a pointer is not pointing into freed space. --- include/QF/zone.h | 1 + libs/util/zone.c | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/include/QF/zone.h b/include/QF/zone.h index 0cd55c66d..93dbc8089 100644 --- a/include/QF/zone.h +++ b/include/QF/zone.h @@ -119,6 +119,7 @@ size_t Hunk_LowMark (memhunk_t *hunk) __attribute__((pure)); void Hunk_RawFreeToLowMark (memhunk_t *hunk, size_t mark) __attribute__((nonnull(1))); void Hunk_FreeToLowMark (memhunk_t *hunk, size_t mark); void *Hunk_TempAlloc (memhunk_t *hunk, size_t size); +int Hunk_PointerIsValid (memhunk_t *hunk, void *ptr) __attribute__((pure)); diff --git a/libs/util/zone.c b/libs/util/zone.c index 275948126..a2b68d754 100644 --- a/libs/util/zone.c +++ b/libs/util/zone.c @@ -715,6 +715,30 @@ Hunk_TempAlloc (memhunk_t *hunk, size_t size) return buf; } +VISIBLE int +Hunk_PointerIsValid (memhunk_t *hunk, void *ptr) +{ + if (!hunk) { hunk = global_hunk; } //FIXME clean up callers + + size_t offset = (byte *) ptr - hunk->base; + if (offset >= hunk->size) { + return 0; + } + if (offset < hunk->low_used) { + // the pointer is somewhere in the lower space of the hunk + // FIXME better checking? + return 1; + } + if (offset >= hunk->size - hunk->high_used + sizeof (hunkblk_t)) { + // the pointer is somewhere in the upper space of the hunk + // FIXME better checking? + return 1; + } + // the pointer is somewhere in between the two marks, so it has probably + // been freed + return 0; +} + /* CACHE MEMORY */