XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
#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<nuint,JsonObject> mapperNodes=new();
    private static bool InImage(nuint at)=>at>=image&&at<end;
    private static bool Prefix(nuint at,ReadOnlySpan<byte> bytes)=>ReadBytes(image+at,bytes.Length).AsSpan().SequenceEqual(bytes);
    private static string Name(nuint address)
    {
        Span<byte> bytes=stackalloc byte[128];
        for(var n=0;n<bytes.Length;n++){var c=Read<byte>(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<uint>(activity+0x108);
        result.categories=Read<uint>(result.definition+0x10);result.countdown=Read<float>(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<ulong>(activity+0x148);
        result.cacheCapacity=Read<ulong>(activity+0x138);result.raw140=Read<ulong>(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<byte>(category);result.categoryName=Name(Pointer(Pointer(category+8)));
        result.count=Read<uint>(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<result.count;i++)
        {
            var original=buttons+i*0x78;result.names[i]=Name(Pointer(Pointer(original)));
            if(!exact)continue;
            var cached=result.cache+i*0xC8;var same=true;
            for(nuint offset=0;offset<0x78;offset+=8)if(Read<ulong>(original+offset)!=Read<ulong>(cached+0x30+offset)){same=false;break;}
            exact&=same;result.allowed[i]=same&&Read<ushort>(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&&current.valid&&Fresh(current.tick,result.tick)&&current.flow==result.flow&&SafeCategory(result)
            &&current.state==result.categoryName&&current.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<observed.names.Length;n++)if(observed.names[n]==wanted.action&&observed.allowed[n]&&AllowedAction(observed,observed.names[n])){if(index!=-1)return;index=n;}
        if(index<0)return;
        // Re-read the complete original definition immediately before dispatch.
        var fresh=CaptureMenu(activity);Root current;lock(gate)current=root;
        if(!fresh.ready||fresh.flow!=r.flow||fresh.categoryName!=observed.categoryName||!Fresh(current.tick,GetTickCount64())
            ||current.state!=fresh.categoryName||current.next!=current.state||fresh.names.Length<=index
            ||fresh.names[index]!=wanted.action||!fresh.allowed[index]||!AllowedAction(fresh,fresh.names[index]))return;
        lock(gate){if(!work.pending||work.id!=wanted.id||work.expires<=GetTickCount64())return;work.pending=false;}
        var applied=false;
        try{Call(image+PauseSelect,(ulong)(activity+0x80),0,(ulong)index);applied=true;}
        finally{lock(gate)if(work.id==wanted.id){work.applied=applied;work.failed=!applied;}}
    }
    [UnmanagedCallersOnly]private static ulong ContextHook(nuint context)
    {
        // Release an expired scope or one about to leave InGame before the
        // original context callback can begin scene teardown. The registry's
        // real destructor additionally owns an independent pre-destroy hook.
        try{CaptureRoot(context);PollFlightContextBeforeOriginal();}catch{}
        ulong result;try{result=Call(originalContext,(ulong)context);}catch{return 0;}
        try
        {
            contextCalls++;CaptureRoot(context);
            ObserveTradePauseIdentity();
            // MenuPoll runs about once a second. Re-read its known activity on
            // the same owning thread while its exact pause flow is active, so
            // a submenu transition does not wait for the slow UI poll. Every
            // original row, selector, category and flow is checked again.
            nuint activity=0;
            lock(gate)if(root.valid&&Fresh(root.tick,GetTickCount64())&&root.thread==expectedThread&&root.flow==menu.flow
                &&root.state==root.next&&root.state is "Pause" or "ExitOptions")activity=menu.address;
            if(activity!=0)CaptureAndDispatch(activity);
        }
        catch{}
        return result;
    }
    [UnmanagedCallersOnly]private static ulong MenuHook(nuint activity)
    {
        ulong result;try{result=Call(originalMenu,(ulong)activity);}catch{return 0;}
        try{menuCalls++;CaptureAndDispatch(activity);}catch(Exception error){menuReadErrors++;lastMenuIssue=error.GetType().Name+": "+error.Message;}
        return result;
    }
    private static string? BindingName(nuint binding)
    {
        if(binding<0x10000)return null;var text=Pointer(binding+8);var length=Read<ulong>(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<float>(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<float>(node+0xD0);var sourceValue=source>=0x10000?Read<float>(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<byte>(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;i<m.names.Length;i++)actions.Add((JsonNode)Obj(("name",m.names[i]),("enabled",m.allowed[i]),("returnToMenu",ReturnToMenu(m.names[i])),("recoveryAction",AllowedAction(m,m.names[i]))));
        return Obj(("name","XFEEDToolBox.SessionRecovery"),("schema",1),("processId",ProcessId),("gameSha256",GameHash),("service",Service),("nativeDockingReset",true),("nativeDockingStart",true),("dockingReset",ResetDescription()),
            ("nativeFlightContextProbe",true),("flightContext",FlightContextDescription()),("tradePauseResumeSchema",1),("tradePauseRecovery",TradePauseDescription()),("tradePauseIdentity",TradePauseIdentityDescription()),
            ("enabled",enabled),("owningThread",expectedThread),("contextCalls",contextCalls),("menuCalls",menuCalls),("menuMatches",menuMatches),
            ("menuReadErrors",menuReadErrors),("lastMenuIssue",lastMenuIssue),("mapperCalls",mapperCalls),("mapperNodes",nodes),
            ("sequence",r.sequence),("observedAtUnixMilliseconds",r.utc),("flow",r.flow.ToString("x")),("csm",r.csm.ToString("x")),
            ("state",r.state),("nextState",r.next),("contextThread",r.thread),("menuThread",m.thread),("menuAddress",m.address.ToString("x")),
            ("menuFlow",m.flow.ToString("x")),("menuReason",m.reason),("menuReady",m.ready&&r.state==m.categoryName&&r.next==r.state&&r.flow==m.flow&&Fresh(m.tick,GetTickCount64())&&Fresh(r.tick,GetTickCount64())),
            ("menuSequence",m.sequence),("category",m.index),("categoryName",m.categoryName),("categories",m.categories),("kind",m.kind),("countdown",m.countdown),
            ("buttonCount",m.count),("cacheCount",m.cacheCount),("cacheCapacity",m.cacheCapacity),("raw140",m.raw140),("actions",actions),("requestId",w.id),("pending",w.pending&&w.expires>GetTickCount64()),
            ("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<nuint,ulong>)&ContextHook,out originalContext)!=0)return 0;
            if(HookCreate(image+MenuPoll,(nuint)(delegate* unmanaged<nuint,ulong>)&MenuHook,out originalMenu)!=0){HookRemove(image+ContextUpdate);return 0;}
            if(HookCreate(image+MapperThunk,(nuint)(delegate* unmanaged<nuint,float,ulong>)&MapperHook,out originalMapper)!=0){HookRemove(image+MenuPoll);HookRemove(image+ContextUpdate);return 0;}
            if(HookCreate(image+RegistryDestroy,(nuint)(delegate* unmanaged<nuint,void>)&RegistryDestroyHook,out originalRegistryDestroy)!=0)
            {HookRemove(image+MapperThunk);HookRemove(image+MenuPoll);HookRemove(image+ContextUpdate);return 0;}
            if(!Pin((nuint)(delegate* unmanaged<nuint,ulong>)&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