[util] Add a function to check hunk pointers

Its only real utility is to check that a pointer is not pointing into
freed space.
This commit is contained in:
Bill Currie 2021-07-29 15:27:48 +09:00
parent 756214ca8e
commit fe98a513bc
2 changed files with 25 additions and 0 deletions

View file

@ -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));

View file

@ -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 */