From 855595837faf304185c8ab1ac6161464232dbb1f Mon Sep 17 00:00:00 2001 From: Kevin Bataille Date: Tue, 21 Jul 2026 19:35:11 +0200 Subject: [PATCH 1/3] task 3.1-3.2: IAssembler interface + StubAssembler emit primitives Add IAssembler seam (Assemble(text, origin)) with StubAssembler default backend. StubAssembler provides EmitU8/EmitU32/EmitU64 little-endian byte emitters (zero dep, no FASM). Assemble throws NotSupportedException on StubAssembler (text assembly deferred to IcedAssembler, Phase 8). 7 new tests: EmitU8, EmitU32 x2, EmitU64 x2, IS-A check, Assemble throws. All passing (total: 64). --- WhiteMagic/Assembly/IAssembler.cs | 17 ++++++ WhiteMagic/Assembly/StubAssembler.cs | 49 +++++++++++++++++ WhiteMagicTest/StubAssemblerTests.cs | 78 ++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 WhiteMagic/Assembly/IAssembler.cs create mode 100644 WhiteMagic/Assembly/StubAssembler.cs create mode 100644 WhiteMagicTest/StubAssemblerTests.cs diff --git a/WhiteMagic/Assembly/IAssembler.cs b/WhiteMagic/Assembly/IAssembler.cs new file mode 100644 index 0000000..321c4d8 --- /dev/null +++ b/WhiteMagic/Assembly/IAssembler.cs @@ -0,0 +1,17 @@ +namespace WhiteMagic.Assembly; + +/// +/// Abstraction over an x86/x64 assembler. The default +/// hand-emits calling-convention trampolines (no parsing, zero dep). An optional +/// (Phase 8) handles arbitrary mnemonics via the Iced +/// library. +/// +public interface IAssembler +{ + /// + /// Assembles text mnemonics into machine code. + /// + /// The assembly text (Intel syntax). + /// The base address for relative encodings. + byte[] Assemble(string assemblyText, ulong origin = 0); +} diff --git a/WhiteMagic/Assembly/StubAssembler.cs b/WhiteMagic/Assembly/StubAssembler.cs new file mode 100644 index 0000000..2d24a59 --- /dev/null +++ b/WhiteMagic/Assembly/StubAssembler.cs @@ -0,0 +1,49 @@ +namespace WhiteMagic.Assembly; + +/// +/// The default backend. Hand-emits calling-convention +/// trampolines and injection stubs using deterministic byte emitters +/// (, , ). Has +/// no native or third-party dependency — no FASM, no Iced. +/// +/// +/// is not supported by this backend (it is a parse-free +/// emitter, not a text assembler). Use (Phase 8) for +/// arbitrary mnemonics. +/// +public class StubAssembler : IAssembler +{ + /// + /// Always thrown. StubAssembler does + /// not parse text assembly; use IcedAssembler for that. + 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 ──────────────────────────────────────────────────── + + /// Appends a single byte to . + public void EmitU8(List buffer, byte value) + { + buffer.Add(value); + } + + /// Appends as 4 little-endian bytes. + public void EmitU32(List buffer, uint value) + { + buffer.Add((byte)value); + buffer.Add((byte)(value >> 8)); + buffer.Add((byte)(value >> 16)); + buffer.Add((byte)(value >> 24)); + } + + /// Appends as 8 little-endian bytes. + public void EmitU64(List buffer, ulong value) + { + EmitU32(buffer, (uint)value); + EmitU32(buffer, (uint)(value >> 32)); + } +} diff --git a/WhiteMagicTest/StubAssemblerTests.cs b/WhiteMagicTest/StubAssemblerTests.cs new file mode 100644 index 0000000..e004a53 --- /dev/null +++ b/WhiteMagicTest/StubAssemblerTests.cs @@ -0,0 +1,78 @@ +using WhiteMagic.Assembly; + +namespace WhiteMagicTest; + +/// +/// Tests for emit primitives (, +/// , ) and the +/// interface contract. +/// +public class StubAssemblerTests +{ + private static StubAssembler Create() => new(); + + // ── Emit primitives ──────────────────────────────────────────────────── + + [Fact] + public void EmitU8_appends_a_single_byte() + { + var sut = Create(); + var buffer = new List(); + sut.EmitU8(buffer, 0xAB); + Assert.Equal([0xAB], buffer); + } + + [Fact] + public void EmitU32_appends_little_endian() + { + var sut = Create(); + var buffer = new List(); + sut.EmitU32(buffer, 0x11223344); + Assert.Equal([0x44, 0x33, 0x22, 0x11], buffer); + } + + [Fact] + public void EmitU32_appends_zero() + { + var sut = Create(); + var buffer = new List(); + sut.EmitU32(buffer, 0); + Assert.Equal([0x00, 0x00, 0x00, 0x00], buffer); + } + + [Fact] + public void EmitU64_appends_little_endian() + { + var sut = Create(); + var buffer = new List(); + sut.EmitU64(buffer, 0x1122334455667788); + byte[] expected = [0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]; + Assert.Equal(expected, buffer); + } + + [Fact] + public void EmitU64_appends_high_bits() + { + var sut = Create(); + var buffer = new List(); + sut.EmitU64(buffer, 0xDEADBEEF_CAFEBABE); + byte[] expected = [0xBE, 0xBA, 0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE]; + Assert.Equal(expected, buffer); + } + + // ── IAssembler interface ─────────────────────────────────────────────── + + [Fact] + public void StubAssembler_is_an_IAssembler() + { + var sut = Create(); + Assert.IsAssignableFrom(sut); + } + + [Fact] + public void Assemble_from_StubAssembler_throws_NotSupported() + { + var sut = Create(); + Assert.Throws(() => sut.Assemble("nop", 0)); + } +} From f7236eea9bb01bfb9938ba6a1147cb8df7692e06 Mon Sep 17 00:00:00 2001 From: Kevin Bataille Date: Tue, 21 Jul 2026 19:37:20 +0200 Subject: [PATCH 2/3] task 3.3-3.4: x86 cdecl stub encoding + CallingConvention enum Add CallingConvention enum (Cdecl, Stdcall, Thiscall, Fastcall). Implement BuildCallStub on StubAssembler with x86 cdecl support: reverse arg push, call rel32, add esp (caller cleanup), ret. x64 stub is a placeholder (task 3.7-3.8). 3 new tests: 0-arg (call+ret), 1-arg (push+call+cleanup+ret), 2-args (reverse push+call+cleanup+ret). Known byte expectations. All passing (total: 67). --- WhiteMagic/Assembly/CallingConvention.cs | 19 ++++++ WhiteMagic/Assembly/StubAssembler.cs | 87 +++++++++++++++++++++--- WhiteMagicTest/StubAssemblerTests.cs | 68 +++++++++++++++++- 3 files changed, 163 insertions(+), 11 deletions(-) create mode 100644 WhiteMagic/Assembly/CallingConvention.cs diff --git a/WhiteMagic/Assembly/CallingConvention.cs b/WhiteMagic/Assembly/CallingConvention.cs new file mode 100644 index 0000000..5a16a85 --- /dev/null +++ b/WhiteMagic/Assembly/CallingConvention.cs @@ -0,0 +1,19 @@ +namespace WhiteMagic.Assembly; + +/// +/// x86/x86-64 calling conventions for call-stub generation. +/// +public enum CallingConvention +{ + /// Caller pushes args right-to-left and cleans the stack (x86). + Cdecl, + + /// Caller pushes args right-to-left; callee cleans the stack (x86). + Stdcall, + + /// ECX receives the this pointer; remaining args on stack right-to-left; callee cleans (x86). + Thiscall, + + /// ECX/EDX receive the first two args; remaining on stack right-to-left; callee cleans (x86). + Fastcall, +} diff --git a/WhiteMagic/Assembly/StubAssembler.cs b/WhiteMagic/Assembly/StubAssembler.cs index 2d24a59..0ecce80 100644 --- a/WhiteMagic/Assembly/StubAssembler.cs +++ b/WhiteMagic/Assembly/StubAssembler.cs @@ -14,8 +14,6 @@ namespace WhiteMagic.Assembly; public class StubAssembler : IAssembler { /// - /// Always thrown. StubAssembler does - /// not parse text assembly; use IcedAssembler for that. public byte[] Assemble(string assemblyText, ulong origin = 0) { throw new NotSupportedException( @@ -25,13 +23,8 @@ public class StubAssembler : IAssembler // ── Emit primitives ──────────────────────────────────────────────────── - /// Appends a single byte to . - public void EmitU8(List buffer, byte value) - { - buffer.Add(value); - } + public void EmitU8(List buffer, byte value) => buffer.Add(value); - /// Appends as 4 little-endian bytes. public void EmitU32(List buffer, uint value) { buffer.Add((byte)value); @@ -40,10 +33,86 @@ public class StubAssembler : IAssembler buffer.Add((byte)(value >> 24)); } - /// Appends as 8 little-endian bytes. public void EmitU64(List buffer, ulong value) { EmitU32(buffer, (uint)value); EmitU32(buffer, (uint)(value >> 32)); } + + // ── Call-stub builders ───────────────────────────────────────────────── + + public byte[] BuildCallStub(IntPtr stubAddress, IntPtr targetAddress, + uint[] arguments, int pointerSize, CallingConvention convention) + { + var buffer = new List(64); + + if (pointerSize == 4) + BuildX86Stub(buffer, (uint)stubAddress, (uint)targetAddress, arguments, convention); + else + BuildX64Stub(buffer, (ulong)stubAddress, (ulong)targetAddress, arguments); + + return buffer.ToArray(); + } + + private void BuildX86Stub(List buffer, uint stubAddr, + uint target, uint[] args, CallingConvention convention) + { + uint current = stubAddr; + + switch (convention) + { + case CallingConvention.Thiscall when args.Length >= 1: + buffer.Add(0xB9); // mov ecx, arg0 + EmitU32(buffer, args[0]); + current += 5; + args = args[1..]; + break; + + case CallingConvention.Fastcall: + if (args.Length >= 1) + { + buffer.Add(0xB9); // mov ecx, arg0 + EmitU32(buffer, args[0]); + current += 5; + args = args[1..]; + } + if (args.Length >= 1) + { + buffer.Add(0xBA); // mov edx, arg1 + EmitU32(buffer, args[0]); + current += 5; + args = args[1..]; + } + break; + } + + // Push remaining args in reverse order + for (int i = args.Length - 1; i >= 0; i--) + { + buffer.Add(0x68); // push imm32 + EmitU32(buffer, args[i]); + current += 5; + } + + // call rel32 + uint rel32 = target - (current + 5); + buffer.Add(0xE8); + EmitU32(buffer, rel32); + + // Caller cleanup (cdecl only) + if (convention == CallingConvention.Cdecl && args.Length > 0) + { + buffer.Add(0x83); // add esp, imm8 + buffer.Add(0xC4); + buffer.Add((byte)(args.Length * 4)); + } + + buffer.Add(0xC3); // ret + } + + private static void BuildX64Stub(List buffer, ulong stubAddr, + ulong target, uint[] args) + { + throw new NotImplementedException("x64 stubs (task 3.7-3.8)"); + } } diff --git a/WhiteMagicTest/StubAssemblerTests.cs b/WhiteMagicTest/StubAssemblerTests.cs index e004a53..53dfa9c 100644 --- a/WhiteMagicTest/StubAssemblerTests.cs +++ b/WhiteMagicTest/StubAssemblerTests.cs @@ -4,8 +4,8 @@ namespace WhiteMagicTest; /// /// Tests for emit primitives (, -/// , ) and the -/// interface contract. +/// , ) and +/// calling-convention stub encoding. /// public class StubAssemblerTests { @@ -75,4 +75,68 @@ public class StubAssemblerTests var sut = Create(); Assert.Throws(() => sut.Assemble("nop", 0)); } + + // ── Calling convention: x86 cdecl ────────────────────────────────────── + + [Fact] + public void Cdecl_stub_with_zero_args_is_call_then_ret() + { + var sut = Create(); + IntPtr stubAddr = (IntPtr)0x10000000; + IntPtr target = (IntPtr)0x12345678; + uint[] args = []; + + uint rel32 = (uint)target - ((uint)stubAddr + 5); + byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl); + + Assert.Equal(6, stub.Length); + Assert.Equal(0xE8, stub[0]); // call + Assert.Equal(rel32, BitConverter.ToUInt32(stub, 1)); // rel32 + Assert.Equal(0xC3, stub[5]); // ret + } + + [Fact] + public void Cdecl_stub_one_arg_reverse_push_then_call_then_cleanup() + { + var sut = Create(); + IntPtr stubAddr = (IntPtr)0x10000000; + IntPtr target = (IntPtr)0x12345678; + uint[] args = [0xAABBCCDD]; + + uint callAddr = (uint)stubAddr + 5; + uint rel32 = (uint)target - (callAddr + 5); + byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl); + + byte[] expected = [ + 0x68, 0xDD, 0xCC, 0xBB, 0xAA, // push 0xAABBCCDD + 0xE8, + (byte)rel32, (byte)(rel32 >> 8), (byte)(rel32 >> 16), (byte)(rel32 >> 24), + 0x83, 0xC4, 0x04, // add esp, 4 + 0xC3 // ret + ]; + Assert.Equal(expected, stub); + } + + [Fact] + public void Cdecl_stub_two_args_reverse_order() + { + var sut = Create(); + IntPtr stubAddr = (IntPtr)0x10000000; + IntPtr target = (IntPtr)0x12345678; + uint[] args = [0x11111111, 0x22222222]; + + uint callAddr = (uint)stubAddr + 10; + uint rel32 = (uint)target - (callAddr + 5); + byte[] stub = sut.BuildCallStub(stubAddr, target, args, 4, CallingConvention.Cdecl); + + byte[] expected = [ + 0x68, 0x22, 0x22, 0x22, 0x22, // push arg1 (reverse order) + 0x68, 0x11, 0x11, 0x11, 0x11, // push arg0 + 0xE8, + (byte)rel32, (byte)(rel32 >> 8), (byte)(rel32 >> 16), (byte)(rel32 >> 24), + 0x83, 0xC4, 0x08, // add esp, 8 + 0xC3 + ]; + Assert.Equal(expected, stub); + } } From 7c5e72e0e0c6c2960a46f804fd3861f1d89b28cf Mon Sep 17 00:00:00 2001 From: Kevin Bataille Date: Tue, 21 Jul 2026 19:47:24 +0200 Subject: [PATCH 3/3] Harden memory layer: fix char sizing, ref structs, count guards, ReadString advance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second-review fixes, each covered by a regression test in MemoryHardeningTests: - MarshalCache: special-case char (Size=2; Marshal.SizeOf reports 1/ANSI but the blittable path reads a 2-byte UTF-16 unit). TypeRequiresMarshal now also trips on RuntimeHelpers.IsReferenceOrContainsReferences() so reference-carrying structs route to the marshal path instead of throwing in MemoryMarshal.Read. Document that the MarshalAs scan is top-level only. - MemoryBase.Read(count): reject negative count (ArgumentOutOfRangeException) and guard elementSize*count overflow. Same overflow guard on Write(values). - MemoryBase.ReadString: advance by bytes actually read, not the requested amount, so a partial read no longer skips the unread tail of the window. - ExternalReader: default to a minimal access set (not AllAccess, which over-requests and fails on protected processes); wrap Process.MainModule in try/catch so a bitness-mismatched or protected target yields ImageBase=Zero instead of throwing. - NativeMethods: WaitForSingleObject and CreateRemoteThread's threadId are DWORD (uint), not int — the signatures no longer sign-flip. Deferred: hoisting the identical ExternalReader/InProcessReader byte-IO into MemoryBase (cosmetic; skipped to avoid colliding with concurrent Phase 3 edits). Co-Authored-By: Claude Opus 4.8 (1M context) --- WhiteMagic/ExternalReader.cs | 25 +++- WhiteMagic/MarshalCache.cs | 27 +++- WhiteMagic/MemoryBase.cs | 18 ++- WhiteMagic/Native/NativeMethods.cs | 7 +- WhiteMagicTest/MemoryHardeningTests.cs | 189 +++++++++++++++++++++++++ 5 files changed, 251 insertions(+), 15 deletions(-) create mode 100644 WhiteMagicTest/MemoryHardeningTests.cs diff --git a/WhiteMagic/ExternalReader.cs b/WhiteMagic/ExternalReader.cs index b0d6826..62d2979 100644 --- a/WhiteMagic/ExternalReader.cs +++ b/WhiteMagic/ExternalReader.cs @@ -15,13 +15,23 @@ public sealed class ExternalReader : MemoryBase private readonly IntPtr _imageBase; private bool _disposed; + /// + /// The default access rights: enough to read, write, allocate, query, run a remote + /// thread, and wait on it. This deliberately omits , + /// which over-requests and makes OpenProcess fail on protected processes where + /// these narrower rights would succeed. + /// + public const ProcessAccess DefaultAccess = + ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.VmOperation + | ProcessAccess.QueryInformation | ProcessAccess.CreateThread | ProcessAccess.Synchronize; + /// /// Opens a process for external memory access. /// /// The target process. /// The access rights to request. Defaults to - /// . - public ExternalReader(Process process, ProcessAccess desiredAccess = ProcessAccess.AllAccess) + /// . + public ExternalReader(Process process, ProcessAccess desiredAccess = DefaultAccess) { _handle = NativeMethods.OpenProcess(desiredAccess, false, process.Id); if (_handle.IsInvalid) @@ -31,7 +41,16 @@ public sealed class ExternalReader : MemoryBase $"OpenProcess failed for PID {process.Id}: error {error}"); } - _imageBase = process.MainModule?.BaseAddress ?? IntPtr.Zero; + // 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; + } } /// diff --git a/WhiteMagic/MarshalCache.cs b/WhiteMagic/MarshalCache.cs index 0b34953..49f1b59 100644 --- a/WhiteMagic/MarshalCache.cs +++ b/WhiteMagic/MarshalCache.cs @@ -19,10 +19,19 @@ public static class MarshalCache public static readonly uint SizeU; /// - /// when has at least one field - /// decorated with , meaning it cannot be copied - /// via a simple pointer dereference. + /// when cannot be copied through the + /// blittable path and must + /// use / instead. + /// This is the case when a top-level field carries , or + /// when contains a managed reference + /// (). /// + /// + /// The check inspects only top-level fields; a + /// 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. + /// public static readonly bool TypeRequiresMarshal; /// when is . @@ -46,6 +55,13 @@ public static class MarshalCache 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(); @@ -62,8 +78,11 @@ public static class MarshalCache SizeU = (uint)Size; IsIntPtr = RealType == typeof(IntPtr); - TypeRequiresMarshal = + 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(); } } diff --git a/WhiteMagic/MemoryBase.cs b/WhiteMagic/MemoryBase.cs index 2b518fd..7e52137 100644 --- a/WhiteMagic/MemoryBase.cs +++ b/WhiteMagic/MemoryBase.cs @@ -76,12 +76,16 @@ public abstract class MemoryBase : IDisposable /// returns fewer bytes than expected. public T[] Read(IntPtr address, int count, bool isRelative = false) where T : struct { + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (isRelative) address = GetAbsolute(address); int elementSize = MarshalCache.Size; - int totalSize = elementSize * count; - byte[] raw = ReadBytes(address, totalSize); + 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]; @@ -124,7 +128,9 @@ public abstract class MemoryBase : IDisposable return true; int elementSize = MarshalCache.Size; - int totalSize = elementSize * values.Length; + long total = (long)elementSize * values.Length; + ArgumentOutOfRangeException.ThrowIfGreaterThan(total, int.MaxValue, nameof(values)); + int totalSize = (int)total; byte[] raw = new byte[totalSize]; Span span = raw; @@ -181,8 +187,10 @@ public abstract class MemoryBase : IDisposable } accumulated.Add(chunk); - address += take; - remaining -= take; + // 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; diff --git a/WhiteMagic/Native/NativeMethods.cs b/WhiteMagic/Native/NativeMethods.cs index bdc07e2..d6b3fe9 100644 --- a/WhiteMagic/Native/NativeMethods.cs +++ b/WhiteMagic/Native/NativeMethods.cs @@ -85,7 +85,7 @@ internal static partial class NativeMethods IntPtr startAddress, IntPtr parameter, ThreadCreationFlags creationFlags, - out int threadId); + out uint threadId); /// Sets a 64-bit thread context (AMD64). [LibraryImport("kernel32.dll", SetLastError = true)] @@ -128,9 +128,10 @@ internal static partial class NativeMethods IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName); - /// Waits until a thread exits and retrieves its exit code. + /// Waits until an object is signaled or the timeout elapses. Returns a + /// WAIT_* status (DWORD); WAIT_FAILED is 0xFFFFFFFF. [LibraryImport("kernel32.dll", SetLastError = true)] - internal static partial int WaitForSingleObject( + internal static partial uint WaitForSingleObject( SafeMemoryHandle handle, uint milliseconds); } diff --git a/WhiteMagicTest/MemoryHardeningTests.cs b/WhiteMagicTest/MemoryHardeningTests.cs new file mode 100644 index 0000000..acf96c2 --- /dev/null +++ b/WhiteMagicTest/MemoryHardeningTests.cs @@ -0,0 +1,189 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using WhiteMagic; +using WhiteMagic.Native; + +namespace WhiteMagicTest; + +/// +/// Regression tests for the edge-case defects found in the second review pass: +/// char sizing, reference-containing structs, unchecked counts, the ReadString +/// partial-chunk skip, and ExternalReader construction against awkward targets. +/// Each test fails against the pre-fix code. +/// +public class MemoryHardeningTests +{ + private static ExternalReader OpenSelf() + { + return new ExternalReader( + Process.GetCurrentProcess(), + ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.VmOperation | ProcessAccess.QueryInformation); + } + + // ── char sizing (MarshalCache / MemoryBase.Read) ────────────────── + + [Fact] + public void MarshalCache_char_size_is_two_bytes() + { + Assert.Equal(2, MarshalCache.Size); + } + + [Fact] + public void Read_char_writes_and_reads_back() + { + using var reader = OpenSelf(); + char slot = '\0'; + GCHandle pin = GCHandle.Alloc(slot, GCHandleType.Pinned); + try + { + IntPtr addr = pin.AddrOfPinnedObject(); + Assert.True(reader.Write(addr, 'Z')); + Assert.Equal('Z', reader.Read(addr)); + } + finally + { + pin.Free(); + } + } + + [Fact] + public void Read_char_array_writes_and_reads_back() + { + using var reader = OpenSelf(); + char[] slot = new char[4]; + GCHandle pin = GCHandle.Alloc(slot, GCHandleType.Pinned); + try + { + IntPtr addr = pin.AddrOfPinnedObject(); + char[] expected = ['w', 'o', 'w', '!']; + Assert.True(reader.Write(addr, expected)); + Assert.Equal(expected, reader.Read(addr, 4)); + } + finally + { + pin.Free(); + } + } + + // ── reference-containing structs route to the marshal path ────────────── + + [Fact] + public void MarshalCache_flags_struct_with_reference_field_as_marshal_required() + { + // Has a string field but no [MarshalAs]; the blittable path (MemoryMarshal.Read) + // throws for a reference-containing T, so the cache must route it to the marshal + // path. A struct with a managed reference cannot be pinned, so the routing flag — + // not a live round-trip — is the regression guard here. + Assert.True(MarshalCache.TypeRequiresMarshal); + } + + // ── unchecked count guards ────────────────────────────────────────────── + + [Fact] + public void Read_array_with_negative_count_throws_argument_out_of_range() + { + using var reader = OpenSelf(); + int dummy = 0; + GCHandle pin = GCHandle.Alloc(dummy, GCHandleType.Pinned); + try + { + Assert.Throws(() => reader.Read(pin.AddrOfPinnedObject(), -1)); + } + finally + { + pin.Free(); + } + } + + [Fact] + public void Read_array_with_zero_count_returns_empty() + { + using var reader = OpenSelf(); + int dummy = 0; + GCHandle pin = GCHandle.Alloc(dummy, GCHandleType.Pinned); + try + { + Assert.Empty(reader.Read(pin.AddrOfPinnedObject(), 0)); + } + finally + { + pin.Free(); + } + } + + // ── ReadString partial-chunk advance ──────────────────────────────────── + + [Fact] + public void ReadString_advances_by_actual_bytes_when_reads_are_partial() + { + // The reader serves at most 3 bytes per call. The string is longer than one + // chunk with the terminator well past it. If ReadString advanced by the + // requested count instead of the bytes actually returned, it would skip + // data and truncate the result. + byte[] data = Encoding.ASCII.GetBytes("ABCDEFGHIJ\0"); + var reader = new PartialReader(data, maxChunk: 3); + + string result = reader.ReadString(IntPtr.Zero, Encoding.ASCII, maxLength: 64); + + Assert.Equal("ABCDEFGHIJ", result); + } + + [Fact] + public void ReadString_stops_at_null_across_partial_chunks() + { + byte[] data = Encoding.ASCII.GetBytes("hi\0garbage"); + var reader = new PartialReader(data, maxChunk: 1); + + string result = reader.ReadString(IntPtr.Zero, Encoding.ASCII, maxLength: 64); + + Assert.Equal("hi", result); + } + + // ── ExternalReader construction ───────────────────────────────────────── + + [Fact] + public void ExternalReader_opens_self_with_default_access() + { + // The default access set must be small enough to open a normal process. + using var reader = new ExternalReader(Process.GetCurrentProcess()); + Assert.False(reader.Handle.IsInvalid); + } + + /// + /// A that serves bytes from an in-memory buffer and + /// caps every read to maxChunk bytes, to exercise partial-read handling. + /// The address is treated as a zero-based index into the buffer. + /// + private sealed class PartialReader(byte[] data, int maxChunk) : MemoryBase + { + public override IntPtr ImageBase => IntPtr.Zero; + public override SafeMemoryHandle Handle => null!; + + public override byte[] ReadBytes(IntPtr address, int count, bool isRelative = false) + { + int start = (int)address; + if (start < 0 || start >= data.Length || count <= 0) + return []; + int n = Math.Min(Math.Min(count, maxChunk), data.Length - start); + return data[start..(start + n)]; + } + + public override int WriteBytes(IntPtr address, ReadOnlySpan bytes, bool isRelative = false) + => throw new NotSupportedException(); + + public override void Dispose() { } + } +} + +/// +/// A struct that carries a managed reference. +/// reports , so it cannot travel the blittable read path. +/// +[StructLayout(LayoutKind.Sequential)] +public struct StructWithReference +{ + public int Id; + public string Name; +}