Fix thread namespace collision and tighten executable stub allocation
Fully qualifies System.Threading.Thread in DllInjector after introducing the WhiteMagic.Thread namespace, and replaces the broken+too-small near-allocation loop with a symmetric +/-2 GiB search so the x64 call stub always lands within rel32 range.
This commit is contained in:
@@ -472,46 +472,42 @@ public sealed class RemoteThreadExecutor
|
||||
nuint mask = AllocationGranularity - (nuint)1;
|
||||
nuint aligned = (preferred + AllocationGranularity - (nuint)1) & ~mask;
|
||||
|
||||
for (int i = 0; i < NearAllocationAttempts; i++)
|
||||
for (long delta = 0; delta <= (long)0x7FFF; delta++)
|
||||
{
|
||||
nuint candidate;
|
||||
if (i == 0)
|
||||
long signedOffset = delta * (long)AllocationGranularity;
|
||||
|
||||
// Try above, then below the target. Keep the original address as the first attempt.
|
||||
for (int sign = 0; sign < 2; sign++)
|
||||
{
|
||||
candidate = aligned;
|
||||
}
|
||||
else if ((i & 1) == 1)
|
||||
{
|
||||
candidate = aligned + (nuint)i * AllocationGranularity;
|
||||
}
|
||||
else
|
||||
{
|
||||
nuint offset = (nuint)i * AllocationGranularity;
|
||||
if (offset > aligned)
|
||||
{
|
||||
if (delta == 0 && sign != 0)
|
||||
continue;
|
||||
|
||||
long offset = sign == 0 ? signedOffset : -signedOffset;
|
||||
nuint candidate = (nuint)((long)aligned + offset);
|
||||
|
||||
// Avoid underflow to zero on below-target search.
|
||||
if (offset < 0 && candidate >= aligned)
|
||||
continue;
|
||||
|
||||
IntPtr result = NativeMethods.VirtualAllocEx(
|
||||
handle,
|
||||
(IntPtr)(nint)candidate,
|
||||
size,
|
||||
MemoryAllocationType.Commit | MemoryAllocationType.Reserve,
|
||||
MemoryProtectionType.ExecuteReadWrite);
|
||||
|
||||
if (result != IntPtr.Zero)
|
||||
{
|
||||
long distance = (long)(nuint)(nint)result - (long)(nuint)(nint)preferredAddress;
|
||||
if (distance >= int.MinValue && distance <= int.MaxValue)
|
||||
return result;
|
||||
|
||||
// The allocator gave us a nearby candidate but on the wrong side
|
||||
// of the 2 GiB boundary; treat it as unusable and keep searching.
|
||||
NativeMethods.VirtualFreeEx(handle, result, 0, MemoryFreeType.Release);
|
||||
}
|
||||
|
||||
candidate = aligned - offset;
|
||||
}
|
||||
|
||||
IntPtr result = NativeMethods.VirtualAllocEx(
|
||||
handle,
|
||||
(IntPtr)(nint)candidate,
|
||||
size,
|
||||
MemoryAllocationType.Commit | MemoryAllocationType.Reserve,
|
||||
MemoryProtectionType.ExecuteReadWrite);
|
||||
|
||||
if (result != IntPtr.Zero)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return NativeMethods.VirtualAllocEx(
|
||||
handle,
|
||||
IntPtr.Zero,
|
||||
size,
|
||||
MemoryAllocationType.Commit | MemoryAllocationType.Reserve,
|
||||
MemoryProtectionType.ExecuteReadWrite);
|
||||
}
|
||||
return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user