using System.Diagnostics; using System.Security.Cryptography; using System.Text.Json; using Mono.Cecil; using Mono.Cecil.Cil; using XFESystem.Kernel; if (args.Length != 3) throw new ArgumentException("GcRuntimePatch.Check "); string patcher = Path.GetFullPath(args[0]), original = Path.GetFullPath(args[1]), fixture = Path.GetFullPath(args[2]); Directory.CreateDirectory(fixture); var checks = new List(); EarlyBootConsoleRuntimePatchChecks.Run(Check); string originalHash = Hash(original); string kernelRoot = Path.Combine(fixture, "KernelCopy"); Directory.CreateDirectory(kernelRoot); File.WriteAllText(Path.Combine(kernelRoot, "XFESystem.Kernel.csproj"), ""); string privateDirectory = Path.Combine(kernelRoot, "obj", "Release", "net10.0", "linux-x64", "cosmos", "ref"); Directory.CreateDirectory(privateDirectory); string privatePath = Path.Combine(privateDirectory, "Cosmos.Kernel.Core.dll"); File.Copy(original, privatePath, true); Check("PinnedPrivatePatch", Invoke(privatePath) == 0); string patchedHash = Hash(privatePath); using (var before = AssemblyDefinition.ReadAssembly(original)) using (var after = AssemblyDefinition.ReadAssembly(privatePath)) { SerialRuntimePatchChecks.Run(before, after, Check); PeriodicSchedulerLogPatchChecks.Run(before, after, Check); var originalGc = Gc(before); var patchedGc = Gc(after); var target = patchedGc.Methods.Single(m => m.Name == "PreciseScanFrameChain"); var helper = patchedGc.Methods.Single(m => m.Name == "XfeScanPreciseTailFallbackV1"); var hooks = target.Body.Instructions.Where(i => i.Operand is MethodReference m && m.FullName == helper.FullName).ToArray(); Check("ExactlyTwoFallbackExits", hooks.Length == 2 && hooks.All(i => i.Next.OpCode == OpCodes.Ret)); Check("LastTrustedStackPointerUsed", hooks.All(i => i.Previous.OpCode == OpCodes.Ldarg_2 && i.Previous.Previous.OpCode == OpCodes.Ldloc && ((VariableDefinition)i.Previous.Previous.Operand).Index == 2)); var invalidEntry = hooks[0].Previous.Previous; Check("InvalidUnwindBranchesRedirected", target.Body.Instructions.Count(i => ReferenceEquals(i.Operand, invalidEntry)) == 3 && target.Body.Instructions.All(i => !ReferenceEquals(i.Operand, hooks[0].Next))); Check("FallbackRangeValidated", helper.Body.Instructions.Count == 9 && helper.Body.Instructions[1].OpCode == OpCodes.Brfalse && helper.Body.Instructions[4].OpCode == OpCodes.Bge_Un && helper.Body.Instructions[7].Operand is MethodReference scan && scan.Name == "ScanMemoryRange"); Check("OriginalPreciseAnd256LimitPreserved", target.Body.Instructions.Any(i => i.OpCode == OpCodes.Ldc_I4 && Equals(i.Operand, 256)) && target.Body.Instructions.Count(i => i.Operand is MethodReference m && m.Name == "RunFrame") == 2 && target.Body.Instructions.Count(i => i.Operand is MethodReference m && m.Name == "UnwindOneFrameWithCFI") == 1); Check("OtherGcMethodsUnchanged", originalGc.Methods.Where(m => m.Name is not "PreciseScanFrameChain" and not "AllocObject" and not "UpdateFrozenSegment").All(m => Il(m) == Il(patchedGc.Methods.Single(x => x.FullName == m.FullName)))); var frozenUpdate = patchedGc.Methods.Single(method => method.Name == "UpdateFrozenSegment"); var frozenValidate = patchedGc.Methods.Single(method => method.Name == "XfeValidateFrozenEndAddressesV1"); Check("FrozenUpdateValidatesBeforeEitherSizeStore", frozenUpdate.Body.Instructions.ToList().FindIndex(instruction => instruction.Operand is MethodReference call && call.Name == frozenValidate.Name) < frozenUpdate.Body.Instructions.ToList().FindIndex(instruction => instruction.OpCode == OpCodes.Stfld)); Check("FrozenSizeStoresSubtractSegmentStart", frozenUpdate.Body.Instructions.Where(instruction => instruction.OpCode == OpCodes.Stfld).All(store => store.Previous.OpCode == OpCodes.Conv_U && store.Previous.Previous.OpCode == OpCodes.Sub && store.Previous.Previous.Previous.OpCode == OpCodes.Ldarg_0)); Check("FrozenRangeChecksAvoidUnderflowAndEnforceReservation", frozenValidate.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Blt_Un) == 2 && frozenValidate.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Bgt_Un) == 1 && frozenValidate.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Sub) == 1 && frozenValidate.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Call or Code.Newobj or Code.Newarr or Code.Stsfld or Code.Stfld))); Check("FrozenRangePatchPreservesBranches", frozenUpdate.Body.Instructions.All(instruction => instruction.Operand is not Instruction branch || frozenUpdate.Body.Instructions.Contains(branch))); var frozenFatal = patchedGc.Methods.Single(method => method.Name == "XfeFailFrozenEndAddressesV1"); Check("InvalidFrozenRangesFailClosedWithoutAllocation", frozenFatal.Body.Instructions[0].Operand is MethodReference mask && mask.Name == "DisableInterruptsScope" && frozenFatal.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Ret or Code.Newobj or Code.Newarr or Code.Throw)) && ReferenceEquals(frozenFatal.Body.Instructions[^1].Operand, frozenFatal.Body.Instructions[^1])); var completedGcFields = new[] { "HeapSizeBytes", "FragmentedBytes", "TotalCommittedBytes", "CollectionIndex" }; foreach (var name in completedGcFields) { var leaf = patchedGc.Methods.Single(method => method.Name == "XfeLastGcMetricV1_" + name); Check("CompletedGcLeafSnapshot_" + name, leaf.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "UnmanagedCallersOnlyAttribute") && leaf.Body.Instructions.Count == (name == "CollectionIndex" ? 4 : 3) && leaf.Body.Instructions[0].OpCode == OpCodes.Ldsflda && leaf.Body.Instructions[0].Operand is FieldReference snapshot && snapshot.Name == "s_lastGCMemoryInfo" && leaf.Body.Instructions[1].OpCode == OpCodes.Ldfld && leaf.Body.Instructions[1].Operand is FieldReference field && field.Name == name && leaf.Body.Instructions[^1].OpCode == OpCodes.Ret && leaf.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Call or Code.Callvirt or Code.Stsfld or Code.Stfld or Code.Newobj or Code.Newarr or Code.Throw))); } var dependentCountExport = patchedGc.Methods.Single(method => method.Name == "XfeDependentHandleCountV1"); Check("DependentHandleLiveCountReadOnly", dependentCountExport.Body.Instructions.Count == 4 && dependentCountExport.Body.Instructions[0].OpCode == OpCodes.Ldsflda && dependentCountExport.Body.Instructions[1].OpCode == OpCodes.Ldflda && dependentCountExport.Body.Instructions[2].Operand is MethodReference countGetter && countGetter.Name == "get_Count" && countGetter.DeclaringType.FullName == "Cosmos.Kernel.Core.Memory.GarbageCollector.GCHandleSegmentStore"); Check("AllBranchTargetsRemainInBody", target.Body.Instructions.All(i => i.Operand switch { Instruction one => target.Body.Instructions.Contains(one), Instruction[] many => many.All(target.Body.Instructions.Contains), _ => true })); var eh = after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.ExceptionHandling.ExceptionHelper"); var initializer = eh.Methods.Single(method => method.IsConstructor && method.IsStatic); foreach (string name in new[] { "s_activeCatchFramePointers", "s_activeCatchHandlers", "s_activeCatchExInfos" }) { var store = initializer.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Stsfld && instruction.Operand is FieldReference field && field.Name == name); Check("EhTrackerCapacity_" + name, store.Previous.OpCode == OpCodes.Newarr && store.Previous.Previous.OpCode == OpCodes.Ldc_I4 && Equals(store.Previous.Previous.Operand, 4096)); } var dispatch = eh.Methods.Single(method => method.Name == "DispatchExceptionWithContext"); Check("EhComparisonAndMetadataCapacity", Equals(eh.Fields.Single(field => field.Name == "MaxActiveCatchDepth").Constant, 4096) && dispatch.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 4096))); var overflow = dispatch.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldstr && Equals(instruction.Operand, "Nested catch tracking capacity exceeded")); Check("EhOverflowCannotResumeUntrackedCatch", overflow.Next.OpCode == OpCodes.Ldarg_0 && overflow.Next.Next.Operand is MethodReference failure && failure.Name == "FailFast" && overflow.Next.Next.Next.OpCode == OpCodes.Ret); Check("EhPruningAndCatchSemanticsPreserved", new[] { "PruneFinishedCatches", "IsActiveCatchClause", "IsUnwoundFrame", "TryFindHandlerInLSDA", "InvokeCatchHandler" }.All(name => Il(eh.Methods.Single(method => method.Name == name)) == Il(before.MainModule.Types.Single(type => type.FullName == eh.FullName).Methods.Single(method => method.Name == name)))); var trace = eh.Methods.Single(method => method.Name == "XfeTraceFirstExceptionTypesV1"); Check("EhTraceBoundedAndNoUserMessageOrReflection", trace.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 8)) && !trace.Body.Instructions.Any(instruction => instruction.Operand is MethodReference call && call.Name is "get_Message" or "GetType" or "get_Name" or "ToString")); Check("EhTraceLocalIndexExplicitlyInitialized", trace.Body.InitLocals && trace.Body.Instructions.Zip(trace.Body.Instructions.Skip(1)).Any(pair => pair.First.OpCode == OpCodes.Ldc_I4_0 && pair.Second.OpCode == OpCodes.Stloc && pair.Second.Operand is VariableDefinition variable && variable.Index == 1)); Check("EhTraceOnlyAfterHandlerSelected", dispatch.Body.Instructions.Count(instruction => instruction.Operand is MethodReference call && call.FullName == trace.FullName) == 1 && dispatch.Body.Instructions.Single(instruction => instruction.Operand is MethodReference call && call.FullName == trace.FullName).Next.Operand is FieldReference countField && countField.Name == "s_activeCatchCount"); var thread = after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Scheduler.SchedulerThread"); var cpu = after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Scheduler.PerCpuState"); var threadSwitch = eh.Methods.Single(method => method.Name == "XfeSwitchThreadEhV1"); var threadConstructor = thread.Methods.Single(method => method.IsConstructor && !method.IsStatic); var currentSetter = cpu.Methods.Single(method => method.Name == "set_CurrentThread"); Check("ThreadEhEightManagedStateFields", thread.Fields.Count(field => field.Name.StartsWith("_xfeThreadEhV1_", StringComparison.Ordinal)) == 8); Check("ThreadEhFourArraysAllocatedBeforeRunnable", threadConstructor.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Newarr) == 4 && threadConstructor.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 4096)) == 3); Check("ThreadEhSingleUnifiedCurrentThreadHook", currentSetter.Body.Instructions[3].Operand is MethodReference switchCall && switchCall.FullName == threadSwitch.FullName && currentSetter.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Stfld) == 1); Check("ThreadEhSwitchIsAllocationAndExceptionFree", threadSwitch.Body.ExceptionHandlers.Count == 0 && threadSwitch.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Newobj or Code.Newarr or Code.Throw)) && threadSwitch.Body.Instructions.All(instruction => instruction.Operand is not MethodReference call || call.Name is "XfeGetNativeExInfoHeadV1" or "XfeSetNativeExInfoHeadV1")); Check("ThreadEhInstalledArraysAreMutable", eh.Fields.Where(field => field.Name is "s_activeCatchFramePointers" or "s_activeCatchHandlers" or "s_activeCatchExInfos" or "s_xfeEhTraceTypesV1").All(field => !field.IsInitOnly)); Check("ThreadEhGateRequiresRunningSingleCpuScheduler", eh.Methods.Single(method => method.Name == "XfeThreadEhContractVersionV1").Body.Instructions.Count(instruction => instruction.Operand is MethodReference call && call.Name is "get_IsRunning" or "get_CpuCount") == 2); var resolver = eh.Methods.Single(method => method.Name == "XfeResolveEhFuncletRootV1"); Check("EhRootResolverUsesSignedDeltas", resolver.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Ldind_I4) == 2 && resolver.Body.Instructions.Count(instruction => instruction.OpCode == OpCodes.Conv_I) == 2); Check("EhResolverDoesNotChangeGcMetadataLookup", Il(before.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.GcInfo.MethodGcInfoLookup").Methods.Single(method => method.Name == "TryGetMethodLSDA")) == Il(after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.GcInfo.MethodGcInfoLookup").Methods.Single(method => method.Name == "TryGetMethodLSDA"))); var stackInitialize = thread.Methods.Single(method => method.Name == "InitializeStack"); var stackGuard = thread.Methods.Single(method => method.Name == "XfeRequireThreadStackV1"); var stackFatal = thread.Methods.Single(method => method.Name == "XfeFailThreadStackV1"); var stackHook = stackInitialize.Body.Instructions.Single(instruction => instruction.Operand is MethodReference call && call.FullName == stackGuard.FullName); Check("RawStackGuardBeforeContextAndStackBaseWrites", stackHook.Previous.OpCode == OpCodes.Conv_U8 && stackHook.Previous.Previous.OpCode == OpCodes.Ldarg && stackHook.Previous.Previous.Previous.Operand is MethodReference rawStackAllocator && rawStackAllocator.Name == "XfeAllocateThreadStackV1" && stackHook.Next.Operand is MethodReference stackBaseStore && stackBaseStore.Name == "set_StackBase"); Check("RawStackNullHaltsWithoutReturning", stackGuard.Body.Instructions.Count == 7 && stackGuard.Body.Instructions[1].OpCode == OpCodes.Brtrue && stackGuard.Body.Instructions[3].Operand is MethodReference stackFailure && stackFailure.FullName == stackFatal.FullName && ReferenceEquals(stackGuard.Body.Instructions[4].Operand, stackGuard.Body.Instructions[4]) && ReferenceEquals(stackFatal.Body.Instructions[^1].Operand, stackFatal.Body.Instructions[^1])); Check("RawStackFailureReportsPhysicalPagesWithoutAllocation", stackFatal.Body.Variables.Count == 0 && stackFatal.Body.ExceptionHandlers.Count == 0 && stackFatal.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Newobj or Code.Newarr or Code.Throw or Code.Ret)) && stackFatal.Body.Instructions.Any(instruction => instruction.Operand is MethodReference getter && getter.Name == "get_FreePageCount") && stackFatal.Body.Instructions.Any(instruction => instruction.Operand is FieldReference field && field.Name == "TotalPageCount")); Check("RawPageCountExportsAreLeafReads", thread.Methods.Where(method => method.Name is "XfeRawFreePageCountV1" or "XfeRawTotalPageCountV1").Count(method => method.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "UnmanagedCallersOnlyAttribute") && method.Body.Instructions.Count == 2) == 2); var rawStackAllocate = thread.Methods.Single(method => method.Name == "XfeAllocateThreadStackV1"); Check("RawStackAllocationCollectsAndRetriesOnlyAfterFailure", rawStackAllocate.Body.Instructions.Count(instruction => instruction.Operand is MethodReference call && call.Name == "Alloc") == 2 && rawStackAllocate.Body.Instructions.Count(instruction => instruction.Operand is MethodReference call && call.Name == "Collect") == 1 && rawStackAllocate.Body.Instructions[4].OpCode == OpCodes.Brtrue && ReferenceEquals(rawStackAllocate.Body.Instructions[4].Operand, rawStackAllocate.Body.Instructions[^2])); var largestRawRun = thread.Methods.Single(method => method.Name == "XfeRawLargestFreeRunPagesV1"); Check("RawLargestRunReadOnlyBoundedAndRestoresInterrupts", largestRawRun.Body.InitLocals && largestRawRun.Body.ExceptionHandlers.Count == 0 && largestRawRun.Body.Instructions.Any(instruction => instruction.Operand is FieldReference field && field.Name == "TotalPageCount") && largestRawRun.Body.Instructions.Count(instruction => instruction.Operand is MethodReference call && call.Name is "DisableInterruptsScope" or "Dispose") == 2 && largestRawRun.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Stsfld or Code.Stfld or Code.Stind_I1 or Code.Stind_I4 or Code.Stind_I8 or Code.Newarr or Code.Newobj or Code.Throw))); var memory = after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.Memory"); var allocationGuard = memory.Methods.Single(method => method.Name == "XfeRequireManagedAllocationV1"); var allocationFatal = memory.Methods.Single(method => method.Name == "XfeFailManagedAllocationV1"); var managedAllocator = patchedGc.Methods.Single(method => method.Name == "AllocObject"); var bootAllocator = memory.Methods.Single(method => method.Name == "AllocObject"); var managedHook = managedAllocator.Body.Instructions.Single(instruction => instruction.Operand is MethodReference call && call.FullName == allocationGuard.FullName); var bootHook = bootAllocator.Body.Instructions.Single(instruction => instruction.Operand is MethodReference call && call.FullName == allocationGuard.FullName); Check("ManagedGuardRunsAfterIrqFinally", managedHook.Next.OpCode == OpCodes.Ret && managedAllocator.Body.ExceptionHandlers[0].HandlerType == ExceptionHandlerType.Finally && ReferenceEquals(managedAllocator.Body.ExceptionHandlers[0].HandlerEnd, managedHook.Previous.Previous.Previous) && managedAllocator.Body.Instructions.Any(instruction => instruction.Operand is MethodReference call && call.Name == "Dispose")); Check("PreGcGuardRunsBeforeRawMemSet", bootHook.Next.OpCode == OpCodes.Stloc_0 && bootHook.Previous.Previous.Previous.Operand is MethodReference rawAllocator && rawAllocator.Name == "Alloc" && bootAllocator.Body.Instructions.IndexOf(bootHook) < bootAllocator.Body.Instructions.IndexOf(bootAllocator.Body.Instructions.Single(instruction => instruction.Operand is MethodReference clear && clear.Name == "MemSet"))); Check("SuccessfulAllocationReturnsExactPointer", allocationGuard.IsAssembly && allocationGuard.ImplAttributes.HasFlag(MethodImplAttributes.AggressiveInlining) && allocationGuard.Body.Instructions.Count == 7 && allocationGuard.Body.Instructions[0].OpCode == OpCodes.Ldarg_0 && allocationGuard.Body.Instructions[1].OpCode == OpCodes.Brtrue && ReferenceEquals(allocationGuard.Body.Instructions[1].Operand, allocationGuard.Body.Instructions[5]) && allocationGuard.Body.Instructions[5].OpCode == OpCodes.Ldarg_0 && allocationGuard.Body.Instructions[6].OpCode == OpCodes.Ret); Check("FailedAllocationCannotReturnNull", allocationGuard.Body.Instructions[2].OpCode == OpCodes.Ldarg_1 && allocationGuard.Body.Instructions[3].Operand is MethodReference fatalCall && fatalCall.FullName == allocationFatal.FullName && allocationGuard.Body.Instructions[4].OpCode == OpCodes.Br && ReferenceEquals(allocationGuard.Body.Instructions[4].Operand, allocationGuard.Body.Instructions[4]) && allocationFatal.Body.Instructions.All(instruction => instruction.OpCode != OpCodes.Ret) && ReferenceEquals(allocationFatal.Body.Instructions[^1].Operand, allocationFatal.Body.Instructions[^1])); Check("AllocationFatalOnlyConstantSerialOperations", allocationFatal.Body.Variables.Count == 0 && allocationFatal.Body.ExceptionHandlers.Count == 0 && allocationFatal.Body.Instructions.All(instruction => instruction.OpCode != OpCodes.Newobj && instruction.OpCode != OpCodes.Newarr && instruction.OpCode != OpCodes.Throw) && allocationFatal.Body.Instructions.All(instruction => instruction.Operand is not MethodReference call || call.DeclaringType.FullName == "Cosmos.Kernel.Core.IO.Serial" && call.Name is "WriteString" or "WriteNumber" || call.Name is "get_FreePageCount" or "XfeRawLargestFreeRunPagesV1" or "DisableInterruptsScope") && allocationFatal.Body.Instructions.Any(instruction => instruction.Operand is string value && value.Contains("GuestHalt"))); Check("ManagedAndRawStackFatalMaskIrqsBeforeFirstDiagnosticUntilPermanentStop", new[] { allocationFatal, stackFatal }.All(method => method.Body.Instructions[0].Operand is MethodReference disable && disable.DeclaringType.FullName == "Cosmos.Kernel.Core.CPU.InternalCpu" && disable.Name == "DisableInterruptsScope" && method.Body.Instructions[1].OpCode == OpCodes.Pop && method.Body.Instructions[2].Operand is string message && message.StartsWith("\nXFE_RUNTIME_", StringComparison.Ordinal) && method.Body.Instructions.All(instruction => instruction.OpCode != OpCodes.Ret && (instruction.Operand is not MethodReference call || call.Name != "Dispose")) && ReferenceEquals(method.Body.Instructions[^1].Operand, method.Body.Instructions[^1]))); Check("AllocatorBranchesAndHandlerBoundariesRemainValid", new[] { managedAllocator, bootAllocator, allocationGuard, allocationFatal }.All(method => method.Body.Instructions.All(instruction => instruction.Operand is not Instruction branch || method.Body.Instructions.Contains(branch))) && managedAllocator.Body.ExceptionHandlers.All(handler => managedAllocator.Body.Instructions.Contains(handler.TryStart) && managedAllocator.Body.Instructions.Contains(handler.TryEnd) && managedAllocator.Body.Instructions.Contains(handler.HandlerStart) && managedAllocator.Body.Instructions.Contains(handler.HandlerEnd))); } Check("ByteIdempotence", Invoke(privatePath) == 0 && Hash(privatePath) == patchedHash); using (var stableReceipt = JsonDocument.Parse(File.ReadAllText(privatePath + ".XfeGc.json"))) { Check("OriginalProvenanceSurvivesIdempotentRun", stableReceipt.RootElement.GetProperty("BeforeSha256").GetString() == originalHash && stableReceipt.RootElement.GetProperty("OriginalPinnedSha256").GetString() == originalHash && stableReceipt.RootElement.GetProperty("InputSha256").GetString() == patchedHash); Check("ForcedTimesliceReceiptBindsActualCoreHashAndHonestChangedPolicy", stableReceipt.RootElement.GetProperty("AfterSha256").GetString() == patchedHash && stableReceipt.RootElement.GetProperty("SchedulerForcedTimesliceNanoseconds").GetInt64() == 1_000_000 && stableReceipt.RootElement.GetProperty("SchedulerStrideAccountingDivisorNanoseconds").GetInt64() == 10_000_000 && stableReceipt.RootElement.GetProperty("SchedulerTimesliceChangedInstructionIndex").GetInt32() == 103 && stableReceipt.RootElement.GetProperty("SchedulerTickCounterAndAccountingPreserved").GetBoolean() && !stableReceipt.RootElement.GetProperty("SchedulerPreemptionPreserved").GetBoolean() && stableReceipt.RootElement.GetProperty("SchedulerPassBasedPreemptionPreserved").GetBoolean()); } File.Copy(original, privatePath, true); Check("OfficialRebuildWithStaleReceiptAccepted", Invoke(privatePath) == 0 && Hash(privatePath) == patchedHash); string outsidePath = Path.Combine(fixture, "Cosmos.Kernel.Core.dll"); File.Copy(original, outsidePath, true); Check("OutsidePrivatePathRejectedWithoutMutation", Invoke(outsidePath) != 0 && Hash(outsidePath) == originalHash); File.Copy(original, privatePath, true); File.Delete(privatePath + ".XfeGc.json"); using (var malformed = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var method = Gc(malformed).Methods.Single(m => m.Name == "PreciseScanFrameChain"); method.Body.Instructions.Single(i => i.OpCode == OpCodes.Ldc_I4 && Equals(i.Operand, 256)).Operand = 255; malformed.Write(privatePath); } string malformedHash = Hash(privatePath); Check("UnexpectedScannerIlRejectedWithoutMutation", Invoke(privatePath) != 0 && Hash(privatePath) == malformedHash); File.Copy(original, privatePath, true); File.Delete(privatePath + ".XfeGc.json"); using (var malformedEh = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var eh = malformedEh.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.ExceptionHandling.ExceptionHelper"); var dispatch = eh.Methods.Single(method => method.Name == "DispatchExceptionWithContext"); dispatch.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4_S && Convert.ToInt32(instruction.Operand) == 64).Operand = (sbyte)63; malformedEh.Write(privatePath); } string badEhHash = Hash(privatePath); Check("UnexpectedEhRejectedBeforeGcAtomicWrite", Invoke(privatePath) != 0 && Hash(privatePath) == badEhHash); File.Copy(original, privatePath, true); File.Delete(privatePath + ".XfeGc.json"); using (var malformedAllocation = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var method = Gc(malformedAllocation).Methods.Single(method => method.Name == "AllocObject"); method.Body.ExceptionHandlers[0].HandlerEnd = method.Body.Instructions[^1]; malformedAllocation.Write(privatePath); } string badAllocationHash = Hash(privatePath); Check("UnexpectedAllocationScopeRejectedBeforeAnyAtomicWrite", Invoke(privatePath) != 0 && Hash(privatePath) == badAllocationHash); File.Copy(original, privatePath, true); File.Delete(privatePath + ".XfeGc.json"); using (var malformedBoot = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var method = malformedBoot.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.Memory").Methods.Single(method => method.Name == "AllocObject"); var clear = method.Body.Instructions.Single(instruction => instruction.Operand is MethodReference call && call.Name == "MemSet"); clear.OpCode = OpCodes.Pop; clear.Operand = null; malformedBoot.Write(privatePath); } string badBootHash = Hash(privatePath); Check("UnexpectedPreGcZeroingRejectedBeforeAnyAtomicWrite", Invoke(privatePath) != 0 && Hash(privatePath) == badBootHash); File.Copy(original, privatePath, true); File.Delete(privatePath + ".XfeGc.json"); using (var malformedStack = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var method = malformedStack.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Scheduler.SchedulerThread").Methods.Single(method => method.Name == "InitializeStack"); method.Body.Instructions[0].OpCode = OpCodes.Nop; malformedStack.Write(privatePath); } string badStackHash = Hash(privatePath); Check("UnexpectedRawStackShapeRejectedBeforeAnyAtomicWrite", Invoke(privatePath) != 0 && Hash(privatePath) == badStackHash); File.Copy(original, privatePath, true); Check("FreshCombinedPatchForReceiptTest", Invoke(privatePath) == 0); using (var altered = AssemblyDefinition.ReadAssembly(privatePath, new ReaderParameters { InMemory = true })) { var helper = altered.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Runtime.ExceptionHandling.ExceptionHelper").Methods.Single(method => method.Name == "XfeTraceFirstExceptionTypesV1"); helper.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldstr && Equals(instruction.Operand, "|Depth|")).Operand = "Changed"; altered.Write(privatePath); } string changedHash = Hash(privatePath); Check("ChangedEhReceiptRejectedWithoutMutation", Invoke(privatePath) != 0 && Hash(privatePath) == changedHash); Check("GlobalPackageCacheUnchanged", Hash(original) == originalHash); Check("NativeFixtureCoreClrControlOnly", NativeGcRegression.Run() && NativeGcRegression.FramesVerified == 321 && NativeGcRegression.CollectionsRequested == 2); bool ehPassed = false; Exception? ehFailure = null; // CoreCLR's Windows default main stack is 1 MiB. This host control isolates fixture semantics // from host stack sizing; the native kernel still executes the fixture on its real boot stack. var ehThread = new Thread(() => { try { ehPassed = NativeEhRegression.Run(); } catch (Exception failure) { ehFailure = failure; } }, 16 * 1024 * 1024); ehThread.Start(); ehThread.Join(); Check("DeepRethrowFixtureCoreClrControlOnly", ehFailure is null && ehPassed && NativeEhRegression.FramesCaught == NativeEhRegression.RequestedDepth + 1 && NativeEhRegression.RequestedDepth + 1 > 64 && NativeEhRegression.OriginalExceptionPreserved && NativeEhRegression.PostCatchFrames == 4); Check("WeakLifetimeFixtureCoreClrControlOnly", NativeWeakLifetimeRegression.Run() && NativeWeakLifetimeRegression.ChecksPassed == 5 && NativeWeakLifetimeRegression.WeakTargetCleared && NativeWeakLifetimeRegression.LiveValuePreserved && NativeWeakLifetimeRegression.CycleCleared && NativeWeakLifetimeRegression.FixedPointPreserved && NativeWeakLifetimeRegression.HandlesDisposed); Check("FrozenRangeFixtureCoreClrControlOnly", NativeFrozenRangeRegression.Run( (start, reserved, allocatedEnd, committedEnd) => start != 0 && allocatedEnd >= start && committedEnd >= allocatedEnd && committedEnd - start <= reserved ? 1 : 0, () => 1) && NativeFrozenRangeRegression.ChecksPassed == 8); File.WriteAllText(Path.Combine(fixture, "Result.json"), JsonSerializer.Serialize(new { Kind = "GcTailPatchHostStructuralControl", Passed = true, NativeGuestTested = false, RootCauseProven = false, OriginalSha256 = originalHash, PatchedSha256 = patchedHash, Checks = checks, NativeFixtureDepth = NativeGcRegression.RequestedDepth, NativeFixtureFramesVerified = NativeGcRegression.FramesVerified, EhLimit = 4096, EhDeepRethrowFrames = NativeEhRegression.FramesCaught, EhPostCatchFrames = NativeEhRegression.PostCatchFrames, AllocationGuards = 2, AllocationFailureHaltsEntireGuest = true, AllocationFailureRecoverySupported = false, Meaning = "Private IL insertion and host fixture control passed; Cosmos native collector regression is required separately." }, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine($"PASS {checks.Count} checks; native GC behavior remains unproven."); void Check(string name, bool passed) { checks.Add(new { Name = name, Passed = passed }); if (!passed) throw new InvalidOperationException(name); } int Invoke(string path) { var info = new ProcessStartInfo("dotnet") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; info.ArgumentList.Add(patcher); info.ArgumentList.Add(path); using var process = Process.Start(info)!; string stdout = process.StandardOutput.ReadToEnd(), stderr = process.StandardError.ReadToEnd(); process.WaitForExit(); File.AppendAllText(Path.Combine(fixture, "Patcher.log"), stdout + stderr + Environment.NewLine); return process.ExitCode; } static string Hash(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path))); static TypeDefinition Gc(AssemblyDefinition assembly) => assembly.MainModule.Types.Single(t => t.FullName == "Cosmos.Kernel.Core.Memory.GarbageCollector.GarbageCollector"); static string Il(MethodDefinition method) => !method.HasBody ? "" : string.Join("\n", method.Body.Instructions.Select(i => i.ToString()));