Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/AzimuthRPC.App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private void OnRuntimeChanged(DebugStatus status)
? $"PID={status.ProcessId}; UiMode={status.Game.UiMode}; Activity={status.Game.Activity}; " +
$"HooksInstalled={status.Game.Hooks.Installed}; TelemetryActive={status.Game.Hooks.Active}; " +
$"EventContext={status.Game.Hooks.EventContext?.ToString() ?? "none"}; " +
$"CarProbe={status.Game.CarProbeStatus}; CarId={status.Game.Car.RawId ?? "none"}"
$"CarProbe={status.Game.CarProbeStatus}; CarRetry={status.Game.CarRetryStatus}; CarId={status.Game.Car.RawId ?? "none"}"
: $"PID={status.ProcessId}; Game not attached; Reason={status.Game.Error ?? "unknown"}";

if (diagnostics != _lastDiagnosticContext)
Expand Down
105 changes: 90 additions & 15 deletions src/AzimuthRPC.Core/Game/GameSnapshotReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,31 @@ public GameSnapshotReader(IMemoryReader memory, ILocationResolver? locationResol
}

public GameSnapshot Capture(ulong gameBase, bool supportedBuild)
{
GameSnapshot initial = CaptureOnce(gameBase, supportedBuild);
if (!initial.Attached || initial.Car.RawId is not null || !ShouldRetryCarProbe(initial.CarProbeStatus))
return initial;

// Re-evaluate roots, AudioEngine and the car field from scratch once.
// Never reuse a stale car when a garage/race transition interrupts a read.
GameSnapshot retried = CaptureOnce(gameBase, supportedBuild);
if (!retried.Attached)
return retried;

return retried with
{
CarRetryStatus = retried.Car.RawId is null
? $"failed:{initial.CarProbeStatus}->{retried.CarProbeStatus}"
: $"recovered:{initial.CarProbeStatus}->{retried.CarProbeStatus}"
};
}

private static bool ShouldRetryCarProbe(string probeStatus) => probeStatus is
"invalid-character" or "unterminated" or "too-short" or "missing-underscore"
or "heap-invalid-pointer" or "heap-unreadable" or "heap-changed"
or "heap-unterminated" or "heap-invalid-id" or "inline-changed";

