Skip to content

Commit

Permalink
[DllInjector] Fix race condition in GetLibraryProcAddress32.
Browse files Browse the repository at this point in the history
  • Loading branch information
num0005 committed Jul 19, 2024
1 parent e6bca62 commit eb0f037
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions Launcher/Utility/DLLInjector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,17 @@ private static bool IsProcessWow64(System.Diagnostics.Process process)

static object _32bitLock = new();
static string? _32bitHelperPath = null;
static FileStream _32bitHelperPathLock = null; // filestream used to lock the file for write and delete
static Dictionary<(string, string), FARPROC> _32bit_procs_cache = new();

private static void _deploy_get_proc_helper()
{

_32bitHelperPath = Path.Combine(App.TempFolder, "DllInjector.GetProcAddrHelper." + Guid.NewGuid().ToString() + ".exe");
File.WriteAllBytes(_32bitHelperPath, Utility.Resources.GetProcAddrHelper);
_32bitHelperPathLock = new(_32bitHelperPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}

/// <summary>
/// Get the address of a procdure. Only works for a few special libararies that are mapped at the same address in all modules
/// </summary>
Expand All @@ -145,7 +154,7 @@ private static bool IsProcessWow64(System.Diagnostics.Process process)
static private async Task<FARPROC> GetLibraryProcAddress32(string moduleName, string procName)
{
System.Diagnostics.Process process;
var cacheKey = (moduleName, procName);
var cacheKey = (moduleName.ToUpperInvariant(), procName);

// check cache first
// this method only works for modules loaded at the same address in all processes anyways
Expand All @@ -157,11 +166,8 @@ static private async Task<FARPROC> GetLibraryProcAddress32(string moduleName, st

lock (_32bitLock)
{
if (_32bitHelperPath is null)
{
_32bitHelperPath = Path.Combine(App.TempFolder, "DllInjector.GetProcAddrHelper." + Guid.NewGuid().ToString() + ".exe");
File.WriteAllBytes(_32bitHelperPath, Utility.Resources.GetProcAddrHelper);
}
if (_32bitHelperPath is null || !File.Exists(_32bitHelperPath))
_deploy_get_proc_helper();

List<string> args = new() { moduleName.Trim(), procName.Trim() };
process = System.Diagnostics.Process.Start(_32bitHelperPath, args);
Expand All @@ -176,7 +182,7 @@ static private async Task<FARPROC> GetLibraryProcAddress32(string moduleName, st
{
lock (_32bit_procs_cache)
{
_32bit_procs_cache.Add(cacheKey, ptrProc);
_32bit_procs_cache[cacheKey] = ptrProc;
}
}

Expand Down

0 comments on commit eb0f037

Please sign in to comment.