From a6e132ea422f9b31a87f6a687958523515cb0332 Mon Sep 17 00:00:00 2001 From: Bugale Bugalit Date: Wed, 6 Apr 2022 19:09:39 +0300 Subject: [PATCH] Reduce memory fragmentation in x86 --- src/detours.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/detours.cpp b/src/detours.cpp index 954050f7..a9e92169 100644 --- a/src/detours.cpp +++ b/src/detours.cpp @@ -1265,7 +1265,14 @@ static PVOID detour_alloc_region_from_lo(PBYTE pbLo, PBYTE pbHi) mbi.State)); if (mbi.State == MEM_FREE && mbi.RegionSize >= DETOUR_REGION_SIZE) { - +#ifdef DETOURS_X86 + // Reduce memory fragmentation by allocating the end of the region + pbTry += mbi.RegionSize; // Advance pbTry to the end of the free block. + if (pbTry > pbHi) { + pbTry = pbHi; + } + pbTry -= DETOUR_REGION_SIZE; // Move pbTry backwards to ensure that the free block is large enough to hold a trampoline region. +#endif PVOID pv = VirtualAlloc(pbTry, DETOUR_REGION_SIZE, MEM_COMMIT|MEM_RESERVE, @@ -1315,7 +1322,14 @@ static PVOID detour_alloc_region_from_hi(PBYTE pbLo, PBYTE pbHi) mbi.State)); if (mbi.State == MEM_FREE && mbi.RegionSize >= DETOUR_REGION_SIZE) { - +#ifdef DETOURS_X86 + // Reduce memory fragmentation by allocating the end of the region + pbTry += mbi.RegionSize; // Advance pbTry to the end of the free block. + if (pbTry > pbHi) { + pbTry = pbHi; + } + pbTry -= DETOUR_REGION_SIZE; // Move pbTry backwards to ensure that the free block is large enough to hold a trampoline region. +#endif PVOID pv = VirtualAlloc(pbTry, DETOUR_REGION_SIZE, MEM_COMMIT|MEM_RESERVE,