Files
whitemagic/WhiteMagic/MemoryBase.cs
T
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

217 lines
7.9 KiB
C#

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>
public T Read<T>(IntPtr address, bool isRelative = false) where T : struct
{
if (isRelative)
address = GetAbsolute(address);
int size = MarshalCache<T>.Size;
Span<byte> buffer = stackalloc byte[size];
byte[] raw = ReadBytes(address, size);
raw.CopyTo(buffer);
if (MarshalCache<T>.TypeRequiresMarshal)
{
return MarshalByteArrayToStructure<T>(raw);
}
return MemoryMarshal.Read<T>(buffer);
}
/// <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;
Span<byte> buffer = stackalloc byte[size];
if (MarshalCache<T>.TypeRequiresMarshal)
{
StructureToByteArray(value, buffer, size);
}
else
{
MemoryMarshal.Write(buffer, in value);
}
int written = WriteBytes(address, buffer, false);
return written == size;
}
/// <summary>Reads an array of values of type <typeparamref name="T"/> from the target address.</summary>
public T[] Read<T>(IntPtr address, int count, bool isRelative = false) where T : struct
{
if (isRelative)
address = GetAbsolute(address);
int elementSize = MarshalCache<T>.Size;
int totalSize = elementSize * count;
byte[] raw = ReadBytes(address, totalSize);
var result = new T[count];
if (MarshalCache<T>.TypeRequiresMarshal)
{
for (int i = 0; i < count; i++)
{
var elementBytes = new ReadOnlySpan<byte>(raw, i * elementSize, elementSize);
result[i] = MarshalByteArrayToStructure<T>(elementBytes.ToArray());
}
}
else
{
ReadOnlySpan<byte> span = raw;
for (int i = 0; i < count; 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;
int totalSize = elementSize * values.Length;
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.</summary>
public virtual string ReadString(IntPtr address, Encoding encoding, int maxLength = 512, bool relative = false)
{
byte[] buffer = ReadBytes(address, maxLength, relative);
string decoded = encoding.GetString(buffer);
int nullIndex = decoded.IndexOf('\0');
if (nullIndex >= 0)
{
return decoded[..nullIndex];
}
return decoded;
}
/// <summary>Writes a null-terminated string to the target address.</summary>
public virtual bool WriteString(IntPtr address, string value, Encoding encoding, bool relative = false)
{
// Ensure null terminator
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 + (int)relative;
}
/// <summary>Converts an absolute address to a relative offset from <see cref="ImageBase"/>.</summary>
public IntPtr GetRelative(IntPtr absolute)
{
return (IntPtr)((int)ImageBase - (int)absolute);
}
// ── 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 void StructureToByteArray<T>(T value, Span<byte> destination, int size) where T : struct
{
byte[] temp = destination.ToArray();
GCHandle pin = GCHandle.Alloc(temp, GCHandleType.Pinned);
try
{
Marshal.StructureToPtr(value, pin.AddrOfPinnedObject(), false);
temp.CopyTo(destination);
}
finally
{
pin.Free();
}
}
}