Skip to content
Merged
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
18 changes: 18 additions & 0 deletions docs/memory-research.md
Original file line number Diff line number Diff line change
Expand Up @@ -698,3 +698,21 @@ no serialized save offset is used as a runtime pointer.
- This is an explicit persistent counter edit, excluded from presets and trainer
cleanup. It does not call the next-journey routine or reset the world. Gameplay
effects, existing-enemy refresh and persistence need live tests on both runtimes.


## BBSC travel observers

BBSC installs register-snapshot observers at `WarpNextStage_Bonfire`
(`image+0x132E050`, tag 124, seven relocated bytes) and `PlayerWarp.LocalApply`
(`image+0x154B110`, tag 149, six relocated bytes). The hook table and trampoline
generator are shared by official bbport 0.6 and 0.7:
[entry definitions](https://github.com/deadinside28/bloodborne_pc/blob/0.7/gpu/bbnet20/bbsc/core/bloodborne_re.cpp#L682),
[trampoline generator](https://github.com/deadinside28/bloodborne_pc/blob/0.7/gpu/shim/bbport_guest_code_hooks.cpp#L128).

The adapter verifies the complete wrapper, site tag, executable callback,
relocated instructions and exact resume target, then rereads the entry and
wrapper to detect changes during inspection. Travel keeps the BBSC observer
in the call path and repeats validation while game threads are paused before
publishing a request. Coordinate restoration also rechecks map context and the
world-resource manager. Lamp travel and coordinate restoration have been
confirmed working in-game.
55 changes: 55 additions & 0 deletions src/BBTools/Memory/BbportObserverCompatibility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System.IO;
using System.Security.Cryptography;

namespace BBTools.Memory;

// Read-only recognition of the bbport BBSC register-snapshot observer ABI.
// The callback remains in the call path; no runtime instructions are patched.
internal static class BbportObserverCompatibility
{
private const int BodySize=562,TagOffset=298,CallbackOffset=308;
private static readonly byte[] bodyHash=Convert.FromHexString("B424D5496F067920DEE3C5D43C4BDF3505D8E4FF966310626601147EC1BD24BC");
public static bool Matches(IMemory memory,ulong image,ulong offset,byte[] expected,byte[] actual)
{
var (relocated,tag)=offset switch
{
0x132E050=>(7,124u), // BBSC Event.WarpNextStage_Bonfire
0x154B110=>(6,149u), // BBSC PlayerWarp.LocalApply
_=>(0,0u)
};
if(relocated==0||memory is not IExecutableMemory code||expected.Length<relocated||actual[0]!=0xE9)return false;
if(!actual.AsSpan(5,relocated-5).SequenceEqual(Enumerable.Repeat((byte)0x90,relocated-5).ToArray())||
!actual.AsSpan(relocated).SequenceEqual(expected.AsSpan(relocated)))return false;
try
{
var entry=checked(image+offset);
var target=RelativeTarget(checked(entry+5),BitConverter.ToInt32(actual,1));
var size=BodySize+relocated+5;
if(Overlaps(target,size,entry,expected.Length)||!code.IsExecutable(entry,expected.Length)||!code.IsExecutable(target,size))return false;
var stub=memory.Read(target,size);
if(BitConverter.ToUInt32(stub,TagOffset)!=tag)return false;
var callback=BitConverter.ToUInt64(stub,CallbackOffset);
if(Overlaps(callback,1,target,size)||Overlaps(callback,1,entry,expected.Length)||!code.IsExecutable(callback,1))return false;
// All 562 body bytes are fixed except the audited site tag and
// ASLR-dependent callback. This includes flags, MXCSR, every GPR
// and YMM save/restore, stack alignment and the red-zone reserve.
var body=stub.AsSpan(0,BodySize).ToArray();
Array.Clear(body,TagOffset,4);Array.Clear(body,CallbackOffset,8);
if(!SHA256.HashData(body).SequenceEqual(bodyHash)||
!stub.AsSpan(BodySize,relocated).SequenceEqual(expected.AsSpan(0,relocated))||stub[BodySize+relocated]!=0xE9||
RelativeTarget(checked(target+(ulong)size),BitConverter.ToInt32(stub,size-4))!=entry+(ulong)relocated)return false;
if(!memory.Read(entry,expected.Length).SequenceEqual(actual)||!memory.Read(target,size).SequenceEqual(stub))return false;
NativeCodeCompatibility.Diagnostic?.Invoke($"Accepted bbport BBSC observer at image+0x{offset:X}; tag {tag}, wrapper 0x{target:X}, callback 0x{callback:X}. Original entry and observer preserved.");
return true;
}
catch(Exception ex)when(ex is IOException or OverflowException){return false;}
}
private static bool Overlaps(ulong first,int length,ulong second,int otherLength)=>
first<checked(second+(ulong)otherLength)&&second<checked(first+(ulong)length);
private static ulong RelativeTarget(ulong next,int displacement)
{
var value=checked((long)next+displacement);
if(value<0x10000||value>=0x800000000000)throw new IOException("Invalid bbport observer branch target.");
return (ulong)value;
}
}
9 changes: 7 additions & 2 deletions src/BBTools/Memory/GameActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public Task WarpAsync(LampChoice lamp)
new(session.ImageBase + 0x156D110, (ulong)lamp.Entity),
new(session.ImageBase + 0x156D0E0, 1),
new(session.ImageBase + 0x132E050, 0, (ulong)lamp.Entity)
]);
],validate:()=>ValidateActionInstructions(memory,session.ImageBase,GameActionKind.Warp));
}
public Task RestoreLocationAsync(SavedLocation location)
{
Expand All @@ -132,7 +132,12 @@ public Task RestoreLocationAsync(SavedLocation location)
session.ValidateLocationContext(location,current);
var dispatcher = Ready(GameActionKind.RestoreLocation);
var world = memory.Pointer(session.ImageBase + 0x553B148);
return dispatcher.ExecuteAsync([new(session.ImageBase + 0x154B110, world, dispatcher.Payload, dispatcher.Payload + 16, dispatcher.Payload + 32)], payload);
return dispatcher.ExecuteAsync([new(session.ImageBase + 0x154B110, world, dispatcher.Payload, dispatcher.Payload + 16, dispatcher.Payload + 32)], payload,validate:()=>
{
ValidateActionInstructions(memory,session.ImageBase,GameActionKind.RestoreLocation);
session.ValidateLocationContext(location,session.ReadLocation("Current"));
if(memory.Pointer(session.ImageBase+0x553B148)!=world)throw new IOException("World resource manager changed before location publication.");
});
}
public void Dispose() { try { ResetMultipliers(); } finally { queue?.Dispose(); queue = null; } }
}
3 changes: 2 additions & 1 deletion src/BBTools/Memory/GameThreadQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public GameThreadQueue(IGameMemory memory, PlayerSession session)
memory.Write(actor, BitConverter.GetBytes(table));
});
}
public async Task ExecuteAsync(NativeCall[] calls, byte[]? payload = null, Func<byte[]>? preparePayload = null)
public async Task ExecuteAsync(NativeCall[] calls, byte[]? payload = null, Func<byte[]>? preparePayload = null, Action? validate = null)
{
if (disposed || busy) throw new IOException("A game request is already active or the dispatcher is closed.");
if (calls.Length is < 1 or > 3 || calls.Any(x => x.Arguments.Length > 6) || payload?.Length > 512)
Expand All @@ -66,6 +66,7 @@ public async Task ExecuteAsync(NativeCall[] calls, byte[]? payload = null, Func<
if (session.ReadPlayer().Actor != actor || session.ReadCharacter().Address != data || memory.Pointer(actor) != table)
throw new IOException("Player changed. Reconnect before submitting a game request.");
if (memory.Int32(workspace) is 1 or 2) throw new IOException("The previous game request has not finished. It will not be repeated.");
validate?.Invoke();
// Resolve pointer-bearing payloads only after the current actor
// is checked and game threads are paused, immediately before publish.
var prepared = preparePayload?.Invoke() ?? payload;
Expand Down
3 changes: 2 additions & 1 deletion src/BBTools/Memory/NativeCodeCompatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace BBTools.Memory;

// Read-only recognition of the documented Nightwatch/visy observer ABI.
// Read-only recognition of audited bbport BBSC and Nightwatch/visy observer ABIs.
// No detour is removed, rewritten, skipped or cached. This verifies a wrapper
// shape, not the identity or correctness of the native callback's publisher.
public static class NativeCodeCompatibility
Expand All @@ -20,6 +20,7 @@ public static bool Matches(IMemory memory, ulong image, ulong offset, byte[] exp
{
var actual = memory.Read(image + offset, expected.Length);
if (actual.SequenceEqual(expected)) return true;
if(BbportObserverCompatibility.Matches(memory,image,offset,expected,actual))return true;
// Exact audited entry sites only. Replacement wrappers and other entry
// points are deliberately excluded even if they begin with E9.
if (offset is not (0x17D89F0 or 0x1BB7F60) || memory is not IExecutableMemory code || expected.Length < 13) return false;
Expand Down
76 changes: 76 additions & 0 deletions tests/BBTools.LinuxChecks/BbportCompatibilityChecks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using BBTools.Memory;

internal static class BbportCompatibilityChecks
{
// Independent register-snapshot ABI fixture, audited against the emitted
// bbport trampoline. Tag and callback immediates are populated per case.
private const string BodyHex=
"488DA424E0FCFFFF4C899C24900200009C415B4C899C24980200004989E34883E4F04889042448895C240848894C24104889542418488974242048897C242848896C24304C894424404C894C24484C895424504C896424604C896C24684C897424704C897C2478"+
"498B83900200004889442458498B83980200004889842480000000498D832003000048894424380FAE9C2488000000"+
"C5FE7F842490000000C5FE7F8C24B0000000C5FE7F9424D0000000C5FE7F9C24F0000000C5FE7FA42410010000C5FE7FAC2430010000C5FE7FB42450010000C5FE7FBC2470010000"+
"C57E7F842490010000C57E7F8C24B0010000C57E7F9424D0010000C57E7F9C24F0010000C57E7FA42410020000C57E7FAC2430020000C57E7FB42450020000C57E7FBC2470020000"+
"4989E4BF00000000498D342448B80000000000000000FFD04C89E4"+
"C5FE6F842490000000C5FE6F8C24B0000000C5FE6F9424D0000000C5FE6F9C24F0000000C5FE6FA42410010000C5FE6FAC2430010000C5FE6FB42450010000C5FE6FBC2470010000"+
"C57E6F842490010000C57E6F8C24B0010000C57E6F9424D0010000C57E6F9C24F0010000C57E6FA42410020000C57E6FAC2430020000C57E6FB42450020000C57E6FBC2470020000"+
"0FAE942488000000488B5C2408488B4C2410488B542418488B742420488B7C2428488B6C24304C8B4424404C8B4C24484C8B5424504C8B5C24584C8B6424604C8B6C24684C8B7424704C8B7C2478488B842480000000509D488B0424488B642438";
private sealed class CodeMemory : IExecutableMemory
{
public readonly Dictionary<ulong,byte[]> Blocks=[];
public readonly HashSet<ulong> NonExecutable=[];
public Action<ulong>? BeforeRead;
public byte[] Read(ulong at,int size)
{
BeforeRead?.Invoke(at);
foreach(var (start,bytes) in Blocks)
if(at>=start&&at-start<=(ulong)bytes.Length&&(ulong)size<=(ulong)bytes.Length-(at-start))return bytes.AsSpan((int)(at-start),size).ToArray();
throw new IOException("Unmapped fixture memory.");
}
public void Write(ulong at,byte[] bytes)=>throw new Exception("Observer checks must never write.");
public bool IsExecutable(ulong at,int size)=>Blocks.Any(p=>!NonExecutable.Contains(p.Key)&&at>=p.Key&&at-p.Key<=(ulong)p.Value.Length&&(ulong)size<=(ulong)p.Value.Length-(at-p.Key));
}
public static void Run(Action<bool,string> check)
{
const ulong image=0x800000000,stub=image-0x10000,callback=0x7F1000001000;
foreach(var (offset,relocated,tag,kind) in new[]{(0x132E050UL,7,124u,GameActionKind.Warp),(0x154B110UL,6,149u,GameActionKind.RestoreLocation)})
{
var memory=new CodeMemory();
foreach(var f in GameActions.Fingerprints)memory.Blocks[image+f.Offset]=f.Bytes.ToArray();
memory.Blocks[callback]=[0xC3];
var expected=GameActions.Fingerprints.Single(f=>f.Offset==offset).Bytes;
var entry=image+offset;
var body=Convert.FromHexString(BodyHex);
BitConverter.GetBytes(tag).CopyTo(body,298);BitConverter.GetBytes(callback).CopyTo(body,308);
var wrapper=body.Concat(expected.Take(relocated)).Concat(new byte[]{0xE9}).Concat(BitConverter.GetBytes(checked((int)((long)(entry+(ulong)relocated)-(long)(stub+(ulong)body.Length+(ulong)relocated+5))))).ToArray();
var patched=expected.ToArray();patched[0]=0xE9;BitConverter.GetBytes(checked((int)((long)stub-(long)(entry+5)))).CopyTo(patched,1);Array.Fill(patched,(byte)0x90,5,relocated-5);
memory.Blocks[entry]=patched;memory.Blocks[stub]=wrapper;
bool Matches()=>NativeCodeCompatibility.Matches(memory,image,offset,expected);
check(Matches(),$"BBSC {kind} observer validates its exact wrapper, tag, original prologue and return address");
GameActions.ValidateActionInstructions(memory,image,kind);
check(true,$"BBSC {kind} passes the complete action profile without writing instructions");
var fixedBytesRejected=true;
for(var i=0;i<body.Length;i++)
{
if(i>=308&&i<316)continue;
memory.Blocks[stub]=wrapper.ToArray();memory.Blocks[stub][i]^=1;
fixedBytesRejected&=!Matches();
}
check(fixedBytesRejected,$"BBSC {kind} rejects every altered fixed register-preservation byte and site tag");
memory.Blocks[stub]=wrapper.ToArray();memory.Blocks[stub][body.Length]^=1;
check(!Matches(),$"BBSC {kind} rejects changed relocated guest instructions");
memory.Blocks[stub]=wrapper.ToArray();memory.Blocks[stub][^1]^=1;
check(!Matches(),$"BBSC {kind} rejects an incorrect resume target");
memory.Blocks[stub]=wrapper.ToArray();memory.NonExecutable.Add(stub);
check(!Matches(),$"BBSC {kind} rejects non-executable wrappers");
memory.NonExecutable.Clear();memory.NonExecutable.Add(callback);
check(!Matches(),$"BBSC {kind} rejects non-executable callbacks");
memory.NonExecutable.Clear();memory.Blocks[entry]=patched.ToArray();memory.Blocks[entry][5]^=1;
check(!Matches(),$"BBSC {kind} rejects unknown entry padding");
memory.Blocks[entry]=patched.ToArray();var reads=0;
memory.BeforeRead=at=>{if(at==entry&&++reads==2)memory.Blocks[entry][1]^=1;};
check(!Matches(),$"BBSC {kind} rejects code changed during validation");
memory.BeforeRead=null;memory.Blocks[entry]=patched.ToArray();
BitConverter.GetBytes(stub).CopyTo(memory.Blocks[stub],308);
check(!Matches(),$"BBSC {kind} rejects callbacks into its own wrapper");
}
}
}
11 changes: 10 additions & 1 deletion tests/BBTools.LinuxChecks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public static async Task<int> Main(string[] args)
Check(!launch.UseShellExecute&&launch.ArgumentList.Count==3&&launch.ArgumentList[1]=="a path with spaces"&&launch.ArgumentList[2]=="$(not-a-command)","launcher arguments are separate literal values and never interpreted as shell code");
Reject<ArgumentException>(()=>LinuxProcessCatalog.CreateStartInfo("relative-file","[]"),"launcher rejects relative executable paths");
}finally{File.Delete(launchFile);}
BbportCompatibilityChecks.Run(Check);
var fixture=new SparseMemory();const ulong image=0x40000000;
foreach(var f in PlayerSession.Fingerprints)fixture.Store(image+f.Offset,f.Bytes);
var anchor=PlayerSession.Fingerprints[0];
Expand Down Expand Up @@ -102,6 +103,12 @@ private static async Task NativeChecks()
Check(memory.IsExecutable(remoteCode,1)&&memory.Read(remoteCode,1)[0]==0xC3,"remote mmap/mprotect finalizes a read/execute dispatcher page");
Reject<IOException>(()=>memory.Write(remoteCode,[0xCC]),"ordinary writes cannot alter finalized native code pages");
var guest=ulong.Parse(locations[1],NumberStyles.HexNumber,CultureInfo.InvariantCulture);
using(var queue=new GameThreadQueue(memory,new PlayerSession(memory,guest)))
{
var validations=0;
Reject<IOException>(()=>queue.ExecuteAsync([new NativeCall(guest+0x132E050)],validate:()=>{validations++;throw new IOException("Changed observer fixture.");}).GetAwaiter().GetResult(),"native publication rejects changed travel instructions while suspended");
Check(validations==1&&memory.Int32(queue.Payload-GameThreadQueue.PayloadOffset)==0,"failed travel validation cannot publish a ready request");
}
var original=MovementSpeed.Original;var changed=Enumerable.Repeat((byte)0x90,original.Length).ToArray();
memory.ReplaceMovementCode(guest,original,changed);
Check(memory.IsExecutable(guest+MovementSpeed.Offset,original.Length)&&memory.Read(guest+MovementSpeed.Offset,original.Length).SequenceEqual(changed),"guarded Linux patch writes across native words without changing executable protection");
Expand Down Expand Up @@ -180,7 +187,9 @@ private static nint CreateGameFixture()
Ptr(PlayerSession.WorldPointer,world);Ptr(world+0x60,actor);Ptr(actor+0x3B0,modules);Ptr(modules+0x20,stats);Ptr(stats+8,actor);Ptr(actor+0x3C0,data);Ptr(0x553B130,manager);Ptr(manager+8,data);
Int(actor+8,123);Int(stats+0xF8,100);Int(stats+0xFC,200);Int(stats+0x134,70);Int(stats+0x138,100);Put(stats+0x200,[0x10]);
foreach(var offset in new ulong[]{0x40,0x48,0x58,0x60,0x68,0x70})Int(data+offset,10);Int(data+0x90,10);Int(data+0x94,1200);
var instructions=PlayerSession.Fingerprints.Concat(PlayerSession.FeatureFingerprints).Append((Offset:MovementSpeed.Offset,Bytes:MovementSpeed.Original)).ToArray();
Ptr(actor,0x5760000);
for(ulong slot=0;slot<0x1D0;slot+=8)Ptr(0x5760000+slot,0x18FD960);
var instructions=PlayerSession.Fingerprints.Concat(PlayerSession.FeatureFingerprints).Concat(GameActions.Fingerprints).Append((Offset:MovementSpeed.Offset,Bytes:MovementSpeed.Original)).ToArray();
foreach(var f in instructions)Put(f.Offset,f.Bytes);
foreach(var page in instructions.Select(f=>f.Offset&~4095UL).Distinct())
if(mprotect(root+(nint)page,4096,5)!=0)throw new IOException("Synthetic code protection failed");
Expand Down