private GameSnapshot CaptureOnce(ulong gameBase, bool supportedBuild)
{
if (!supportedBuild) return GameSnapshot.Unavailable("Unsupported FH2 PE identity");
if (!MemoryRead.Pointer(gameBase)) return GameSnapshot.Unavailable("Invalid game base");
Expand All @@ -29,7 +54,7 @@ public GameSnapshot Capture(ulong gameBase, bool supportedBuild)
var raw = frame.Read(audio, 0x2C0);
if (raw is null) return GameSnapshot.Unavailable("Audio/vehicle snapshot read failed");
var ui = UiModeReader.ReadSnapshot(gameBase, true, frame.Read);
string? car = ReadCar(raw.AsSpan(0x278, 64), out string carProbeStatus);
string? car = ReadCar(raw.AsSpan(0x278, 64), checked(audio + 0x278), frame, out string carProbeStatus);
if (car != _lastCarId) { _lastCarId = car; _displayName = FriendlyCarName(car); }
float mph = F32(raw, 0x90);
float? speed = float.IsFinite(mph) && mph >= 0 && mph <= 400 ? mph : null;
Expand Down Expand Up @@ -67,8 +92,51 @@ private static WorldPresence VehiclePresence(UiMode mode, string? car, VehicleSt
float x = F32(data, offset), y = F32(data, offset + 4), z = F32(data, offset + 8);
return float.IsFinite(x) && float.IsFinite(y) && float.IsFinite(z) && MathF.Abs(x) <= bound && MathF.Abs(y) <= bound && MathF.Abs(z) <= bound ? new Vector3(x, y, z) : null;
}
private static string? ReadCar(ReadOnlySpan<byte> bytes, out string status)
private static string? ReadCar(ReadOnlySpan<byte> bytes, ulong fieldAddress, PointerSnapshot frame, out string status)
{
// Candidate MSVC std::string (32-byte object): 16-byte buffer/pointer,
// followed by 64-bit size and capacity. Short IDs remain inline.
// This is a guarded fallback, not yet a live-validated FH2 layout.
ulong length = BinaryPrimitives.ReadUInt64LittleEndian(bytes[16..]);
ulong capacity = BinaryPrimitives.ReadUInt64LittleEndian(bytes[24..]);
if (length is >= 16 and <= 127 && capacity >= length && capacity <= 4096)
{
ulong pointer = BinaryPrimitives.ReadUInt64LittleEndian(bytes);
if (!MemoryRead.Pointer(pointer))
{
status = "heap-invalid-pointer";
return null;
}

byte[]? first = frame.Read(pointer, (int)length + 1);
byte[]? second = frame.Read(pointer, (int)length + 1);
byte[]? currentField = frame.Read(fieldAddress, 32);
if (first is null || second is null)
{
status = "heap-unreadable";
return null;
}
if (!first.AsSpan().SequenceEqual(second) || currentField is null ||
!bytes[..32].SequenceEqual(currentField))
{
status = "heap-changed";
return null;
}
if (first[(int)length] != 0)
{
status = "heap-unterminated";
return null;
}
if (!ValidCarId(first.AsSpan(0, (int)length)))
{
status = "heap-invalid-id";
return null;
}

status = "ok-heap";
return Encoding.ASCII.GetString(first, 0, (int)length);
}

int end = bytes.IndexOf((byte)0);
if (end < 0 || end > 63)
{
Expand All @@ -85,26 +153,33 @@ private static WorldPresence VehiclePresence(UiMode mode, string? car, VehicleSt
status = "too-short";
return null;
}
for (int i = 0; i < end; i++)
if (!ValidCarId(bytes[..end]))
{
byte b = bytes[i];
if (!((b >= 'A' && b <= 'Z') ||
(b >= 'a' && b <= 'z') ||
(b >= '0' && b <= '9') || b == '_'))
{
status = "invalid-character";
return null;
}
status = "invalid-character";
return null;
}

string value = Encoding.ASCII.GetString(bytes[..end]);
if (!value.Contains('_'))
// The inline identifier can change after the bulk AudioEngine read.
// Reject torn snapshots instead of attributing an old ID to a new car.
byte[]? currentInline = frame.Read(fieldAddress, 32);
if (currentInline is null || !bytes[..32].SequenceEqual(currentInline))
{
status = "missing-underscore";
status = "inline-changed";
return null;
}
status = "ok";
return value;
return Encoding.ASCII.GetString(bytes[..end]);
}

private static bool ValidCarId(ReadOnlySpan<byte> bytes)
{
if (bytes.Length < 5 || !bytes.Contains((byte)'_')) return false;
foreach (byte b in bytes)
if (!((b >= 'A' && b <= 'Z') ||
(b >= 'a' && b <= 'z') ||
(b >= '0' && b <= '9') || b == '_'))
return false;
return true;
}
private static string? FriendlyCarName(string? raw)
{
Expand Down
2 changes: 2 additions & 0 deletions src/AzimuthRPC.Core/Models/GameSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public sealed record GameSnapshot
public CarState Car { get; init; } = new();
// Diagnostic only: classification of the car ID field, no raw heap bytes.
public string CarProbeStatus { get; init; } = "Not sampled";
// Standalone: shows whether a fresh one-shot probe recovered a transient ID.
public string CarRetryStatus { get; init; } = "not-needed";
public VehicleState Vehicle { get; init; } = new();
public UiMode UiMode { get; init; }
public GameActivity Activity { get; init; }
Expand Down
128 changes: 128 additions & 0 deletions tests/AzimuthRPC.Core.Tests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Globalization;
using System.Numerics;
using System.Text.Json;
using System.Text;
using AzimuthRPC;
using AzimuthRPC.Tests;

Expand Down Expand Up @@ -63,6 +64,133 @@ var s when s.StartsWith("worldmap_") => UiMode.WorldMap,
Check(!reader.Capture(gameBase, true).Attached, "Changing root published a mixed snapshot");
});
}
Test("Car IDs survive heap string / inline changes and never reuse stale IDs", () =>
{
var memory = new FixtureMemory();
var fixture = captures.First(c => c.Label == "free-roam-stopped");
foreach (var block in fixture.Memory()) memory.Blocks.Add(block.Key, block.Value);
var audio = memory.Blocks[SyntheticFixture.Audio];
var reader = new GameSnapshotReader(memory);
const ulong heapA = 0x7500000000, heapB = 0x7600000000;

void PutHeap(string id, ulong address)
{
Check(id.Length >= 16 && id.Length <= 127);
audio.AsSpan(0x278, 64).Clear();
BinaryPrimitives.WriteUInt64LittleEndian(audio.AsSpan(0x278), address);
BinaryPrimitives.WriteUInt64LittleEndian(audio.AsSpan(0x288), (ulong)id.Length);
BinaryPrimitives.WriteUInt64LittleEndian(audio.AsSpan(0x290), (ulong)Math.Max(31, id.Length));
memory.Blocks[address] = Encoding.ASCII.GetBytes(id + "\0");
}
void PutShort(string id)
{
Check(id.Length >= 5 && id.Length <= 15);
audio.AsSpan(0x278, 64).Clear();
Encoding.ASCII.GetBytes(id + "\0").CopyTo(audio, 0x278);
BinaryPrimitives.WriteUInt64LittleEndian(audio.AsSpan(0x288), (ulong)id.Length);
BinaryPrimitives.WriteUInt64LittleEndian(audio.AsSpan(0x290), 15);
}

PutHeap("HON_CivicTypeR_2015", heapA);
var first = reader.Capture(SyntheticFixture.GameBase, true);
Check(first.Car.RawId == "HON_CivicTypeR_2015" && first.CarProbeStatus == "ok-heap",
"Long MSVC string should resolve via guarded heap pointer");

PutHeap("BMW_M3Coupe_2010", heapB);
var switched = reader.Capture(SyntheticFixture.GameBase, true);
Check(switched.Car.RawId == "BMW_M3Coupe_2010" && switched.CarProbeStatus == "ok-heap",
"Second long car should replace first");

PutShort("TOY_SupraRZ_98");
var shortCar = reader.Capture(SyntheticFixture.GameBase, true);
Check(shortCar.Car.RawId == "TOY_SupraRZ_98" && shortCar.CarProbeStatus == "ok",
"Short car should switch back to inline encoding");

PutHeap("HON_CivicTypeR_2015", heapA);
memory.Blocks.Remove(heapA);
var unreadable = reader.Capture(SyntheticFixture.GameBase, true);
Check(unreadable.Attached && unreadable.Car.RawId is null && unreadable.CarProbeStatus == "heap-unreadable",
"Unreadable heap must not reuse a previous valid car");

PutHeap("HON_CivicTypeR_2015", heapA);
memory.Blocks[heapA][0] = (byte)'!';
var malformed = reader.Capture(SyntheticFixture.GameBase, true);
Check(malformed.Car.RawId is null && malformed.CarProbeStatus == "heap-invalid-id",
"Malformed pointer payload must be rejected");

PutHeap("HON_CivicTypeR_2015", heapA);
int heapReads = 0;
memory.BeforeRead = (address, size) =>
{
if (address == heapA && ++heapReads == 2)
memory.Blocks[heapA][0] = (byte)'!';
};
var racing = reader.Capture(SyntheticFixture.GameBase, true);
Check(racing.Car.RawId is null && racing.CarProbeStatus == "heap-invalid-id" &&
racing.CarRetryStatus == "failed:heap-changed->heap-invalid-id",
"A changed heap that becomes invalid must fail closed after retry");
});

