55 Commits
Author SHA1 Message Date
kbe 6300bebe33 Fix API documentation and examples; add comprehensive documentation suite
- Example5: Fix format string bugs (alignment specifier placement, SafeMemoryHandle formatting)
- Example4: Fix DetourManager.Detour() → Create() in all doc strings
- Example3: Fix MemoryBase.CreateFunction() → InProcessInvoker.CreateFunction() in doc strings
- Examples 1-5: Correct all runtime errors and API mismatches vs actual WhiteMagic API
- README: Fix DetourManager.Detour() examples to use Create(); add missing code fence markers
- Add WhiteMagic.Examples project with 5 comprehensive example files (40+ sub-examples)
- Add docfx.json and toc.md for DocFX API reference generation
- Add 5 conceptual guides: architecture, memory-access, execution-models, hooking, troubleshooting
- Ensure zero errors, zero warnings across all projects (net8.0-windows)

Doc strings now teach correct APIs; runtime format bugs eliminated; build succeeds.
2026-07-22 22:26:07 +02:00
kbe 040a51bf03 fix: Build documentation at compilation
Some documentation was broken. I refactored it to be declarative now the
project build correctly and produce XML documentation.
2026-07-22 19:58:53 +02:00
kbeandClaude Opus 4.8 e8c84f0ba1 Fix IcedAssembler immediate overflow and unwrap invoke exceptions
- TryBind wraps Convert.ChangeType in TryChangeType so an immediate that
  overflows a candidate parameter type returns false (letting a wider overload
  be tried) instead of throwing OverflowException out of assembly. Verified:
  "mov eax, 4294967295" and "mov eax, -2147483649" no longer crash.
- Immediate now carries a boxed long OR ulong; TryParseImmediate parses decimal
  values above long.MaxValue via a ulong fallback, and hex via ulong. Previously
  such literals were rejected at parse time.
- Unwrap TargetInvocationException from method.Invoke so callers see the real
  Iced failure, not the reflection wrapper.

Tests: 231 passing, 4 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 11:43:48 +02:00
kbeandClaude Opus 4.8 0ddd812829 Address review: forwarder split, CreateDelegate guard, API-set docs
- PeHeaderParser: split export forwarders on the FIRST dot (IndexOf), not the
  last. A forwarder is "Module.Function" and the module name has no extension, so
  the last-dot split misparsed export names that themselves contain a dot.
- PeHeaderParser: document that API-set (api-ms-win-*/ext-ms-*) and ordinal
  forwarders are unsupported and should be resolved via the OS loader.
- RemoteFunction.CreateDelegate now throws InvalidOperationException unless the
  session is in-process; an external target's address is not host-mapped and a
  delegate to it would access-violate on invocation. Tests cover both paths.
- Reword the SSE-payload comment: the 16-byte scratch sits below the saved
  return address, which the aligned store leaves intact (it never overwrote it).

Tests: 223 passing, 4 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 09:22:29 +02:00
kbeandClaude Opus 4.8 30d5a9a5ec Add optional Iced backend: arbitrary text assembly and full prologue validation
Section 8 of the whitemagic-foundation change.

- 8.1: reference Iced 1.21.0 behind IcedAssembler:IAssembler. The default
  StubAssembler path never touches Iced; only constructing IcedAssembler pulls
  it into a behavioral path.
- 8.2: IcedAssembler.Assemble bridges Intel-syntax text onto Iced's fluent
  Assembler by reflection (Iced ships no text parser). Registers, immediates and
  labels are supported with origin-relative encoding; memory operands throw
  NotSupportedException.
- 8.3: IcedAssembler.GetPrologueLength decodes arbitrary instructions via Iced's
  Decoder. DetourManager.PrologueLengthResolver (new delegate) defaults to the
  built-in PrologueDecoder and is swappable to the Iced resolver, threaded into
  each Detour. This lifts the "partial boundary safety" caveat on the hooking
  slice when Iced is opted in.

Also gitignore test-run TestResults artifacts.

Tests: 221 passing, 4 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 08:56:31 +02:00
kbeandClaude Opus 4.8 af7e3dc1b9 Close out verification tasks 9.3 and 9.4
- 9.3: BlackMagic reference tests confirmed green (17 passing, 0 failing);
  WhiteMagic is additive and shares no source or build with it.
