Skip to content

Commit

Permalink
gh-583 Heap arena ownership guard
Browse files Browse the repository at this point in the history
  • Loading branch information
nolan-veed authored Oct 14, 2023
1 parent 4f329e6 commit 105fcc3
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/internal_modules/roc_core/heap_arena.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ void* HeapArena::allocate(size_t size) {

ChunkHeader* chunk = (ChunkHeader*)malloc(chunk_size);

chunk->owner = this;

char* canary_before = (char*)chunk->data;
char* memory = (char*)chunk->data + sizeof(ChunkCanary);
char* canary_after = (char*)chunk->data + sizeof(ChunkCanary) + size;
Expand All @@ -70,12 +72,6 @@ void HeapArena::deallocate(void* ptr) {
roc_panic("heap arena: null pointer");
}

const int n = num_allocations_--;

if (n == 0) {
roc_panic("heap arena: unpaired deallocate");
}

ChunkHeader* chunk =
ROC_CONTAINER_OF((char*)ptr - sizeof(ChunkCanary), ChunkHeader, data);

Expand All @@ -98,6 +94,25 @@ void HeapArena::deallocate(void* ptr) {
}
}

const bool is_owner = chunk->owner == this;

if (!is_owner) {
num_guard_failures_++;
if (AtomicOps::load_seq_cst(flags_) & HeapArenaFlag_EnableGuards) {
roc_panic("heap arena: attempt to deallocate chunk not belonging to this "
"heap arena:"
" this_pool=%p chunk_pool=%p",
(const void*)this, (const void*)chunk->owner);
}
return;
}

const int n = num_allocations_--;

if (n == 0) {
roc_panic("heap arena: unpaired deallocate");
}

MemoryOps::poison_after_use(memory, chunk->size);

free(chunk);
Expand Down
2 changes: 2 additions & 0 deletions src/internal_modules/roc_core/heap_arena.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ class HeapArena : public IArena, public NonCopyable<> {
private:
struct ChunkHeader {
size_t size;
//! The heap arena that the chunk belongs to.
HeapArena* owner;
AlignMax data[];
};

Expand Down
14 changes: 14 additions & 0 deletions src/tests/roc_core/test_heap_arena.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,19 @@ TEST(heap_arena, guard_object_violations) {
CHECK(arena.num_guard_failures() == 2);
}

TEST(heap_arena, ownership_guard) {
HeapArena arena0;
HeapArena arena1;

void* pointer = arena0.allocate(128);
CHECK(pointer);

arena1.deallocate(pointer);
CHECK(arena1.num_guard_failures() == 1);

arena0.deallocate(pointer);
CHECK(arena0.num_guard_failures() == 0);
}

} // namespace core
} // namespace roc

0 comments on commit 105fcc3

Please sign in to comment.