Skip to content

Commit

Permalink
🐛 Fix memory manager with multithreading
Browse files Browse the repository at this point in the history
  • Loading branch information
valentinbreiz committed Dec 26, 2023
1 parent ca9bf96 commit 68dc3e0
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions source/Cosmos.Core/Memory/Heap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public static unsafe void Init()
/// <returns>New pointer with specified size while maintaining old data.</returns>
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
Expand Down Expand Up @@ -75,6 +80,12 @@ public static unsafe void Init()

// Free the old data and return
Free(aPtr);

if (mMemeoryGate != null)
{
mMemeoryGate.Unlock();
}

return ToReturn;
}

Expand Down Expand Up @@ -128,11 +139,6 @@ public static unsafe void Init()

return ptr;
}

if (mMemeoryGate != null)
{
mMemeoryGate.Unlock();
}
}

/// <summary>
Expand All @@ -159,6 +165,11 @@ public static uint SafeAlloc(uint aSize)
/// </exception>
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);
Expand All @@ -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();
}
}

/// <summary>
Expand All @@ -185,6 +201,11 @@ public static void Free(void* aPtr)
/// <returns>Number of objects freed</returns>
public static int Collect()
{
if (mMemeoryGate != null)
{
mMemeoryGate.Lock();
}

//Disable interrupts: Prevent CPU exception when allocation is called from interrupt code
CPU.DisableInterrupts();

Expand Down Expand Up @@ -322,6 +343,11 @@ public static int Collect()
//Enable interrupts back
CPU.EnableInterrupts();

if (mMemeoryGate != null)
{
mMemeoryGate.Unlock();
}

return freed;
}

Expand Down

0 comments on commit 68dc3e0

Please sign in to comment.