#if PLUGIN_SESSION_RECOVERY
namespace XFEEDToolBox.Plugin;
internal static unsafe partial class SessionRecoveryRuntime
{
private const nuint RegistryDestroy=0x8E9D50;
private static nuint originalRegistryDestroy;
private sealed class FlightContextWork
{
internal string id="",owner="",phase="preparing",issue="";
internal ulong generation,entity,deadline,absoluteEnd,bridgeAt,createdAt,activeAt,releasedAt,inactiveAt;
internal bool pending,createAttempted,created,activeObserved,releaseRequested,explicitRelease,releaseAttempted,releaseCalled,inactiveObserved,failed,registryDestroyed,abandoned;
internal nuint token;
internal float[]? throttle;
internal ulong throttleAt;
internal Navigation.RecoveryFlightContextBinding? proof;
internal Navigation.RecoveryFlightContextLayers? layers;
internal bool reproduction,seedRequested,seedAttempted,seedApplied,seedRestored,seedOutstanding,preserveSeed,seedCleanupCalled,seedZeroObserved;
internal uint unseededFrames;
internal ulong seedAt,lastTrialFrame,seedCleanupDeadline;
internal JsonObject[] trialSamples=[];
}
private static readonly object flightContextGate=new();
private static readonly Dictionary<string,FlightContextWork> flightContextReceipts=new(StringComparer.Ordinal);
private static FlightContextWork? flightContext;
private static bool stationaryContextQualified;
private readonly record struct FlightContextGate(ulong now,ulong deadline,ulong absoluteEnd,ulong bridgeAt,
bool inGame,bool owner,bool sameShip,bool health,bool empty,bool ownLayer,bool overridePresent,bool sceneChange);
private static bool FlightContextAllowed(in FlightContextGate value)
=>value.inGame&&value.owner&&value.sameShip&&value.health&&value.empty&&value.ownLayer&&!value.overridePresent&&!value.sceneChange
&&value.now<value.deadline&&value.deadline-value.now<=250&&value.now<value.absoluteEnd
&&value.bridgeAt<=value.now&&value.now-value.bridgeAt<=200;
private static JsonObject FlightContextDescription(FlightContextWork? selected=null)
{
lock(flightContextGate)
{
var value=selected??flightContext;var layers=value?.layers;
return Obj(("requestId",value?.id),("owner",value?.owner),("selectionGeneration",value?.generation??0),
("phase",value?.phase),("issue",value?.issue),("pending",value?.pending==true),("failed",value?.failed==true),
("created",value?.created==true),("createAttempted",value?.createAttempted==true),("activeObserved",value?.activeObserved==true),
("releaseRequested",value?.releaseRequested==true),("explicitRelease",value?.explicitRelease==true),("releaseAttempted",value?.releaseAttempted==true),("originalReleaseCalled",value?.releaseCalled==true),
("inactiveObserved",value?.inactiveObserved==true),("owned",value is not null&&value.token!=0),("token",value?.token.ToString("x")),
("registryDestroyed",value?.registryDestroyed==true),("abandonedWithoutStaleCall",value?.abandoned==true),
("entityId",value?.entity.ToString()),("registry",value?.proof?.ship.registry.ToString("x")),("profileEntry",value?.proof?.entry.ToString("x")),
("node",value?.proof?.ship.node.ToString("x")),("source",value?.proof?.ship.source.ToString("x")),
("activeFlag",layers?.active),("originalVm",layers?.vm.ToString("x")),("ownTokenMember",layers?.ownMember==true),
("foreignTokens",layers?.foreignCount??0),("layerOccupancies",layers is null?null:Arr(layers.occupancy.Select(v=>(JsonNode?)JsonValue.Create(v)).ToArray())),
("accumulator",value?.throttle?[0]),("sourceValue",value?.throttle?[1]),("actualThrottle",value?.throttle?[2]),("controllerThrottle",value?.throttle?[3]),
("throttleObservedAtUnixMilliseconds",value?.throttleAt??0),
("createdAtUnixMilliseconds",value?.createdAt??0),("activeAtUnixMilliseconds",value?.activeAt??0),
("originalReleaseAtUnixMilliseconds",value?.releasedAt??0),("inactiveAtUnixMilliseconds",value?.inactiveAt??0),
("expiresAtUnixMilliseconds",value?.deadline??0),("absoluteEndAtUnixMilliseconds",value?.absoluteEnd??0),
("stationaryContextQualified",stationaryContextQualified),("fixedContext","Bindings_Flight"),("fixedPriority",0),
("reproduction",value?.reproduction==true),("seedAttempted",value?.seedAttempted==true),("originalSeedApplied",value?.seedApplied==true),
("commandRestored",value?.seedRestored==true),("unseededFrames",value?.unseededFrames??0),("persistent075",value?.unseededFrames>=3),
("seedOutstanding",value?.seedOutstanding==true),("seedCleanupCalled",value?.seedCleanupCalled==true),("seedZeroObserved",value?.seedZeroObserved==true),
("seedAtUnixMilliseconds",value?.seedAt??0),("seedCleanupDeadline",value?.seedCleanupDeadline??0),
("trialSamples",Arr((value?.trialSamples??[]).Select(v=>(JsonNode?)v.DeepClone()).ToArray())),
("originalConstructorRva","8fa080"),("originalTypedReleaseRva","77a6a0"),("gameInputWritten",value?.seedApplied==true),
("gameActiveWritten",false),("gameReferenceCountWritten",false),("gameAccumulatorWritten",false),("osInputSent",false));
}
}
private static void CheckFlightContextBridge(JsonElement frame,JsonElement health,JsonElement local,ulong sequence,bool reproduction)
{
var now=Utc();var ship=health.GetProperty("shipHealth");var docking=local.GetProperty("docking");var sca=local.GetProperty("supercruiseAssist");
if(!ResetFresh(frame,now)||!ResetFresh(health,now)||!ResetFresh(local,now)||!frame.GetProperty("inGame").GetBoolean()
||!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("localPlayerShipVerified").GetBoolean()
||!ship.GetProperty("verified").GetBoolean()||ship.GetProperty("hullFraction").GetDouble()<.95||ship.GetProperty("emergency").GetBoolean()
||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString()||frame.GetProperty("entityId").GetString()!=local.GetProperty("entityId").GetString()
||frame.GetProperty("playerOverride").GetBoolean()||frame.GetProperty("fsd").GetProperty("ownedCharging").GetBoolean()
||frame.GetProperty("rawFsdState").GetInt32() is not(1 or 2)||frame.GetProperty("sequence").GetUInt64()<sequence||frame.GetProperty("sequence").GetUInt64()-sequence>32
||!local.GetProperty("geometryVerified").GetBoolean()||!local.GetProperty("selected").GetBoolean()||local.GetProperty("inSupercruise").GetBoolean()
||local.GetProperty("distanceMetres").GetDouble()>7500||local.GetProperty("speedMetresPerSecond").GetDouble()>(reproduction?100:.1)
||(!reproduction&&local.GetProperty("rawDockingState").GetInt32()!=5)
||reproduction&&(!docking.GetProperty("clearanceGranted").GetBoolean()||local.GetProperty("rawDockingState").GetInt32() is not(3 or 4)
||local.GetProperty("rawRequestState").GetInt32()!=2||local.GetProperty("rawPad").GetInt32()==255)
||docking.GetProperty("nativeLaunchActive").GetBoolean()
||docking.GetProperty("nativeLaunchRequested").GetBoolean()||docking.GetProperty("nativeDutyActive").GetBoolean()
||sca.GetProperty("enabled").GetBoolean()||sca.GetProperty("engaged").GetBoolean())
throw new InvalidOperationException("Stationary no-seed context probe requires the fresh healthy empty docked main ship and no SCA or original duty");
}
private static JsonNode FlightContextRequest(string op,JsonElement request)
{
var id=request.Str("requestId");var owner=request.Str("owner");if(!ResetId(id)||!ResetId(owner))throw new InvalidOperationException("Explicit one-use original Flight scope identity required");
FlightContextWork wanted;
lock(flightContextGate)
{
if(flightContextReceipts.TryGetValue(id,out var known))
{
if(known.owner!=owner)throw new InvalidOperationException("Original Flight scope belongs to another owner");
if(op=="flight.context.seed")
{
if(!known.reproduction||!known.activeObserved||known.token==0||known.failed||known.releaseRequested||known.seedAttempted||known.seedRequested||Utc()>=known.deadline)
throw new InvalidOperationException("Only one active original after-grant seed is allowed");
known.seedRequested=true;return FlightContextDescription(known);
}
if(op=="flight.context.release")
{
known.releaseRequested=true;known.explicitRelease=true;known.pending=false;
known.preserveSeed=known.reproduction&&known.unseededFrames>=3&&request.TryGetProperty("preserveOwnedSeedForReset",out var preserve)&&preserve.ValueKind==JsonValueKind.True;
known.seedCleanupDeadline=Math.Min(known.absoluteEnd,Utc()+200);
}
if(op!="flight.context.renew")return FlightContextDescription(known);
if(known.failed||known.releaseRequested||known.releaseAttempted||known.token==0||Utc()>=known.deadline||Utc()>=known.absoluteEnd)
throw new InvalidOperationException("Original Flight scope is no longer renewable");
wanted=known;
}
else
{
if(op!="flight.context.arm"||flightContextReceipts.Count>=32||flightContext is {} current&&(current.token!=0||current.pending))
throw new InvalidOperationException("No new original Flight scope is available");
var purpose=request.Str("purpose");var reproduction=purpose=="after-grant-persistent075";
if(purpose!="stationary-no-seed"&&!reproduction||reproduction&&!stationaryContextQualified)
throw new InvalidOperationException("The fixed after-grant trial requires its original no-seed admission proof");
wanted=new(){id=id,owner=owner,entity=0,generation=request.U64("selectionGeneration"),absoluteEnd=Utc()+(reproduction?1800UL:3000UL),reproduction=reproduction};
flightContextReceipts.Add(id,wanted);flightContext=wanted;
}
}
try
{
var deadline=request.U64("expiresAtUnixMilliseconds");var ttl=request.Int("ttlMilliseconds");var sequence=request.U64("sequence");
if(!enabled||!ResetDeadline(deadline,Utc(),ttl)||sequence==0||wanted.generation==0)throw new InvalidOperationException("Original Flight scope deadline or selection is unavailable");
Root context;lock(gate)context=root;
if(!context.valid||context.state!="InGame"||context.next!=context.state||!Fresh(context.tick,GetTickCount64()))throw new InvalidOperationException("Stable original InGame required for Flight scope");
var frame=ResetNav(Obj(("op","read")),deadline);var health=ResetNav(Obj(("op","health.read")),deadline);var local=ResetNav(Obj(("op","local.read")),deadline);
CheckFlightContextBridge(frame,health,local,sequence,wanted.reproduction);
var selected=ResetNav(Obj(("op","local.status"),("owner",owner),("generation",wanted.generation)),deadline);
if(!selected.GetProperty("selected").GetBoolean()||!selected.GetProperty("telemetryReady").GetBoolean()||!SameResetTarget(selected.GetProperty("target"),local.GetProperty("target")))
throw new InvalidOperationException("Flight context current base owner or selection changed");
var entity=ulong.Parse(frame.GetProperty("entityId").GetString()!);var world=ulong.Parse(frame.GetProperty("referenceWorldAddress").GetString()!);
if(wanted.proof is null)
{
JsonObject[] candidates;lock(gate)candidates=mapperNodes.Values.Where(row=>row["expectedType"]?.GetValue<bool>()==true
&&Utc()>=row["observedAtUnixMilliseconds"]!.GetValue<ulong>()&&Utc()-row["observedAtUnixMilliseconds"]!.GetValue<ulong>()<=200).ToArray();
var h=health.GetProperty("shipHealth");Navigation.RecoveryFlightContextBinding? proof=null;
foreach(var candidate in candidates)
{
Navigation.RecoveryFlightContextBinding bound;
try{bound=Navigation.BindRecoveryFlightContext(entity,world,local.GetProperty("target"),h.GetProperty("hullFraction").GetDouble(),
h.GetProperty("shieldFraction").ValueKind==JsonValueKind.Number?h.GetProperty("shieldFraction").GetDouble():null,
(nuint)Convert.ToUInt64(candidate["node"]!.GetValue<string>(),16),wanted.reproduction);}catch{continue;}
if(proof!=null)throw new InvalidOperationException("Current Flight context mapper is ambiguous");proof=bound;
}
if(proof is null)throw new InvalidOperationException("Current owned Flight mapper has not been observed");wanted.proof=proof;wanted.entity=entity;
}
if(entity!=wanted.entity||world!=wanted.proof.ship.baseline.referenceWorld||!SameResetTarget(local.GetProperty("target"),wanted.proof.ship.target))
throw new InvalidOperationException("Flight context main ship, world or target changed");
lock(flightContextGate)
{
if(wanted.releaseRequested||wanted.failed||Utc()>=deadline||Utc()>=wanted.absoluteEnd)throw new InvalidOperationException("Original Flight context was cancelled or expired while checking");
wanted.deadline=deadline;wanted.bridgeAt=Utc();wanted.pending=!wanted.created;wanted.phase=wanted.created?"owned-renewed":"armed";
}
}
catch(Exception error){lock(flightContextGate){wanted.failed=true;wanted.releaseRequested=true;wanted.pending=false;wanted.issue=error.ToString();wanted.phase="bridge-rejected";}}
return FlightContextDescription(wanted);
}
private static void ReleaseFlightContext(FlightContextWork wanted,string reason,bool destroying=false)
{
if(wanted.token==0)return;
if(GetCurrentThreadId()!=expectedThread)throw new InvalidOperationException("Original Flight token may only be released on its owning thread");
if(wanted.proof is null||wanted.registryDestroyed)throw new InvalidOperationException("No live original Flight token proof remains");
wanted.pending=false;wanted.phase="checking-original-token-release";
var submitted=false;
try
{
Navigation.ReleaseRecoveryFlightContext(wanted.proof,ref wanted.token,()=>
{submitted=true;wanted.releaseAttempted=true;wanted.phase="releasing-original-token";});
wanted.releaseCalled=true;wanted.releasedAt=Utc();wanted.phase="original-token-released";
if(reason!="explicit-release")wanted.issue=reason+(wanted.issue.Length==0?"":": "+wanted.issue);
}
catch(Exception error)
{
wanted.failed=true;wanted.releaseRequested=true;wanted.issue=reason+": "+error;
if(submitted||destroying)
{
// An uncertain original call is never replayed, and a token
// cannot outlive its raw entry when the registry is destroyed.
wanted.token=0;wanted.abandoned=true;wanted.phase="release-unresolved-no-replay";
}
else
{
// Validation did not invoke native code. Keep the owned slot
// so a later stable frame can release it instead of leaking
// an enabled original input layer after a transient refusal.
wanted.phase="release-precheck-refused";
}
if(!destroying)throw;
}
}
private static void PollFlightContextBeforeOriginal()
{
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted is null||wanted.proof is null||wanted.registryDestroyed)return;
Root context;lock(gate)context=root;var now=Utc();
CleanupFlightThrottleTrial(wanted);
var allowed=FlightContextAllowed(new(now,wanted.deadline,wanted.absoluteEnd,wanted.bridgeAt,
enabled&&context.valid&&context.state=="InGame",true,true,true,true,true,false,context.next!=context.state||!Fresh(context.tick,GetTickCount64())));
try
{
if(GetCurrentThreadId()!=expectedThread)throw new InvalidOperationException("Original Flight scope frame is on another thread");
if(wanted.token!=0)
{
if(!allowed||wanted.releaseRequested||wanted.failed){ReleaseFlightContext(wanted,wanted.releaseRequested?"explicit-release":"expired-or-scene-changed");return;}
Navigation.CheckRecoveryFlightContextFrame(wanted.proof,false);wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(!wanted.layers.OnlyOwn){wanted.failed=true;ReleaseFlightContext(wanted,"non-owned-original-input-layer");}
}
else if(wanted.pending&&!wanted.createAttempted)
{
if(!allowed){wanted.pending=false;wanted.failed=true;wanted.phase="expired-before-create";return;}
wanted.createAttempted=true;wanted.pending=false;
Navigation.CreateRecoveryFlightContext(wanted.proof,ref wanted.token);
if(wanted.token==0||!Navigation.RecoveryFlightContextTokenValid(wanted.proof,wanted.token))throw new InvalidOperationException("Original lowest-priority Flight token was not created");
wanted.created=true;wanted.createdAt=Utc();wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(!wanted.layers.OnlyOwn)throw new InvalidOperationException("Original Flight layer0 does not contain exactly the owned token");
wanted.phase="created-awaiting-original-active";
}
}
catch(Exception error)
{
wanted.failed=true;wanted.pending=false;wanted.issue=error.ToString();wanted.phase="original-scope-refused";
if(wanted.token!=0&&!wanted.releaseAttempted)try{ReleaseFlightContext(wanted,"native-guard-refusal");}catch{}
}
}
private static void ObserveFlightContextAfterMapper(nuint node)
{
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted?.proof is null||wanted.registryDestroyed||node!=wanted.proof.ship.node||GetCurrentThreadId()!=expectedThread||!wanted.created)return;
try
{
wanted.throttle=Navigation.ReadRecoveryFlightContextThrottle(wanted.proof);wanted.throttleAt=Utc();
wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(wanted.token!=0)
{
if(!wanted.layers.OnlyOwn){wanted.failed=true;ReleaseFlightContext(wanted,"original-ui-or-foreign-layer");return;}
if(wanted.layers.active!=0&&wanted.layers.vm!=0)
{wanted.activeObserved=true;if(wanted.activeAt==0)wanted.activeAt=Utc();wanted.phase="original-active-observed";}
}
else if(wanted.releaseCalled&&wanted.layers.Empty&&wanted.layers.active==0&&wanted.layers.vm==0)
{
wanted.inactiveObserved=true;if(wanted.inactiveAt==0)wanted.inactiveAt=Utc();wanted.phase="original-inactive-observed";
stationaryContextQualified|=!wanted.reproduction&&wanted.activeObserved&&wanted.explicitRelease&&!wanted.failed&&!wanted.abandoned;
}
}
catch(Exception error){wanted.failed=true;wanted.releaseRequested=true;wanted.issue=error.ToString();}
}
private static bool PrepareFlightContextDeactivate()
{
lock(flightContextGate)
{
if(flightContext is not {} wanted)return true;
wanted.pending=false;wanted.releaseRequested=true;
return wanted.token==0;
}
}
[UnmanagedCallersOnly]private static void RegistryDestroyHook(nuint registryRoot)
{
// 8ED50C's adjusting destructor subtracts 58 then calls this exact
// root-only void destructor. Its original profile map is still alive
// here. Always forward once, with RCX unmodified, after our cleanup.
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted?.proof is {} proof&&proof.ship.registry==registryRoot+0x58)
{
try{if(wanted.token!=0)ReleaseFlightContext(wanted,"registry-destroy-before-original",true);}
catch(Exception error){wanted.failed=true;wanted.abandoned=true;wanted.issue=error.ToString();wanted.token=0;}
finally{wanted.registryDestroyed=true;wanted.pending=false;wanted.failed=true;wanted.phase="registry-destroyed-no-late-release";}
}
try{Call(originalRegistryDestroy,(ulong)registryRoot);}catch{}
}
internal static uint FlightContextSelfTest()
{
if(started||ImageHash(ModulePath())==GameHash)return 0;uint mask=0;
var valid=new FlightContextGate(1000,1200,4000,950,true,true,true,true,true,true,false,false);
if(FlightContextAllowed(valid))mask|=1;
if(!FlightContextAllowed(valid with{deadline=1000})&&!FlightContextAllowed(valid with{deadline=1251}))mask|=2;
if(!FlightContextAllowed(valid with{bridgeAt=799})&&!FlightContextAllowed(valid with{bridgeAt=1001}))mask|=4;
if(!FlightContextAllowed(valid with{overridePresent=true})&&!FlightContextAllowed(valid with{sceneChange=true}))mask|=8;
if(!FlightContextAllowed(valid with{owner=false})&&!FlightContextAllowed(valid with{sameShip=false}))mask|=16;
if(!FlightContextAllowed(valid with{health=false})&&!FlightContextAllowed(valid with{empty=false})&&!FlightContextAllowed(valid with{ownLayer=false}))mask|=32;
var own=new Navigation.RecoveryFlightContextLayers(1,2,3,4,1,[1,0,0],true,0);
if(own.OnlyOwn&&!own.Empty&&!((own with{ownMember=false}).OnlyOwn)&&!((own with{foreignCount=1}).OnlyOwn)&&!((own with{occupancy=[2,0,0]}).OnlyOwn))mask|=64;
var empty=own with{vm=0,active=0,occupancy=[0,0,0],ownMember=false};
if(empty.Empty&&!empty.OnlyOwn&&!FlightContextAllowed(valid with{absoluteEnd=1000})&&!FlightContextAllowed(valid with{inGame=false}))mask|=128;
if(Navigation.FlightContextNoSeedThrottle([0,0,0,0])&&Navigation.FlightContextNoSeedThrottle([0,0,0,-100])
&&!Navigation.FlightContextNoSeedThrottle([0,0,.75f,-100])&&!Navigation.FlightContextNoSeedThrottle([0,.75f,0,-100])
&&!Navigation.FlightContextNoSeedThrottle([.75f,0,0,-100])&&!Navigation.FlightContextNoSeedThrottle([0,0,0,-1])
&&!Navigation.FlightContextNoSeedThrottle([0,0,0,float.NaN]))mask|=256;
return mask;
}
}
#endif
#if PLUGIN_SESSION_RECOVERY
namespace XFEEDToolBox.Plugin;
internal static unsafe partial class SessionRecoveryRuntime
{
private const nuint RegistryDestroy=0x8E9D50;
private static nuint originalRegistryDestroy;
private sealed class FlightContextWork
{
internal string id="",owner="",phase="preparing",issue="";
internal ulong generation,entity,deadline,absoluteEnd,bridgeAt,createdAt,activeAt,releasedAt,inactiveAt;
internal bool pending,createAttempted,created,activeObserved,releaseRequested,explicitRelease,releaseAttempted,releaseCalled,inactiveObserved,failed,registryDestroyed,abandoned;
internal nuint token;
internal float[]? throttle;
internal ulong throttleAt;
internal Navigation.RecoveryFlightContextBinding? proof;
internal Navigation.RecoveryFlightContextLayers? layers;
internal bool reproduction,seedRequested,seedAttempted,seedApplied,seedRestored,seedOutstanding,preserveSeed,seedCleanupCalled,seedZeroObserved;
internal uint unseededFrames;
internal ulong seedAt,lastTrialFrame,seedCleanupDeadline;
internal JsonObject[] trialSamples=[];
}
private static readonly object flightContextGate=new();
private static readonly Dictionary<string,FlightContextWork> flightContextReceipts=new(StringComparer.Ordinal);
private static FlightContextWork? flightContext;
private static bool stationaryContextQualified;
private readonly record struct FlightContextGate(ulong now,ulong deadline,ulong absoluteEnd,ulong bridgeAt,
bool inGame,bool owner,bool sameShip,bool health,bool empty,bool ownLayer,bool overridePresent,bool sceneChange);
private static bool FlightContextAllowed(in FlightContextGate value)
=>value.inGame&&value.owner&&value.sameShip&&value.health&&value.empty&&value.ownLayer&&!value.overridePresent&&!value.sceneChange
&&value.now<value.deadline&&value.deadline-value.now<=250&&value.now<value.absoluteEnd
&&value.bridgeAt<=value.now&&value.now-value.bridgeAt<=200;
private static JsonObject FlightContextDescription(FlightContextWork? selected=null)
{
lock(flightContextGate)
{
var value=selected??flightContext;var layers=value?.layers;
return Obj(("requestId",value?.id),("owner",value?.owner),("selectionGeneration",value?.generation??0),
("phase",value?.phase),("issue",value?.issue),("pending",value?.pending==true),("failed",value?.failed==true),
("created",value?.created==true),("createAttempted",value?.createAttempted==true),("activeObserved",value?.activeObserved==true),
("releaseRequested",value?.releaseRequested==true),("explicitRelease",value?.explicitRelease==true),("releaseAttempted",value?.releaseAttempted==true),("originalReleaseCalled",value?.releaseCalled==true),
("inactiveObserved",value?.inactiveObserved==true),("owned",value is not null&&value.token!=0),("token",value?.token.ToString("x")),
("registryDestroyed",value?.registryDestroyed==true),("abandonedWithoutStaleCall",value?.abandoned==true),
("entityId",value?.entity.ToString()),("registry",value?.proof?.ship.registry.ToString("x")),("profileEntry",value?.proof?.entry.ToString("x")),
("node",value?.proof?.ship.node.ToString("x")),("source",value?.proof?.ship.source.ToString("x")),
("activeFlag",layers?.active),("originalVm",layers?.vm.ToString("x")),("ownTokenMember",layers?.ownMember==true),
("foreignTokens",layers?.foreignCount??0),("layerOccupancies",layers is null?null:Arr(layers.occupancy.Select(v=>(JsonNode?)JsonValue.Create(v)).ToArray())),
("accumulator",value?.throttle?[0]),("sourceValue",value?.throttle?[1]),("actualThrottle",value?.throttle?[2]),("controllerThrottle",value?.throttle?[3]),
("throttleObservedAtUnixMilliseconds",value?.throttleAt??0),
("createdAtUnixMilliseconds",value?.createdAt??0),("activeAtUnixMilliseconds",value?.activeAt??0),
("originalReleaseAtUnixMilliseconds",value?.releasedAt??0),("inactiveAtUnixMilliseconds",value?.inactiveAt??0),
("expiresAtUnixMilliseconds",value?.deadline??0),("absoluteEndAtUnixMilliseconds",value?.absoluteEnd??0),
("stationaryContextQualified",stationaryContextQualified),("fixedContext","Bindings_Flight"),("fixedPriority",0),
("reproduction",value?.reproduction==true),("seedAttempted",value?.seedAttempted==true),("originalSeedApplied",value?.seedApplied==true),
("commandRestored",value?.seedRestored==true),("unseededFrames",value?.unseededFrames??0),("persistent075",value?.unseededFrames>=3),
("seedOutstanding",value?.seedOutstanding==true),("seedCleanupCalled",value?.seedCleanupCalled==true),("seedZeroObserved",value?.seedZeroObserved==true),
("seedAtUnixMilliseconds",value?.seedAt??0),("seedCleanupDeadline",value?.seedCleanupDeadline??0),
("trialSamples",Arr((value?.trialSamples??[]).Select(v=>(JsonNode?)v.DeepClone()).ToArray())),
("originalConstructorRva","8fa080"),("originalTypedReleaseRva","77a6a0"),("gameInputWritten",value?.seedApplied==true),
("gameActiveWritten",false),("gameReferenceCountWritten",false),("gameAccumulatorWritten",false),("osInputSent",false));
}
}
private static void CheckFlightContextBridge(JsonElement frame,JsonElement health,JsonElement local,ulong sequence,bool reproduction)
{
var now=Utc();var ship=health.GetProperty("shipHealth");var docking=local.GetProperty("docking");var sca=local.GetProperty("supercruiseAssist");
if(!ResetFresh(frame,now)||!ResetFresh(health,now)||!ResetFresh(local,now)||!frame.GetProperty("inGame").GetBoolean()
||!frame.GetProperty("localPlayerShipVerified").GetBoolean()||!health.GetProperty("localPlayerShipVerified").GetBoolean()
||!ship.GetProperty("verified").GetBoolean()||ship.GetProperty("hullFraction").GetDouble()<.95||ship.GetProperty("emergency").GetBoolean()
||frame.GetProperty("entityId").GetString()!=health.GetProperty("entityId").GetString()||frame.GetProperty("entityId").GetString()!=local.GetProperty("entityId").GetString()
||frame.GetProperty("playerOverride").GetBoolean()||frame.GetProperty("fsd").GetProperty("ownedCharging").GetBoolean()
||frame.GetProperty("rawFsdState").GetInt32() is not(1 or 2)||frame.GetProperty("sequence").GetUInt64()<sequence||frame.GetProperty("sequence").GetUInt64()-sequence>32
||!local.GetProperty("geometryVerified").GetBoolean()||!local.GetProperty("selected").GetBoolean()||local.GetProperty("inSupercruise").GetBoolean()
||local.GetProperty("distanceMetres").GetDouble()>7500||local.GetProperty("speedMetresPerSecond").GetDouble()>(reproduction?100:.1)
||(!reproduction&&local.GetProperty("rawDockingState").GetInt32()!=5)
||reproduction&&(!docking.GetProperty("clearanceGranted").GetBoolean()||local.GetProperty("rawDockingState").GetInt32() is not(3 or 4)
||local.GetProperty("rawRequestState").GetInt32()!=2||local.GetProperty("rawPad").GetInt32()==255)
||docking.GetProperty("nativeLaunchActive").GetBoolean()
||docking.GetProperty("nativeLaunchRequested").GetBoolean()||docking.GetProperty("nativeDutyActive").GetBoolean()
||sca.GetProperty("enabled").GetBoolean()||sca.GetProperty("engaged").GetBoolean())
throw new InvalidOperationException("Stationary no-seed context probe requires the fresh healthy empty docked main ship and no SCA or original duty");
}
private static JsonNode FlightContextRequest(string op,JsonElement request)
{
var id=request.Str("requestId");var owner=request.Str("owner");if(!ResetId(id)||!ResetId(owner))throw new InvalidOperationException("Explicit one-use original Flight scope identity required");
FlightContextWork wanted;
lock(flightContextGate)
{
if(flightContextReceipts.TryGetValue(id,out var known))
{
if(known.owner!=owner)throw new InvalidOperationException("Original Flight scope belongs to another owner");
if(op=="flight.context.seed")
{
if(!known.reproduction||!known.activeObserved||known.token==0||known.failed||known.releaseRequested||known.seedAttempted||known.seedRequested||Utc()>=known.deadline)
throw new InvalidOperationException("Only one active original after-grant seed is allowed");
known.seedRequested=true;return FlightContextDescription(known);
}
if(op=="flight.context.release")
{
known.releaseRequested=true;known.explicitRelease=true;known.pending=false;
known.preserveSeed=known.reproduction&&known.unseededFrames>=3&&request.TryGetProperty("preserveOwnedSeedForReset",out var preserve)&&preserve.ValueKind==JsonValueKind.True;
known.seedCleanupDeadline=Math.Min(known.absoluteEnd,Utc()+200);
}
if(op!="flight.context.renew")return FlightContextDescription(known);
if(known.failed||known.releaseRequested||known.releaseAttempted||known.token==0||Utc()>=known.deadline||Utc()>=known.absoluteEnd)
throw new InvalidOperationException("Original Flight scope is no longer renewable");
wanted=known;
}
else
{
if(op!="flight.context.arm"||flightContextReceipts.Count>=32||flightContext is {} current&&(current.token!=0||current.pending))
throw new InvalidOperationException("No new original Flight scope is available");
var purpose=request.Str("purpose");var reproduction=purpose=="after-grant-persistent075";
if(purpose!="stationary-no-seed"&&!reproduction||reproduction&&!stationaryContextQualified)
throw new InvalidOperationException("The fixed after-grant trial requires its original no-seed admission proof");
wanted=new(){id=id,owner=owner,entity=0,generation=request.U64("selectionGeneration"),absoluteEnd=Utc()+(reproduction?1800UL:3000UL),reproduction=reproduction};
flightContextReceipts.Add(id,wanted);flightContext=wanted;
}
}
try
{
var deadline=request.U64("expiresAtUnixMilliseconds");var ttl=request.Int("ttlMilliseconds");var sequence=request.U64("sequence");
if(!enabled||!ResetDeadline(deadline,Utc(),ttl)||sequence==0||wanted.generation==0)throw new InvalidOperationException("Original Flight scope deadline or selection is unavailable");
Root context;lock(gate)context=root;
if(!context.valid||context.state!="InGame"||context.next!=context.state||!Fresh(context.tick,GetTickCount64()))throw new InvalidOperationException("Stable original InGame required for Flight scope");
var frame=ResetNav(Obj(("op","read")),deadline);var health=ResetNav(Obj(("op","health.read")),deadline);var local=ResetNav(Obj(("op","local.read")),deadline);
CheckFlightContextBridge(frame,health,local,sequence,wanted.reproduction);
var selected=ResetNav(Obj(("op","local.status"),("owner",owner),("generation",wanted.generation)),deadline);
if(!selected.GetProperty("selected").GetBoolean()||!selected.GetProperty("telemetryReady").GetBoolean()||!SameResetTarget(selected.GetProperty("target"),local.GetProperty("target")))
throw new InvalidOperationException("Flight context current base owner or selection changed");
var entity=ulong.Parse(frame.GetProperty("entityId").GetString()!);var world=ulong.Parse(frame.GetProperty("referenceWorldAddress").GetString()!);
if(wanted.proof is null)
{
JsonObject[] candidates;lock(gate)candidates=mapperNodes.Values.Where(row=>row["expectedType"]?.GetValue<bool>()==true
&&Utc()>=row["observedAtUnixMilliseconds"]!.GetValue<ulong>()&&Utc()-row["observedAtUnixMilliseconds"]!.GetValue<ulong>()<=200).ToArray();
var h=health.GetProperty("shipHealth");Navigation.RecoveryFlightContextBinding? proof=null;
foreach(var candidate in candidates)
{
Navigation.RecoveryFlightContextBinding bound;
try{bound=Navigation.BindRecoveryFlightContext(entity,world,local.GetProperty("target"),h.GetProperty("hullFraction").GetDouble(),
h.GetProperty("shieldFraction").ValueKind==JsonValueKind.Number?h.GetProperty("shieldFraction").GetDouble():null,
(nuint)Convert.ToUInt64(candidate["node"]!.GetValue<string>(),16),wanted.reproduction);}catch{continue;}
if(proof!=null)throw new InvalidOperationException("Current Flight context mapper is ambiguous");proof=bound;
}
if(proof is null)throw new InvalidOperationException("Current owned Flight mapper has not been observed");wanted.proof=proof;wanted.entity=entity;
}
if(entity!=wanted.entity||world!=wanted.proof.ship.baseline.referenceWorld||!SameResetTarget(local.GetProperty("target"),wanted.proof.ship.target))
throw new InvalidOperationException("Flight context main ship, world or target changed");
lock(flightContextGate)
{
if(wanted.releaseRequested||wanted.failed||Utc()>=deadline||Utc()>=wanted.absoluteEnd)throw new InvalidOperationException("Original Flight context was cancelled or expired while checking");
wanted.deadline=deadline;wanted.bridgeAt=Utc();wanted.pending=!wanted.created;wanted.phase=wanted.created?"owned-renewed":"armed";
}
}
catch(Exception error){lock(flightContextGate){wanted.failed=true;wanted.releaseRequested=true;wanted.pending=false;wanted.issue=error.ToString();wanted.phase="bridge-rejected";}}
return FlightContextDescription(wanted);
}
private static void ReleaseFlightContext(FlightContextWork wanted,string reason,bool destroying=false)
{
if(wanted.token==0)return;
if(GetCurrentThreadId()!=expectedThread)throw new InvalidOperationException("Original Flight token may only be released on its owning thread");
if(wanted.proof is null||wanted.registryDestroyed)throw new InvalidOperationException("No live original Flight token proof remains");
wanted.pending=false;wanted.phase="checking-original-token-release";
var submitted=false;
try
{
Navigation.ReleaseRecoveryFlightContext(wanted.proof,ref wanted.token,()=>
{submitted=true;wanted.releaseAttempted=true;wanted.phase="releasing-original-token";});
wanted.releaseCalled=true;wanted.releasedAt=Utc();wanted.phase="original-token-released";
if(reason!="explicit-release")wanted.issue=reason+(wanted.issue.Length==0?"":": "+wanted.issue);
}
catch(Exception error)
{
wanted.failed=true;wanted.releaseRequested=true;wanted.issue=reason+": "+error;
if(submitted||destroying)
{
// An uncertain original call is never replayed, and a token
// cannot outlive its raw entry when the registry is destroyed.
wanted.token=0;wanted.abandoned=true;wanted.phase="release-unresolved-no-replay";
}
else
{
// Validation did not invoke native code. Keep the owned slot
// so a later stable frame can release it instead of leaking
// an enabled original input layer after a transient refusal.
wanted.phase="release-precheck-refused";
}
if(!destroying)throw;
}
}
private static void PollFlightContextBeforeOriginal()
{
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted is null||wanted.proof is null||wanted.registryDestroyed)return;
Root context;lock(gate)context=root;var now=Utc();
CleanupFlightThrottleTrial(wanted);
var allowed=FlightContextAllowed(new(now,wanted.deadline,wanted.absoluteEnd,wanted.bridgeAt,
enabled&&context.valid&&context.state=="InGame",true,true,true,true,true,false,context.next!=context.state||!Fresh(context.tick,GetTickCount64())));
try
{
if(GetCurrentThreadId()!=expectedThread)throw new InvalidOperationException("Original Flight scope frame is on another thread");
if(wanted.token!=0)
{
if(!allowed||wanted.releaseRequested||wanted.failed){ReleaseFlightContext(wanted,wanted.releaseRequested?"explicit-release":"expired-or-scene-changed");return;}
Navigation.CheckRecoveryFlightContextFrame(wanted.proof,false);wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(!wanted.layers.OnlyOwn){wanted.failed=true;ReleaseFlightContext(wanted,"non-owned-original-input-layer");}
}
else if(wanted.pending&&!wanted.createAttempted)
{
if(!allowed){wanted.pending=false;wanted.failed=true;wanted.phase="expired-before-create";return;}
wanted.createAttempted=true;wanted.pending=false;
Navigation.CreateRecoveryFlightContext(wanted.proof,ref wanted.token);
if(wanted.token==0||!Navigation.RecoveryFlightContextTokenValid(wanted.proof,wanted.token))throw new InvalidOperationException("Original lowest-priority Flight token was not created");
wanted.created=true;wanted.createdAt=Utc();wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(!wanted.layers.OnlyOwn)throw new InvalidOperationException("Original Flight layer0 does not contain exactly the owned token");
wanted.phase="created-awaiting-original-active";
}
}
catch(Exception error)
{
wanted.failed=true;wanted.pending=false;wanted.issue=error.ToString();wanted.phase="original-scope-refused";
if(wanted.token!=0&&!wanted.releaseAttempted)try{ReleaseFlightContext(wanted,"native-guard-refusal");}catch{}
}
}
private static void ObserveFlightContextAfterMapper(nuint node)
{
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted?.proof is null||wanted.registryDestroyed||node!=wanted.proof.ship.node||GetCurrentThreadId()!=expectedThread||!wanted.created)return;
try
{
wanted.throttle=Navigation.ReadRecoveryFlightContextThrottle(wanted.proof);wanted.throttleAt=Utc();
wanted.layers=Navigation.ReadRecoveryFlightContextLayers(wanted.proof,wanted.token);
if(wanted.token!=0)
{
if(!wanted.layers.OnlyOwn){wanted.failed=true;ReleaseFlightContext(wanted,"original-ui-or-foreign-layer");return;}
if(wanted.layers.active!=0&&wanted.layers.vm!=0)
{wanted.activeObserved=true;if(wanted.activeAt==0)wanted.activeAt=Utc();wanted.phase="original-active-observed";}
}
else if(wanted.releaseCalled&&wanted.layers.Empty&&wanted.layers.active==0&&wanted.layers.vm==0)
{
wanted.inactiveObserved=true;if(wanted.inactiveAt==0)wanted.inactiveAt=Utc();wanted.phase="original-inactive-observed";
stationaryContextQualified|=!wanted.reproduction&&wanted.activeObserved&&wanted.explicitRelease&&!wanted.failed&&!wanted.abandoned;
}
}
catch(Exception error){wanted.failed=true;wanted.releaseRequested=true;wanted.issue=error.ToString();}
}
private static bool PrepareFlightContextDeactivate()
{
lock(flightContextGate)
{
if(flightContext is not {} wanted)return true;
wanted.pending=false;wanted.releaseRequested=true;
return wanted.token==0;
}
}
[UnmanagedCallersOnly]private static void RegistryDestroyHook(nuint registryRoot)
{
// 8ED50C's adjusting destructor subtracts 58 then calls this exact
// root-only void destructor. Its original profile map is still alive
// here. Always forward once, with RCX unmodified, after our cleanup.
FlightContextWork? wanted;lock(flightContextGate)wanted=flightContext;
if(wanted?.proof is {} proof&&proof.ship.registry==registryRoot+0x58)
{
try{if(wanted.token!=0)ReleaseFlightContext(wanted,"registry-destroy-before-original",true);}
catch(Exception error){wanted.failed=true;wanted.abandoned=true;wanted.issue=error.ToString();wanted.token=0;}
finally{wanted.registryDestroyed=true;wanted.pending=false;wanted.failed=true;wanted.phase="registry-destroyed-no-late-release";}
}
try{Call(originalRegistryDestroy,(ulong)registryRoot);}catch{}
}
internal static uint FlightContextSelfTest()
{
if(started||ImageHash(ModulePath())==GameHash)return 0;uint mask=0;
var valid=new FlightContextGate(1000,1200,4000,950,true,true,true,true,true,true,false,false);
if(FlightContextAllowed(valid))mask|=1;
if(!FlightContextAllowed(valid with{deadline=1000})&&!FlightContextAllowed(valid with{deadline=1251}))mask|=2;
if(!FlightContextAllowed(valid with{bridgeAt=799})&&!FlightContextAllowed(valid with{bridgeAt=1001}))mask|=4;
if(!FlightContextAllowed(valid with{overridePresent=true})&&!FlightContextAllowed(valid with{sceneChange=true}))mask|=8;
if(!FlightContextAllowed(valid with{owner=false})&&!FlightContextAllowed(valid with{sameShip=false}))mask|=16;
if(!FlightContextAllowed(valid with{health=false})&&!FlightContextAllowed(valid with{empty=false})&&!FlightContextAllowed(valid with{ownLayer=false}))mask|=32;
var own=new Navigation.RecoveryFlightContextLayers(1,2,3,4,1,[1,0,0],true,0);
if(own.OnlyOwn&&!own.Empty&&!((own with{ownMember=false}).OnlyOwn)&&!((own with{foreignCount=1}).OnlyOwn)&&!((own with{occupancy=[2,0,0]}).OnlyOwn))mask|=64;
var empty=own with{vm=0,active=0,occupancy=[0,0,0],ownMember=false};
if(empty.Empty&&!empty.OnlyOwn&&!FlightContextAllowed(valid with{absoluteEnd=1000})&&!FlightContextAllowed(valid with{inGame=false}))mask|=128;
if(Navigation.FlightContextNoSeedThrottle([0,0,0,0])&&Navigation.FlightContextNoSeedThrottle([0,0,0,-100])
&&!Navigation.FlightContextNoSeedThrottle([0,0,.75f,-100])&&!Navigation.FlightContextNoSeedThrottle([0,.75f,0,-100])
&&!Navigation.FlightContextNoSeedThrottle([.75f,0,0,-100])&&!Navigation.FlightContextNoSeedThrottle([0,0,0,-1])
&&!Navigation.FlightContextNoSeedThrottle([0,0,0,float.NaN]))mask|=256;
return mask;
}
}
#endif