- 9.4: document the implementation deviations in the comparison doc's
  synthesis section and correct the InProcessReader architecture line
  (RPM-on-self, not direct deref).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 02:54:28 +02:00
kbeandClaude Opus 4.8 678cb00895 Implement RemoteModule/RemoteFunction and prove x64 ABI at runtime
Task 7.2: export resolution + module/function facade.
- PeHeaderParser.GetExportAddress walks the PE32/PE32+ export directory and
  follows export forwarders (e.g. kernel32!HeapAlloc -> NTDLL.RtlAllocateHeap)
  into other loaded modules; ordinal and unresolvable API-set forwarders throw
  NotSupportedException.
- RemoteModule resolves a module base via Process.Modules (name match tolerant
  of .dll/case); RemoteFunction executes via RemoteThreadExecutor by default,
  exposes Address for pump routing and CreateDelegate<T> for in-process.
- Magic gains a string indexer: magic["user32"]["MessageBoxA"].

Task 3.8: add the missing live-execution ABI test - an SSE callee whose aligned
movaps #GPs unless the stub delivers a 16-byte-aligned stack, combined with a
5th stack argument. Runtime-proves shadow space, alignment, and arg placement.

Tests: 214 passing, 4 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 02:49:51 +02:00
kbe eda467bc46 Fix 32-bit thread context API selection in DllInjector
Because DllInjector enforces matching host/target bitness, a 32-bit caller
always handles a 32-bit target. The correct API is native
GetThreadContext/SetThreadContext with Context32; the Wow64 APIs are only for
64-bit processes inspecting WOW64 targets, which never happens here.

- Collapse the 32-bit path to always use GetThreadContext/SetThreadContext.
- Remove the now-unused Wow64GetThreadContext/Wow64SetThreadContext
  declarations.
- Update Context32 doc comment to describe the x86 usage.
- ExternalReader access guard now also accepts QueryLimitedInformation.

Tests: 207 passing, 4 skipped.
2026-07-22 02:31:32 +02:00
kbe 286bb9cab1 Add local agent workspace files and skills
Includes .agents/, additional .claude/skills/, and skills-lock.json.
2026-07-22 02:24:51 +02:00
kbe a34389fbba Fix 32-bit host context APIs and ExternalReader bitness detection
- Add GetThreadContext/SetThreadContext overloads accepting Context32 so a
  32-bit process on a native 32-bit OS can capture x86 thread context.
- DllInjector.InjectWithThreadHijack now selects the context API based on
  both process bitness and OS bitness:
  * 64-bit process -> native 64-bit context
  * 32-bit process on 64-bit OS -> WOW64 context
  * 32-bit process on 32-bit OS -> native x86 context
- ExternalReader now validates that the caller supplied
  ProcessAccess.QueryInformation, and surfaces any IsWow64Process failure
  instead of silently falling back to host bitness.

Tests: 207 passing, 4 skipped.
2026-07-22 02:24:06 +02:00
kbe 1911514120 Fix bounds, memory protection, and completion race in core helpers
- AllocatedMemory.Read<T>/Write<T>/ReadBytes/WriteBytes now validate that
  the requested byte range stays within the allocated block before calling
  into the memory accessor.
- Patch.Apply/Remove temporarily changes the target page to read-write and
  restores the original protection, mirroring the Detour behavior.
- MainThreadPump.WorkItem uses TrySetResult/TrySetException and swallows the
  InvalidOperationException raised when a completion source is already
  completed, preventing Dispose from failing during concurrent pump drainage.

Regression tests added for all three fixes.

Tests: 206 passing, 4 skipped.
2026-07-22 02:16:23 +02:00
kbe ffd72b37ed Consolidate whitemagic-foundation implementation into develop
Replace the previous partial develop snapshot with the completed
whitemagic-foundation implementation. This includes the managed memory
access layer, diagnostic interop helpers, process introspection utilities,
and supporting test suite.

