From 8a1a2e97624d15617197248a5e292c5ead5e74a2 Mon Sep 17 00:00:00 2001 From: p0358 Date: Wed, 29 Dec 2021 05:48:33 +0100 Subject: add launcher.dll proxy option --- NorthstarDedicatedTest/gameutils.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) (limited to 'NorthstarDedicatedTest/gameutils.cpp') diff --git a/NorthstarDedicatedTest/gameutils.cpp b/NorthstarDedicatedTest/gameutils.cpp index 642c44e6..97011059 100644 --- a/NorthstarDedicatedTest/gameutils.cpp +++ b/NorthstarDedicatedTest/gameutils.cpp @@ -79,11 +79,17 @@ void InitialiseServerGameUtilFunctions(HMODULE baseAddress) void InitialiseTier0GameUtilFunctions(HMODULE baseAddress) { baseAddress = GetModuleHandleA("tier0.dll"); - - CreateGlobalMemAlloc = (CreateGlobalMemAllocType)GetProcAddress(baseAddress, "CreateGlobalMemAlloc"); - g_pMemAllocSingleton = CreateGlobalMemAlloc(); - - Error = (ErrorType)GetProcAddress(baseAddress, "Error"); - CommandLine = (CommandLineType)GetProcAddress(baseAddress, "CommandLine"); - Plat_FloatTime = (Plat_FloatTimeType)GetProcAddress(baseAddress, "Plat_FloatTime"); + if (!baseAddress) + throw "tier0.dll is not loaded"; + + CreateGlobalMemAlloc = reinterpret_cast(GetProcAddress(baseAddress, "CreateGlobalMemAlloc")); + IMemAlloc** ppMemAllocSingleton = reinterpret_cast(GetProcAddress(baseAddress, "g_pMemAllocSingleton")); + if (!ppMemAllocSingleton || !*ppMemAllocSingleton) + g_pMemAllocSingleton = CreateGlobalMemAlloc(); + else + g_pMemAllocSingleton = *ppMemAllocSingleton; + + Error = reinterpret_cast(GetProcAddress(baseAddress, "Error")); + CommandLine = reinterpret_cast(GetProcAddress(baseAddress, "CommandLine")); + Plat_FloatTime = reinterpret_cast(GetProcAddress(baseAddress, "Plat_FloatTime")); } \ No newline at end of file -- cgit v1.2.3 From d2ee389192aa425ef9c81b2c3367ffb0de6976d0 Mon Sep 17 00:00:00 2001 From: p0358 Date: Thu, 30 Dec 2021 02:58:19 +0100 Subject: Refactor and fix of various issues, add run_northstar.txt support --- LauncherInjector/main.cpp | 228 +++++++++++---------- LauncherInjector/memalloc.cpp | 11 +- NorthstarDedicatedTest/dllmain.cpp | 7 +- NorthstarDedicatedTest/gameutils.cpp | 19 +- NorthstarDedicatedTest/hooks.cpp | 82 ++++++-- NorthstarDedicatedTest/memalloc.cpp | 30 ++- loader_launcher_proxy/Memory.cpp | 22 +- loader_launcher_proxy/dllmain.cpp | 76 +++++-- .../loader_launcher_proxy.vcxproj | 2 +- 9 files changed, 313 insertions(+), 164 deletions(-) (limited to 'NorthstarDedicatedTest/gameutils.cpp') diff --git a/LauncherInjector/main.cpp b/LauncherInjector/main.cpp index 0fd41daf..4f21b200 100644 --- a/LauncherInjector/main.cpp +++ b/LauncherInjector/main.cpp @@ -16,6 +16,7 @@ extern "C" { HMODULE hLauncherModule; HMODULE hHookModule; +HMODULE hTier0Module; wchar_t exePath[4096]; wchar_t buffer[8196]; @@ -68,144 +69,147 @@ void LibraryLoadError(DWORD dwMessageId, const wchar_t* libName, const wchar_t* char text[2048]; std::string message = std::system_category().message(dwMessageId); sprintf_s(text, "Failed to load the %ls at \"%ls\" (%lu):\n\n%hs\n\nMake sure you followed the Northstar installation instructions carefully.", libName, location, dwMessageId, message.c_str()); - MessageBoxA(GetForegroundWindow(), text, "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), text, "Northstar Launcher Error", 0); } -int main(int argc, char* argv[]) { - - // checked to avoid starting origin, Northstar.dll will check for -dedicated as well on its own - bool isDedicated = false; - for (int i = 0; i < argc; i++) - if (!strcmp(argv[i], "-dedicated")) - isDedicated = true; +void EnsureOriginStarted() +{ + if (GetProcessByName(L"Origin.exe") || GetProcessByName(L"EADesktop.exe")) + return; // already started - bool noOriginStartup = false; - for (int i = 0; i < argc; i++) - if (!strcmp(argv[i], "-noOriginStartup")) - noOriginStartup = true; + // unpacked exe will crash if origin isn't open on launch, so launch it + // get origin path from registry, code here is reversed from OriginSDK.dll + HKEY key; + if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Origin", 0, KEY_READ, &key) != ERROR_SUCCESS) + { + MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); + return; + } - if (!isDedicated && !GetProcessByName(L"Origin.exe") && !GetProcessByName(L"EADesktop.exe") && !noOriginStartup) + char originPath[520]; + DWORD originPathLength = 520; + if (RegQueryValueExA(key, "ClientPath", 0, 0, (LPBYTE)&originPath, &originPathLength) != ERROR_SUCCESS) { - // unpacked exe will crash if origin isn't open on launch, so launch it - // get origin path from registry, code here is reversed from OriginSDK.dll - HKEY key; - if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Origin", 0, KEY_READ, &key) != ERROR_SUCCESS) - { - MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); - return 1; - } + MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); + return; + } - char originPath[520]; - DWORD originPathLength = 520; - if (RegQueryValueExA(key, "ClientPath", 0, 0, (LPBYTE)&originPath, &originPathLength) != ERROR_SUCCESS) - { - MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); - return 1; - } + PROCESS_INFORMATION pi; + memset(&pi, 0, sizeof(pi)); + STARTUPINFO si; + memset(&si, 0, sizeof(si)); + CreateProcessA(originPath, (char*)"", NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP, NULL, NULL, (LPSTARTUPINFOA)&si, &pi); - PROCESS_INFORMATION pi; - memset(&pi, 0, sizeof(pi)); - STARTUPINFO si; - memset(&si, 0, sizeof(si)); - CreateProcessA(originPath, (char*)"", NULL, NULL, false, CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP, NULL, NULL, (LPSTARTUPINFOA)&si, &pi); + printf("[*] Waiting for Origin...\n"); - // wait for origin to be ready, this process is created when origin is ready enough to launch game without any errors - while (!GetProcessByName(L"OriginClientService.exe") && !GetProcessByName(L"EADesktop.exe")) - Sleep(200); + // wait for origin to be ready, this process is created when origin is ready enough to launch game without any errors + while (!GetProcessByName(L"OriginClientService.exe") && !GetProcessByName(L"EADesktop.exe")) + Sleep(200); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); - } + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); +} -#if 0 - // TODO: MOVE TO Northstar.dll itself and inject in some place - // for example hook GetCommandLineA() before real LauncherMain gets called (ie. during InitialiseNorthstar) - // GetCommandLineA() is always used, the parameters passed to LauncherMain are basically ignored - // get cmdline args from file - std::wstring args; - std::ifstream cmdlineArgFile; +void PrependPath() +{ + wchar_t* pPath; + size_t len; + errno_t err = _wdupenv_s(&pPath, &len, L"PATH"); + if (!err) + { + swprintf_s(buffer, L"PATH=%s\\bin\\x64_retail\\;%s", exePath, pPath); + auto result = _wputenv(buffer); + if (result == -1) + { + MessageBoxW(GetForegroundWindow(), L"Warning: could not prepend the current directory to app's PATH environment variable. Something may break because of that.", L"Northstar Launcher Warning", 0); + } + //free(pPath); + } + else + { + MessageBoxW(GetForegroundWindow(), L"Warning: could not get current PATH environment variable in order to prepend the current directory to it. Something may break because of that.", L"Northstar Launcher Warning", 0); + } +} - args.append(L" "); +bool ShouldLoadNorthstar(int argc, char* argv[]) +{ + bool loadNorthstar = true; for (int i = 0; i < argc; i++) - { - std::string str = argv[i]; + if (!strcmp(argv[i], "-vanilla")) + loadNorthstar = false; - args.append(std::wstring(str.begin(), str.end())); - args.append(L" "); - } + if (!loadNorthstar) + return loadNorthstar; - if (!isDedi) - cmdlineArgFile = std::ifstream("ns_startup_args.txt"); - else - cmdlineArgFile = std::ifstream("ns_startup_args_dedi.txt"); + auto runNorthstarFile = std::ifstream("run_northstar.txt"); + if (runNorthstarFile) + { + std::stringstream runNorthstarFileBuffer; + runNorthstarFileBuffer << runNorthstarFile.rdbuf(); + runNorthstarFile.close(); + if (runNorthstarFileBuffer.str()._Starts_with("0")) + loadNorthstar = false; + } + return loadNorthstar; +} - if (cmdlineArgFile) +bool LoadNorthstar() +{ + FARPROC Hook_Init = nullptr; { - std::stringstream argBuffer; - argBuffer << cmdlineArgFile.rdbuf(); - cmdlineArgFile.close(); - - std::string str = argBuffer.str(); - args.append(std::wstring(str.begin(), str.end())); + swprintf_s(buffer, L"%s\\Northstar.dll", exePath); + hHookModule = LoadLibraryExW(buffer, 0i64, 8u); + if (hHookModule) Hook_Init = GetProcAddress(hHookModule, "InitialiseNorthstar"); + if (!hHookModule || Hook_Init == nullptr) + { + LibraryLoadError(GetLastError(), L"Northstar.dll", buffer); + return false; + } } - //if (isDedicated) - // // copy -dedicated into args if we have it in commandline args - // args.append(L" -dedicated"); -#endif + ((bool (*)()) Hook_Init)(); + return true; +} - // +int main(int argc, char* argv[]) { - bool loadNorthstar = true; + // checked to avoid starting origin, Northstar.dll will check for -dedicated as well on its own + bool isDedicated = false; for (int i = 0; i < argc; i++) - if (!strcmp(argv[i], "-vanilla")) - loadNorthstar = false; + if (!strcmp(argv[i], "-dedicated")) + isDedicated = true; + + bool noOriginStartup = false; + for (int i = 0; i < argc; i++) + if (!strcmp(argv[i], "-noOriginStartup")) + noOriginStartup = true; + + if (!isDedicated && !noOriginStartup) + { + EnsureOriginStarted(); + } { if (!GetExePathWide(exePath, 4096)) { - MessageBoxA(GetForegroundWindow(), "Failed getting game directory.\nThe game cannot continue and has to exit.", "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), "Failed getting game directory.\nThe game cannot continue and has to exit.", "Northstar Launcher Error", 0); return 1; } - { - wchar_t* pPath; - size_t len; - errno_t err = _wdupenv_s(&pPath, &len, L"PATH"); - if (!err) - { - swprintf_s(buffer, L"PATH=%s\\bin\\x64_retail\\;%s", exePath, pPath); - auto result = _wputenv(buffer); - if (result == -1) - { - MessageBoxW(GetForegroundWindow(), L"Warning: could not prepend the current directory to app's PATH environment variable. Something may break because of that.", L"Launcher Warning", 0); - } - free(pPath); - } - else - { - MessageBoxW(GetForegroundWindow(), L"Warning: could not get current PATH environment variable in order to prepend the current directory to it. Something may break because of that.", L"Launcher Warning", 0); - } - } + PrependPath(); + bool loadNorthstar = ShouldLoadNorthstar(argc, argv); if (loadNorthstar) { - FARPROC Hook_Init = nullptr; - { - swprintf_s(buffer, L"%s\\Northstar.dll", exePath); - hHookModule = LoadLibraryExW(buffer, 0i64, 8u); - if (hHookModule) Hook_Init = GetProcAddress(hHookModule, "InitialiseNorthstar"); - if (!hHookModule || Hook_Init == nullptr) - { - LibraryLoadError(GetLastError(), L"Northstar.dll", buffer); - return 1; - } - } - - ((bool (*)()) Hook_Init)(); + printf("[*] Loading Northstar\n"); + if (!LoadNorthstar()) + return 1; } + else + printf("[*] Going to load the vanilla game\n"); + printf("[*] Loading launcher.dll\n"); swprintf_s(buffer, L"%s\\bin\\x64_retail\\launcher.dll", exePath); hLauncherModule = LoadLibraryExW(buffer, 0i64, 8u); if (!hLauncherModule) @@ -213,12 +217,24 @@ int main(int argc, char* argv[]) { LibraryLoadError(GetLastError(), L"launcher.dll", buffer); return 1; } + + printf("[*] Loading tier0.dll\n"); + // this makes zero sense given tier0.dll is already loaded via imports on launcher.dll, but we do it for full consistency with original launcher exe + // and to also let load callbacks in Northstar work for tier0.dll + swprintf_s(buffer, L"%s\\bin\\x64_retail\\tier0.dll", exePath); + hTier0Module = LoadLibraryW(buffer); + if (!hTier0Module) + { + LibraryLoadError(GetLastError(), L"tier0.dll", buffer); + return 1; + } } + printf("[*] Launching the game...\n"); auto LauncherMain = GetLauncherMain(); if (!LauncherMain) - MessageBoxA(GetForegroundWindow(), "Failed loading launcher.dll.\nThe game cannot continue and has to exit.", "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), "Failed loading launcher.dll.\nThe game cannot continue and has to exit.", "Northstar Launcher Error", 0); //auto result = ((__int64(__fastcall*)())LauncherMain)(); //auto result = ((signed __int64(__fastcall*)(__int64))LauncherMain)(0i64); - return ((int(__fastcall*)(HINSTANCE, HINSTANCE, LPSTR, int))LauncherMain)(NULL, NULL, NULL, 0); // the parameters aren't really used anyways + return ((int(/*__fastcall*/*)(HINSTANCE, HINSTANCE, LPSTR, int))LauncherMain)(NULL, NULL, NULL, 0); // the parameters aren't really used anyways } \ No newline at end of file diff --git a/LauncherInjector/memalloc.cpp b/LauncherInjector/memalloc.cpp index 64bc7b76..1d0f13e6 100644 --- a/LauncherInjector/memalloc.cpp +++ b/LauncherInjector/memalloc.cpp @@ -1,13 +1,14 @@ #define WIN32_LEAN_AND_MEAN #include #include "memalloc.h" +#include -HMODULE hTier0Module; +extern HMODULE hTier0Module; IMemAlloc** g_ppMemAllocSingleton; void LoadTier0Handle() { - hTier0Module = GetModuleHandleA("tier0.dll"); + if (!hTier0Module) hTier0Module = GetModuleHandleA("tier0.dll"); if (!hTier0Module) return; g_ppMemAllocSingleton = (IMemAlloc**)GetProcAddress(hTier0Module, "g_pMemAllocSingleton"); @@ -18,10 +19,11 @@ const int STATIC_ALLOC_SIZE = 16384; size_t g_iStaticAllocated = 0; char pStaticAllocBuf[STATIC_ALLOC_SIZE]; -// they should never be used here, except in LibraryLoadError +// they should never be used here, except in LibraryLoadError // haha not true void* malloc(size_t n) { + //printf("NorthstarLauncher malloc: %llu\n", n); // allocate into static buffer if (g_iStaticAllocated + n <= STATIC_ALLOC_SIZE) { @@ -32,7 +34,7 @@ void* malloc(size_t n) else { // try to fallback to g_pMemAllocSingleton - if (!hTier0Module) LoadTier0Handle(); + if (!hTier0Module || !g_ppMemAllocSingleton) LoadTier0Handle(); if (g_ppMemAllocSingleton && *g_ppMemAllocSingleton) return (*g_ppMemAllocSingleton)->m_vtable->Alloc(*g_ppMemAllocSingleton, n); else @@ -42,6 +44,7 @@ void* malloc(size_t n) void free(void* p) { + //printf("NorthstarLauncher free: %p\n", p); // if it was allocated into the static buffer, just do nothing, safest way to deal with it if (p >= pStaticAllocBuf && p <= pStaticAllocBuf + STATIC_ALLOC_SIZE) return; diff --git a/NorthstarDedicatedTest/dllmain.cpp b/NorthstarDedicatedTest/dllmain.cpp index 1aa4bd3b..dfc3afe1 100644 --- a/NorthstarDedicatedTest/dllmain.cpp +++ b/NorthstarDedicatedTest/dllmain.cpp @@ -70,7 +70,7 @@ bool InitialiseNorthstar() { if (initialised) { - fprintf(stderr, "[WARN] Called InitialiseNorthstar more than once!\n"); + fprintf(stderr, "[info] Called InitialiseNorthstar more than once!\n"); return false; } initialised = true; @@ -81,8 +81,7 @@ bool InitialiseNorthstar() InstallInitialHooks(); InitialiseInterfaceCreationHooks(); - // adding a callback to tier0 won't work for some reason - AddDllLoadCallback("launcher.org.dll", InitialiseTier0GameUtilFunctions); + AddDllLoadCallback("tier0.dll", InitialiseTier0GameUtilFunctions); AddDllLoadCallback("engine.dll", WaitForDebugger); AddDllLoadCallback("engine.dll", InitialiseEngineGameUtilFunctions); AddDllLoadCallback("server.dll", InitialiseServerGameUtilFunctions); @@ -91,7 +90,7 @@ bool InitialiseNorthstar() // dedi patches { AddDllLoadCallback("engine.dll", InitialiseDedicated); - AddDllLoadCallback("launcher.org.dll", InitialiseDedicatedOrigin); + AddDllLoadCallback("tier0.dll", InitialiseDedicatedOrigin); AddDllLoadCallback("server.dll", InitialiseDedicatedServerGameDLL); AddDllLoadCallback("materialsystem_dx11.dll", InitialiseDedicatedMaterialSystem); // this fucking sucks, but seemingly we somehow load after rtech_game???? unsure how, but because of this we have to apply patches here, not on rtech_game load diff --git a/NorthstarDedicatedTest/gameutils.cpp b/NorthstarDedicatedTest/gameutils.cpp index 97011059..3e62037c 100644 --- a/NorthstarDedicatedTest/gameutils.cpp +++ b/NorthstarDedicatedTest/gameutils.cpp @@ -78,16 +78,25 @@ void InitialiseServerGameUtilFunctions(HMODULE baseAddress) void InitialiseTier0GameUtilFunctions(HMODULE baseAddress) { - baseAddress = GetModuleHandleA("tier0.dll"); - if (!baseAddress) - throw "tier0.dll is not loaded"; - CreateGlobalMemAlloc = reinterpret_cast(GetProcAddress(baseAddress, "CreateGlobalMemAlloc")); IMemAlloc** ppMemAllocSingleton = reinterpret_cast(GetProcAddress(baseAddress, "g_pMemAllocSingleton")); - if (!ppMemAllocSingleton || !*ppMemAllocSingleton) + if (!ppMemAllocSingleton) + { + spdlog::critical("Address of g_pMemAllocSingleton is a null pointer, this should never happen"); + throw "Address of g_pMemAllocSingleton is a null pointer, this should never happen"; + } + if (!*ppMemAllocSingleton) + { g_pMemAllocSingleton = CreateGlobalMemAlloc(); + *ppMemAllocSingleton = g_pMemAllocSingleton; + spdlog::warn("Created new g_pMemAllocSingleton"); + } else + { g_pMemAllocSingleton = *ppMemAllocSingleton; + extern size_t g_iStaticAllocated; + spdlog::info("Using existing g_pMemAllocSingleton for memory allocations, preallocated {} bytes beforehand", g_iStaticAllocated); + } Error = reinterpret_cast(GetProcAddress(baseAddress, "Error")); CommandLine = reinterpret_cast(GetProcAddress(baseAddress, "CommandLine")); diff --git a/NorthstarDedicatedTest/hooks.cpp b/NorthstarDedicatedTest/hooks.cpp index 3de8d483..9d2be61c 100644 --- a/NorthstarDedicatedTest/hooks.cpp +++ b/NorthstarDedicatedTest/hooks.cpp @@ -6,14 +6,24 @@ #include #include +// note that these load library callbacks only support explicitly loaded dynamic libraries + typedef HMODULE(*LoadLibraryExAType)(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); +typedef HMODULE(*LoadLibraryAType)(LPCSTR lpLibFileName); +HMODULE LoadLibraryAHook(LPCSTR lpLibFileName); + typedef HMODULE(*LoadLibraryExWType)(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); HMODULE LoadLibraryExWHook(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); +typedef HMODULE(*LoadLibraryWType)(LPCWSTR lpLibFileName); +HMODULE LoadLibraryWHook(LPCWSTR lpLibFileName); + LoadLibraryExAType LoadLibraryExAOriginal; +LoadLibraryAType LoadLibraryAOriginal; LoadLibraryExWType LoadLibraryExWOriginal; +LoadLibraryWType LoadLibraryWOriginal; void InstallInitialHooks() { @@ -22,7 +32,9 @@ void InstallInitialHooks() HookEnabler hook; ENABLER_CREATEHOOK(hook, &LoadLibraryExA, &LoadLibraryExAHook, reinterpret_cast(&LoadLibraryExAOriginal)); + ENABLER_CREATEHOOK(hook, &LoadLibraryA, &LoadLibraryAHook, reinterpret_cast(&LoadLibraryAOriginal)); ENABLER_CREATEHOOK(hook, &LoadLibraryExW, &LoadLibraryExWHook, reinterpret_cast(&LoadLibraryExWOriginal)); + ENABLER_CREATEHOOK(hook, &LoadLibraryW, &LoadLibraryWHook, reinterpret_cast(&LoadLibraryWOriginal)); } // dll load callback stuff @@ -46,20 +58,51 @@ void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback) dllLoadCallbacks.push_back(callbackStruct); } +void CallLoadLibraryACallbacks(LPCSTR lpLibFileName, HMODULE moduleAddress) +{ + for (auto& callbackStruct : dllLoadCallbacks) + { + if (!callbackStruct->called && strstr(lpLibFileName + (strlen(lpLibFileName) - strlen(callbackStruct->dll.c_str())), callbackStruct->dll.c_str()) != nullptr) + { + callbackStruct->callback(moduleAddress); + callbackStruct->called = true; + } + } +} + +void CallLoadLibraryWCallbacks(LPCWSTR lpLibFileName, HMODULE moduleAddress) +{ + for (auto& callbackStruct : dllLoadCallbacks) + { + std::wstring wcharStrDll = std::wstring(callbackStruct->dll.begin(), callbackStruct->dll.end()); + const wchar_t* callbackDll = wcharStrDll.c_str(); + if (!callbackStruct->called && wcsstr(lpLibFileName + (wcslen(lpLibFileName) - wcslen(callbackDll)), callbackDll) != nullptr) + { + callbackStruct->callback(moduleAddress); + callbackStruct->called = true; + } + } +} + HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE moduleAddress = LoadLibraryExAOriginal(lpLibFileName, hFile, dwFlags); if (moduleAddress) { - for (auto& callbackStruct : dllLoadCallbacks) - { - if (!callbackStruct->called && strstr(lpLibFileName + (strlen(lpLibFileName) - strlen(callbackStruct->dll.c_str())), callbackStruct->dll.c_str()) != nullptr) - { - callbackStruct->callback(moduleAddress); - callbackStruct->called = true; - } - } + CallLoadLibraryACallbacks(lpLibFileName, moduleAddress); + } + + return moduleAddress; +} + +HMODULE LoadLibraryAHook(LPCSTR lpLibFileName) +{ + HMODULE moduleAddress = LoadLibraryAOriginal(lpLibFileName); + + if (moduleAddress) + { + CallLoadLibraryACallbacks(lpLibFileName, moduleAddress); } return moduleAddress; @@ -71,16 +114,19 @@ HMODULE LoadLibraryExWHook(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) if (moduleAddress) { - for (auto& callbackStruct : dllLoadCallbacks) - { - std::wstring wcharStrDll = std::wstring(callbackStruct->dll.begin(), callbackStruct->dll.end()); - const wchar_t* callbackDll = wcharStrDll.c_str(); - if (!callbackStruct->called && wcsstr(lpLibFileName + (wcslen(lpLibFileName) - wcslen(callbackDll)), callbackDll) != nullptr) - { - callbackStruct->callback(moduleAddress); - callbackStruct->called = true; - } - } + CallLoadLibraryWCallbacks(lpLibFileName, moduleAddress); + } + + return moduleAddress; +} + +HMODULE LoadLibraryWHook(LPCWSTR lpLibFileName) +{ + HMODULE moduleAddress = LoadLibraryWOriginal(lpLibFileName); + + if (moduleAddress) + { + CallLoadLibraryWCallbacks(lpLibFileName, moduleAddress); } return moduleAddress; diff --git a/NorthstarDedicatedTest/memalloc.cpp b/NorthstarDedicatedTest/memalloc.cpp index 113f56b9..cff0ecac 100644 --- a/NorthstarDedicatedTest/memalloc.cpp +++ b/NorthstarDedicatedTest/memalloc.cpp @@ -17,24 +17,48 @@ const int STATIC_ALLOC_SIZE = 100000; // alot more than we need, could reduce to size_t g_iStaticAllocated = 0; char pStaticAllocBuf[STATIC_ALLOC_SIZE]; -void* operator new(size_t n) +// TODO: rename to malloc and free after removing statically compiled .libs + +void* malloc_(size_t n) { // allocate into static buffer if g_pMemAllocSingleton isn't initialised if (g_pMemAllocSingleton) + { + //printf("Northstar malloc (g_pMemAllocSingleton): %llu\n", n); return g_pMemAllocSingleton->m_vtable->Alloc(g_pMemAllocSingleton, n); + } else { + if (g_iStaticAllocated + n > STATIC_ALLOC_SIZE) + { + throw "Ran out of prealloc space"; // we could log, but spdlog probably does use allocations as well... + } + //printf("Northstar malloc (prealloc): %llu\n", n); void* ret = pStaticAllocBuf + g_iStaticAllocated; g_iStaticAllocated += n; return ret; - } + } } -void operator delete(void* p) +void free_(void* p) { // if it was allocated into the static buffer, just do nothing, safest way to deal with it if (p >= pStaticAllocBuf && p <= pStaticAllocBuf + STATIC_ALLOC_SIZE) + { + //printf("Northstar free (prealloc): %p\n", p); return; + } + //printf("Northstar free (g_pMemAllocSingleton): %p\n", p); g_pMemAllocSingleton->m_vtable->Free(g_pMemAllocSingleton, p); +} + +void* operator new(size_t n) +{ + return malloc_(n); +} + +void operator delete(void* p) +{ + free_(p); } \ No newline at end of file diff --git a/loader_launcher_proxy/Memory.cpp b/loader_launcher_proxy/Memory.cpp index d5642ca5..6c69d80f 100644 --- a/loader_launcher_proxy/Memory.cpp +++ b/loader_launcher_proxy/Memory.cpp @@ -1,11 +1,11 @@ #include "pch.h" -HMODULE hTier0Module; +extern HMODULE hTier0Module; IMemAlloc** g_ppMemAllocSingleton; void LoadTier0Handle() { - hTier0Module = GetModuleHandleA("tier0.dll"); + if (!hTier0Module) hTier0Module = GetModuleHandleA("tier0.dll"); if (!hTier0Module) return; g_ppMemAllocSingleton = (IMemAlloc**)GetProcAddress(hTier0Module, "g_pMemAllocSingleton"); @@ -16,9 +16,9 @@ const int STATIC_ALLOC_SIZE = 4096; size_t g_iStaticAllocated = 0; char pStaticAllocBuf[STATIC_ALLOC_SIZE]; -// they should never be used here, except in LibraryLoadError +// they should never be used here, except in LibraryLoadError? -void* operator new(size_t n) +void* malloc(size_t n) { // allocate into static buffer if (g_iStaticAllocated + n <= STATIC_ALLOC_SIZE) @@ -30,7 +30,7 @@ void* operator new(size_t n) else { // try to fallback to g_pMemAllocSingleton - if (!hTier0Module) LoadTier0Handle(); + if (!hTier0Module || !g_ppMemAllocSingleton) LoadTier0Handle(); if (g_ppMemAllocSingleton && *g_ppMemAllocSingleton) return (*g_ppMemAllocSingleton)->m_vtable->Alloc(*g_ppMemAllocSingleton, n); else @@ -38,7 +38,7 @@ void* operator new(size_t n) } } -void operator delete(void* p) +void free(void* p) { // if it was allocated into the static buffer, just do nothing, safest way to deal with it if (p >= pStaticAllocBuf && p <= pStaticAllocBuf + STATIC_ALLOC_SIZE) @@ -47,3 +47,13 @@ void operator delete(void* p) if (g_ppMemAllocSingleton && *g_ppMemAllocSingleton) (*g_ppMemAllocSingleton)->m_vtable->Free(*g_ppMemAllocSingleton, p); } + +void* operator new(size_t n) +{ + return malloc(n); +} + +void operator delete(void* p) +{ + return free(p); +} diff --git a/loader_launcher_proxy/dllmain.cpp b/loader_launcher_proxy/dllmain.cpp index 31360a8e..6db50986 100644 --- a/loader_launcher_proxy/dllmain.cpp +++ b/loader_launcher_proxy/dllmain.cpp @@ -3,9 +3,12 @@ #include #include #include +#include +#include HMODULE hLauncherModule; HMODULE hHookModule; +HMODULE hTier0Module; using CreateInterfaceFn = void* (*)(const char* pName, int* pReturnCode); @@ -44,7 +47,7 @@ void LibraryLoadError(DWORD dwMessageId, const wchar_t* libName, const wchar_t* char text[2048]; std::string message = std::system_category().message(dwMessageId); sprintf_s(text, "Failed to load the %ls at \"%ls\" (%lu):\n\n%hs", libName, location, dwMessageId, message.c_str()); - MessageBoxA(GetForegroundWindow(), text, "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), text, "Northstar Launcher Proxy Error", 0); } BOOL APIENTRY DllMain( HMODULE hModule, @@ -66,32 +69,61 @@ BOOL APIENTRY DllMain( HMODULE hModule, wchar_t exePath[4096]; wchar_t dllPath[4096]; +bool ShouldLoadNorthstar() +{ + bool loadNorthstar = !strstr(GetCommandLineA(), "-vanilla"); + + if (!loadNorthstar) + return loadNorthstar; + + auto runNorthstarFile = std::ifstream("run_northstar.txt"); + if (runNorthstarFile) + { + std::stringstream runNorthstarFileBuffer; + runNorthstarFileBuffer << runNorthstarFile.rdbuf(); + runNorthstarFile.close(); + if (runNorthstarFileBuffer.str()._Starts_with("0")) + loadNorthstar = false; + } + return loadNorthstar; +} + +bool LoadNorthstar() +{ + FARPROC Hook_Init = nullptr; + { + swprintf_s(dllPath, L"%s\\Northstar.dll", exePath); + hHookModule = LoadLibraryExW(dllPath, 0i64, 8u); + if (hHookModule) Hook_Init = GetProcAddress(hHookModule, "InitialiseNorthstar"); + if (!hHookModule || Hook_Init == nullptr) + { + LibraryLoadError(GetLastError(), L"Northstar.dll", dllPath); + return false; + } + } + + printf("WILL CALL HOOK INIT\n"); + ((bool (*)()) Hook_Init)(); + return true; +} + extern "C" __declspec(dllexport) int LauncherMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { { if (!GetExePathWide(exePath, 4096)) { - MessageBoxA(GetForegroundWindow(), "Failed getting game directory.\nThe game cannot continue and has to exit.", "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), "Failed getting game directory.\nThe game cannot continue and has to exit.", "Northstar Launcher Proxy Error", 0); return 1; } - bool loadNorthstar = !strstr(GetCommandLineA(), "-vanilla"); + bool loadNorthstar = ShouldLoadNorthstar(); + if (loadNorthstar) { - FARPROC Hook_Init = nullptr; - { - swprintf_s(dllPath, L"%s\\Northstar.dll", exePath); - hHookModule = LoadLibraryExW(dllPath, 0i64, 8u); - if (hHookModule) Hook_Init = GetProcAddress(hHookModule, "InitialiseNorthstar"); - if (!hHookModule || Hook_Init == nullptr) - { - LibraryLoadError(GetLastError(), L"Northstar.dll", dllPath); - return 1; - } - } - - ((bool (*)()) Hook_Init)(); + if (!LoadNorthstar()) + return 1; } + //else printf("\n\n WILL !!!NOT!!! LOAD NORTHSTAR\n\n"); swprintf_s(dllPath, L"%s\\bin\\x64_retail\\launcher.org.dll", exePath); hLauncherModule = LoadLibraryExW(dllPath, 0i64, 8u); @@ -100,11 +132,21 @@ extern "C" __declspec(dllexport) int LauncherMain(HINSTANCE hInstance, HINSTANCE LibraryLoadError(GetLastError(), L"launcher.org.dll", dllPath); return 1; } + + // this makes zero sense given tier0.dll is already loaded via imports on launcher.dll, but we do it for full consistency with original launcher exe + // and to also let load callbacks in Northstar work for tier0.dll + swprintf_s(dllPath, L"%s\\bin\\x64_retail\\tier0.dll", exePath); + hTier0Module = LoadLibraryW(dllPath); + if (!hTier0Module) + { + LibraryLoadError(GetLastError(), L"tier0.dll", dllPath); + return 1; + } } auto LauncherMain = GetLauncherMain(); if (!LauncherMain) - MessageBoxA(GetForegroundWindow(), "Failed loading launcher.org.dll.\nThe game cannot continue and has to exit.", "Launcher Error", 0); + MessageBoxA(GetForegroundWindow(), "Failed loading launcher.org.dll.\nThe game cannot continue and has to exit.", "Northstar Launcher Proxy Error", 0); //auto result = ((__int64(__fastcall*)())LauncherMain)(); //auto result = ((signed __int64(__fastcall*)(__int64))LauncherMain)(0i64); return ((int(__fastcall*)(HINSTANCE, HINSTANCE, LPSTR, int))LauncherMain)(hInstance, hPrevInstance, lpCmdLine, nCmdShow); diff --git a/loader_launcher_proxy/loader_launcher_proxy.vcxproj b/loader_launcher_proxy/loader_launcher_proxy.vcxproj index 65ef19ba..9cc7a4c7 100644 --- a/loader_launcher_proxy/loader_launcher_proxy.vcxproj +++ b/loader_launcher_proxy/loader_launcher_proxy.vcxproj @@ -78,7 +78,7 @@ true Use pch.h - Default + stdcpp17 Windows -- cgit v1.2.3 From 32b1257cd62ee6ec7f1087355a2d9e181429d165 Mon Sep 17 00:00:00 2001 From: geni Date: Fri, 31 Dec 2021 14:44:15 +0200 Subject: Remove linear allocator --- LauncherInjector/main.cpp | 22 +++++------ NorthstarDedicatedTest/dllmain.cpp | 6 +-- NorthstarDedicatedTest/gameutils.cpp | 2 - NorthstarDedicatedTest/memalloc.cpp | 75 ++++++++---------------------------- NorthstarDedicatedTest/memalloc.h | 12 +++--- 5 files changed, 35 insertions(+), 82 deletions(-) (limited to 'NorthstarDedicatedTest/gameutils.cpp') diff --git a/LauncherInjector/main.cpp b/LauncherInjector/main.cpp index f35a3015..761f443e 100644 --- a/LauncherInjector/main.cpp +++ b/LauncherInjector/main.cpp @@ -192,6 +192,15 @@ int main(int argc, char* argv[]) { PrependPath(); + printf("[*] Loading tier0.dll\n"); + swprintf_s(buffer, L"%s\\bin\\x64_retail\\tier0.dll", exePath); + hTier0Module = LoadLibraryExW(buffer, 0, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!hTier0Module) + { + LibraryLoadError(GetLastError(), L"tier0.dll", buffer); + return 1; + } + bool loadNorthstar = ShouldLoadNorthstar(argc, argv); if (loadNorthstar) { @@ -204,23 +213,12 @@ int main(int argc, char* argv[]) { printf("[*] Loading launcher.dll\n"); swprintf_s(buffer, L"%s\\bin\\x64_retail\\launcher.dll", exePath); - hLauncherModule = LoadLibraryExW(buffer, 0i64, 8u); + hLauncherModule = LoadLibraryExW(buffer, 0, LOAD_WITH_ALTERED_SEARCH_PATH); if (!hLauncherModule) { LibraryLoadError(GetLastError(), L"launcher.dll", buffer); return 1; } - - printf("[*] Loading tier0.dll\n"); - // this makes zero sense given tier0.dll is already loaded via imports on launcher.dll, but we do it for full consistency with original launcher exe - // and to also let load callbacks in Northstar work for tier0.dll - swprintf_s(buffer, L"%s\\bin\\x64_retail\\tier0.dll", exePath); - hTier0Module = LoadLibraryW(buffer); - if (!hTier0Module) - { - LibraryLoadError(GetLastError(), L"tier0.dll", buffer); - return 1; - } } printf("[*] Launching the game...\n"); diff --git a/NorthstarDedicatedTest/dllmain.cpp b/NorthstarDedicatedTest/dllmain.cpp index 4f8a445c..07741801 100644 --- a/NorthstarDedicatedTest/dllmain.cpp +++ b/NorthstarDedicatedTest/dllmain.cpp @@ -58,7 +58,6 @@ void WaitForDebugger(HMODULE baseAddress) if (strstr(GetCommandLineA(), "-waitfordebugger")) { spdlog::info("waiting for debugger..."); - spdlog::info("{} bytes have been statically allocated", g_iStaticAllocated); while (!IsDebuggerPresent()) Sleep(100); @@ -71,7 +70,7 @@ bool InitialiseNorthstar() { if (initialised) { - fprintf(stderr, "[info] Called InitialiseNorthstar more than once!\n"); + spdlog::warn("Called InitialiseNorthstar more than once!"); return false; } initialised = true; @@ -85,7 +84,6 @@ bool InitialiseNorthstar() g_SourceAllocator = new SourceAllocator; curl_global_init(CURL_GLOBAL_DEFAULT); - AddDllLoadCallback("tier0.dll", InitialiseTier0GameUtilFunctions); AddDllLoadCallback("engine.dll", WaitForDebugger); AddDllLoadCallback("engine.dll", InitialiseEngineGameUtilFunctions); AddDllLoadCallback("server.dll", InitialiseServerGameUtilFunctions); @@ -93,8 +91,8 @@ bool InitialiseNorthstar() // dedi patches { + AddDllLoadCallback("launcher.dll", InitialiseDedicatedOrigin); AddDllLoadCallback("engine.dll", InitialiseDedicated); - AddDllLoadCallback("tier0.dll", InitialiseDedicatedOrigin); AddDllLoadCallback("server.dll", InitialiseDedicatedServerGameDLL); AddDllLoadCallback("materialsystem_dx11.dll", InitialiseDedicatedMaterialSystem); // this fucking sucks, but seemingly we somehow load after rtech_game???? unsure how, but because of this we have to apply patches here, not on rtech_game load diff --git a/NorthstarDedicatedTest/gameutils.cpp b/NorthstarDedicatedTest/gameutils.cpp index 3e62037c..b2c88e49 100644 --- a/NorthstarDedicatedTest/gameutils.cpp +++ b/NorthstarDedicatedTest/gameutils.cpp @@ -94,8 +94,6 @@ void InitialiseTier0GameUtilFunctions(HMODULE baseAddress) else { g_pMemAllocSingleton = *ppMemAllocSingleton; - extern size_t g_iStaticAllocated; - spdlog::info("Using existing g_pMemAllocSingleton for memory allocations, preallocated {} bytes beforehand", g_iStaticAllocated); } Error = reinterpret_cast(GetProcAddress(baseAddress, "Error")); diff --git a/NorthstarDedicatedTest/memalloc.cpp b/NorthstarDedicatedTest/memalloc.cpp index c1fb70e7..c9cf4d60 100644 --- a/NorthstarDedicatedTest/memalloc.cpp +++ b/NorthstarDedicatedTest/memalloc.cpp @@ -2,43 +2,16 @@ #include "memalloc.h" #include "gameutils.h" -// so for anyone reading this code, you may be curious why the fuck i'm overriding new to alloc into a static 100k buffer -// pretty much, the issue here is that we need to use the game's memory allocator (g_pMemAllocSingleton) or risk heap corruptions, but this allocator is defined in tier0 -// as such, it doesn't exist when we inject -// initially i wanted to just call malloc and free until g_pMemAllocSingleton was initialised, but the issue then becomes that we might try to -// call g_pMemAllocSingleton->Free on memory that was allocated with malloc, which will cause game to crash -// so, the best idea i had for this was to just alloc 100k of memory, have all pre-tier0 allocations use that -// (from what i can tell we hit about 12k before tier0 is loaded atm in debug builds, so it's more than enough) -// then just use the game's allocator after that -// yes, this means we leak 100k of memory, idk how else to do this without breaking stuff - -const int STATIC_ALLOC_SIZE = 100000; // alot more than we need, could reduce to 50k or even 25k later potentially - -size_t g_iStaticAllocated = 0; -void* g_pLastAllocated = nullptr; -char pStaticAllocBuf[STATIC_ALLOC_SIZE]; - // TODO: rename to malloc and free after removing statically compiled .libs extern "C" void* _malloc_base(size_t n) { // allocate into static buffer if g_pMemAllocSingleton isn't initialised - if (g_pMemAllocSingleton) - { - //printf("Northstar malloc (g_pMemAllocSingleton): %llu\n", n); - return g_pMemAllocSingleton->m_vtable->Alloc(g_pMemAllocSingleton, n); - } - else + if (!g_pMemAllocSingleton) { - if (g_iStaticAllocated + n > STATIC_ALLOC_SIZE) - { - throw "Ran out of prealloc space"; // we could log, but spdlog probably does use allocations as well... - } - //printf("Northstar malloc (prealloc): %llu\n", n); - void* ret = pStaticAllocBuf + g_iStaticAllocated; - g_iStaticAllocated += n; - return ret; + InitialiseTier0GameUtilFunctions(GetModuleHandleA("tier0.dll")); } + return g_pMemAllocSingleton->m_vtable->Alloc(g_pMemAllocSingleton, n); } /*extern "C" void* malloc(size_t n) @@ -48,44 +21,30 @@ extern "C" void* _malloc_base(size_t n) extern "C" void _free_base(void* p) { - // if it was allocated into the static buffer, just do nothing, safest way to deal with it - if (p >= pStaticAllocBuf && p <= pStaticAllocBuf + STATIC_ALLOC_SIZE) + if (!g_pMemAllocSingleton) { - //printf("Northstar free (prealloc): %p\n", p); - return; + InitialiseTier0GameUtilFunctions(GetModuleHandleA("tier0.dll")); } - - //printf("Northstar free (g_pMemAllocSingleton): %p\n", p); g_pMemAllocSingleton->m_vtable->Free(g_pMemAllocSingleton, p); } -extern "C" void* _realloc_base(void* old_ptr, size_t size) { - // it was allocated into the static buffer - if (old_ptr >= pStaticAllocBuf && old_ptr <= pStaticAllocBuf + STATIC_ALLOC_SIZE) + +extern "C" void* _realloc_base(void* oldPtr, size_t size) { + if (!g_pMemAllocSingleton) { - if (g_pLastAllocated == old_ptr) - { - // nothing was allocated after this - size_t old_size = g_iStaticAllocated - ((size_t)g_pLastAllocated - (size_t)pStaticAllocBuf); - size_t diff = size - old_size; - if (diff > 0) - g_iStaticAllocated += diff; - return old_ptr; - } - else - { - return _malloc_base(size); - } + InitialiseTier0GameUtilFunctions(GetModuleHandleA("tier0.dll")); } - - if (g_pMemAllocSingleton) - return g_pMemAllocSingleton->m_vtable->Realloc(g_pMemAllocSingleton, old_ptr, size); - return nullptr; + return g_pMemAllocSingleton->m_vtable->Realloc(g_pMemAllocSingleton, oldPtr, size); } extern "C" void* _calloc_base(size_t n, size_t size) { - return _malloc_base(n * size); + size_t bytes = n * size; + void* memory = _malloc_base(bytes); + if (memory) { + memset(memory, 0, bytes); + } + return memory; } extern "C" char* _strdup_base(const char* src) @@ -96,7 +55,7 @@ extern "C" char* _strdup_base(const char* src) while (src[len]) len++; - str = reinterpret_cast(_malloc_base(len + 1)); + str = (char*)(_malloc_base(len + 1)); p = str; while (*src) *p++ = *src++; diff --git a/NorthstarDedicatedTest/memalloc.h b/NorthstarDedicatedTest/memalloc.h index d9277694..86d2ff58 100644 --- a/NorthstarDedicatedTest/memalloc.h +++ b/NorthstarDedicatedTest/memalloc.h @@ -3,16 +3,16 @@ #include "include/rapidjson/document.h" //#include "include/rapidjson/allocators.h" -extern size_t g_iStaticAllocated; - -extern "C" { - char* _strdup_base(const char* src); -} +extern "C" void* _malloc_base(size_t size); +extern "C" void* _calloc_base(size_t const count, size_t const size); +extern "C" void* _realloc_base(void* block, size_t size); +extern "C" void* _recalloc_base(void* const block, size_t const count, size_t const size); +extern "C" void _free_base(void* const block); +extern "C" char* _strdup_base(const char* src); void* operator new(size_t n); void operator delete(void* p); -void* _malloc_base(size_t n); //void* malloc(size_t n); class SourceAllocator { -- cgit v1.2.3 From 9b13df7bc6f4c09c3fdab27cd51fe76d30b756b8 Mon Sep 17 00:00:00 2001 From: p0358 Date: Fri, 31 Dec 2021 22:46:45 +0100 Subject: some post-merge changes combined with my local changes --- LauncherInjector/main.cpp | 6 +++--- NorthstarDedicatedTest/dedicated.cpp | 2 +- NorthstarDedicatedTest/dllmain.cpp | 16 ++++++---------- NorthstarDedicatedTest/gameutils.cpp | 9 ++++++++- NorthstarDedicatedTest/hooks.cpp | 26 ++++++++++++++++++++++++-- NorthstarDedicatedTest/hooks.h | 4 +++- NorthstarDedicatedTest/masterserver.cpp | 4 ++-- NorthstarDedicatedTest/memalloc.cpp | 6 ++++-- NorthstarDedicatedTest/memalloc.h | 2 -- 9 files changed, 51 insertions(+), 24 deletions(-) (limited to 'NorthstarDedicatedTest/gameutils.cpp') diff --git a/LauncherInjector/main.cpp b/LauncherInjector/main.cpp index 761f443e..0f70fd4b 100644 --- a/LauncherInjector/main.cpp +++ b/LauncherInjector/main.cpp @@ -81,7 +81,7 @@ void EnsureOriginStarted() HKEY key; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Origin", 0, KEY_READ, &key) != ERROR_SUCCESS) { - MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); + MessageBoxA(0, "Error: failed reading Origin path!", "", MB_OK); return; } @@ -89,7 +89,7 @@ void EnsureOriginStarted() DWORD originPathLength = 520; if (RegQueryValueExA(key, "ClientPath", 0, 0, (LPBYTE)&originPath, &originPathLength) != ERROR_SUCCESS) { - MessageBoxA(0, "Error: failed reading origin path!", "", MB_OK); + MessageBoxA(0, "Error: failed reading Origin path!", "", MB_OK); return; } @@ -122,7 +122,7 @@ void PrependPath() { MessageBoxW(GetForegroundWindow(), L"Warning: could not prepend the current directory to app's PATH environment variable. Something may break because of that.", L"Northstar Launcher Warning", 0); } - //free(pPath); + free(pPath); } else { diff --git a/NorthstarDedicatedTest/dedicated.cpp b/NorthstarDedicatedTest/dedicated.cpp index 0ecc1dba..8dedcdd9 100644 --- a/NorthstarDedicatedTest/dedicated.cpp +++ b/NorthstarDedicatedTest/dedicated.cpp @@ -394,7 +394,7 @@ void InitialiseDedicatedOrigin(HMODULE baseAddress) char* ptr = (char*)GetProcAddress(GetModuleHandleA("tier0.dll"), "Tier0_InitOrigin"); TempReadWrite rw(ptr); - *ptr = (char)0xC3; + *ptr = (char)0xC3; // ret } typedef void(*PrintFatalSquirrelErrorType)(void* sqvm); diff --git a/NorthstarDedicatedTest/dllmain.cpp b/NorthstarDedicatedTest/dllmain.cpp index 81bae847..87fb4d5f 100644 --- a/NorthstarDedicatedTest/dllmain.cpp +++ b/NorthstarDedicatedTest/dllmain.cpp @@ -43,11 +43,6 @@ BOOL APIENTRY DllMain( HMODULE hModule, break; } - // pls no xD - //if (!initialised) - // InitialiseNorthstar(); - //initialised = true; - return TRUE; } @@ -71,9 +66,10 @@ bool InitialiseNorthstar() spdlog::warn("Called InitialiseNorthstar more than once!"); return false; } + initialised = true; - curl_global_init(CURL_GLOBAL_DEFAULT); + curl_global_init_mem(CURL_GLOBAL_DEFAULT, _malloc_base, _free_base, _realloc_base, _strdup_base, _calloc_base); InitialiseLogging(); @@ -81,6 +77,7 @@ bool InitialiseNorthstar() InstallInitialHooks(); InitialiseInterfaceCreationHooks(); + AddDllLoadCallback("tier0.dll", InitialiseTier0GameUtilFunctions); AddDllLoadCallback("engine.dll", WaitForDebugger); AddDllLoadCallback("engine.dll", InitialiseEngineGameUtilFunctions); AddDllLoadCallback("server.dll", InitialiseServerGameUtilFunctions); @@ -88,7 +85,7 @@ bool InitialiseNorthstar() // dedi patches { - AddDllLoadCallback("launcher.dll", InitialiseDedicatedOrigin); + AddDllLoadCallback("tier0.dll", InitialiseDedicatedOrigin); AddDllLoadCallback("engine.dll", InitialiseDedicated); AddDllLoadCallback("server.dll", InitialiseDedicatedServerGameDLL); AddDllLoadCallback("materialsystem_dx11.dll", InitialiseDedicatedMaterialSystem); @@ -128,9 +125,8 @@ bool InitialiseNorthstar() // mod manager after everything else AddDllLoadCallback("engine.dll", InitialiseModManager); - // TODO: If you wanna make it more flexible and for example injectable with old Icepick injector - // in this place you should iterate over all already loaded DLLs and execute their callbacks and mark them as executed - // (as they will never get called otherwise and stuff will fail) + // run callbacks for any libraries that are already loaded by now + CallAllPendingDLLLoadCallbacks(); return true; } \ No newline at end of file diff --git a/NorthstarDedicatedTest/gameutils.cpp b/NorthstarDedicatedTest/gameutils.cpp index b2c88e49..1cbd8648 100644 --- a/NorthstarDedicatedTest/gameutils.cpp +++ b/NorthstarDedicatedTest/gameutils.cpp @@ -78,6 +78,13 @@ void InitialiseServerGameUtilFunctions(HMODULE baseAddress) void InitialiseTier0GameUtilFunctions(HMODULE baseAddress) { + if (!baseAddress) + { + spdlog::critical("tier0 base address is null, but it should be already loaded"); + throw "tier0 base address is null, but it should be already loaded"; + } + if (g_pMemAllocSingleton) + return; // seems this function was already called CreateGlobalMemAlloc = reinterpret_cast(GetProcAddress(baseAddress, "CreateGlobalMemAlloc")); IMemAlloc** ppMemAllocSingleton = reinterpret_cast(GetProcAddress(baseAddress, "g_pMemAllocSingleton")); if (!ppMemAllocSingleton) @@ -89,7 +96,7 @@ void InitialiseTier0GameUtilFunctions(HMODULE baseAddress) { g_pMemAllocSingleton = CreateGlobalMemAlloc(); *ppMemAllocSingleton = g_pMemAllocSingleton; - spdlog::warn("Created new g_pMemAllocSingleton"); + spdlog::info("Created new g_pMemAllocSingleton"); } else { diff --git a/NorthstarDedicatedTest/hooks.cpp b/NorthstarDedicatedTest/hooks.cpp index 19010e83..0e653d4e 100644 --- a/NorthstarDedicatedTest/hooks.cpp +++ b/NorthstarDedicatedTest/hooks.cpp @@ -8,12 +8,11 @@ #include #include #include +#include typedef LPSTR(*GetCommandLineAType)(); LPSTR GetCommandLineAHook(); -// note that these load library callbacks only support explicitly loaded dynamic libraries - typedef HMODULE(*LoadLibraryExAType)(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); @@ -138,6 +137,29 @@ void CallLoadLibraryWCallbacks(LPCWSTR lpLibFileName, HMODULE moduleAddress) } } +void CallAllPendingDLLLoadCallbacks() +{ + HMODULE hMods[1024]; + HANDLE hProcess = GetCurrentProcess(); + DWORD cbNeeded; + unsigned int i; + + // Get a list of all the modules in this process. + if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) + { + for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) + { + wchar_t szModName[MAX_PATH]; + + // Get the full path to the module's file. + if (GetModuleFileNameExW(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) + { + CallLoadLibraryWCallbacks(szModName, hMods[i]); + } + } + } +} + HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE moduleAddress = LoadLibraryExAOriginal(lpLibFileName, hFile, dwFlags); diff --git a/NorthstarDedicatedTest/hooks.h b/NorthstarDedicatedTest/hooks.h index 972b38a6..10e4d4ba 100644 --- a/NorthstarDedicatedTest/hooks.h +++ b/NorthstarDedicatedTest/hooks.h @@ -4,4 +4,6 @@ void InstallInitialHooks(); typedef void(*DllLoadCallbackFuncType)(HMODULE moduleAddress); -void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback); \ No newline at end of file +void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback); + +void CallAllPendingDLLLoadCallbacks(); \ No newline at end of file diff --git a/NorthstarDedicatedTest/masterserver.cpp b/NorthstarDedicatedTest/masterserver.cpp index 2fec6c82..e25be8ab 100644 --- a/NorthstarDedicatedTest/masterserver.cpp +++ b/NorthstarDedicatedTest/masterserver.cpp @@ -1022,9 +1022,9 @@ void CHostState__State_GameShutdownHook(CHostState* hostState) CHostState__State_GameShutdown(hostState); } -MasterServerManager::MasterServerManager() +MasterServerManager::MasterServerManager() : m_pendingConnectionInfo{}, m_ownServerId{ "" }, m_ownClientAuthToken{ "" } { - curl_global_init_mem(CURL_GLOBAL_DEFAULT, _malloc_base, _free_base, _realloc_base, _strdup_base, _calloc_base); + } void InitialiseSharedMasterServer(HMODULE baseAddress) diff --git a/NorthstarDedicatedTest/memalloc.cpp b/NorthstarDedicatedTest/memalloc.cpp index 86215e3f..1b9eaae8 100644 --- a/NorthstarDedicatedTest/memalloc.cpp +++ b/NorthstarDedicatedTest/memalloc.cpp @@ -23,13 +23,15 @@ extern "C" void _free_base(void* p) { if (!g_pMemAllocSingleton) { + spdlog::warn("Trying to free something before g_pMemAllocSingleton was ready, this should never happen"); InitialiseTier0GameUtilFunctions(GetModuleHandleA("tier0.dll")); } g_pMemAllocSingleton->m_vtable->Free(g_pMemAllocSingleton, p); } -extern "C" void* _realloc_base(void* oldPtr, size_t size) { +extern "C" void* _realloc_base(void* oldPtr, size_t size) +{ if (!g_pMemAllocSingleton) { InitialiseTier0GameUtilFunctions(GetModuleHandleA("tier0.dll")); @@ -56,7 +58,7 @@ extern "C" char* _strdup_base(const char* src) while (src[len]) len++; - str = (char*)(_malloc_base(len + 1)); + str = reinterpret_cast(_malloc_base(len + 1)); p = str; while (*src) *p++ = *src++; diff --git a/NorthstarDedicatedTest/memalloc.h b/NorthstarDedicatedTest/memalloc.h index b98fe3c8..92ab9672 100644 --- a/NorthstarDedicatedTest/memalloc.h +++ b/NorthstarDedicatedTest/memalloc.h @@ -35,8 +35,6 @@ public: static void Free(void* ptr) { _free_base(ptr); } }; -static SourceAllocator g_SourceAllocator; - typedef rapidjson::GenericDocument, rapidjson::MemoryPoolAllocator, SourceAllocator> rapidjson_document; //typedef rapidjson::GenericDocument, SourceAllocator, SourceAllocator> rapidjson_document; //typedef rapidjson::Document rapidjson_document; -- cgit v1.2.3