using System.Reflection; using System.Runtime.Loader; using Mono.Cecil; using Mono.Cecil.Cil; using XfeBootPlatformPatch; internal static class LatencyPolicyChecks { public static byte[] OriginalCoreLibFixture(byte[] officialPlugs, byte[] officialCorelib) { using var plugs = Read(officialPlugs); using var fixture = Read(officialCorelib); var sys = fixture.MainModule.Types.Single(type => type.FullName == "Interop").NestedTypes.Single(type => type.Name == "Sys"); foreach (var source in plugs.MainModule.Types.Single(type => type.Name == "InteropSysPlug").Methods.Where(method => LatencyPolicyPatch.Monitors.Any(contract => contract.Name == method.Name))) { CloneMethod(source, sys, false, sys.Methods.Single(method => method.Name == source.Name)); } return Write(fixture); } public static void Run(byte[] originalHal, byte[] originalDrivers, byte[] originalCorelib, Action check) { using var hal = Read(originalHal); using var drivers = Read(originalDrivers); using var corelib = Read(originalCorelib); var start = LatencyPolicyPatch.SchedulerTimer(hal); var startBefore = Shape(start); LatencyPolicyPatch.ApplySchedulerTimer(hal); check("LatencyLapicOnlyArgumentConstantChanged", Diff(startBefore, Shape(start)) == 1 && start.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "StartPeriodicTimer").Previous.OpCode == OpCodes.Ldc_I4_1); var hot = LatencyPolicyPatch.HotPlug(drivers); var hotBefore = Shape(hot); var driverMethods = AllMethods(drivers).Where(method => method.HasBody && method != hot).ToDictionary(method => method, PlatformPatch.Fingerprint); var otherRuntimeMethods = AllMethods(corelib).Where(method => method.HasBody && !(method.DeclaringType.FullName == "Interop/Sys" && LatencyPolicyPatch.Monitors.Any(contract => contract.Name == method.Name))) .ToDictionary(method => method, PlatformPatch.Fingerprint); var originals = LatencyPolicyPatch.Monitors.ToDictionary(contract => contract.Name, contract => Shape(LatencyPolicyPatch.Monitor(corelib, contract.Name))); var originalLocals = LatencyPolicyPatch.Monitors.ToDictionary(contract => contract.Name, contract => string.Join(';', LatencyPolicyPatch.Monitor(corelib, contract.Name).Body.Variables.Select(variable => variable.VariableType.FullName))); LatencyPolicyPatch.ApplyIo(drivers, corelib); check("LatencyEveryOtherDriverQueueAndIrqMethodUnchanged", AllMethods(drivers).Where(method => method.HasBody && method != hot).All(method => driverMethods[method] == PlatformPatch.Fingerprint(method))); check("LatencyEveryOtherCoreLibGcThreadAndWaitMethodUnchanged", AllMethods(corelib).Where(otherRuntimeMethods.ContainsKey).All(method => otherRuntimeMethods[method] == PlatformPatch.Fingerprint(method))); check("LatencyXhciOnlyFallbackSleepArgumentChanged", Diff(hotBefore, Shape(hot)) == 1 && hot.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "Sleep").Previous.OpCode == OpCodes.Ldc_I4_1); check("LatencyXhciMsiWait1000StillPresent", hot.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "Wait").Previous is { OpCode.Code: Code.Ldc_I4, Operand: 1000 }); check("LatencyXhciLockFinallyDrainDetachUnchanged", hot.Body.ExceptionHandlers.Count == 1 && hot.Body.ExceptionHandlers[0].HandlerType == ExceptionHandlerType.Finally && new[] { "HandlePortChanges", "get_Lock", "Acquire", "DrainEvents", "Dispose", "get_IsDetaching" }.All(name => hot.Body.Instructions.Any(instruction => instruction.Operand is MethodReference method && method.Name == name))); foreach (var contract in LatencyPolicyPatch.Monitors) { var method = LatencyPolicyPatch.Monitor(corelib, contract.Name); var after = Shape(method); check("LatencyMonitorOnlyLogsNopped_" + contract.Name, after.Length == originals[contract.Name].Length && after.Where((_, index) => !contract.LogInstructions.Contains(index)).SequenceEqual(originals[contract.Name].Where((_, index) => !contract.LogInstructions.Contains(index))) && contract.LogInstructions.All(index => method.Body.Instructions[index].OpCode == OpCodes.Nop)); check("LatencyMonitorLocalsAndWaitCallsPreserved_" + contract.Name, string.Join(';', method.Body.Variables.Select(variable => variable.VariableType.FullName)) == originalLocals[contract.Name] && method.Body.ExceptionHandlers.Count == 0 && !method.Body.Instructions.Any(instruction => instruction.Operand is MethodReference call && call.DeclaringType.FullName == "Cosmos.Kernel.System.Diagnostics.Log")); } using (var roundDrivers = Read(Write(drivers))) using (var roundCorelib = Read(Write(corelib))) { LatencyPolicyPatch.VerifyIo(roundDrivers, roundCorelib); check("LatencyGeneratedIoRoundTripContract", true); } CheckRejected("LatencyChangedOriginalXhciDrainRejected", () => { using var changed = Read(originalDrivers); using var original = Read(originalCorelib); LatencyPolicyPatch.HotPlug(changed).Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "DrainEvents").OpCode = OpCodes.Nop; LatencyPolicyPatch.ApplyIo(changed, original); }); CheckRejected("LatencyChangedMonitorTimeoutBranchRejected", () => { using var changed = Read(originalCorelib); using var original = Read(originalDrivers); LatencyPolicyPatch.Monitor(changed, "LowLevelMonitor_TimedWait").Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Bge_S).OpCode = OpCodes.Bgt_S; LatencyPolicyPatch.ApplyIo(original, changed); }); CheckRejected("LatencyChangedPatchedWaitRejected", () => { using var changed = Read(Write(corelib)); using var patched = Read(Write(drivers)); LatencyPolicyPatch.Monitor(changed, "LowLevelMonitor_TimedWait").Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Pop).OpCode = OpCodes.Nop; LatencyPolicyPatch.VerifyIo(patched, changed); }); using (var original = Read(originalCorelib)) using (var oldRunner = new Runner(original)) using (var newRunner = new Runner(corelib)) { foreach (var contract in LatencyPolicyPatch.Monitors) foreach (int timeout in contract.Name == "LowLevelMonitor_TimedWait" ? new[] { -1, 0, 7, 1000 } : new[] { 0 }) { var before = oldRunner.Call(contract.Name, timeout); var after = newRunner.Call(contract.Name, timeout); check("LatencyExecutableWaitSemantics_" + contract.Name + "_" + timeout, before.Logs > 0 && after.Logs == 0 && after == before with { Logs = 0 } && before.HandleResolutions == 1); if (contract.Name == "LowLevelMonitor_TimedWait") check("LatencyExecutableTimeoutBranch_" + timeout, after.Result is true && (timeout < 0 ? after.IndefiniteWaits == 1 && after.TimedWaits == 0 : after.IndefiniteWaits == 0 && after.TimedWaits == 1 && after.Timeout == timeout)); } } void CheckRejected(string name, Action operation) { bool rejected; try { operation(); rejected = false; } catch (InvalidOperationException) { rejected = true; } check(name, rejected); } } private static int Diff(string[] before, string[] after) => before.Length != after.Length ? int.MaxValue : before.Where((line, index) => line != after[index]).Count(); private static IEnumerable AllMethods(AssemblyDefinition assembly) { IEnumerable Types(TypeDefinition type) => new[] { type }.Concat(type.NestedTypes.SelectMany(Types)); return assembly.MainModule.Types.SelectMany(Types).SelectMany(type => type.Methods); } private static string[] Shape(MethodDefinition method) => method.Body.Instructions.Select(instruction => instruction.OpCode.Code + ":" + (instruction.Operand switch { Instruction branch => "#" + method.Body.Instructions.IndexOf(branch), VariableDefinition local => "$" + local.Index, MemberReference reference => reference.FullName, null => "", var value => value.ToString() })).ToArray(); private static AssemblyDefinition Read(byte[] bytes) => AssemblyDefinition.ReadAssembly(new MemoryStream(bytes, false), new ReaderParameters { InMemory = true }); private static byte[] Write(AssemblyDefinition assembly) { using var stream = new MemoryStream(); assembly.Write(stream); return stream.ToArray(); } private static MethodDefinition CloneMethod(MethodDefinition source, TypeDefinition destination, bool executable, MethodDefinition? existing = null) { var module = destination.Module; TypeReference Type(TypeReference type) => executable && type.FullName.Contains("GCHandle`1", StringComparison.Ordinal) ? module.ImportReference(typeof(LatencyMonitorFixture.Handle)) : executable && type.FullName == "Cosmos.Kernel.Core.Scheduler.Monitor" ? module.ImportReference(typeof(LatencyMonitorFixture.Monitor)) : module.ImportReference(type); var method = existing ?? new MethodDefinition(source.Name, Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, Type(source.ReturnType)); if (existing is null) { foreach (var parameter in source.Parameters) method.Parameters.Add(new(parameter.Name, parameter.Attributes, Type(parameter.ParameterType))); destination.Methods.Add(method); } else { method.PInvokeInfo = null; method.IsPInvokeImpl = false; method.ImplAttributes = Mono.Cecil.MethodImplAttributes.IL | Mono.Cecil.MethodImplAttributes.Managed; } method.Body = new Mono.Cecil.Cil.MethodBody(method) { InitLocals = source.Body.InitLocals, MaxStackSize = source.Body.MaxStackSize }; var locals = source.Body.Variables.ToDictionary(variable => variable, variable => new VariableDefinition(Type(variable.VariableType))); foreach (var local in locals.Values) method.Body.Variables.Add(local); var instructions = source.Body.Instructions.ToDictionary(instruction => instruction, _ => Instruction.Create(OpCodes.Nop)); foreach (var instruction in source.Body.Instructions) { var clone = instructions[instruction]; clone.OpCode = instruction.OpCode; clone.Operand = instruction.Operand switch { Instruction branch => instructions[branch], ParameterDefinition parameter => method.Parameters[parameter.Index], VariableDefinition local => locals[local], MethodReference call => Call(call), TypeReference type => Type(type), FieldReference field => module.ImportReference(field), null => null, _ => instruction.Operand }; method.Body.Instructions.Add(clone); } return method; MethodReference Call(MethodReference call) { if (!executable) return module.ImportReference(call); System.Type? target = call.DeclaringType.FullName.Contains("GCHandle`1", StringComparison.Ordinal) ? typeof(LatencyMonitorFixture.Handle) : call.DeclaringType.FullName == "Cosmos.Kernel.Core.Scheduler.Monitor" ? typeof(LatencyMonitorFixture.Monitor) : call.DeclaringType.FullName == "Cosmos.Kernel.System.Diagnostics.Log" ? typeof(LatencyMonitorFixture) : null; if (target is null) return module.ImportReference(call); return module.ImportReference(target.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) .Single(candidate => candidate.Name == call.Name && candidate.GetParameters().Length == call.Parameters.Count)); } } private sealed class Runner : IDisposable { private readonly AssemblyLoadContext context = new("MonitorWaitSemantics", true); private readonly Type callbacks; public Runner(AssemblyDefinition source) { using var fixture = AssemblyDefinition.CreateAssembly(new("MonitorFixture_" + Guid.NewGuid().ToString("N"), new Version(1, 0)), "MonitorFixture", ModuleKind.Dll); var type = new TypeDefinition("Fixture", "Callbacks", Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Abstract | Mono.Cecil.TypeAttributes.Sealed, fixture.MainModule.TypeSystem.Object); fixture.MainModule.Types.Add(type); foreach (var contract in LatencyPolicyPatch.Monitors) CloneMethod(LatencyPolicyPatch.Monitor(source, contract.Name), type, true); using var stream = new MemoryStream(Write(fixture)); callbacks = context.LoadFromStream(stream).GetType("Fixture.Callbacks", true)!; } public LatencyMonitorFixture.Observation Call(string name, int timeout) { LatencyMonitorFixture.Reset(); object? value = callbacks.GetMethod(name)!.Invoke(null, name == "LowLevelMonitor_TimedWait" ? [new IntPtr(42), timeout] : [new IntPtr(42)]); return LatencyMonitorFixture.Read(value); } public void Dispose() => context.Unload(); } } public static class LatencyMonitorFixture { private static int logs, resolutions; private static Monitor monitor = new(); public static void Reset() { logs = resolutions = 0; monitor = new(); } public static void Write(ReadOnlySpan args) => logs++; public static void WriteNumber(int value) => logs++; public static Observation Read(object? value) => new(logs, resolutions, monitor.Acquires, monitor.Releases, monitor.IndefiniteWaits, monitor.TimedWaits, monitor.Timeout, monitor.Signals, value); public sealed record Observation(int Logs, int HandleResolutions, int Acquires, int Releases, int IndefiniteWaits, int TimedWaits, int Timeout, int Signals, object? Result); public struct Handle { public static Handle FromIntPtr(IntPtr pointer) { resolutions++; return new(); } public Monitor Target => monitor; } public sealed class Monitor { public int Acquires, Releases, IndefiniteWaits, TimedWaits, Timeout, Signals; public void Acquire() => Acquires++; public void Release() => Releases++; public void Wait() => IndefiniteWaits++; public bool Wait(int timeout) { TimedWaits++; Timeout = timeout; return false; } public void Signal() => Signals++; } }