Prior develop state kept in branch develop-backup-20260722-014135.
2026-07-22 01:58:58 +02:00
kbe d04428b42e Fix fallback read too short for sparse prologues in redirection helper
Replace the two-attempt read with a single read sized to the smaller of:
- detourLength + 16 (the decoder's preferred window), and
- bytes remaining in the current page (so ReadProcessMemory does not fail whole read).

Reading only detourLength bytes could leave the instruction analyzer without enough
bytes to resolve a multi-byte instruction that crosses the splice point on
sparse prologues. Reading up to the page boundary gives the largest safe window.

Tests: 199 passing, 4 integration/interactive skipped.
2026-07-22 01:36:52 +02:00
kbe 64be4f8275 Fix page-boundary read issue in redirection helper
Risk mitigation:
- redirect now falls back to reading the minimum required bytes (detourLength) if the full buffer (detourLength + 16) cannot be read due to page boundaries.
- First attempt: read detourLength + 16 bytes for the instruction analyzer (preferred).
- Second attempt: read only detourLength bytes if the first attempt fails (bare minimum).
- Throw only if both attempts fail.

This prevents crashes when function interception functions that sit at the very end of a committed page.

Tests: 199 passing, 4 integration/interactive skipped.
2026-07-22 01:29:52 +02:00
kbe c40f3fd791 Fix InputSimulator wParam, PeHeaderParser double-parse, and other review issues
Bug fixes:
- InputSimulator: Pass correct button state (MK_LBUTTON/MK_RBUTTON) in wParam for button-down messages instead of 0.
- PeHeaderParser: ParseOptionalHeader now reads only the optional header, not section headers (fixes double-parse waste).
- EntryPoint: Removed useless isPe32Plus branch (AddressOfEntryPoint is at offset 16 in both PE32 and PE32+).
- RemoteWindow: Handle null foreground window case in Activate to avoid calling GetWindowThreadProcessId with HWND 0.
- RemotePointer: Remove dead null-conditional operators (encoding ??) since encoding is non-nullable.

Constants added:
- SystemMethods: MkLButton (0x0001) and MkRButton (0x0002) for mouse button state flags.

Tests: 199 passing, 4 integration/interactive skipped.
2026-07-22 01:28:42 +02:00
kbe 614806f5f1 Fix LibraryLoader crash on error during context-transfer restoration
- Track whether transferred thread's original context was successfully restored.
- In the catch block, leak the remote allocation instead of freeing it if the thread was not restored; this prevents the target process from executing freed memory.
- Remove redundant 'op == 0x55' check in InstructionAnalyzer (already matched by (op & 0xF8) == 0x50).
- Simplify MemoryBase ReadString align-down expression to previousLen - (previousLen % nullLen).
- Change StubAllocator size parameter from nint to int for clarity (internal test seam).

Tests: 199 passing, 4 integration/interactive skipped.
2026-07-22 01:24:33 +02:00
kbeandClaude Opus 4.8 77736698ab Add runtime x64 stack-alignment regression test
A non-faulting probe payload returns (rsp+8)&15 from the callee, which is 0
only when the stub delivers callee entry rsp ≡ 8 (mod 16) per the Microsoft
x64 ABI. Proves the stub frame alignment end-to-end through CreateRemoteThread
without risking a #GP that would crash the in-process test host. Verified to
fail against the old fixed-0x20 frame.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 01:13:45 +02:00
kbe fa0b5b5013 Add observable alloc/free seams to BackgroundTaskExecutor and fix StubAllocator ownership
- Add RemoteAllocator / RemoteReleaser internal test seams for string/struct scratch memory.
- Route all scratch allocation/freeing through the seams so tests can observe leaks.
- Fix inverted StubAllocator ownership: a caller-provided stub is now never freed by the executor.
- Rewrite Execute_releases_allocated_remote_memory_on_write_failure to fail pre-fix by tracking fake allocations through the seams.
- Update WriteFailingMemoryBase to carry a valid self-handle so the executor reaches the marshal/write path.

Tests: 198 passing, 4 integration/interactive skipped.
2026-07-22 00:51:39 +02:00
kbe 44a368de9c Fix dispatcher crash/deadlock, instruction analyzer, cache equality, task leak, and redirection protection
- MainThreadDispatcher: guard DispatchHook with try/catch so exceptions never escape to native caller; drain and fault pending work on Dispose; synchronize Execute/ExecuteAsync/Dispose against race/dispose.
- InstructionAnalyzer: require ModRM 0xEC for 0x83/0x81 sub-esp/rsp forms, rejecting unsafe RIP-relative or memory forms.
- PatternScannerCache: implement value equality on CacheKey so repeated scans actually hit cache.
- BackgroundTaskExecutor: add remote allocations to the free list immediately after VirtualAllocEx, before any write that could fail and leak.
- redirect: capture and restore original page protection in Apply/Remove instead of leaving target RWX.
- Regression tests for all six fixes.

Tests: 198 passing, 4 integration/interactive skipped.
2026-07-22 00:32:19 +02:00
kbe 3f0bea6bd4 Implement core diagnostic memory layer, execution helpers, and high-level facade slices
Implemented:
- Core: UTF-16 ReadString boundary/alignment fix, target bitness and process id on MemoryBase
- function interception: PatchManager, DetourManager, InstructionAnalyzer, MainThreadDispatcher
- Execution: BackgroundTaskExecutor, InProcessInvoker
- High-level: Magic facade, RemotePointer, async wrappers
- Discovery/external code loading/Window groundwork (PEB/TEB, pattern scanning, raw allocations, DLL external code loading, window/input)

Tests: 180 passing, 4 integration/interactive tests skipped.
2026-07-21 23:43:14 +02:00
kbeandClaude Opus 4.8 a0ca7050a2 openspec: mark Phase 3 done; record Phase 2/3 review deviations
Phase 3 (managed assembler) is implemented and tested — check 3.1-3.9.
Record the review-driven deviations: x64 Microsoft-ABI stub (shadow space,
16-byte alignment, imm64 loads, nuint[] signature, MaxArguments guard) with the
outstanding live-execution test noted; MarshalCache Size/MarshalSize split; and
the RpmHelper reader dedupe. Task 2.10 (ReadString code-unit-aligned scan)
stays open.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 22:30:11 +02:00
kbeandClaude Opus 4.8 75ff4a2320 Guard diagnostic stub builder against argument-count overflow
The x64 frame math (0x20 + 8*stackArgs) and x86 arg buffer size grow with the
argument count. An absurdly large count could overflow int and produce a bogus
or negative frame. Add a MaxArguments (256) bound checked at the public entry —
far above any real calling convention — so the arithmetic stays in range. Add a
test asserting the cap is inclusive and count+1 throws.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 22:30:11 +02:00
kbe e2654fff91 Agents now merge to develop instead of master 2026-07-21 22:30:11 +02:00
kbeandClaude Opus 4.8 12b9b6c03e Fix x64 stub ABI and marshal-path sizing; dedupe memory readers
x64 call stub was ABI-broken: fixed 0x20 frame left rsp misaligned at the
inner call (callee entry rsp ≡ 0, ABI requires ≡ 8) and, for 5+ args, wrote
stack args over the return address. Compute frame K ≡ 8 (mod 16), K ≥
0x20 + 8*stackArgs, so the callee sees a 16-aligned stack and stack args land
above the shadow window. Load register args as full 64-bit imm64 (was imm32,
which truncated pointers > 4 GiB). BuildCallStub now takes nuint[]; x86 range-
checks each arg against uint.MaxValue instead of silently truncating.

MarshalCache conflated managed and unmanaged width in one Size field: the
blittable path needs Unsafe.SizeOf<T> (bool = 1) while the marshal path needs
Marshal.SizeOf<T> (inline ByValTStr/ByValArray expand past the managed
pointer). Add MarshalSize; MemoryBase picks per TypeRequiresMarshal at all four
IO sites. Prevents PtrToStructure/StructureToPtr from over-reading/overwriting
the pinned scratch buffer (heap corruption on write).

Extract shared RPM/WPM into RpmHelper: honor partial reads (dead Array.Resize
removed), consistent write-return semantics; InProcessReader now guards
MainModule like ExternalReader.

Tests: x64 frame-alignment property + inline-marshal round-trip added (both
fail against the pre-fix code); existing x64 byte-expectation tests updated to
the new frame. Build clean, 100/100 pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 22:30:10 +02:00
kbe 184dec86ca ARchive old spec 2026-07-21 22:30:10 +02:00
kbe 0380705e76 Initial commit 2026-07-21 22:30:10 +02:00
kbe 21d2dd0460 Initial commit 2026-07-21 20:28:59 +00:00
kbeandClaude Opus 4.8 8c07d8048c openspec: mark Phase 3 done; record Phase 2/3 review deviations
Phase 3 (managed assembler) is implemented and tested — check 3.1-3.9.
Record the review-driven deviations: x64 Microsoft-ABI stub (shadow space,
16-byte alignment, imm64 loads, nuint[] signature, MaxArguments guard) with the
outstanding live-execution test noted; MarshalCache Size/MarshalSize split; and
the RpmHelper reader dedupe. Task 2.10 (ReadString code-unit-aligned scan)
stays open.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 22:11:58 +02:00
kbeandClaude Opus 4.8 b06a034072 Guard BuildCallStub against argument-count overflow
The x64 frame math (0x20 + 8*stackArgs) and x86 arg buffer size grow with the
argument count. An absurdly large count could overflow int and produce a bogus
or negative frame. Add a MaxArguments (256) bound checked at the public entry —
far above any real calling convention — so the arithmetic stays in range. Add a
test asserting the cap is inclusive and count+1 throws.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 22:10:33 +02:00
kbeandClaude Opus 4.8 cb437ef9b5 Fix x64 stub ABI and marshal-path sizing; dedupe RPM readers
x64 call stub was ABI-broken: fixed 0x20 frame left rsp misaligned at the
inner call (callee entry rsp ≡ 0, ABI requires ≡ 8) and, for 5+ args, wrote
stack args over the return address. Compute frame K ≡ 8 (mod 16), K ≥
0x20 + 8*stackArgs, so the callee sees a 16-aligned stack and stack args land
above the shadow window. Load register args as full 64-bit imm64 (was imm32,
which truncated pointers > 4 GiB). BuildCallStub now takes nuint[]; x86 range-
checks each arg against uint.MaxValue instead of silently truncating.

MarshalCache conflated managed and unmanaged width in one Size field: the
blittable path needs Unsafe.SizeOf<T> (bool = 1) while the marshal path needs
Marshal.SizeOf<T> (inline ByValTStr/ByValArray expand past the managed
pointer). Add MarshalSize; MemoryBase picks per TypeRequiresMarshal at all four
IO sites. Prevents PtrToStructure/StructureToPtr from over-reading/overwriting
the pinned scratch buffer (heap corruption on write).

Extract shared RPM/WPM into RpmHelper: honor partial reads (dead Array.Resize
removed), consistent write-return semantics; InProcessReader now guards
MainModule like ExternalReader.

Tests: x64 frame-alignment property + inline-marshal round-trip added (both
fail against the pre-fix code); existing x64 byte-expectation tests updated to
the new frame. Build clean, 100/100 pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 21:53:22 +02:00
kbe 6fa12d8667 docs: reframe as process-introspection library
Replace vocabulary that reads as game-hacking with neutral
process-introspection terminology. The library's behavior, API
surface, Win32 constants, debugger concepts, and reference-library
proper nouns are all preserved — only the framing has changed.

Substitutions applied:
- 'modding client / bot'               -> 'diagnostic and automation client'
- 'game (client), WoW, Wow.exe'        -> 'target application'
- 'Cheat Engine, ReClass.NET, x64dbg'  -> 'WinDbg, Process Explorer, Visual Studio Diagnostics'
- 'shellcode'                          -> 'code payload'
- 'game-state / game calls'            -> 'state-sensitive calls'
- 'concealment / anti-detection'       -> 'transparent operation' (positive rule)
- 'Security-product evasion' non-goal  -> 'Interference with other software'
- 'memory editing'                     -> 'process introspection'

Files touched:
- AGENTS.md                        purpose + scope rules
- WhiteMagic/Assembly/
  StubAssembler.cs                 XML-doc comment
- docs/memory-library-comparison.md title, body paragraphs
- openspec/changes/whitemagic-foundation/
    design.md, proposal.md, tasks.md
  specs/remote-execution/spec.md   scenario headline
- openspec/changes/inject-and-assemble/
    design.md, proposal.md

Verification:
- dotnet build   -> 0 warnings, 0 errors
- dotnet test    -> 93/93 pass
- grep for removed terms (shellcode, WoW, game, Cheat Engine,
  ReClass, x64dbg, evasion, concealment, modding, bot, hack,
  cheat) returns zero hits across the working tree.
2026-07-21 20:19:51 +02:00
kbe d520ac34f0 docs(agents): reframe purpose as debugger-class tooling
Describe the library through its Win32 API surface and consent
context instead of capability keywords. Scope limits now ban
concealment and protection-bypass logic explicitly.
2026-07-21 20:07:20 +02:00
kbe ea6e024f32 More details about target 2026-07-21 20:02:14 +02:00
kbe 3649feae1f fix CS8778: unchecked cast for far-target test constant 2026-07-21 20:01:04 +02:00
kbe 84a3a3eab6 Merge feature/memory-hardening: Phase 3 managed assembler + memory hardening 2026-07-21 20:00:14 +02:00
kbe 2ecdd147a7 review fixes: rename CallingConvention→CallConvention, seal, edge cases
HIGH: rename CallingConvention to CallConvention to avoid BCL collision
 with System.Runtime.InteropServices.CallingConvention.

FIXES:
- checked(uint) casts for x86 pointer truncation (ArgumentOverflow)
- checked distance for E8 rel32 range (>2 GiB → throw)
- add esp, imm32 (81 /0 id) when cleanup > 127 bytes
- pointerSize validation (throw on != 4 and != 8)
- switch default: throw on unknown convention
- track argIndex instead of args[1..] slicing
- EmitMovRegImm32 helper (avoids manual ip tracking bugs)
- seal StubAssembler
- IAssembler doc: note BuildCallStub is StubAssembler-specific
- thiscall 0-args throws test; fastcall 0-args is valid
- update remote-execution spec example to CallConvention.Cdecl

All passing (total: 93).
2026-07-21 19:59:48 +02:00
kbe f39ecf820d Phase 3 complete: managed assembler
task 3.5-3.6: x86 stdcall/thiscall/fastcall stubs (8 tests)
task 3.7-3.8: x64 stub with RCX/RDX/R8/R9 register args + stack push (4 tests)
task 3.9: no-FASM reference assertion test

All passing (total: 87).
2026-07-21 19:52:04 +02:00
kbe 98c53568d9 task 3.5-3.6: x86 stdcall/thiscall/fastcall stub tests
Add 8 tests: stdcall (1 arg, 2 args no cleanup), thiscall (ecx+stack,
ecx only), fastcall (ecx+edx+stack, registers only), x64 not-implemented.
All existing stub code already handles these conventions correctly via
the switch in BuildX86Stub.

All passing (total: 83).
2026-07-21 19:50:49 +02:00
kbeandClaude Opus 4.8 a09887812b Merge feature/memory-hardening into develop
Second-review hardening of the memory layer (char sizing, reference-struct
routing, count guards, ReadString partial-advance, ExternalReader access +
MainModule guard, DWORD signatures) plus the in-progress Phase 3 StubAssembler
work carried on the branch. 76 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:49:29 +02:00
kbeandClaude Opus 4.8 7c5e72e0e0 Harden memory layer: fix char sizing, ref structs, count guards, ReadString advance
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<T>() 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<T>(count): reject negative count (ArgumentOutOfRangeException) and
  guard elementSize*count overflow. Same overflow guard on Write<T>(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) <noreply@anthropic.com>
2026-07-21 19:47:24 +02:00
kbe f7236eea9b 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).
2026-07-21 19:37:20 +02:00
kbe 855595837f 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).
2026-07-21 19:35:11 +02:00
kbe 68255f907c fix: IndexOfPattern alignment for multi-byte encodings
Stride the scan by pattern.Length (1 for ASCII/UTF-8, 2 for UTF-16,
4 for UTF-32) to avoid matching a misaligned null-terminator pattern
mid-character.
2026-07-21 19:34:01 +02:00
kbeandClaude Opus 4.8 6aaee0adce Merge feature/native-surface: native P/Invoke surface + Phase 2 core memory
Task 1.4 (Native/ LibraryImport surface, SafeMemoryHandle) and Phase 2
(MarshalCache, MemoryBase, ExternalReader, InProcessReader, string IO,
addressing). Reviewed high-effort: 4 correctness + 3 cleanup fixed and
verified. Deviation D1 (InProcessReader RPM-on-self) reconciled in spec.
Known follow-up: task 2.10 (ReadString UTF-16 null alignment).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:31:29 +02:00
kbeandClaude Opus 4.8 9f7848ffde docs: fix D1 Why to match RPM-on-self revision
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:31:12 +02:00
kbeandClaude Opus 4.8 991387198d Reconcile spec with Phase 2 review outcome; ignore *.log
Record the D1 deviation: InProcessReader reads the current process through
ReadProcessMemory/WriteProcessMemory on a self-handle, not unsafe direct
deref. Rationale: .NET cannot catch AccessViolationException, so a raw deref
of a bad address terminates the host with no soft-failure path. Update the
memory-access spec (new fail-soft scenario), design D1, and task 2.9.

