#if PLUGIN_SESSION_RECOVERY using System.Text; namespace XFEEDToolBox.Plugin; // A separately hashed SDK extension: observes the existing application/menu // callbacks and may select one enabled, original return-to-menu item. No ship // axes, credentials, direct FSM writes, OS input, or process termination. internal static unsafe partial class SessionRecoveryRuntime { private const nuint ContextUpdate=0x21697F0,MenuPoll=0x488AC60,MapperThunk=0x8D60D0,FlowAction=0x1D65500,PauseSelect=0x4838B50; private const string Service="SessionRecovery0514k"; private static nuint image,end,originalContext,originalMenu,originalMapper; private static uint expectedThread; private static bool started,enabled; private static readonly object init=new(),gate=new(); private struct Root {public nuint flow,csm;public ulong tick,utc,sequence;public uint thread;public string? state,next;public bool valid;} private sealed class Menu { public nuint address,flow,selector,definition,cache; public ulong tick,utc,sequence;public uint thread,index,categories,count;public ulong cacheCount,cacheCapacity,raw140; public byte kind;public float countdown;public string reason="not-observed",categoryName=""; public bool ready;public string[] names=[];public bool[] allowed=[]; } private struct Work {public string? id,action;public ulong expires,sequence;public bool pending,applied,failed;} private static Root root; private static Menu menu=new(); private static Work work; private static ulong contextCalls,menuCalls,menuMatches,menuReadErrors,mapperCalls; private static string? lastMenuIssue; private static readonly Dictionary mapperNodes=new(); private static bool InImage(nuint at)=>at>=image&&at bytes)=>ReadBytes(image+at,bytes.Length).AsSpan().SequenceEqual(bytes); private static string Name(nuint address) { Span bytes=stackalloc byte[128]; for(var n=0;n(address+(nuint)n);if(c==0)return Encoding.ASCII.GetString(bytes[..n]);if(c<32||c>126)throw new InvalidOperationException("Original menu name is not bounded ASCII");bytes[n]=c;} throw new InvalidOperationException("Original menu name exceeds bound"); } private static bool ReturnToMenu(string name)=>name=="Confirmed Quit To Main Menu"; private static bool SafeCategory(Menu m)=>m.categoryName=="Pause"&&m.kind==1||m.categoryName=="ExitOptions"&&m.kind==2; private static bool AllowedAction(Menu m,string name)=>m.categoryName=="Pause"&&m.kind==1&&name=="ExitOptions" ||m.categoryName=="ExitOptions"&&m.kind==2&&ReturnToMenu(name); private static bool ValidCache(uint count,ulong used,ulong capacity)=>count is >0 and <=64&&used==count&&capacity>=used&&capacity<=4096; private static bool Fresh(ulong at,ulong now)=>at!=0&&now>=at&&now-at<=200; private static bool MayDispatch(Root r,Menu m,Work w,ulong now,uint thread) =>enabled&&r.valid&&r.thread==expectedThread&&SafeCategory(m)&&r.state==m.categoryName&&r.next==r.state&&Fresh(r.tick,now)&&m.ready&&Fresh(m.tick,now) &&r.flow==m.flow&&thread==m.thread&&thread==expectedThread&&w.pending&&w.expires>now&&w.sequence<=m.sequence; private static void CaptureRoot(nuint context) { if(!enabled)return; Root next=new(){thread=GetCurrentThreadId(),tick=GetTickCount64(),utc=Utc()}; var flow=Pointer(context+0xA0);var table=Pointer(flow); if(!InImage(table)||Pointer(table+0x20)!=image+FlowAction)return; var csm=Pointer(flow+0x310);if(Pointer(csm)!=image+0x513BE00)return; next.flow=flow;next.csm=csm;next.state=Name(Pointer(Pointer(csm+0x100)));next.next=Name(Pointer(Pointer(csm+0x108)));next.valid=true; lock(gate){next.sequence=root.sequence+1;root=next;} } private static Menu CaptureMenu(nuint activity) { var result=new Menu{address=activity,thread=GetCurrentThreadId(),tick=GetTickCount64(),utc=Utc()}; var table=Pointer(activity+0x80);if(!InImage(table)||Pointer(table+8)!=image+PauseSelect)return result; result.selector=Pointer(table+8);result.flow=Pointer(activity+0xC8); result.definition=Pointer(activity+0x10);result.index=Read(activity+0x108); result.categories=Read(result.definition+0x10);result.countdown=Read(activity+0x164); // Original 47E7660/47F4760 append and 47FA930 erase use header+0x10 // as live row count; header is activity+0x138. +0x140 is not count. result.cache=Pointer(activity+0x150);result.cacheCount=Read(activity+0x148); result.cacheCapacity=Read(activity+0x138);result.raw140=Read(activity+0x140); result.reason="category-bound"; if(result.categories is 0 or >128||result.index>=result.categories)return result; var category=Pointer(result.definition+8)+result.index*0x58; result.kind=Read(category);result.categoryName=Name(Pointer(Pointer(category+8))); result.count=Read(category+0x48);var buttons=Pointer(category+0x40); result.reason="button-bound"; if(result.kind is <1 or >3||result.count>64||!float.IsFinite(result.countdown))return result; result.names=new string[result.count];result.allowed=new bool[result.count]; var exact=ValidCache(result.count,result.cacheCount,result.cacheCapacity)&&result.cache>=0x10000; for(uint i=0;i(original+offset)!=Read(cached+0x30+offset)){same=false;break;} exact&=same;result.allowed[i]=same&&Read(cached)==0x0101&&result.countdown<=0; } Root current;lock(gate)current=root; result.reason=!exact?"cache-definition-mismatch":current.flow!=result.flow?"flow-owner-mismatch" :!SafeCategory(result)||current.state!=result.categoryName||current.next!=current.state?"not-stable-recovery-menu":result.thread!=expectedThread?"menu-thread-differs":"ready"; result.ready=exact&¤t.valid&&Fresh(current.tick,result.tick)&¤t.flow==result.flow&&SafeCategory(result) &¤t.state==result.categoryName&¤t.next==current.state&&result.thread==expectedThread; return result; } private static void CaptureAndDispatch(nuint activity) { if(!enabled)return; var observed=CaptureMenu(activity);if(observed.selector==0)return; Root r;Work wanted; lock(gate){observed.sequence=menu.sequence+1;menu=observed;menuMatches++;r=root;wanted=work;} PollTradePauseResume(activity,observed,r); var now=GetTickCount64(); if(!MayDispatch(r,observed,wanted,now,GetCurrentThreadId()))return; var index=-1; for(var n=0;n(text); if(length is 0 or >64)return null;var bytes=ReadBytes(text+0x14,(int)length); if(bytes.Any(value=>value<32||value>126))return null;return Encoding.ASCII.GetString(bytes); } [UnmanagedCallersOnly]private static ulong MapperHook(nuint node,float dt) { ResetWork? resetting=null; try{resetting=BeginOriginalReset(node,dt);}catch(Exception error){FailOriginalReset(error.Message);} Navigation.RecoveryThrottlePulse trial=default; try{trial=BeginFlightThrottleTrial(node,dt);}catch{} float? before=null;try{if(enabled)before=Read(node+0xD0);}catch{} ulong result;try{result=Call(originalMapper,(ulong)node,F32(dt));}catch{FailOriginalReset("Original mapper call failed");return 0;} finally{try{EndFlightThrottleTrial(trial);}catch{}} try{FinishOriginalReset(resetting,node);}catch(Exception error){FailOriginalReset(error.Message);} try{ObserveFlightThrottleTrial(node);}catch{} try{ObserveFlightContextAfterMapper(node);}catch{} try { if(!enabled)return result;mapperCalls++; var table=Pointer(node);var expected=table==image+0x512E330;var now=GetTickCount64(); var row=Obj(("node",node.ToString("x")),("vtableRva",InImage(table)?(table-image).ToString("x"):null), ("expectedType",expected),("thread",GetCurrentThreadId()),("tick",now),("observedAtUnixMilliseconds",Utc()),("dt",float.IsFinite(dt)?(float?)dt:null)); if(expected) { var source=Pointer(node+0x78);var zero=Pointer(node+0xB8);var absolute=Pointer(node+0xB0);var active=Pointer(node+0x90); var after=Read(node+0xD0);var sourceValue=source>=0x10000?Read(source+0x18):float.NaN; row["registry"]=Pointer(node+0x40).ToString("x");row["source"]=source.ToString("x");row["zero"]=zero.ToString("x");row["absolute"]=absolute.ToString("x"); row["zeroName"]=BindingName(zero);row["absoluteName"]=BindingName(absolute);row["sourceName"]=BindingName(source); row["activeBinding"]=active.ToString("x");row["activeFlag"]=active>=0x10000?Read(active+0x24):0; row["accumulatorBefore"]=before is {} b&&float.IsFinite(b)?b:null;row["accumulatorAfter"]=float.IsFinite(after)?after:null; row["sourceAfter"]=float.IsFinite(sourceValue)?sourceValue:null; } lock(gate){if(mapperNodes.Count>=64&&!mapperNodes.ContainsKey(node))mapperNodes.Remove(mapperNodes.Keys.First());mapperNodes[node]=row;} } catch{} return result; } private static JsonObject Description() { Root r;Menu m;Work w;JsonArray nodes; lock(gate){r=root;m=menu;w=work;nodes=new JsonArray(mapperNodes.Values.Select(value=>(JsonNode)value.DeepClone()).ToArray());} var actions=new JsonArray(); for(var i=0;iGetTickCount64()), ("applied",w.applied),("failed",w.failed||w.pending&&w.expires<=GetTickCount64()),("gameAxesWritten",false),("authFieldsWritten",false),("osInputSent",false)); } private static JsonNode Handle(JsonElement request) { var op=request.Str("op"); if(op is "trade.pause.renew" or "trade.pause.resume" or "trade.pause.end")return TradePauseRequest(op,request); if(op is "flight.context.arm" or "flight.context.renew" or "flight.context.release" or "flight.context.status" or "flight.context.seed")return FlightContextRequest(op,request); if(op=="docking.reset.probe")return ResetBridgeProbe(); if(op is "docking.reset.arm" or "docking.reset.status" or "docking.reset.cancel")return ResetRequest(op,request); if(op is "describe" or "read")return Description(); if(op=="deactivate") { CancelTradePauseScope(); if(!PrepareFlightContextDeactivate())return Description(); lock(gate){enabled=false;work.pending=false;} CancelOriginalReset(); HookDisable(image+MapperThunk);HookDisable(image+MenuPoll);HookDisable(image+ContextUpdate);HookDisable(image+RegistryDestroy); // Keep pinned code and trampolines alive for in-flight callbacks. return Description(); } if(op!="session.recovery.leave")throw new InvalidOperationException("Unsupported purpose-built session recovery operation"); if(!PrepareFlightContextDeactivate())throw new InvalidOperationException("Original Flight scope must be released before a menu action is queued"); var id=request.Str("requestId");var action=request.Str("action");var ttl=request.Int("ttlMilliseconds");var expected=request.U64("menuSequence"); if(id.Length!=32||id.Any(c=>!char.IsAsciiHexDigit(c))||action is not("ExitOptions" or "Confirmed Quit To Main Menu")||ttl is <1 or >250)throw new InvalidOperationException("Bounded original return-to-menu request required"); lock(gate) { if(work.id==id)return Description(); var now=GetTickCount64();if(!enabled||work.pending&&work.expires>now||!menu.ready||!Fresh(menu.tick,now)||!Fresh(root.tick,now) ||!SafeCategory(menu)||root.state!=menu.categoryName||root.next!=root.state||!AllowedAction(menu,action) ||expected==0||expected>menu.sequence||menu.sequence-expected>32||!menu.names.Where((name,index)=>name==action&&menu.allowed[index]).Any())throw new InvalidOperationException("Original pause menu is not ready for this action"); work=new(){id=id,action=action,sequence=expected,expires=Math.Min(now+(ulong)ttl,menu.tick+250),pending=true}; } return Description(); } internal static uint Start(nuint thread) { lock(init) { if(started)return expectedThread==thread?1u:0u; if(thread is 0 or >uint.MaxValue||ImageHash(ModulePath())!=GameHash)return 0; image=ImageBase;end=ImageEnd;expectedThread=(uint)thread; Navigation.ConfigureRecoveryReadOnlyImage(); if(!Prefix(ContextUpdate,[0x40,0x55,0x53,0x56,0x57,0x41,0x54,0x41,0x56,0x41,0x57]))return 0; if(!Prefix(MenuPoll,[0x4C,0x8B,0xDC,0x49,0x89,0x4B,0x08,0x55,0x41,0x55])||!Prefix(MapperThunk,[0xE9,0x2B,0xD4,0x01,0x00]))return 0; if(!Prefix(RegistryDestroy,[0x48,0x89,0x5C,0x24,0x08,0x48,0x89,0x6C,0x24,0x10,0x48,0x89,0x74,0x24,0x18,0x57]))return 0; if(!Prefix(0x25E9360,[0xC7,0x81,0x80,0x06,0,0,0,0,0xC8,0xC2,0xC3]))return 0; var status=HookInitialize();if(status is not(0 or 1))return 0; if(HookCreate(image+ContextUpdate,(nuint)(delegate* unmanaged)&ContextHook,out originalContext)!=0)return 0; if(HookCreate(image+MenuPoll,(nuint)(delegate* unmanaged)&MenuHook,out originalMenu)!=0){HookRemove(image+ContextUpdate);return 0;} if(HookCreate(image+MapperThunk,(nuint)(delegate* unmanaged)&MapperHook,out originalMapper)!=0){HookRemove(image+MenuPoll);HookRemove(image+ContextUpdate);return 0;} if(HookCreate(image+RegistryDestroy,(nuint)(delegate* unmanaged)&RegistryDestroyHook,out originalRegistryDestroy)!=0) {HookRemove(image+MapperThunk);HookRemove(image+MenuPoll);HookRemove(image+ContextUpdate);return 0;} if(!Pin((nuint)(delegate* unmanaged)&ContextHook)||HookQueueEnable(image+RegistryDestroy)!=0||HookQueueEnable(image+ContextUpdate)!=0||HookQueueEnable(image+MenuPoll)!=0||HookQueueEnable(image+MapperThunk)!=0||HookApplyQueued()!=0) {HookDisable(image+MapperThunk);HookDisable(image+MenuPoll);HookDisable(image+ContextUpdate);HookDisable(image+RegistryDestroy);return 0;} enabled=true;started=true;PipeServer.StartJson(Service,32768,Handle);return 1; } } internal static uint SelfTest() { if(started||ImageHash(ModulePath())==GameHash||!TradePauseGuardSelfTest())return 0; uint mask=0; var pause=new Menu{categoryName="Pause",kind=1};var exit=new Menu{categoryName="ExitOptions",kind=2}; if(AllowedAction(pause,"ExitOptions")&&AllowedAction(exit,"Confirmed Quit To Main Menu"))mask|=1; if(!AllowedAction(pause,"Confirmed Quit To Main Menu")&&!AllowedAction(exit,"Confirmed Quit Game")&&!AllowedAction(exit,"Confirmed Quit To Game"))mask|=2; if(!ReturnToMenu("InGame")&&!ReturnToMenu("SetupPlaySolo")&&!ReturnToMenu("CancelExitToMenu")&&!ReturnToMenu("ExitToDesktop"))mask|=4; if(Fresh(100,300)&&!Fresh(100,301)&&!Fresh(100,99))mask|=8; var before=enabled;var previous=expectedThread; try { enabled=true;expectedThread=7;var r=new Root{valid=true,state="Pause",next="Pause",flow=0x10000,tick=100,thread=7}; var m=new Menu{ready=true,flow=r.flow,tick=100,sequence=9,thread=7,categoryName="Pause",kind=1};var w=new Work{pending=true,expires=200,sequence=9}; if(MayDispatch(r,m,w,150,7))mask|=16; r.state="InGame";if(!MayDispatch(r,m,w,150,7))mask|=32;r.state="Pause"; if(!MayDispatch(r,m,w,150,8)&&!MayDispatch(r,m,w,201,7))mask|=64; m.flow++;if(!MayDispatch(r,m,w,150,7)&&ValidCache(10,10,10)&&!ValidCache(10,0,10)&&!ValidCache(10,10,9)&&!ValidCache(10,10,5000))mask|=128; } finally{enabled=before;expectedThread=previous;} return mask; } } internal static class SessionRecoveryExports { [UnmanagedCallersOnly(EntryPoint="XFEInteractionStart")]internal static uint Start(nuint thread){try{return SessionRecoveryRuntime.Start(thread);}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFESessionRecoverySelfTest")]internal static uint SelfTest(){try{return SessionRecoveryRuntime.SelfTest();}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFEDockingResetSelfTest")]internal static uint ResetSelfTest(){try{return SessionRecoveryRuntime.ResetSelfTest();}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFEDockingResetTelemetrySelfTest")]internal static uint ResetTelemetrySelfTest(){try{return SessionRecoveryRuntime.ResetTelemetrySelfTest();}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFEDockingStartSelfTest")]internal static uint DockingStartSelfTest(){try{return Navigation.RecoveryDockingStartSelfTest();}catch{return 0;}} [UnmanagedCallersOnly(EntryPoint="XFEFlightContextSelfTest")]internal static uint FlightContextSelfTest(){try{return SessionRecoveryRuntime.FlightContextSelfTest();}catch{return 0;}} } #endif