From 4edae21bd13ea17290990f2730670f7fd035b18f Mon Sep 17 00:00:00 2001 From: Idan Horowitz Date: Mon, 15 Aug 2022 01:32:45 +0300 Subject: [PATCH] Kernel: Remove regions from the region tree after failing to map them At the point at which we try to map the Region it was already added to the Process region tree, so we have to make sure to remove it before freeing it in the mapping failure path, otherwise the tree will contain a dangling pointer to the free'd instance. --- Kernel/Memory/AddressSpace.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Kernel/Memory/AddressSpace.cpp b/Kernel/Memory/AddressSpace.cpp index 7f3bb554e0a..01964f324b7 100644 --- a/Kernel/Memory/AddressSpace.cpp +++ b/Kernel/Memory/AddressSpace.cpp @@ -217,7 +217,14 @@ ErrorOr AddressSpace::allocate_region_with_vmobject(RandomizeVirtualAdd SpinlockLocker mm_locker(s_mm_lock); region->set_page_directory(page_directory()); } else { - TRY(region->map(page_directory(), ShouldFlushTLB::No)); + auto result = region->map(page_directory(), ShouldFlushTLB::No); + if (result.is_error()) [[unlikely]] { + // At this point the region is already part of the Process region tree, so we have to make sure + // we remove it from the tree before returning this error, or else the Region tree will contain + // a dangling pointer to the free'd Region instance + m_region_tree.remove(*region); + return result.release_error(); + } } return region.leak_ptr(); }