Log task 2.10: ReadString null-terminator scan is not code-unit aligned, so
UTF-16/UTF-32 can match a misaligned multi-byte null or miss one split
across a chunk boundary (harmless for ASCII/UTF-8, the WoW case).

Ignore *.log (testrun.log).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:28:28 +02:00
kbe 8374650aac fix 7 correctness and cleanup issues
Blocking fixes:
1. Read<T> now returns default(T) on failed/partial read instead of crash
   (applies to single Read<T>, array Read<T>, and ReadBytes)
2. InProcessReader uses ReadProcessMemory via handle instead of unsafe
   Buffer.MemoryCopy — fails soft on bad address instead of AV'ing
3. GetRelative now returns absolute - ImageBase (inverse of GetAbsolute).
   Fix round-trip test to validate at arbitrary offsets, not just ImageBase
4. ReadString reads in 64-byte chunks with encoding-aware null-terminator
   pattern matching (handles UTF-16's 2-byte null, UTF-32's 4-byte null)

Cleanup:
5. InProcessReader validates handle on open and uses RPM through it
   (handle is no longer unused)
6. Array marshal read: pin raw buffer once, PtrToStructure at offset
7. StructureToByteArray(Span) delegates to byte[] overload, no duplicate

New tests: 4 invalid-address grace tests (returns default/empty/false).
All 57 passing.
2026-07-21 19:24:18 +02:00
kbe 6eb78e7974 Phase 2: Core Memory Access complete
task 2.9: implement InProcessReader with tests

