Initial commit

This commit is contained in:
kbe
2026-07-21 22:30:10 +02:00
parent 21d2dd0460
commit 0380705e76
67 changed files with 7356 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
namespace WhiteMagic.Assembly;
/// <summary>
/// x86/x86-64 calling conventions for call-stub generation.
/// Named <c>CallConvention</c> (not <c>CallingConvention</c>) to avoid ambiguity with
/// <see cref="System.Runtime.InteropServices.CallingConvention"/>.
/// </summary>
public enum CallConvention
{
/// <summary>Caller pushes args right-to-left and cleans the stack (x86).</summary>
Cdecl,
/// <summary>Caller pushes args right-to-left; callee cleans the stack (x86).</summary>
Stdcall,
/// <summary>ECX receives the <c>this</c> pointer; remaining args on stack right-to-left; callee cleans (x86).</summary>
Thiscall,
/// <summary>ECX/EDX receive the first two args; remaining on stack right-to-left; callee cleans (x86).</summary>
Fastcall,
}
+22
View File
@@ -0,0 +1,22 @@
namespace WhiteMagic.Assembly;
/// <summary>
/// Abstraction over an x86/x64 assembler. The default <see cref="StubAssembler"/>
/// hand-emits calling-convention trampolines (no parsing, zero dep). An optional
/// <see cref="IcedAssembler"/> (Phase 8) handles arbitrary mnemonics via the Iced
/// library.
/// </summary>
/// <remarks>
/// This seam covers text assembly only (<see cref="Assemble"/>). Call-stub building
/// (<c>BuildCallStub</c>, <c>EmitU8</c>/<c>EmitU32</c>/<c>EmitU64</c>) is a
/// <see cref="StubAssembler"/> capability — not all backends need it.
/// </remarks>
public interface IAssembler
{
/// <summary>
/// Assembles text mnemonics into machine code.
/// </summary>
/// <param name="assemblyText">The assembly text (Intel syntax).</param>
/// <param name="origin">The base address for relative encodings.</param>
byte[] Assemble(string assemblyText, ulong origin = 0);
}
+222
View File
@@ -0,0 +1,222 @@
namespace WhiteMagic.Assembly;
/// <summary>
/// The default <see cref="IAssembler"/> backend. Hand-emits calling-convention
/// trampolines and remote-execution stubs using deterministic byte emitters
/// (<see cref="EmitU8"/>, <see cref="EmitU32"/>, <see cref="EmitU64"/>). Has
/// no native or third-party dependency — no FASM, no Iced.
/// </summary>
/// <remarks>
/// <see cref="Assemble"/> is not supported by this backend (it is a parse-free
/// emitter, not a text assembler). Use <see cref="IcedAssembler"/> (Phase 8) for
/// arbitrary mnemonics.
/// </remarks>
public sealed class StubAssembler : IAssembler
{
/// <inheritdoc />
public byte[] Assemble(string assemblyText, ulong origin = 0)
{
throw new NotSupportedException(
"StubAssembler does not parse text assembly. " +
"Use IcedAssembler (Phase 8) for arbitrary mnemonics.");
}
// ── Emit primitives ────────────────────────────────────────────────────
public void EmitU8(List<byte> buffer, byte value) => buffer.Add(value);
public void EmitU32(List<byte> buffer, uint value)
{
buffer.Add((byte)value);
buffer.Add((byte)(value >> 8));
buffer.Add((byte)(value >> 16));
buffer.Add((byte)(value >> 24));
}
public void EmitU64(List<byte> buffer, ulong value)
{
EmitU32(buffer, (uint)value);
EmitU32(buffer, (uint)(value >> 32));
}
// ── Call-stub builders ─────────────────────────────────────────────────
/// <summary>
/// Builds a calling-convention call stub for x86 or x64.
/// </summary>
/// <param name="stubAddress">Where the stub lands (for E8 rel32 encoding).</param>
/// <param name="targetAddress">Function to call.</param>
/// <param name="arguments">Argument values (uint[] — each 4 or 8 bytes per pointerSize).</param>
/// <param name="pointerSize">4 (x86) or 8 (x64).</param>
/// <param name="convention">Calling convention.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="pointerSize"/> is not 4 or 8,
/// or <paramref name="convention"/> is not known, or the distance between stub and target
/// exceeds the E8 rel32 range.</exception>
public byte[] BuildCallStub(IntPtr stubAddress, IntPtr targetAddress,
uint[] arguments, int pointerSize, CallConvention convention)
{
var buffer = new List<byte>(64);
if (pointerSize == 4)
{
BuildX86Stub(buffer, checked((uint)stubAddress), checked((uint)targetAddress),
arguments, convention);
}
else if (pointerSize == 8)
{
// Windows x64 uses a single ABI — the convention parameter is unused.
BuildX64Stub(buffer, (ulong)(nint)stubAddress, (ulong)(nint)targetAddress, arguments);
}
else
{
throw new ArgumentOutOfRangeException(nameof(pointerSize), pointerSize,
$"Expected 4 (x86) or 8 (x64), got {pointerSize}.");
}
return buffer.ToArray();
}
private void BuildX86Stub(List<byte> buffer, uint stubAddr,
uint target, uint[] args, CallConvention convention)
{
uint current = stubAddr;
int argIndex = 0;
switch (convention)
{
case CallConvention.Thiscall when args.Length - argIndex >= 1:
EmitMovRegImm32(buffer, 0xB9, args[argIndex], ref current); // mov ecx, arg0
argIndex++;
break;
case CallConvention.Fastcall:
if (args.Length - argIndex >= 1)
{
EmitMovRegImm32(buffer, 0xB9, args[argIndex], ref current); // mov ecx, arg0
argIndex++;
}
if (args.Length - argIndex >= 1)
{
EmitMovRegImm32(buffer, 0xBA, args[argIndex], ref current); // mov edx, arg1
argIndex++;
}
break;
case CallConvention.Cdecl:
case CallConvention.Stdcall:
break;
default:
throw new ArgumentOutOfRangeException(nameof(convention), convention,
$"Unsupported calling convention: {convention}.");
}
// Push remaining args in reverse order (right-to-left)
for (int i = args.Length - 1; i >= argIndex; i--)
{
current += 5;
buffer.Add(0x68); // push imm32
EmitU32(buffer, args[i]);
}
// call rel32
long distance = (long)target - (long)(current + 5);
if (distance < int.MinValue || distance > int.MaxValue)
{
throw new ArgumentOutOfRangeException(
$"target (0x{target:X}) is >2 GiB from stub (0x{stubAddr:X}); " +
"E8 rel32 cannot encode this distance. Place the stub closer to the target.");
}
buffer.Add(0xE8);
EmitU32(buffer, (uint)distance);
current += 5;
// Caller cleanup (cdecl only)
int stackCount = args.Length - argIndex;
if (convention == CallConvention.Cdecl && stackCount > 0)
{
int cleanup = stackCount * 4;
if (cleanup <= 127)
{
buffer.Add(0x83); // add esp, imm8
buffer.Add(0xC4);
buffer.Add((byte)cleanup);
}
else
{
buffer.Add(0x81); // add esp, imm32
buffer.Add(0xC4);
EmitU32(buffer, (uint)cleanup);
}
}
buffer.Add(0xC3); // ret
}
private void BuildX64Stub(List<byte> buffer, ulong stubAddr,
ulong target, uint[] args)
{
// Windows x64 single ABI: first 4 args in RCX, RDX, R8D, R9D.
ulong current = stubAddr;
var regCodes = new byte[] { 0xB9, 0xBA, 0xB8, 0xB9 };
var rexBytes = new byte[] { 0x00, 0x00, 0x41, 0x41 };
int regCount = Math.Min(args.Length, 4);
for (int i = 0; i < regCount; i++)
{
if (rexBytes[i] != 0)
buffer.Add(rexBytes[i]);
buffer.Add(regCodes[i]);
EmitU32(buffer, args[i]);
current += (rexBytes[i] != 0 ? 6u : 5u);
}
// Push remaining args in reverse order
for (int i = args.Length - 1; i >= 4; i--)
{
current += 5;
buffer.Add(0x68);
EmitU32(buffer, args[i]);
}
// call rel32
long distance = (long)target - (long)(current + 5);
if (distance < int.MinValue || distance > int.MaxValue)
{
throw new ArgumentOutOfRangeException(
"target and stub are >2 GiB apart; E8 rel32 cannot encode this distance.");
}
buffer.Add(0xE8);
EmitU32(buffer, (uint)distance);
// Pop any args pushed on stack (x64 is caller-clean)
int stackArgs = args.Length > 4 ? args.Length - 4 : 0;
if (stackArgs > 0)
{
int bytes = stackArgs * 8;
buffer.Add(0x48); // REX.W
buffer.Add(bytes <= 127 ? (byte)0x83 : (byte)0x81); // add r/m64, imm8/imm32
buffer.Add(0xC4); // rsp
if (bytes <= 127)
buffer.Add((byte)bytes);
else
EmitU32(buffer, (uint)bytes);
}
buffer.Add(0xC3);
}
// ── Instruction helpers ────────────────────────────────────────────────
/// <summary>Emit <c>mov reg32, imm32</c> and advances <paramref name="ip"/> by 5.</summary>
private static void EmitMovRegImm32(List<byte> buffer, byte opcode, uint imm32, ref uint ip)
{
buffer.Add(opcode);
buffer.Add((byte)imm32);
buffer.Add((byte)(imm32 >> 8));
buffer.Add((byte)(imm32 >> 16));
buffer.Add((byte)(imm32 >> 24));
ip += 5;
}
}
+105
View File
@@ -0,0 +1,105 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using WhiteMagic.Native;
namespace WhiteMagic;
/// <summary>
/// Out-of-process memory reader that accesses the target's memory through
/// <see cref="NativeMethods.ReadProcessMemory"/> and
/// <see cref="NativeMethods.WriteProcessMemory"/>.
/// </summary>
public sealed class ExternalReader : MemoryBase
{
private readonly SafeMemoryHandle _handle;
private readonly IntPtr _imageBase;
private bool _disposed;
/// <summary>
/// The default access rights: enough to read, write, allocate, query, run a remote
/// thread, and wait on it. This deliberately omits <see cref="ProcessAccess.AllAccess"/>,
/// which over-requests and makes <c>OpenProcess</c> fail on protected processes where
/// these narrower rights would succeed.
/// </summary>
public const ProcessAccess DefaultAccess =
ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.VmOperation
| ProcessAccess.QueryInformation | ProcessAccess.CreateThread | ProcessAccess.Synchronize;
/// <summary>
/// Opens a process for external memory access.
/// </summary>
/// <param name="process">The target process.</param>
/// <param name="desiredAccess">The access rights to request. Defaults to
/// <see cref="DefaultAccess"/>.</param>
public ExternalReader(Process process, ProcessAccess desiredAccess = DefaultAccess)
{
_handle = NativeMethods.OpenProcess(desiredAccess, false, process.Id);
if (_handle.IsInvalid)
{
int error = Marshal.GetLastPInvokeError();
throw new InvalidOperationException(
$"OpenProcess failed for PID {process.Id}: error {error}");
}
// Process.MainModule throws Win32Exception for a bitness-mismatched or protected
// target; a missing image base must not sink the whole reader.
try
{
_imageBase = process.MainModule?.BaseAddress ?? IntPtr.Zero;
}
catch (System.ComponentModel.Win32Exception)
{
_imageBase = IntPtr.Zero;
}
}
/// <inheritdoc />
public override IntPtr ImageBase => _imageBase;
/// <inheritdoc />
public override SafeMemoryHandle Handle => _handle;
/// <inheritdoc />
public override byte[] ReadBytes(IntPtr address, int count, bool isRelative = false)
{
if (isRelative)
address = GetAbsolute(address);
byte[] buffer = new byte[count];
if (!NativeMethods.ReadProcessMemory(_handle, address, buffer, count, out nint bytesRead))
{
return [];
}
if ((int)bytesRead != count)
{
Array.Resize(ref buffer, (int)bytesRead);
}
return buffer;
}
/// <inheritdoc />
public override int WriteBytes(IntPtr address, ReadOnlySpan<byte> bytes, bool isRelative = false)
{
if (isRelative)
address = GetAbsolute(address);
if (!NativeMethods.WriteProcessMemory(_handle, address, bytes, bytes.Length, out nint written))
{
return 0;
}
return (int)written;
}
/// <inheritdoc />
public override void Dispose()
{
if (!_disposed)
{
_disposed = true;
_handle.Dispose();
}
}
}
+90
View File
@@ -0,0 +1,90 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using WhiteMagic.Native;
namespace WhiteMagic;
/// <summary>
/// In-process memory reader that accesses the owning process's memory through
/// <see cref="NativeMethods.ReadProcessMemory"/> and
/// <see cref="NativeMethods.WriteProcessMemory"/> on a handle to the current
/// process. Unlike the unsafe-deref approach, this fails softly (returns
/// empty / zero bytes) on invalid or protected addresses instead of crashing
/// the host process with an <see cref="AccessViolationException"/>.
/// </summary>
public sealed class InProcessReader : MemoryBase
{
private readonly SafeMemoryHandle _handle;
private readonly IntPtr _imageBase;
private bool _disposed;
/// <summary>
/// Creates an in-process reader for the current process.
/// </summary>
public InProcessReader()
{
Process current = Process.GetCurrentProcess();
_handle = NativeMethods.OpenProcess(
ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.VmOperation | ProcessAccess.QueryInformation,
false,
current.Id);
if (_handle.IsInvalid)
{
int error = Marshal.GetLastPInvokeError();
throw new InvalidOperationException(
$"OpenProcess failed for PID {current.Id}: error {error}");
}
_imageBase = current.MainModule?.BaseAddress ?? IntPtr.Zero;
}
/// <inheritdoc />
public override IntPtr ImageBase => _imageBase;
/// <inheritdoc />
public override SafeMemoryHandle Handle => _handle;
/// <inheritdoc />
public override byte[] ReadBytes(IntPtr address, int count, bool isRelative = false)
{
if (isRelative)
address = GetAbsolute(address);
byte[] buffer = new byte[count];
if (!NativeMethods.ReadProcessMemory(_handle, address, buffer, count, out nint bytesRead))
{
return [];
}
if ((int)bytesRead != count)
{
Array.Resize(ref buffer, (int)bytesRead);
}
return buffer;
}
/// <inheritdoc />
public override int WriteBytes(IntPtr address, ReadOnlySpan<byte> bytes, bool isRelative = false)
{
if (isRelative)
address = GetAbsolute(address);
if (!NativeMethods.WriteProcessMemory(_handle, address, bytes, bytes.Length, out nint written))
{
return 0;
}
return (int)written;
}
/// <inheritdoc />
public override void Dispose()
{
if (!_disposed)
{
_disposed = true;
_handle.Dispose();
}
}
}
+88
View File
@@ -0,0 +1,88 @@
using System.Reflection;
using System.Runtime.InteropServices;
namespace WhiteMagic;
/// <summary>
/// Computes and caches marshal-related metadata for type <typeparamref name="T"/>
/// exactly once. <see cref="MemoryBase.Read{T}"/> and <see cref="MemoryBase.Write{T}"/>
/// branch on these cached flags to decide between blittable <c>Span</c>/<c>MemoryMarshal</c>
/// paths and the fallback marshal path.
/// </summary>
/// <typeparam name="T">The type to cache metadata for.</typeparam>
public static class MarshalCache<T>
{
/// <summary>The unmanaged size of <typeparamref name="T"/> in bytes.</summary>
public static readonly int Size;
/// <summary>The unmanaged size of <typeparamref name="T"/> as an unsigned integer.</summary>
public static readonly uint SizeU;
/// <summary>
/// <see langword="true"/> when <typeparamref name="T"/> cannot be copied through the
/// blittable <see cref="System.Runtime.InteropServices.MemoryMarshal"/> path and must
/// use <see cref="Marshal.PtrToStructure"/>/<see cref="Marshal.StructureToPtr"/> instead.
/// This is the case when a top-level field carries <see cref="MarshalAsAttribute"/>, or
/// when <typeparamref name="T"/> contains a managed reference
/// (<see cref="System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences{T}"/>).
/// </summary>
/// <remarks>
/// The <see cref="MarshalAsAttribute"/> check inspects only top-level fields; a
/// <see cref="MarshalAsAttribute"/> on a field of a nested struct is not detected.
/// Reference-containing nested structs are still caught, because the reference check
/// propagates through nested value types.
/// </remarks>
public static readonly bool TypeRequiresMarshal;
/// <summary><see langword="true"/> when <typeparamref name="T"/> is <see cref="IntPtr"/>.</summary>
public static readonly bool IsIntPtr;
/// <summary>The underlying type code of <typeparamref name="T"/>.</summary>
public static readonly TypeCode TypeCode;
/// <summary>
/// The effective type that the marshaler uses. For an enum this is the underlying
/// integer type; for all other types it is <typeparamref name="T"/> itself.
/// </summary>
public static readonly Type RealType;
static MarshalCache()
{
TypeCode = Type.GetTypeCode(typeof(T));
if (typeof(T) == typeof(bool))
{
Size = 1;
RealType = typeof(T);
}
else if (typeof(T) == typeof(char))
{
// Marshal.SizeOf(char) is 1 (ANSI), but the blittable path reads/writes a
// char as a 2-byte UTF-16 code unit. Size must match the blittable width.
Size = 2;
RealType = typeof(T);
}
else if (typeof(T).IsEnum)
{
Type underlying = typeof(T).GetEnumUnderlyingType();
Size = Marshal.SizeOf(underlying);
RealType = underlying;
TypeCode = Type.GetTypeCode(underlying);
}
else
{
Size = Marshal.SizeOf(typeof(T));
RealType = typeof(T);
}
SizeU = (uint)Size;
IsIntPtr = RealType == typeof(IntPtr);
bool hasMarshalAsField =
RealType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Any(f => f.GetCustomAttributes(typeof(MarshalAsAttribute), true).Length != 0);
TypeRequiresMarshal =
hasMarshalAsField || System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences<T>();
}
}
+301
View File
@@ -0,0 +1,301 @@
using WhiteMagic.Native;
using System.Runtime.InteropServices;
using System.Text;
namespace WhiteMagic;
/// <summary>
/// Abstract base for all memory-access readers and writers. Provides typed
/// <see cref="Read{T}"/>/<see cref="Write{T}"/>, array IO, string IO, and
/// relative/absolute addressing. Subclasses implement the concrete
/// <see cref="ReadBytes"/> and <see cref="WriteBytes"/> methods.
/// </summary>
public abstract class MemoryBase : IDisposable
{
/// <summary>The base address of the target process's main module.</summary>
public abstract IntPtr ImageBase { get; }
/// <summary>The native handle to the target process.</summary>
public abstract SafeMemoryHandle Handle { get; }
// ── Raw byte IO ────────────────────────────────────────────────────────
/// <summary>Reads a sequence of bytes from the target address.</summary>
public abstract byte[] ReadBytes(IntPtr address, int count, bool isRelative = false);
/// <summary>Writes a sequence of bytes to the target address.</summary>
/// <returns>The number of bytes written.</returns>
public abstract int WriteBytes(IntPtr address, ReadOnlySpan<byte> bytes, bool isRelative = false);
// ── Typed IO ───────────────────────────────────────────────────────────
/// <summary>Reads a value of type <typeparamref name="T"/> from the target address.</summary>
/// <returns>The value, or <c>default(T)</c> when the read fails or returns fewer bytes than
/// <see cref="MarshalCache{T}.Size"/>.</returns>
public T Read<T>(IntPtr address, bool isRelative = false) where T : struct
{
if (isRelative)
address = GetAbsolute(address);
int size = MarshalCache<T>.Size;
byte[] raw = ReadBytes(address, size);
if (raw.Length < size)
return default;
if (MarshalCache<T>.TypeRequiresMarshal)
return MarshalByteArrayToStructure<T>(raw);
return MemoryMarshal.Read<T>(raw.AsSpan());
}
/// <summary>Writes a value of type <typeparamref name="T"/> to the target address.</summary>
/// <returns><see langword="true"/> if all bytes were written.</returns>
public bool Write<T>(IntPtr address, T value, bool isRelative = false) where T : struct
{
if (isRelative)
address = GetAbsolute(address);
int size = MarshalCache<T>.Size;
byte[] raw;
if (MarshalCache<T>.TypeRequiresMarshal)
raw = StructureToByteArray(value, size);
else
{
raw = new byte[size];
MemoryMarshal.Write(raw.AsSpan(), in value);
}
int written = WriteBytes(address, raw, false);
return written == size;
}
/// <summary>Reads an array of values of type <typeparamref name="T"/> from the target address.</summary>
/// <returns>An array of at most <paramref name="count"/> elements. May be shorter when the read
/// returns fewer bytes than expected.</returns>
public T[] Read<T>(IntPtr address, int count, bool isRelative = false) where T : struct
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (isRelative)
address = GetAbsolute(address);
int elementSize = MarshalCache<T>.Size;
long totalSize = (long)elementSize * count;
ArgumentOutOfRangeException.ThrowIfGreaterThan(totalSize, int.MaxValue, nameof(count));
byte[] raw = ReadBytes(address, (int)totalSize);
int actualCount = Math.Min(count, raw.Length / elementSize);
var result = new T[actualCount];
if (actualCount == 0)
return result;
if (MarshalCache<T>.TypeRequiresMarshal)
{
GCHandle pin = GCHandle.Alloc(raw, GCHandleType.Pinned);
try
{
IntPtr basePtr = pin.AddrOfPinnedObject();
for (int i = 0; i < actualCount; i++)
result[i] = Marshal.PtrToStructure<T>(basePtr + (i * elementSize));
}
finally
{
pin.Free();
}
}
else
{
ReadOnlySpan<byte> span = raw;
for (int i = 0; i < actualCount; i++)
result[i] = MemoryMarshal.Read<T>(span.Slice(i * elementSize, elementSize));
}
return result;
}
/// <summary>Writes an array of values of type <typeparamref name="T"/> to the target address.</summary>
/// <returns><see langword="true"/> if all bytes were written.</returns>
public bool Write<T>(IntPtr address, T[] values, bool isRelative = false) where T : struct
{
if (isRelative)
address = GetAbsolute(address);
if (values is null || values.Length == 0)
return true;
int elementSize = MarshalCache<T>.Size;
long total = (long)elementSize * values.Length;
ArgumentOutOfRangeException.ThrowIfGreaterThan(total, int.MaxValue, nameof(values));
int totalSize = (int)total;
byte[] raw = new byte[totalSize];
Span<byte> span = raw;
for (int i = 0; i < values.Length; i++)
{
Span<byte> slice = span.Slice(i * elementSize, elementSize);
if (MarshalCache<T>.TypeRequiresMarshal)
StructureToByteArray(values[i], slice, elementSize);
else
MemoryMarshal.Write(slice, in values[i]);
}
int written = WriteBytes(address, raw, false);
return written == totalSize;
}
// ── String IO ──────────────────────────────────────────────────────────
/// <summary>Reads a null-terminated string from the target address by scanning in small
/// chunks. Stops at the null terminator, the maximum length, or the first page boundary
/// that fails to read (avoids an atomic failure when a 512-byte window crosses an unmapped
/// region).</summary>
/// <param name="address">The address to read from.</param>
/// <param name="encoding">The text encoding.</param>
/// <param name="maxLength">The maximum number of bytes to read.</param>
/// <param name="relative">If <see langword="true"/>, <paramref name="address"/> is relative
/// to <see cref="ImageBase"/>.</param>
public virtual string ReadString(IntPtr address, Encoding encoding, int maxLength = 512, bool relative = false)
{
if (relative)
address = GetAbsolute(address);
// The encoded null terminator. For ASCII/UTF-8 this is a single 0x00 byte;
// for UTF-16 it is two zero bytes (0x00 0x00); for UTF-32 it is four.
byte[] nullTerminator = encoding.GetBytes("\0");
const int chunkSize = 64;
int remaining = maxLength;
var accumulated = new System.Collections.Generic.List<byte[]>();
while (remaining > 0)
{
int take = Math.Min(chunkSize, remaining);
byte[] chunk = ReadBytes(address, take);
if (chunk.Length == 0)
break;
int nullPos = IndexOfPattern(chunk, nullTerminator);
if (nullPos >= 0)
{
if (nullPos > 0)
accumulated.Add(chunk[..nullPos]);
break;
}
accumulated.Add(chunk);
// Advance by the bytes actually read, not the amount requested: a partial
// read (chunk.Length < take) must not skip the unread tail of the window.
address += chunk.Length;
remaining -= chunk.Length;
}
int totalLength = 0;
foreach (byte[] part in accumulated)
totalLength += part.Length;
byte[] combined = new byte[totalLength];
int offset = 0;
foreach (byte[] part in accumulated)
{
part.CopyTo(combined, offset);
offset += part.Length;
}
return encoding.GetString(combined);
}
/// <summary>Writes a null-terminated string to the target address.</summary>
public virtual bool WriteString(IntPtr address, string value, Encoding encoding, bool relative = false)
{
if (value.Length == 0 || value[^1] != '\0')
value += '\0';
byte[] bytes = encoding.GetBytes(value);
int written = WriteBytes(address, bytes, relative);
return written == bytes.Length;
}
// ── Addressing ─────────────────────────────────────────────────────────
/// <summary>Converts a relative offset to an absolute address relative to <see cref="ImageBase"/>.</summary>
public IntPtr GetAbsolute(IntPtr relative)
{
return ImageBase + (nint)relative;
}
/// <summary>Converts an absolute address to a relative offset from <see cref="ImageBase"/>.
/// This is the inverse of <see cref="GetAbsolute"/>: <c>GetAbsolute(GetRelative(a)) == a</c>.</summary>
public IntPtr GetRelative(IntPtr absolute)
{
return (IntPtr)((nint)absolute - (nint)ImageBase);
}
// ── Lifecycle ──────────────────────────────────────────────────────────
/// <inheritdoc />
public virtual void Dispose()
{
Handle?.Dispose();
}
// ── Private helpers ────────────────────────────────────────────────────
private static T MarshalByteArrayToStructure<T>(byte[] bytes) where T : struct
{
GCHandle pin = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
return Marshal.PtrToStructure<T>(pin.AddrOfPinnedObject());
}
finally
{
pin.Free();
}
}
private static byte[] StructureToByteArray<T>(T value, int size) where T : struct
{
byte[] bytes = new byte[size];
GCHandle pin = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
Marshal.StructureToPtr(value, pin.AddrOfPinnedObject(), false);
}
finally
{
pin.Free();
}
return bytes;
}
private static void StructureToByteArray<T>(T value, Span<byte> destination, int size) where T : struct
{
byte[] bytes = StructureToByteArray(value, size);
bytes.CopyTo(destination);
}
private static int IndexOfPattern(byte[] data, byte[] pattern)
{
int lastStart = data.Length - pattern.Length;
int stride = Math.Max(1, pattern.Length);
for (int i = 0; i <= lastStart; i += stride)
{
bool match = true;
for (int j = 0; j < pattern.Length; j++)
{
if (data[i + j] != pattern[j])
{
match = false;
break;
}
}
if (match)
return i;
}
return -1;
}
}
+136
View File
@@ -0,0 +1,136 @@
namespace WhiteMagic.Native;
/// <summary>
/// Access rights that open a process object.
/// </summary>
[Flags]
public enum ProcessAccess : uint
{
/// <summary>The right to terminate the process with TerminateProcess.</summary>
Terminate = 0x0001,
/// <summary>The right to create a thread in the process.</summary>
CreateThread = 0x0002,
/// <summary>The right to operate on the address space of the process.</summary>
VmOperation = 0x0008,
/// <summary>The right to read memory with ReadProcessMemory.</summary>
VmRead = 0x0010,
/// <summary>The right to write memory with WriteProcessMemory.</summary>
VmWrite = 0x0020,
/// <summary>The right to duplicate a handle with DuplicateHandle.</summary>
DupHandle = 0x0040,
/// <summary>The right to set information about the process.</summary>
SetInformation = 0x0200,
/// <summary>The right to read information about the process, such as the exit code.</summary>
QueryInformation = 0x0400,
/// <summary>The right to suspend or resume the process.</summary>
SuspendResume = 0x0800,
/// <summary>The right to read a limited set of information about the process.</summary>
QueryLimitedInformation = 0x1000,
/// <summary>The right to use the process object for synchronization.</summary>
Synchronize = 0x00100000,
/// <summary>All access rights for a process object.</summary>
AllAccess = 0x001F0000 | Synchronize | 0xFFFF,
}
/// <summary>
/// Values that control how VirtualAllocEx allocates memory.
/// </summary>
[Flags]
public enum MemoryAllocationType : uint
{
/// <summary>Commit physical storage for the reserved pages. The pages start as zero.</summary>
Commit = 0x00001000,
/// <summary>Reserve a range of address space without physical storage.</summary>
Reserve = 0x00002000,
/// <summary>Reset the data in the range to indicate that it is no longer of interest.</summary>
Reset = 0x00080000,
/// <summary>Allocate memory at the highest possible address.</summary>
TopDown = 0x00100000,
}
/// <summary>
/// Values that protect a block of memory.
/// </summary>
[Flags]
public enum MemoryProtectionType : uint
{
/// <summary>No access to the committed pages.</summary>
NoAccess = 0x01,
/// <summary>Read access to the committed pages.</summary>
ReadOnly = 0x02,
/// <summary>Read and write access to the committed pages.</summary>
ReadWrite = 0x04,
/// <summary>Copy-on-write access to the committed pages.</summary>
WriteCopy = 0x08,
/// <summary>Execute access to the committed pages.</summary>
Execute = 0x10,
/// <summary>Execute and read access to the committed pages.</summary>
ExecuteRead = 0x20,
/// <summary>Execute, read, and write access to the committed pages.</summary>
ExecuteReadWrite = 0x40,
/// <summary>Execute and copy-on-write access to the committed pages.</summary>
ExecuteWriteCopy = 0x80,
/// <summary>The pages in the range become guard pages.</summary>
Guard = 0x100,
/// <summary>The system does not cache the committed pages.</summary>
NoCache = 0x200,
/// <summary>The system uses write-combined access for the pages.</summary>
WriteCombine = 0x400,
}
/// <summary>
/// Values that control how VirtualFreeEx frees memory.
/// </summary>
[Flags]
public enum MemoryFreeType : uint
{
/// <summary>Decommit the committed pages. The address range stays reserved.</summary>
Decommit = 0x4000,
/// <summary>Release the range of pages. The size must be zero.</summary>
Release = 0x8000,
}
/// <summary>
/// Values that set the initial state of a new thread.
/// </summary>
[Flags]
public enum ThreadCreationFlags : uint
{
/// <summary>The thread runs immediately after creation.</summary>
RunImmediately = 0,
/// <summary>The thread starts in a suspended state. Call ResumeThread to start it.</summary>
CreateSuspended = 0x00000004,
/// <summary>The stack-size parameter sets the reserve size of the stack.</summary>
StackSizeParamIsAReservation = 0x00010000,
}
/// <summary>
/// Flags that select the registers that the thread-context functions read or write.
/// There are separate constants for 32-bit (x86/WOW64) and 64-bit (AMD64) contexts.
/// </summary>
public static class ContextFlags
{
/// <summary>Architecture identifier for x86 contexts.</summary>
public const uint X86 = 0x00010000;
/// <summary>Architecture identifier for AMD64 contexts.</summary>
public const uint Amd64 = 0x00100000;
/// <summary>x86: SS:SP, CS:IP, FLAGS, and BP.</summary>
public const uint X86Control = X86 | 0x01;
/// <summary>x86: AX, BX, CX, DX, SI, and DI.</summary>
public const uint X86Integer = X86 | 0x02;
/// <summary>x86: DS, ES, FS, and GS.</summary>
public const uint X86Segments = X86 | 0x04;
/// <summary>x86: control, integer, and segment registers.</summary>
public const uint X86Full = X86Control | X86Integer | X86Segments;
/// <summary>AMD64: SegSs, Rsp, SegCs, Rip, and EFlags.</summary>
public const uint Amd64Control = Amd64 | 0x01;
/// <summary>AMD64: Rax, Rcx, Rdx, Rbx, Rbp, Rsi, Rdi, and R8 to R15.</summary>
public const uint Amd64Integer = Amd64 | 0x02;
/// <summary>AMD64: SegDs, SegEs, SegFs, and SegGs.</summary>
public const uint Amd64Segments = Amd64 | 0x04;
/// <summary>AMD64: control, integer, and segment registers.</summary>
public const uint Amd64Full = Amd64Control | Amd64Integer | Amd64Segments;
}
+137
View File
@@ -0,0 +1,137 @@
using System.Runtime.InteropServices;
namespace WhiteMagic.Native;
/// <summary>
/// P/Invoke declarations for the Win32 process, memory, thread, and module
/// APIs that WhiteMagic uses. Every declaration uses <see cref="LibraryImportAttribute"/>
/// (source-generated interop). SetLastError is enabled on all calls that the
/// Win32 API documents as setting a thread-local last-error value.
/// </summary>
internal static partial class NativeMethods
{
// ── Process ──────────────────────────────────────────────────────────────
/// <summary>Opens an existing process and returns a handle to it.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial SafeMemoryHandle OpenProcess(
ProcessAccess desiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool inheritHandle,
int processId);
/// <summary>Closes an open object handle.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool CloseHandle(IntPtr handle);
// ── Memory ───────────────────────────────────────────────────────────────
/// <summary>Reads memory from a process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool ReadProcessMemory(
SafeMemoryHandle process,
IntPtr baseAddress,
Span<byte> buffer,
int size,
out nint bytesRead);
/// <summary>Writes memory to a process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool WriteProcessMemory(
SafeMemoryHandle process,
IntPtr baseAddress,
ReadOnlySpan<byte> buffer,
int size,
out nint bytesWritten);
/// <summary>Reserves or commits a region of memory in a process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial IntPtr VirtualAllocEx(
SafeMemoryHandle process,
IntPtr address,
nint size,
MemoryAllocationType allocationType,
MemoryProtectionType protect);
/// <summary>Changes the protection on a committed region of memory.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool VirtualProtectEx(
SafeMemoryHandle process,
IntPtr address,
nint size,
MemoryProtectionType newProtect,
out MemoryProtectionType oldProtect);
/// <summary>Releases or decommits a region of memory in a process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool VirtualFreeEx(
SafeMemoryHandle process,
IntPtr address,
nint size,
MemoryFreeType freeType);
// ── Threading ────────────────────────────────────────────────────────────
/// <summary>Creates a thread that runs in the virtual address space of a process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial SafeMemoryHandle CreateRemoteThread(
SafeMemoryHandle process,
IntPtr threadAttributes,
nint stackSize,
IntPtr startAddress,
IntPtr parameter,
ThreadCreationFlags creationFlags,
out uint threadId);
/// <summary>Sets a 64-bit thread context (AMD64).</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool SetThreadContext(
SafeMemoryHandle thread,
ref Context64 context);
/// <summary>Gets a 64-bit thread context (AMD64).</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool GetThreadContext(
SafeMemoryHandle thread,
ref Context64 context);
/// <summary>Sets a 32-bit (WOW64) thread context.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool Wow64SetThreadContext(
SafeMemoryHandle thread,
ref Context32 context);
/// <summary>Gets a 32-bit (WOW64) thread context.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool Wow64GetThreadContext(
SafeMemoryHandle thread,
ref Context32 context);
// ── Modules ──────────────────────────────────────────────────────────────
/// <summary>Loads a module into the calling process.</summary>
[LibraryImport("kernel32.dll", SetLastError = true, EntryPoint = "LoadLibraryW")]
internal static partial IntPtr LoadLibrary(
[MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
/// <summary>Returns the address of a function or variable from a loaded module.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial IntPtr GetProcAddress(
IntPtr hModule,
[MarshalAs(UnmanagedType.LPStr)] string lpProcName);
/// <summary>Waits until an object is signaled or the timeout elapses. Returns a
/// <c>WAIT_*</c> status (DWORD); <c>WAIT_FAILED</c> is <c>0xFFFFFFFF</c>.</summary>
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial uint WaitForSingleObject(
SafeMemoryHandle handle,
uint milliseconds);
}
+207
View File
@@ -0,0 +1,207 @@
using System.Runtime.InteropServices;
namespace WhiteMagic.Native;
/// <summary>
/// The x87 and MMX state inside a 32-bit thread context.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe struct FloatingSaveArea32
{
/// <summary>The x87 FPU control word.</summary>
public uint ControlWord;
/// <summary>The x87 FPU status word.</summary>
public uint StatusWord;
/// <summary>The x87 FPU tag word.</summary>
public uint TagWord;
/// <summary>The offset of the instruction that caused the last FPU exception.</summary>
public uint ErrorOffset;
/// <summary>The selector of the instruction that caused the last FPU exception.</summary>
public uint ErrorSelector;
/// <summary>The offset of the operand that caused the last FPU exception.</summary>
public uint DataOffset;
/// <summary>The selector of the operand that caused the last FPU exception.</summary>
public uint DataSelector;
/// <summary>The 80-byte register area.</summary>
public fixed byte RegisterArea[80];
/// <summary>The CR0 numeric-processor-extension state.</summary>
public uint Cr0NpxState;
}
/// <summary>
/// A 32-bit (x86/WOW64) thread context. Use it with
/// <c>Wow64GetThreadContext</c> and <c>Wow64SetThreadContext</c> to inspect a 32-bit thread.
/// The total size is 716 bytes.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe struct Context32
{
/// <summary>Selects which parts of the context are valid. See <see cref="ContextFlags"/>.</summary>
public uint ContextFlags;
/// <summary>Debug register 0.</summary>
public uint Dr0;
/// <summary>Debug register 1.</summary>
public uint Dr1;
/// <summary>Debug register 2.</summary>
public uint Dr2;
/// <summary>Debug register 3.</summary>
public uint Dr3;
/// <summary>Debug register 6.</summary>
public uint Dr6;
/// <summary>Debug register 7.</summary>
public uint Dr7;
/// <summary>The floating-point state.</summary>
public FloatingSaveArea32 FloatSave;
/// <summary>The GS segment.</summary>
public uint SegGs;
/// <summary>The FS segment.</summary>
public uint SegFs;
/// <summary>The ES segment.</summary>
public uint SegEs;
/// <summary>The DS segment.</summary>
public uint SegDs;
/// <summary>The EDI register.</summary>
public uint Edi;
/// <summary>The ESI register.</summary>
public uint Esi;
/// <summary>The EBX register.</summary>
public uint Ebx;
/// <summary>The EDX register.</summary>
public uint Edx;
/// <summary>The ECX register.</summary>
public uint Ecx;
/// <summary>The EAX register.</summary>
public uint Eax;
/// <summary>The base (frame) pointer.</summary>
public uint Ebp;
/// <summary>The instruction pointer.</summary>
public uint Eip;
/// <summary>The CS segment.</summary>
public uint SegCs;
/// <summary>The flags register.</summary>
public uint EFlags;
/// <summary>The stack pointer.</summary>
public uint Esp;
/// <summary>The SS segment.</summary>
public uint SegSs;
/// <summary>The extended (processor-specific) registers. The size is 512 bytes.</summary>
public fixed byte ExtendedRegisters[512];
}
/// <summary>
/// A 64-bit (AMD64) thread context. Use it with the native
/// <c>GetThreadContext</c> and <c>SetThreadContext</c> from a 64-bit process.
/// The structure needs 16-byte alignment. The total size is 1232 bytes.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 16)]
public unsafe struct Context64
{
/// <summary>Home storage for a register parameter.</summary>
public ulong P1Home;
/// <summary>Home storage for a register parameter.</summary>
public ulong P2Home;
/// <summary>Home storage for a register parameter.</summary>
public ulong P3Home;
/// <summary>Home storage for a register parameter.</summary>
public ulong P4Home;
/// <summary>Home storage for a register parameter.</summary>
public ulong P5Home;
/// <summary>Home storage for a register parameter.</summary>
public ulong P6Home;
/// <summary>Selects which parts of the context are valid. See <see cref="ContextFlags"/>.</summary>
public uint ContextFlags;
/// <summary>The MXCSR register.</summary>
public uint MxCsr;
/// <summary>The CS segment.</summary>
public ushort SegCs;
/// <summary>The DS segment.</summary>
public ushort SegDs;
/// <summary>The ES segment.</summary>
public ushort SegEs;
/// <summary>The FS segment.</summary>
public ushort SegFs;
/// <summary>The GS segment.</summary>
public ushort SegGs;
/// <summary>The SS segment.</summary>
public ushort SegSs;
/// <summary>The flags register.</summary>
public uint EFlags;
/// <summary>Debug register 0.</summary>
public ulong Dr0;
/// <summary>Debug register 1.</summary>
public ulong Dr1;
/// <summary>Debug register 2.</summary>
public ulong Dr2;
/// <summary>Debug register 3.</summary>
public ulong Dr3;
/// <summary>Debug register 6.</summary>
public ulong Dr6;
/// <summary>Debug register 7.</summary>
public ulong Dr7;
/// <summary>The RAX register.</summary>
public ulong Rax;
/// <summary>The RCX register.</summary>
public ulong Rcx;
/// <summary>The RDX register.</summary>
public ulong Rdx;
/// <summary>The RBX register.</summary>
public ulong Rbx;
/// <summary>The stack pointer.</summary>
public ulong Rsp;
/// <summary>The base (frame) pointer.</summary>
public ulong Rbp;
/// <summary>The RSI register.</summary>
public ulong Rsi;
/// <summary>The RDI register.</summary>
public ulong Rdi;
/// <summary>The R8 register.</summary>
public ulong R8;
/// <summary>The R9 register.</summary>
public ulong R9;
/// <summary>The R10 register.</summary>
public ulong R10;
/// <summary>The R11 register.</summary>
public ulong R11;
/// <summary>The R12 register.</summary>
public ulong R12;
/// <summary>The R13 register.</summary>
public ulong R13;
/// <summary>The R14 register.</summary>
public ulong R14;
/// <summary>The R15 register.</summary>
public ulong R15;
/// <summary>The instruction pointer.</summary>
public ulong Rip;
/// <summary>The XMM save area. The size is 512 bytes.</summary>
public fixed byte FltSave[512];
/// <summary>The vector registers (26 entries of 16 bytes, stored as 52 entries of 8 bytes).</summary>
public fixed ulong VectorRegister[52];
/// <summary>The vector control register.</summary>
public ulong VectorControl;
/// <summary>The debug-control MSR.</summary>
public ulong DebugControl;
/// <summary>The target RIP of the last branch.</summary>
public ulong LastBranchToRip;
/// <summary>The source RIP of the last branch.</summary>
public ulong LastBranchFromRip;
/// <summary>The target RIP of the last exception.</summary>
public ulong LastExceptionToRip;
/// <summary>The source RIP of the last exception.</summary>
public ulong LastExceptionFromRip;
}
+34
View File
@@ -0,0 +1,34 @@
using Microsoft.Win32.SafeHandles;
namespace WhiteMagic.Native;
/// <summary>
/// A Win32 handle (process, thread, or snapshot) with a managed lifetime.
/// The handle closes with <c>CloseHandle</c>, even after an exception or a thread abort.
/// </summary>
/// <remarks>The pattern comes from MemorySharp's SafeMemoryHandle.</remarks>
public sealed class SafeMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Makes an empty handle. The interop marshaller uses this constructor for a
/// handle that a system call returns (for example, <see cref="NativeMethods.OpenProcess"/>).
/// </summary>
public SafeMemoryHandle() : base(true)
{
}
/// <summary>
/// Wraps a raw handle and takes ownership of the handle.
/// </summary>
/// <param name="handle">The handle to own.</param>
public SafeMemoryHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
/// <inheritdoc />
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(handle);
}
}
+16
View File
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Platforms>x86;x64;AnyCPU</Platforms>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="WhiteMagicTest" />
</ItemGroup>
</Project>