Test("Invalid car ID is retried exactly once using a new full snapshot", () =>
{
var memory = new FixtureMemory();
var fixture = captures.First(c => c.Label == "free-roam-stopped");
foreach (var block in fixture.Memory()) memory.Blocks.Add(block.Key, block.Value);
var audio = memory.Blocks[SyntheticFixture.Audio];
var reader = new GameSnapshotReader(memory);
void WriteCar(string id)
{
audio.AsSpan(0x278, 64).Clear();
Encoding.ASCII.GetBytes(id + "\0").CopyTo(audio, 0x278);
}

WriteCar("BAD!_model_2026");
int rawReads = 0;
memory.BeforeRead = (address, size) =>
{
if (address == SyntheticFixture.Audio && size == 0x2C0 && ++rawReads == 2)
WriteCar("TOY_SupraRZ_98");
};
var recovered = reader.Capture(SyntheticFixture.GameBase, true);
Check(rawReads == 2, "Expected exactly one fresh retry for invalid-character");
Check(recovered.Car.RawId == "TOY_SupraRZ_98" && recovered.CarProbeStatus == "ok");
Check(recovered.CarRetryStatus == "recovered:invalid-character->ok");

WriteCar("BAD!_model_2026");
rawReads = 0;
memory.BeforeRead = (address, size) =>
{
if (address == SyntheticFixture.Audio && size == 0x2C0) rawReads++;
};
var rejected = reader.Capture(SyntheticFixture.GameBase, true);
Check(rawReads == 2, "Persistent invalid ID must not cause unbounded rescanning");
Check(rejected.Attached && rejected.Car.RawId is null && rejected.Car.DisplayName is null);
Check(rejected.CarProbeStatus == "invalid-character");
Check(rejected.CarRetryStatus == "failed:invalid-character->invalid-character");
});

Test("Changing an inline car during sampling recovers without a stale result", () =>
{
var memory = new FixtureMemory();
var fixture = captures.First(c => c.Label == "free-roam-stopped");
foreach (var block in fixture.Memory()) memory.Blocks.Add(block.Key, block.Value);
var audio = memory.Blocks[SyntheticFixture.Audio];
var reader = new GameSnapshotReader(memory);
audio.AsSpan(0x278, 64).Clear();
Encoding.ASCII.GetBytes("TOY_SupraRZ_98\0").CopyTo(audio, 0x278);
int fieldReads = 0;
memory.BeforeRead = (address, size) =>
{
if (address != SyntheticFixture.Audio + 0x278 || size != 32 || ++fieldReads != 1) return;
audio.AsSpan(0x278, 64).Clear();
Encoding.ASCII.GetBytes("LAM_Huracan_15\0").CopyTo(audio, 0x278);
};
var recovered = reader.Capture(SyntheticFixture.GameBase, true);
Check(fieldReads == 2, "Second car read should use a fresh memory snapshot");
Check(recovered.Car.RawId == "LAM_Huracan_15");
Check(recovered.CarRetryStatus == "recovered:inline-changed->ok");
});

Test("Unsupported and overflowing bases fail without reads", () =>
{
using var memory = new FixtureMemory(); var reader = new GameSnapshotReader(memory);
Expand Down
Loading