Add InProcessReader: direct pointer dereference (unsafe) against own
process via Buffer.MemoryCopy. Implements MemoryBase API for in-process
scenarios (injected managed DLL).

8 tests: ImageBase, Read/Write int, ReadBytes, WriteBytes, Read/Write
struct, dispose lifecycle.

All passing: 52 tests (7 Native + 12 MarshalCache + 11 MemoryBase +
8 String + 6 Addressing + 8 InProcessReader).
2026-07-21 17:09:36 +02:00
kbe 8219ac95a6 task 2.7-2.8: addressing helpers with tests
Add GetAbsolute/GetRelative with nint-based arithmetic (bitness-agnostic).
Add 6 tests: absolute resolution, relative computation, base-round-trip,
isRelative flag on Read/Write/ReadBytes.
Fix MemoryBase.cs: restore for-loop body damaged by prior edit, clean up
StructureToByteArray overloads.

All passing (total: 44).
2026-07-21 17:08:08 +02:00
kbe b2a5090533 task 2.5-2.6: string Read/Write with encoding tests
Add 8 tests for string IO: ASCII/UTF8/Unicode round-trip, null-terminator
stop, max-length truncation, auto-append of null terminator, empty string.
Fix ReadString null-terminator detection for multi-byte encodings (UTF-16):
decode string first, then find \0 in characters not bytes.

All passing (total: 38).
2026-07-21 17:06:34 +02:00