using System.Text.Json;
using Mono.Cecil;
using Mono.Cecil.Cil;
using XfeBootPlatformPatch;
if (args.Length != 1) throw new ArgumentException("BootPlatformPatch.Check <repository root>");
string root = Path.GetFullPath(args[0]);
string packages = Path.Combine(root, ".tools", "CSharpBoot", "NuGetPackages");
string corePath = Path.Combine(packages, "cosmos.kernel.core.x64", "3.0.94", "lib", "net10.0", PlatformPatch.CoreName + ".dll");
string halPath = Path.Combine(packages, "cosmos.kernel.hal.x64", "3.0.94", "lib", "net10.0", PlatformPatch.HalName + ".dll");
byte[] originalCore = File.ReadAllBytes(corePath), originalHal = File.ReadAllBytes(halPath);
string driversPath = Path.Combine(packages, "cosmos.kernel.drivers", "3.0.94", "lib", "net10.0", LatencyPolicyPatch.DriversName + ".dll");
string plugsPath = Path.Combine(packages, "cosmos.kernel.plugs", "3.0.94", "runtimes", "linux-x64", "lib", "net10.0", "Cosmos.Kernel.Plugs.dll");
byte[] originalDrivers = File.ReadAllBytes(driversPath), originalPlugs = File.ReadAllBytes(plugsPath);
string frameworkPath = Path.Combine(packages, "microsoft.netcore.app.runtime.nativeaot.linux-x64", "10.0.12", "runtimes", "linux-x64", "native", "System.Private.CoreLib.dll");
byte[] originalFramework = File.ReadAllBytes(frameworkPath);
byte[] originalCorelib = LatencyPolicyChecks.OriginalCoreLibFixture(originalPlugs, originalFramework);
int checks = 0;
void Check(string name, bool passed)
{
Console.WriteLine(name + "|" + (passed ? "PASS" : "FAIL"));
if (!passed) throw new InvalidOperationException(name);
checks++;
}
bool Rejects(Action action)
{
try { action(); return false; }
catch (Exception error) when (error is InvalidOperationException or ArgumentException or IOException) { return true; }
}
AssemblyDefinition Read(byte[] bytes) => AssemblyDefinition.ReadAssembly(new MemoryStream(bytes, false), new ReaderParameters { InMemory = true });
Dictionary<string, string> Methods(AssemblyDefinition assembly) => assembly.MainModule.Types.SelectMany(type => type.Methods).Where(method => method.HasBody)
.ToDictionary(method => method.FullName, PlatformPatch.Fingerprint);
Check("PinnedOfficialCore", PlatformPatch.Hash(originalCore) == PlatformPatch.CoreOriginalSha256);
Check("PinnedOfficialHal", PlatformPatch.Hash(originalHal) == PlatformPatch.HalOriginalSha256);
Check("PinnedOfficialDrivers", PlatformPatch.Hash(originalDrivers) == LatencyPolicyPatch.DriversOriginalSha256);
Check("PinnedOfficialMonitorPlugs", PlatformPatch.Hash(originalPlugs) == LatencyPolicyPatch.OfficialPlugsSha256);
Check("PinnedOfficialNativeAotCorelib", PlatformPatch.Hash(originalFramework) == LatencyPolicyPatch.OfficialCoreLibSha256);
using (var monitorSource = Read(originalCorelib)) Check("OfficialMonitorPlugIlMatchesGeneratedCorelibContract", LatencyPolicyPatch.OriginalMonitorState(monitorSource));
LatencyPolicyChecks.Run(originalHal, originalDrivers, originalCorelib, Check);
using (var core = Read(originalCore))
using (var hal = Read(originalHal))
{
var beforeCore = Methods(core);
var beforeHal = Methods(hal);
PlatformPatch.Apply(core, hal);
PlatformPatch.Verify(core, hal);
using (var originalCoreAssembly = Read(originalCore))
using (var beforeHalAssembly = Read(originalHal))
using (var commonCore = Read(File.ReadAllBytes(Path.Combine(packages, "cosmos.kernel.core", "3.0.94", "runtimes", "linux-x64", "lib", "net10.0", "Cosmos.Kernel.Core.dll"))))
LatencyClockChecks.Run(originalCoreAssembly, core, beforeHalAssembly, hal, commonCore, Check);
Check("AppliedActualOfficialAssemblies", true);
Check("UnrelatedCoreMethodsUnchanged", Methods(core).All(pair => pair.Key.Contains("::HandleTimerInterrupt(") ||
pair.Key.Contains("X64InterruptController::Dispatch(") || beforeCore[pair.Key] == pair.Value));
Check("UnrelatedHalMethodsUnchanged", beforeHal.All(pair => pair.Key.Contains("::GetCpuCount(") || pair.Key.Contains("::StartSchedulerTimer(") || Methods(hal)[pair.Key] == pair.Value));
var timer = PlatformPatch.Timer(core);
Check("TimerCounterPreserved", timer.Body.Instructions.Take(4).Select(instruction => instruction.OpCode.Code).SequenceEqual(new[] { Code.Ldsfld, Code.Ldc_I4_1, Code.Add, Code.Stsfld }));
Check("TimerUsesLogicalZero", timer.Body.Instructions[4].OpCode == OpCodes.Ldc_I4_0 && timer.Body.Instructions[5].OpCode == OpCodes.Stloc_0);
var dispatch = PlatformPatch.Dispatch(core);
var reschedule = dispatch.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "ReschedulePendingFromIrq");
Check("DeviceIrqUsesLogicalZero", reschedule.Previous.Previous.OpCode == OpCodes.Ldc_I4_0 && reschedule.Previous.OpCode == OpCodes.Ldloc_2);
Check("DeviceIrqOriginalEOIAndSpuriousPathsPreserved", dispatch.Body.Instructions.Count(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI") == 2 &&
dispatch.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 255)) == 2);
Check("HardwareGetIdUnchanged", Methods(core).Single(pair => pair.Key.EndsWith("LocalApic::GetId()")).Value == beforeCore.Single(pair => pair.Key.EndsWith("LocalApic::GetId()")).Value);
Check("NormalTimerTextPhysicallyRemoved", !timer.Body.Instructions.Any(instruction => instruction.Operand is string text && text == "[LAPIC] Timer tick "));
Check("OnlyErrorBoxRemains", timer.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Box) == 1);
var box = timer.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Box);
var errorReturn = timer.Body.Instructions.First(instruction => instruction.OpCode == OpCodes.Ret);
var valid = timer.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Beq_S);
Check("NormalPathSkipsAllErrorAllocation", timer.Body.Instructions.IndexOf((Instruction)valid.Operand) > timer.Body.Instructions.IndexOf(errorReturn) && timer.Body.Instructions.IndexOf(box) < timer.Body.Instructions.IndexOf(errorReturn));
using var coreStream = new MemoryStream(); using var halStream = new MemoryStream();
core.Write(coreStream); hal.Write(halStream);
using var coreRound = Read(coreStream.ToArray()); using var halRound = Read(halStream.ToArray());
PlatformPatch.Verify(coreRound, halRound);
Check("RoundTripActualGeneratedIl", true);
Check("ApplyingTwiceWithoutReceiptRejected", Rejects(() => PlatformPatch.Apply(coreRound, halRound)));
}
void Mutation(string name, Action<AssemblyDefinition, AssemblyDefinition> change, bool patched = false)
{
using var core = Read(originalCore); using var hal = Read(originalHal);
if (patched) PlatformPatch.Apply(core, hal);
change(core, hal);
Check(name, Rejects(() => { if (patched) PlatformPatch.Verify(core, hal); else PlatformPatch.Apply(core, hal); }));
}
Mutation("ChangedVersionRejected", (core, _) => core.Name.Version = new Version(3, 0, 95, 0));
Mutation("ChangedSchedulerTimerArgumentRejected", (_, hal) => LatencyPolicyPatch.SchedulerTimer(hal).Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldarg_1).OpCode = OpCodes.Ldc_I4_2);
Mutation("PatchedSchedulerTimerArgumentRejected", (_, hal) => LatencyPolicyPatch.SchedulerTimer(hal).Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4_1).OpCode = OpCodes.Ldc_I4_2, true);
Mutation("ChangedTimerCounterRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions[1].OpCode = OpCodes.Ldc_I4_2);
Mutation("ChangedCpuGetterRejected", (_, hal) => PlatformPatch.Count(hal).Body.Instructions[0].OpCode = OpCodes.Ldc_I4_2);
Mutation("ChangedRSPGuardRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Offset == 0x35).OpCode = OpCodes.Bne_Un_S);
Mutation("ChangedNormalLogBlockRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Offset == 0xb7).Operand = "changed timer" );
Mutation("RemovedSchedulerDispatchRejected", (core, _) => { var instruction = PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "OnTimerInterrupt"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; });
Mutation("ChangedDeviceIrqCpuCallRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Offset == 0x73); instruction.OpCode = OpCodes.Ldc_I4_1; instruction.Operand = null; });
Mutation("ChangedDeviceIrqEOIRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.First(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; });
Mutation("ChangedDeviceIrqSpuriousGuardRejected", (core, _) => PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Offset == 0x3a).Operand = 254);
Mutation("PatchedLogicalCpuMutationRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions[4].OpCode = OpCodes.Ldc_I4_1, true);
Mutation("PatchedDeviceIrqLogicalCpuMutationRejected", (core, _) => PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "ReschedulePendingFromIrq").Previous.Previous.OpCode = OpCodes.Ldc_I4_1, true);
Mutation("PatchedDeviceIrqEOIMutationRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.First(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; }, true);
Mutation("PatchedErrorLogMutationRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Operand is string text && text == "[LAPIC] ERROR: Invalid RSP at tick ").Operand = "silenced error", true);
Mutation("PatchedPhysicalDiagnosticMutationRejected", (_, hal) => hal.MainModule.Types.SelectMany(type => type.Methods).Single(method => method.Name == "XfePhysicalCpuCountV1").Body.Instructions[0].OpCode = OpCodes.Ldc_I4_1, true);
string fixtureBase = Path.Combine(root, "Source", "XFESystem.Kernel", "obj", "BootPlatformPatchChecks", "Current");
string fixture = Path.Combine(fixtureBase, "cosmos", "ref");
if (Directory.Exists(fixture)) throw new IOException("Previous check fixture exists; inspect it before retrying.");
Directory.CreateDirectory(fixture);
string fixtureCore = Path.Combine(fixture, Path.GetFileName(corePath)), fixtureHal = Path.Combine(fixture, Path.GetFileName(halPath));
string fixtureDrivers = Path.Combine(fixture, LatencyPolicyPatch.DriversName + ".dll"), fixtureCorelib = Path.Combine(fixture, LatencyPolicyPatch.CoreLibName + ".dll");
string receiptPath = Path.Combine(fixture, PrivatePlatformFiles.ReceiptName);
string pendingPath = Path.Combine(fixture, PrivatePlatformFiles.PendingName);
try
{
File.WriteAllBytes(fixtureCore, originalCore); File.WriteAllBytes(fixtureHal, originalHal);
File.WriteAllBytes(fixtureDrivers, originalDrivers); File.WriteAllBytes(fixtureCorelib, originalCorelib);
PrivatePlatformFiles.Run(fixture);
byte[] afterCore = File.ReadAllBytes(fixtureCore), afterHal = File.ReadAllBytes(fixtureHal), receipt = File.ReadAllBytes(receiptPath);
byte[] afterDrivers = File.ReadAllBytes(fixtureDrivers), afterCorelib = File.ReadAllBytes(fixtureCorelib);
Check("PrivateFixturePairPatched", !afterCore.SequenceEqual(originalCore) && !afterHal.SequenceEqual(originalHal));
Check("SuccessfulWriteLeavesNoPendingTransaction", !File.Exists(pendingPath));
PrivatePlatformFiles.Run(fixture);
Check("ReceiptRepeatByteIdempotent", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal) &&
File.ReadAllBytes(fixtureDrivers).SequenceEqual(afterDrivers) && File.ReadAllBytes(fixtureCorelib).SequenceEqual(afterCorelib) && File.ReadAllBytes(receiptPath).SequenceEqual(receipt));
var policyReceipt = JsonSerializer.Deserialize<PrivatePlatformFiles.Receipt>(receipt)!;
Check("LatencyPolicyBoundInReceipt", policyReceipt.SchedulerTimerIntervalMs == 1 && policyReceipt.XhciPolledDrainIntervalMs == 1 &&
policyReceipt.SuppressedMonitorLogCalls == 9 && policyReceipt.MonitorWaitAlgorithmsPreserved && policyReceipt.SchedulerAccountingQuantumPreserved &&
policyReceipt.XhciMsiPathPreserved && policyReceipt.DriversAfterSha256 == PlatformPatch.Hash(afterDrivers) && policyReceipt.CoreLibAfterSha256 == PlatformPatch.Hash(afterCorelib));
var badReceipt = JsonSerializer.Deserialize<PrivatePlatformFiles.Receipt>(receipt)!;
badReceipt.CoreAfterSha256 = new string('0', 64);
File.WriteAllText(receiptPath, JsonSerializer.Serialize(badReceipt));
Check("ChangedReceiptRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("RejectionDoesNotChangeAssemblies", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal));
File.WriteAllBytes(receiptPath, receipt);
File.WriteAllBytes(fixtureHal, originalHal);
Check("PartialPairRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
File.WriteAllBytes(fixtureCore, originalCore);
Check("LatencyPartialRestorationRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
File.WriteAllBytes(fixtureDrivers, originalDrivers); File.WriteAllBytes(fixtureCorelib, originalCorelib);
// A stale receipt after Cosmos restores ALL exact official/generated inputs is safe to replace.
PrivatePlatformFiles.Run(fixture);
Check("OfficialPairRestorationAcceptsOldReceipt", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal));
File.WriteAllText(pendingPath, "{}", System.Text.Encoding.UTF8);
Check("InterruptedTransactionRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("PackageCachePathRejected", Rejects(() => PrivatePlatformFiles.Run(Path.GetDirectoryName(corePath)!)));
Check("PrivateParentOutsideObjRejected", Rejects(() => PrivatePlatformFiles.ValidateDirectory(Path.Combine(root, ".tools"))));
File.Delete(pendingPath);
File.WriteAllBytes(fixtureCore, afterCore.Concat(new byte[] { 99 }).ToArray());
Check("TamperedPatchedAssemblyRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("GlobalPackagesRemainUnchanged", File.ReadAllBytes(corePath).SequenceEqual(originalCore) && File.ReadAllBytes(halPath).SequenceEqual(originalHal) &&
File.ReadAllBytes(driversPath).SequenceEqual(originalDrivers) && File.ReadAllBytes(plugsPath).SequenceEqual(originalPlugs));
}
finally
{
foreach (string name in new[] { Path.GetFileName(corePath), Path.GetFileName(halPath), LatencyPolicyPatch.DriversName + ".dll", LatencyPolicyPatch.CoreLibName + ".dll", PrivatePlatformFiles.ReceiptName, PrivatePlatformFiles.PendingName, "XfeBootPlatformV1.lock" })
{
string path = Path.Combine(fixture, name);
if (File.Exists(path)) File.Delete(path);
}
Directory.Delete(fixture); Directory.Delete(Path.GetDirectoryName(fixture)!); Directory.Delete(fixtureBase);
}
Console.WriteLine(JsonSerializer.Serialize(new { Passed = true, Checks = checks, NativeGuestTested = false, HardwareBootTested = false, FixtureImageCreated = false }));
using System.Text.Json;
using Mono.Cecil;
using Mono.Cecil.Cil;
using XfeBootPlatformPatch;
if (args.Length != 1) throw new ArgumentException("BootPlatformPatch.Check <repository root>");
string root = Path.GetFullPath(args[0]);
string packages = Path.Combine(root, ".tools", "CSharpBoot", "NuGetPackages");
string corePath = Path.Combine(packages, "cosmos.kernel.core.x64", "3.0.94", "lib", "net10.0", PlatformPatch.CoreName + ".dll");
string halPath = Path.Combine(packages, "cosmos.kernel.hal.x64", "3.0.94", "lib", "net10.0", PlatformPatch.HalName + ".dll");
byte[] originalCore = File.ReadAllBytes(corePath), originalHal = File.ReadAllBytes(halPath);
string driversPath = Path.Combine(packages, "cosmos.kernel.drivers", "3.0.94", "lib", "net10.0", LatencyPolicyPatch.DriversName + ".dll");
string plugsPath = Path.Combine(packages, "cosmos.kernel.plugs", "3.0.94", "runtimes", "linux-x64", "lib", "net10.0", "Cosmos.Kernel.Plugs.dll");
byte[] originalDrivers = File.ReadAllBytes(driversPath), originalPlugs = File.ReadAllBytes(plugsPath);
string frameworkPath = Path.Combine(packages, "microsoft.netcore.app.runtime.nativeaot.linux-x64", "10.0.12", "runtimes", "linux-x64", "native", "System.Private.CoreLib.dll");
byte[] originalFramework = File.ReadAllBytes(frameworkPath);
byte[] originalCorelib = LatencyPolicyChecks.OriginalCoreLibFixture(originalPlugs, originalFramework);
int checks = 0;
void Check(string name, bool passed)
{
Console.WriteLine(name + "|" + (passed ? "PASS" : "FAIL"));
if (!passed) throw new InvalidOperationException(name);
checks++;
}
bool Rejects(Action action)
{
try { action(); return false; }
catch (Exception error) when (error is InvalidOperationException or ArgumentException or IOException) { return true; }
}
AssemblyDefinition Read(byte[] bytes) => AssemblyDefinition.ReadAssembly(new MemoryStream(bytes, false), new ReaderParameters { InMemory = true });
Dictionary<string, string> Methods(AssemblyDefinition assembly) => assembly.MainModule.Types.SelectMany(type => type.Methods).Where(method => method.HasBody)
.ToDictionary(method => method.FullName, PlatformPatch.Fingerprint);
Check("PinnedOfficialCore", PlatformPatch.Hash(originalCore) == PlatformPatch.CoreOriginalSha256);
Check("PinnedOfficialHal", PlatformPatch.Hash(originalHal) == PlatformPatch.HalOriginalSha256);
Check("PinnedOfficialDrivers", PlatformPatch.Hash(originalDrivers) == LatencyPolicyPatch.DriversOriginalSha256);
Check("PinnedOfficialMonitorPlugs", PlatformPatch.Hash(originalPlugs) == LatencyPolicyPatch.OfficialPlugsSha256);
Check("PinnedOfficialNativeAotCorelib", PlatformPatch.Hash(originalFramework) == LatencyPolicyPatch.OfficialCoreLibSha256);
using (var monitorSource = Read(originalCorelib)) Check("OfficialMonitorPlugIlMatchesGeneratedCorelibContract", LatencyPolicyPatch.OriginalMonitorState(monitorSource));
LatencyPolicyChecks.Run(originalHal, originalDrivers, originalCorelib, Check);
using (var core = Read(originalCore))
using (var hal = Read(originalHal))
{
var beforeCore = Methods(core);
var beforeHal = Methods(hal);
PlatformPatch.Apply(core, hal);
PlatformPatch.Verify(core, hal);
using (var originalCoreAssembly = Read(originalCore))
using (var beforeHalAssembly = Read(originalHal))
using (var commonCore = Read(File.ReadAllBytes(Path.Combine(packages, "cosmos.kernel.core", "3.0.94", "runtimes", "linux-x64", "lib", "net10.0", "Cosmos.Kernel.Core.dll"))))
LatencyClockChecks.Run(originalCoreAssembly, core, beforeHalAssembly, hal, commonCore, Check);
Check("AppliedActualOfficialAssemblies", true);
Check("UnrelatedCoreMethodsUnchanged", Methods(core).All(pair => pair.Key.Contains("::HandleTimerInterrupt(") ||
pair.Key.Contains("X64InterruptController::Dispatch(") || beforeCore[pair.Key] == pair.Value));
Check("UnrelatedHalMethodsUnchanged", beforeHal.All(pair => pair.Key.Contains("::GetCpuCount(") || pair.Key.Contains("::StartSchedulerTimer(") || Methods(hal)[pair.Key] == pair.Value));
var timer = PlatformPatch.Timer(core);
Check("TimerCounterPreserved", timer.Body.Instructions.Take(4).Select(instruction => instruction.OpCode.Code).SequenceEqual(new[] { Code.Ldsfld, Code.Ldc_I4_1, Code.Add, Code.Stsfld }));
Check("TimerUsesLogicalZero", timer.Body.Instructions[4].OpCode == OpCodes.Ldc_I4_0 && timer.Body.Instructions[5].OpCode == OpCodes.Stloc_0);
var dispatch = PlatformPatch.Dispatch(core);
var reschedule = dispatch.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "ReschedulePendingFromIrq");
Check("DeviceIrqUsesLogicalZero", reschedule.Previous.Previous.OpCode == OpCodes.Ldc_I4_0 && reschedule.Previous.OpCode == OpCodes.Ldloc_2);
Check("DeviceIrqOriginalEOIAndSpuriousPathsPreserved", dispatch.Body.Instructions.Count(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI") == 2 &&
dispatch.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 255)) == 2);
Check("HardwareGetIdUnchanged", Methods(core).Single(pair => pair.Key.EndsWith("LocalApic::GetId()")).Value == beforeCore.Single(pair => pair.Key.EndsWith("LocalApic::GetId()")).Value);
Check("NormalTimerTextPhysicallyRemoved", !timer.Body.Instructions.Any(instruction => instruction.Operand is string text && text == "[LAPIC] Timer tick "));
Check("OnlyErrorBoxRemains", timer.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Box) == 1);
var box = timer.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Box);
var errorReturn = timer.Body.Instructions.First(instruction => instruction.OpCode == OpCodes.Ret);
var valid = timer.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Beq_S);
Check("NormalPathSkipsAllErrorAllocation", timer.Body.Instructions.IndexOf((Instruction)valid.Operand) > timer.Body.Instructions.IndexOf(errorReturn) && timer.Body.Instructions.IndexOf(box) < timer.Body.Instructions.IndexOf(errorReturn));
using var coreStream = new MemoryStream(); using var halStream = new MemoryStream();
core.Write(coreStream); hal.Write(halStream);
using var coreRound = Read(coreStream.ToArray()); using var halRound = Read(halStream.ToArray());
PlatformPatch.Verify(coreRound, halRound);
Check("RoundTripActualGeneratedIl", true);
Check("ApplyingTwiceWithoutReceiptRejected", Rejects(() => PlatformPatch.Apply(coreRound, halRound)));
}
void Mutation(string name, Action<AssemblyDefinition, AssemblyDefinition> change, bool patched = false)
{
using var core = Read(originalCore); using var hal = Read(originalHal);
if (patched) PlatformPatch.Apply(core, hal);
change(core, hal);
Check(name, Rejects(() => { if (patched) PlatformPatch.Verify(core, hal); else PlatformPatch.Apply(core, hal); }));
}
Mutation("ChangedVersionRejected", (core, _) => core.Name.Version = new Version(3, 0, 95, 0));
Mutation("ChangedSchedulerTimerArgumentRejected", (_, hal) => LatencyPolicyPatch.SchedulerTimer(hal).Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldarg_1).OpCode = OpCodes.Ldc_I4_2);
Mutation("PatchedSchedulerTimerArgumentRejected", (_, hal) => LatencyPolicyPatch.SchedulerTimer(hal).Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4_1).OpCode = OpCodes.Ldc_I4_2, true);
Mutation("ChangedTimerCounterRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions[1].OpCode = OpCodes.Ldc_I4_2);
Mutation("ChangedCpuGetterRejected", (_, hal) => PlatformPatch.Count(hal).Body.Instructions[0].OpCode = OpCodes.Ldc_I4_2);
Mutation("ChangedRSPGuardRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Offset == 0x35).OpCode = OpCodes.Bne_Un_S);
Mutation("ChangedNormalLogBlockRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Offset == 0xb7).Operand = "changed timer" );
Mutation("RemovedSchedulerDispatchRejected", (core, _) => { var instruction = PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "OnTimerInterrupt"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; });
Mutation("ChangedDeviceIrqCpuCallRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Offset == 0x73); instruction.OpCode = OpCodes.Ldc_I4_1; instruction.Operand = null; });
Mutation("ChangedDeviceIrqEOIRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.First(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; });
Mutation("ChangedDeviceIrqSpuriousGuardRejected", (core, _) => PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Offset == 0x3a).Operand = 254);
Mutation("PatchedLogicalCpuMutationRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions[4].OpCode = OpCodes.Ldc_I4_1, true);
Mutation("PatchedDeviceIrqLogicalCpuMutationRejected", (core, _) => PlatformPatch.Dispatch(core).Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "ReschedulePendingFromIrq").Previous.Previous.OpCode = OpCodes.Ldc_I4_1, true);
Mutation("PatchedDeviceIrqEOIMutationRejected", (core, _) => { var instruction = PlatformPatch.Dispatch(core).Body.Instructions.First(instruction => instruction.Operand is MethodReference method && method.Name == "SendEOI"); instruction.OpCode = OpCodes.Nop; instruction.Operand = null; }, true);
Mutation("PatchedErrorLogMutationRejected", (core, _) => PlatformPatch.Timer(core).Body.Instructions.Single(instruction => instruction.Operand is string text && text == "[LAPIC] ERROR: Invalid RSP at tick ").Operand = "silenced error", true);
Mutation("PatchedPhysicalDiagnosticMutationRejected", (_, hal) => hal.MainModule.Types.SelectMany(type => type.Methods).Single(method => method.Name == "XfePhysicalCpuCountV1").Body.Instructions[0].OpCode = OpCodes.Ldc_I4_1, true);
string fixtureBase = Path.Combine(root, "Source", "XFESystem.Kernel", "obj", "BootPlatformPatchChecks", "Current");
string fixture = Path.Combine(fixtureBase, "cosmos", "ref");
if (Directory.Exists(fixture)) throw new IOException("Previous check fixture exists; inspect it before retrying.");
Directory.CreateDirectory(fixture);
string fixtureCore = Path.Combine(fixture, Path.GetFileName(corePath)), fixtureHal = Path.Combine(fixture, Path.GetFileName(halPath));
string fixtureDrivers = Path.Combine(fixture, LatencyPolicyPatch.DriversName + ".dll"), fixtureCorelib = Path.Combine(fixture, LatencyPolicyPatch.CoreLibName + ".dll");
string receiptPath = Path.Combine(fixture, PrivatePlatformFiles.ReceiptName);
string pendingPath = Path.Combine(fixture, PrivatePlatformFiles.PendingName);
try
{
File.WriteAllBytes(fixtureCore, originalCore); File.WriteAllBytes(fixtureHal, originalHal);
File.WriteAllBytes(fixtureDrivers, originalDrivers); File.WriteAllBytes(fixtureCorelib, originalCorelib);
PrivatePlatformFiles.Run(fixture);
byte[] afterCore = File.ReadAllBytes(fixtureCore), afterHal = File.ReadAllBytes(fixtureHal), receipt = File.ReadAllBytes(receiptPath);
byte[] afterDrivers = File.ReadAllBytes(fixtureDrivers), afterCorelib = File.ReadAllBytes(fixtureCorelib);
Check("PrivateFixturePairPatched", !afterCore.SequenceEqual(originalCore) && !afterHal.SequenceEqual(originalHal));
Check("SuccessfulWriteLeavesNoPendingTransaction", !File.Exists(pendingPath));
PrivatePlatformFiles.Run(fixture);
Check("ReceiptRepeatByteIdempotent", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal) &&
File.ReadAllBytes(fixtureDrivers).SequenceEqual(afterDrivers) && File.ReadAllBytes(fixtureCorelib).SequenceEqual(afterCorelib) && File.ReadAllBytes(receiptPath).SequenceEqual(receipt));
var policyReceipt = JsonSerializer.Deserialize<PrivatePlatformFiles.Receipt>(receipt)!;
Check("LatencyPolicyBoundInReceipt", policyReceipt.SchedulerTimerIntervalMs == 1 && policyReceipt.XhciPolledDrainIntervalMs == 1 &&
policyReceipt.SuppressedMonitorLogCalls == 9 && policyReceipt.MonitorWaitAlgorithmsPreserved && policyReceipt.SchedulerAccountingQuantumPreserved &&
policyReceipt.XhciMsiPathPreserved && policyReceipt.DriversAfterSha256 == PlatformPatch.Hash(afterDrivers) && policyReceipt.CoreLibAfterSha256 == PlatformPatch.Hash(afterCorelib));
var badReceipt = JsonSerializer.Deserialize<PrivatePlatformFiles.Receipt>(receipt)!;
badReceipt.CoreAfterSha256 = new string('0', 64);
File.WriteAllText(receiptPath, JsonSerializer.Serialize(badReceipt));
Check("ChangedReceiptRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("RejectionDoesNotChangeAssemblies", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal));
File.WriteAllBytes(receiptPath, receipt);
File.WriteAllBytes(fixtureHal, originalHal);
Check("PartialPairRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
File.WriteAllBytes(fixtureCore, originalCore);
Check("LatencyPartialRestorationRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
File.WriteAllBytes(fixtureDrivers, originalDrivers); File.WriteAllBytes(fixtureCorelib, originalCorelib);
// A stale receipt after Cosmos restores ALL exact official/generated inputs is safe to replace.
PrivatePlatformFiles.Run(fixture);
Check("OfficialPairRestorationAcceptsOldReceipt", File.ReadAllBytes(fixtureCore).SequenceEqual(afterCore) && File.ReadAllBytes(fixtureHal).SequenceEqual(afterHal));
File.WriteAllText(pendingPath, "{}", System.Text.Encoding.UTF8);
Check("InterruptedTransactionRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("PackageCachePathRejected", Rejects(() => PrivatePlatformFiles.Run(Path.GetDirectoryName(corePath)!)));
Check("PrivateParentOutsideObjRejected", Rejects(() => PrivatePlatformFiles.ValidateDirectory(Path.Combine(root, ".tools"))));
File.Delete(pendingPath);
File.WriteAllBytes(fixtureCore, afterCore.Concat(new byte[] { 99 }).ToArray());
Check("TamperedPatchedAssemblyRejected", Rejects(() => PrivatePlatformFiles.Run(fixture)));
Check("GlobalPackagesRemainUnchanged", File.ReadAllBytes(corePath).SequenceEqual(originalCore) && File.ReadAllBytes(halPath).SequenceEqual(originalHal) &&
File.ReadAllBytes(driversPath).SequenceEqual(originalDrivers) && File.ReadAllBytes(plugsPath).SequenceEqual(originalPlugs));
}
finally
{
foreach (string name in new[] { Path.GetFileName(corePath), Path.GetFileName(halPath), LatencyPolicyPatch.DriversName + ".dll", LatencyPolicyPatch.CoreLibName + ".dll", PrivatePlatformFiles.ReceiptName, PrivatePlatformFiles.PendingName, "XfeBootPlatformV1.lock" })
{
string path = Path.Combine(fixture, name);
if (File.Exists(path)) File.Delete(path);
}
Directory.Delete(fixture); Directory.Delete(Path.GetDirectoryName(fixture)!); Directory.Delete(fixtureBase);
}
Console.WriteLine(JsonSerializer.Serialize(new { Passed = true, Checks = checks, NativeGuestTested = false, HardwareBootTested = false, FixtureImageCreated = false }));