From 68dc3e06ef87f6558e5ba920396d71dc3d275664 Mon Sep 17 00:00:00 2001 From: valentinbreiz Date: Tue, 26 Dec 2023 10:57:04 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20memory=20manager=20with=20?= =?UTF-8?q?multithreading?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/Cosmos.Core/Memory/Heap.cs | 36 ++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/source/Cosmos.Core/Memory/Heap.cs b/source/Cosmos.Core/Memory/Heap.cs index 07d1930341..862c10c7c3 100644 --- a/source/Cosmos.Core/Memory/Heap.cs +++ b/source/Cosmos.Core/Memory/Heap.cs @@ -47,6 +47,11 @@ public static unsafe void Init() /// New pointer with specified size while maintaining old data. public static byte* Realloc(byte* aPtr, uint newSize) { + if (mMemeoryGate != null) + { + mMemeoryGate.Lock(); + } + // TODO: don't move memory position if there is enough space in the current one. // Get existing size @@ -75,6 +80,12 @@ public static unsafe void Init() // Free the old data and return Free(aPtr); + + if (mMemeoryGate != null) + { + mMemeoryGate.Unlock(); + } + return ToReturn; } @@ -128,11 +139,6 @@ public static unsafe void Init() return ptr; } - - if (mMemeoryGate != null) - { - mMemeoryGate.Unlock(); - } } /// @@ -159,6 +165,11 @@ public static uint SafeAlloc(uint aSize) /// public static void Free(void* aPtr) { + if (mMemeoryGate != null) + { + mMemeoryGate.Lock(); + } + //TODO find a better way to remove the double look up here for GetPageType and then again in the // .Free methods which actually free the entries in the RAT. //Debugger.DoSendNumber(0x77); @@ -177,6 +188,11 @@ public static void Free(void* aPtr) default: throw new Exception("Heap item not found in RAT."); } + + if (mMemeoryGate != null) + { + mMemeoryGate.Unlock(); + } } /// @@ -185,6 +201,11 @@ public static void Free(void* aPtr) /// Number of objects freed public static int Collect() { + if (mMemeoryGate != null) + { + mMemeoryGate.Lock(); + } + //Disable interrupts: Prevent CPU exception when allocation is called from interrupt code CPU.DisableInterrupts(); @@ -322,6 +343,11 @@ public static int Collect() //Enable interrupts back CPU.EnableInterrupts(); + if (mMemeoryGate != null) + { + mMemeoryGate.Unlock(); + } + return freed; }