using System.Reflection;
using System.Runtime.Loader;
using Mono.Cecil;
using Mono.Cecil.Cil;
using XfeBootPlatformPatch;
internal static class LatencyClockChecks
{
public static void Run(AssemblyDefinition originalCoreX64, AssemblyDefinition patchedCoreX64,
AssemblyDefinition originalHal, AssemblyDefinition patchedHal, AssemblyDefinition commonCore, Action<string, bool> check)
{
var apic = originalCoreX64.MainModule.Types.Single(type => type.Name == "LocalApic");
var originalStart = apic.Methods.Single(method => method.Name == "StartPeriodicTimer");
var patchedStart = patchedCoreX64.MainModule.Types.Single(type => type.Name == "LocalApic").Methods.Single(method => method.Name == "StartPeriodicTimer");
check("LatencyLapicCounterCalibrationAndIntervalWriterUnchanged", PlatformPatch.Fingerprint(originalStart) == PlatformPatch.Fingerprint(patchedStart));
var callback = PlatformPatch.Timer(patchedCoreX64);
var callbackCall = callback.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "OnTimerInterrupt");
check("LatencyIsrElapsedArgumentUsesProgrammedIntervalNs", callbackCall.Previous.OpCode == OpCodes.Ldsfld &&
callbackCall.Previous.Operand is FieldReference field && field.Name == "s_timerIntervalNs");
var manager = commonCore.MainModule.Types.Single(type => type.Name == "SchedulerManager");
var tick = manager.Methods.Single(method => method.Name == "OnTimerInterrupt");
check("LatencySchedulerReportsActualElapsedArgument", tick.Body.Instructions.Single(instruction => instruction.Operand is FieldReference field && field.Name == "s_tickPeriodNs" && instruction.OpCode == OpCodes.Stsfld).Previous.OpCode == OpCodes.Ldarg_2);
var clock = manager.Methods.Single(method => method.Name == "GetTimestamp");
check("LatencySleepClockReadsStopwatchNotTickCount", clock.Body.Instructions.Any(instruction => instruction.Operand is MethodReference method && method.FullName == "System.Int64 System.Diagnostics.Stopwatch::GetTimestamp()") &&
!clock.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldsfld));
var sleeping = manager.Methods.Single(method => method.Name == "MarkSleeping");
check("LatencySleepDeadlineUsesStopwatchFrequencyPerMillisecond", sleeping.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldsfld && instruction.Operand is FieldReference field && field.FullName == "System.Int64 System.Diagnostics.Stopwatch::Frequency") &&
sleeping.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 1000)) &&
sleeping.Body.Instructions.Any(instruction => instruction.Operand is MethodReference method && method.Name == "set_WakeupTime") &&
sleeping.Body.Instructions.All(instruction => instruction.Operand is not FieldReference field || field.Name != "s_tickCount"));
using var oldRunner = new Runner(originalStart, LatencyPolicyPatch.SchedulerTimer(originalHal));
using var newRunner = new Runner(patchedStart, LatencyPolicyPatch.SchedulerTimer(patchedHal));
var old = oldRunner.Run(10);
var current = newRunner.Run(10);
var arbitrary = newRunner.Run(43);
check("LatencyActualLapicArithmeticTenMillisecondControl", old == new LatencyClockFixture.Observation(10, 10_000_000, 1_000_000, 1, 3));
check("LatencyActualLapicArithmeticAndHardwareCountBothOneMillisecond", current == new LatencyClockFixture.Observation(1, 1_000_000, 100_000, 1, 3));
check("LatencyHalAlwaysProgramsOneMillisecondNotCallerAccountingQuantum", arbitrary == current);
check("LatencyTenOneMsIrqsEqualOneOldTickElapsed", current.ElapsedNanoseconds * 10 == old.ElapsedNanoseconds && current.InitialHardwareCount * 10 == old.InitialHardwareCount);
}
private sealed class Runner : IDisposable
{
private readonly AssemblyLoadContext context = new("LapicClockArithmetic", true);
private readonly MethodInfo setup;
public Runner(MethodDefinition originalStart, MethodDefinition originalSetup)
{
using var assembly = AssemblyDefinition.CreateAssembly(new("ClockFixture_" + Guid.NewGuid().ToString("N"), new Version(1, 0)), "ClockFixture", ModuleKind.Dll);
var module = assembly.MainModule;
var type = new TypeDefinition("Fixture", "Callbacks", Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Abstract | Mono.Cecil.TypeAttributes.Sealed, module.TypeSystem.Object);
module.Types.Add(type);
var start = new MethodDefinition("StartPeriodicTimer", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void);
start.Parameters.Add(new(module.TypeSystem.UInt32)); type.Methods.Add(start);
start.Body.InitLocals = true; start.Body.Variables.Add(new(module.TypeSystem.UInt32)); start.Body.MaxStackSize = 3;
var instructions = originalStart.Body.Instructions;
int begin = instructions.IndexOf(instructions.First(instruction => instruction.OpCode == OpCodes.Ldsfld && instruction.Operand is FieldReference field && field.Name == "s_ticksPerMs"));
int end = instructions.IndexOf(instructions.Single(instruction => instruction.OpCode == OpCodes.Stsfld && instruction.Operand is FieldReference field && field.Name == "s_timerIntervalNs"));
int writes = instructions.IndexOf(instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 992)));
// Execute the exact source arithmetic and MMIO-write arguments. Only
// static state and hardware Write tokens are replaced by host doubles;
// startup string formatting is outside this timing arithmetic control.
foreach (var source in instructions.Skip(begin).Take(end - begin + 1).Concat(instructions.Skip(writes)))
{
var clone = Instruction.Create(OpCodes.Nop); clone.OpCode = source.OpCode;
clone.Operand = source.Operand switch
{
FieldReference field => module.ImportReference(typeof(LatencyClockFixture).GetField(field.Name)!),
MethodReference method when method.Name == "Write" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("Write")!),
VariableDefinition variable => start.Body.Variables[variable.Index], null => null, _ => source.Operand
};
start.Body.Instructions.Add(clone);
}
var setup = new MethodDefinition("Setup", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void);
setup.Parameters.Add(new(module.TypeSystem.Object)); setup.Parameters.Add(new(module.TypeSystem.UInt32)); type.Methods.Add(setup);
foreach (var source in originalSetup.Body.Instructions)
{
var clone = Instruction.Create(OpCodes.Nop); clone.OpCode = source.OpCode;
clone.Operand = source.Operand is MethodReference call ? call.Name switch
{
"StartPeriodicTimer" => start,
"RegisterTimerHandler" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("RegisterTimerHandler")!),
"WriteString" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("WriteString")!),
_ => throw new InvalidOperationException("Unknown LAPIC setup callback")
} : source.Operand;
setup.Body.Instructions.Add(clone);
}
using var stream = new MemoryStream(); assembly.Write(stream); stream.Position = 0;
this.setup = context.LoadFromStream(stream).GetType("Fixture.Callbacks", true)!.GetMethod("Setup")!;
}
public LatencyClockFixture.Observation Run(uint requested)
{
LatencyClockFixture.Reset(); setup.Invoke(null, [null, requested]); return LatencyClockFixture.Read();
}
public void Dispose() => context.Unload();
}
}
public static class LatencyClockFixture
{
public static uint s_ticksPerMs, s_timerIntervalMs;
public static ulong s_timerIntervalNs;
private static uint initialCount;
private static int registered, writes;
public static void Reset() { s_ticksPerMs = 100_000; s_timerIntervalMs = 0; s_timerIntervalNs = 0; initialCount = 0; registered = writes = 0; }
public static void Write(uint address, uint value) { writes++; if (address == 896) initialCount = value; }
public static void WriteString(string value) { }
public static void RegisterTimerHandler() => registered++;
public static Observation Read() => new(s_timerIntervalMs, s_timerIntervalNs, initialCount, registered, writes);
public sealed record Observation(uint IntervalMilliseconds, ulong ElapsedNanoseconds, uint InitialHardwareCount, int Registered, int Writes);
}
using System.Reflection;
using System.Runtime.Loader;
using Mono.Cecil;
using Mono.Cecil.Cil;
using XfeBootPlatformPatch;
internal static class LatencyClockChecks
{
public static void Run(AssemblyDefinition originalCoreX64, AssemblyDefinition patchedCoreX64,
AssemblyDefinition originalHal, AssemblyDefinition patchedHal, AssemblyDefinition commonCore, Action<string, bool> check)
{
var apic = originalCoreX64.MainModule.Types.Single(type => type.Name == "LocalApic");
var originalStart = apic.Methods.Single(method => method.Name == "StartPeriodicTimer");
var patchedStart = patchedCoreX64.MainModule.Types.Single(type => type.Name == "LocalApic").Methods.Single(method => method.Name == "StartPeriodicTimer");
check("LatencyLapicCounterCalibrationAndIntervalWriterUnchanged", PlatformPatch.Fingerprint(originalStart) == PlatformPatch.Fingerprint(patchedStart));
var callback = PlatformPatch.Timer(patchedCoreX64);
var callbackCall = callback.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method && method.Name == "OnTimerInterrupt");
check("LatencyIsrElapsedArgumentUsesProgrammedIntervalNs", callbackCall.Previous.OpCode == OpCodes.Ldsfld &&
callbackCall.Previous.Operand is FieldReference field && field.Name == "s_timerIntervalNs");
var manager = commonCore.MainModule.Types.Single(type => type.Name == "SchedulerManager");
var tick = manager.Methods.Single(method => method.Name == "OnTimerInterrupt");
check("LatencySchedulerReportsActualElapsedArgument", tick.Body.Instructions.Single(instruction => instruction.Operand is FieldReference field && field.Name == "s_tickPeriodNs" && instruction.OpCode == OpCodes.Stsfld).Previous.OpCode == OpCodes.Ldarg_2);
var clock = manager.Methods.Single(method => method.Name == "GetTimestamp");
check("LatencySleepClockReadsStopwatchNotTickCount", clock.Body.Instructions.Any(instruction => instruction.Operand is MethodReference method && method.FullName == "System.Int64 System.Diagnostics.Stopwatch::GetTimestamp()") &&
!clock.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldsfld));
var sleeping = manager.Methods.Single(method => method.Name == "MarkSleeping");
check("LatencySleepDeadlineUsesStopwatchFrequencyPerMillisecond", sleeping.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldsfld && instruction.Operand is FieldReference field && field.FullName == "System.Int64 System.Diagnostics.Stopwatch::Frequency") &&
sleeping.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 1000)) &&
sleeping.Body.Instructions.Any(instruction => instruction.Operand is MethodReference method && method.Name == "set_WakeupTime") &&
sleeping.Body.Instructions.All(instruction => instruction.Operand is not FieldReference field || field.Name != "s_tickCount"));
using var oldRunner = new Runner(originalStart, LatencyPolicyPatch.SchedulerTimer(originalHal));
using var newRunner = new Runner(patchedStart, LatencyPolicyPatch.SchedulerTimer(patchedHal));
var old = oldRunner.Run(10);
var current = newRunner.Run(10);
var arbitrary = newRunner.Run(43);
check("LatencyActualLapicArithmeticTenMillisecondControl", old == new LatencyClockFixture.Observation(10, 10_000_000, 1_000_000, 1, 3));
check("LatencyActualLapicArithmeticAndHardwareCountBothOneMillisecond", current == new LatencyClockFixture.Observation(1, 1_000_000, 100_000, 1, 3));
check("LatencyHalAlwaysProgramsOneMillisecondNotCallerAccountingQuantum", arbitrary == current);
check("LatencyTenOneMsIrqsEqualOneOldTickElapsed", current.ElapsedNanoseconds * 10 == old.ElapsedNanoseconds && current.InitialHardwareCount * 10 == old.InitialHardwareCount);
}
private sealed class Runner : IDisposable
{
private readonly AssemblyLoadContext context = new("LapicClockArithmetic", true);
private readonly MethodInfo setup;
public Runner(MethodDefinition originalStart, MethodDefinition originalSetup)
{
using var assembly = AssemblyDefinition.CreateAssembly(new("ClockFixture_" + Guid.NewGuid().ToString("N"), new Version(1, 0)), "ClockFixture", ModuleKind.Dll);
var module = assembly.MainModule;
var type = new TypeDefinition("Fixture", "Callbacks", Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Abstract | Mono.Cecil.TypeAttributes.Sealed, module.TypeSystem.Object);
module.Types.Add(type);
var start = new MethodDefinition("StartPeriodicTimer", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void);
start.Parameters.Add(new(module.TypeSystem.UInt32)); type.Methods.Add(start);
start.Body.InitLocals = true; start.Body.Variables.Add(new(module.TypeSystem.UInt32)); start.Body.MaxStackSize = 3;
var instructions = originalStart.Body.Instructions;
int begin = instructions.IndexOf(instructions.First(instruction => instruction.OpCode == OpCodes.Ldsfld && instruction.Operand is FieldReference field && field.Name == "s_ticksPerMs"));
int end = instructions.IndexOf(instructions.Single(instruction => instruction.OpCode == OpCodes.Stsfld && instruction.Operand is FieldReference field && field.Name == "s_timerIntervalNs"));
int writes = instructions.IndexOf(instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 992)));
// Execute the exact source arithmetic and MMIO-write arguments. Only
// static state and hardware Write tokens are replaced by host doubles;
// startup string formatting is outside this timing arithmetic control.
foreach (var source in instructions.Skip(begin).Take(end - begin + 1).Concat(instructions.Skip(writes)))
{
var clone = Instruction.Create(OpCodes.Nop); clone.OpCode = source.OpCode;
clone.Operand = source.Operand switch
{
FieldReference field => module.ImportReference(typeof(LatencyClockFixture).GetField(field.Name)!),
MethodReference method when method.Name == "Write" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("Write")!),
VariableDefinition variable => start.Body.Variables[variable.Index], null => null, _ => source.Operand
};
start.Body.Instructions.Add(clone);
}
var setup = new MethodDefinition("Setup", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.TypeSystem.Void);
setup.Parameters.Add(new(module.TypeSystem.Object)); setup.Parameters.Add(new(module.TypeSystem.UInt32)); type.Methods.Add(setup);
foreach (var source in originalSetup.Body.Instructions)
{
var clone = Instruction.Create(OpCodes.Nop); clone.OpCode = source.OpCode;
clone.Operand = source.Operand is MethodReference call ? call.Name switch
{
"StartPeriodicTimer" => start,
"RegisterTimerHandler" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("RegisterTimerHandler")!),
"WriteString" => module.ImportReference(typeof(LatencyClockFixture).GetMethod("WriteString")!),
_ => throw new InvalidOperationException("Unknown LAPIC setup callback")
} : source.Operand;
setup.Body.Instructions.Add(clone);
}
using var stream = new MemoryStream(); assembly.Write(stream); stream.Position = 0;
this.setup = context.LoadFromStream(stream).GetType("Fixture.Callbacks", true)!.GetMethod("Setup")!;
}
public LatencyClockFixture.Observation Run(uint requested)
{
LatencyClockFixture.Reset(); setup.Invoke(null, [null, requested]); return LatencyClockFixture.Read();
}
public void Dispose() => context.Unload();
}
}
public static class LatencyClockFixture
{
public static uint s_ticksPerMs, s_timerIntervalMs;
public static ulong s_timerIntervalNs;
private static uint initialCount;
private static int registered, writes;
public static void Reset() { s_ticksPerMs = 100_000; s_timerIntervalMs = 0; s_timerIntervalNs = 0; initialCount = 0; registered = writes = 0; }
public static void Write(uint address, uint value) { writes++; if (address == 896) initialCount = value; }
public static void WriteString(string value) { }
public static void RegisterTimerHandler() => registered++;
public static Observation Read() => new(s_timerIntervalMs, s_timerIntervalNs, initialCount, registered, writes);
public sealed record Observation(uint IntervalMilliseconds, ulong ElapsedNanoseconds, uint InitialHardwareCount, int Registered, int Writes);
}