namespace Spice86.Core.Emulator.CPU.CfgCpu.Feeder; using Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction; using Spice86.Core.Emulator.CPU.Registers; using Spice86.Core.Emulator.Memory; using Spice86.Core.Emulator.Memory.Mmu; using Spice86.Core.Emulator.VM.Breakpoint; using Spice86.Shared.Emulator.Memory; using Spice86.Shared.Emulator.VM.Breakpoint; using System.Linq; /// /// Cache of current instructions in memory. /// Cache coherency is managed by breakpoints, as soon as an instruction is written in memory it is evicted. /// public class CurrentInstructions : InstructionReplacer, IClearable { private readonly IMemory _memory; private readonly State _state; private readonly EmulatorBreakpointsManager _emulatorBreakpointsManager; /// /// Instruction currently known to be in memory at a given address. /// Memory write breakpoints invalidate this cache when CPU writes there. /// private readonly Dictionary Breakpoints, uint[] PhysicalAddresses)> _currentInstructionAtAddress = new(); private (CfgInstruction Instruction, uint[] PhysicalAddresses)? _prefetched; public CurrentInstructions(IMemory memory, State state, EmulatorBreakpointsManager emulatorBreakpointsManager, InstructionReplacerRegistry replacerRegistry) : base(replacerRegistry) { _memory = memory; _state = state; _emulatorBreakpointsManager = emulatorBreakpointsManager; } public IEnumerable GetAll() { return _currentInstructionAtAddress.Values.Select(entry => entry.Instruction); } public CfgInstruction? GetAtAddress(SegmentedAddress address) { return _currentInstructionAtAddress.TryGetValue(address, out (CfgInstruction Instruction, List Breakpoints, uint[] PhysicalAddresses) entry) ? entry.Instruction : null; } public override void ReplaceInstruction(CfgInstruction oldInstruction, CfgInstruction newInstruction) { SegmentedAddress instructionAddress = newInstruction.Address; if (_currentInstructionAtAddress.ContainsKey(instructionAddress)) { ClearCurrentInstruction(oldInstruction); SetAsCurrent(newInstruction); } } /// /// Handles removal fan-out: if is the current entry at its /// address, evicts it and unregisters its memory-write breakpoints. No-op when the instruction /// is not the current entry. /// public override void RemoveInstruction(CfgInstruction instruction) { if (GetAtAddress(instruction.Address) == instruction) { ClearCurrentInstruction(instruction); } } public void SetAsCurrent(CfgInstruction instruction) { // Clear it because in some cases it can be added twice (signature reducer) ClearCurrentInstruction(instruction); uint[] physicalAddresses = TranslateInstruction(instruction); List breakpoints = CreateBreakpointsForInstruction(instruction, physicalAddresses); _currentInstructionAtAddress.Add(instruction.Address, (instruction, breakpoints, physicalAddresses)); instruction.SetLive(true); } internal void SetAsPrefetched(CfgInstruction instruction) { ClearPrefetch(); _prefetched = (instruction, TranslateInstruction(instruction)); instruction.SetLive(true); } private void ClearPrefetch() { _prefetched?.Instruction.SetLive(false); _prefetched = null; } internal bool ValidateFetchForExecution(CfgInstruction instruction) { if (_prefetched is { } prefetched) { // A REP store's already-decoded fallthrough is executable once, not a cache of live memory. ClearPrefetch(); if (prefetched.Instruction == instruction) { return FetchMappingMatches(instruction, prefetched.PhysicalAddresses); } } if (!_currentInstructionAtAddress.TryGetValue(instruction.Address, out var entry) || entry.Instruction != instruction || entry.PhysicalAddresses.Length != instruction.Length) { return false; } if (_state.ControlRegisters.PagingEnable || _state.CpuMode != CpuMode.Real) { return FetchMappingMatches(instruction, entry.PhysicalAddresses); } SegmentDescriptorCache code = _state.SegmentDescriptorCaches[SegmentRegisterIndex.CsIndex]; uint firstOffset = instruction.Address.Offset; uint lastOffset = firstOffset + instruction.Length - 1u; return (code.Present && lastOffset <= code.Limit && _memory.A20Gate.TransformAddress(code.Base + firstOffset) == entry.PhysicalAddresses[0] && _memory.A20Gate.TransformAddress(code.Base + lastOffset) == entry.PhysicalAddresses[^1]) || FetchMappingMatches(instruction, entry.PhysicalAddresses); } private bool FetchMappingMatches(CfgInstruction instruction, uint[] physicalAddresses) { bool matches = true; uint physicalAddress = 0; for (uint index = 0; index < instruction.Length; index++) { if (index == 0 || (physicalAddress & PagingUnit.PageOffsetMask) == PagingUnit.PageOffsetMask) { physicalAddress = TranslateByte(instruction, index, checkAccess: true); } else { _memory.Mmu.CheckAccess(instruction.Address.Segment, instruction.Address.Offset + index, 1, SegmentAccessKind.Data, isWrite: false); physicalAddress = _memory.A20Gate.TransformAddress(physicalAddress + 1); } if (physicalAddress != physicalAddresses[index]) { matches = false; } } return matches; } private uint[] TranslateInstruction(CfgInstruction instruction) { uint[] addresses = new uint[instruction.Length]; for (uint index = 0; index < instruction.Length; index++) { addresses[index] = TranslateByte(instruction, index, checkAccess: false); } return addresses; } private uint TranslateByte(CfgInstruction instruction, uint index, bool checkAccess) { uint offset = instruction.Address.Offset + index; if (checkAccess) { _memory.Mmu.CheckAccess(instruction.Address.Segment, offset, 1, SegmentAccessKind.Data, isWrite: false); } uint physicalAddress = _memory.Mmu.TranslateAddress(instruction.Address.Segment, offset, isWrite: false); return _memory.A20Gate.TransformAddress(physicalAddress); } private List CreateBreakpointsForInstruction(CfgInstruction instruction, uint[] physicalAddresses) { List breakpoints = new(); int fieldOffset = 0; foreach (FieldWithValue field in instruction.FieldsInOrder) { for (int i = 0; i < field.SignatureValue.Count; i++) { byte? instructionByte = field.SignatureValue[i]; if (instructionByte is null) { // Do not create breakpoints for fields that are not read from memory continue; } uint byteAddress = physicalAddresses[fieldOffset + i]; AddressBreakPoint breakPoint = new AddressBreakPoint(BreakPointType.MEMORY_WRITE, byteAddress, (b, _) => { OnBreakPointReached((AddressBreakPoint)b, instruction); }, false); breakpoints.Add(breakPoint); _emulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } fieldOffset += field.Length; } return breakpoints; } private void OnBreakPointReached(AddressBreakPoint addressBreakPoint, CfgInstruction instruction) { // Check that value is effectively being modified byte current = _memory.UInt8[addressBreakPoint.Address]; byte newValue = _memory.CurrentlyWritingByte; if (current == newValue) { return; } ClearCurrentInstruction(instruction); } private void ClearCurrentInstruction(CfgInstruction instruction) { if (_currentInstructionAtAddress.Remove(instruction.Address, out (CfgInstruction Instruction, List Breakpoints, uint[] PhysicalAddresses) entry)) { foreach (AddressBreakPoint breakPoint in entry.Breakpoints) { _emulatorBreakpointsManager.ToggleBreakPoint(breakPoint, false); } } instruction.SetLive(false); } /// public void Clear() { ClearPrefetch(); // Clear all instructions by removing breakpoints and marking them as not live foreach (CfgInstruction instruction in GetAll().ToList()) { ClearCurrentInstruction(instruction); } } }