Skip to content

Commit

Permalink
Ensure module is only loaded once
Browse files Browse the repository at this point in the history
  • Loading branch information
elishacloud committed Jun 3, 2024
1 parent dea0a05 commit f1bec9f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Resources/BuildNo.rc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
#define BUILD_NUMBER 2147
#define BUILD_NUMBER 2148
40 changes: 40 additions & 0 deletions dllmain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#define DLLMAIN_CPP
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <sstream>
#include <shlwapi.h>
#include "winmm.h"
#include "Patches\Patches.h"
Expand All @@ -39,6 +40,7 @@ std::ofstream LOG;
HMODULE m_hModule = nullptr;
SH2VERSION GameVersion = SH2V_UNKNOWN;
HMODULE wrapper_dll = nullptr;
HANDLE g_hMutex = nullptr;
EXECUTION_STATE esFlags = 0;
bool CustomExeStrSet = false;
bool EnableCustomShaders = false;
Expand All @@ -53,6 +55,13 @@ extern "C" BOOL WINAPI DSOAL_DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID

void VerifySH2EE(){}

std::wstring CreateUniqueMutexName()
{
std::wstringstream ss;
ss << L"SH2EECoreModule_" << GetCurrentProcessId();
return ss.str();
}

void GetConfig()
{
// Get config file path
Expand Down Expand Up @@ -120,6 +129,14 @@ void GetGameVersion()

void DelayedStart()
{
// Only allow function to run once
static bool AlreadyRun = false;
if (AlreadyRun)
{
return;
}
AlreadyRun = true;

// Init Logs
Logging::LogComputerManufacturer();
Logging::LogOSVersion();
Expand Down Expand Up @@ -794,6 +811,21 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved)
{
case DLL_PROCESS_ATTACH:
{
// Create a unique mutex name using the process ID
std::wstring mutexName = CreateUniqueMutexName();
g_hMutex = CreateMutex(nullptr, TRUE, mutexName.c_str());

// Check if the mutex already exists
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// Clear the error code
SetLastError(ERROR_SUCCESS);

// Mutex already exists, another instance of the DLL is loaded in this process
g_hMutex = nullptr;
return FALSE; // Return FALSE to prevent the DLL from loading
}

// Store Module handle
m_hModule = hModule;

Expand Down Expand Up @@ -843,6 +875,14 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved)
break;
case DLL_PROCESS_DETACH:
{
// Release the mutex when the DLL is unloaded
if (g_hMutex)
{
ReleaseMutex(g_hMutex);
CloseHandle(g_hMutex);
g_hMutex = nullptr;
}

// Stop thread
m_StopThreadFlag = true;

Expand Down

0 comments on commit f1bec9f

Please sign in to comment.