From 8b3dd1bb6c4caa098805d1a7d6b77b6dcd1b3b02 Mon Sep 17 00:00:00 2001 From: DismissedLight <1686188646@qq.com> Date: Tue, 28 Oct 2025 11:15:41 +0800 Subject: [PATCH] handle CreateToolhelp32Snapshot ERROR_BAD_LENGTH --- YaeAchievement/src/Utilities/GameProcess.cs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/YaeAchievement/src/Utilities/GameProcess.cs b/YaeAchievement/src/Utilities/GameProcess.cs index ebacfc7..e78b7b8 100644 --- a/YaeAchievement/src/Utilities/GameProcess.cs +++ b/YaeAchievement/src/Utilities/GameProcess.cs @@ -1,4 +1,5 @@ -using System.ComponentModel; +using Microsoft.Win32.SafeHandles; +using System.ComponentModel; using System.Runtime.InteropServices; using Windows.Win32; using Windows.Win32.Foundation; @@ -76,10 +77,20 @@ internal sealed unsafe class GameProcess { } // Get lib base address in target process byte* baseAddress = null; - using (var hSnap = Native.CreateToolhelp32Snapshot_SafeHandle(CREATE_TOOLHELP_SNAPSHOT_FLAGS.TH32CS_SNAPMODULE, Id)) { - if (hSnap.IsInvalid) { - throw new Win32Exception { Data = { { "api", "CreateToolhelp32Snapshot" } } }; + SafeFileHandle hSnap; + do + { + hSnap = Native.CreateToolhelp32Snapshot_SafeHandle(CREATE_TOOLHELP_SNAPSHOT_FLAGS.TH32CS_SNAPMODULE, Id); + if (Marshal.GetLastSystemError() is not (0 or 24)) // ERROR_BAD_LENGTH + { + break; } + } + while (hSnap.IsInvalid); + if (hSnap.IsInvalid) { + throw new Win32Exception { Data = { { "api", "CreateToolhelp32Snapshot" } } }; + } + using (hSnap) { var moduleEntry = new MODULEENTRY32 { dwSize = (uint) sizeof(MODULEENTRY32) }; @@ -124,4 +135,4 @@ internal sealed unsafe class GameProcess { public bool Terminate(uint exitCode) => Native.TerminateProcess(Handle, exitCode); -} +} \ No newline at end of file