namespace Spice86.Core.Emulator.CPU.CfgCpu;
using Microsoft.Extensions.Logging;
using Spice86.Logging;
using Spice86.Core.Emulator.CPU.CfgCpu.ControlFlowGraph;
using Spice86.Core.Emulator.CPU.CfgCpu.Feeder;
using Spice86.Core.Emulator.CPU.CfgCpu.InstructionExecutor;
using Spice86.Core.Emulator.CPU.CfgCpu.InstructionExecutor.Expressions;
using Spice86.Core.Emulator.CPU.CfgCpu.Linker;
using Spice86.Core.Emulator.CPU.CfgCpu.Logging;
using Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction;
using Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction.SelfModifying;
using Spice86.Core.Emulator.CPU.Exceptions;
using Spice86.Core.Emulator.CPU.InterruptDelivery;
using Spice86.Core.Emulator.Devices.ExternalInput;
using Spice86.Core.Emulator.Function;
using Spice86.Core.Emulator.InterruptHandlers.Common.Callback;
using Spice86.Core.Emulator.IOPorts;
using Spice86.Core.Emulator.Memory;
using Spice86.Core.Emulator.VM;
using Spice86.Core.Emulator.VM.Breakpoint;
using Spice86.Shared.Emulator.Memory;
using Spice86.Shared.Utils;
public class CfgCpu : IFunctionHandlerProvider, IClearable {
private readonly ILogger _loggerService;
private readonly Spice86LoggerState _loggerState;
private readonly InstructionExecutionHelper _instructionExecutionHelper;
private readonly State _state;
private readonly ExecutionContextManager _executionContextManager;
private readonly InstructionReplacerRegistry _replacerRegistry = new();
private readonly CpuHeavyLogger? _cpuHeavyLogger;
private readonly EmulatorBreakpointsManager _emulatorBreakpointsManager;
private readonly IPauseHandler _pauseHandler;
private bool _retryMappingChange;
private bool _fetchFault;
public CfgCpu(IMemory memory, State state, IOPortDispatcher ioPortDispatcher, CallbackHandler callbackHandler,
DualPic dualPic, EmulatorBreakpointsManager emulatorBreakpointsManager,
IPauseHandler pauseHandler,
FunctionCatalogue functionCatalogue,
bool useCodeOverride, bool failOnInvalidOpcode, bool allowIvtAddress0, bool hltStopsEmulation, bool enableSpeculativeExploration, ILogger loggerService, Spice86LoggerState loggerState, CfgNodeExecutionCompiler executionCompiler, SequentialIdAllocator idAllocator, CpuHeavyLogger? cpuHeavyLogger = null) {
_loggerService = loggerService;
_loggerState = loggerState;
_state = state;
_cpuHeavyLogger = cpuHeavyLogger;
_emulatorBreakpointsManager = emulatorBreakpointsManager;
_pauseHandler = pauseHandler;
CfgNodeFeeder = new(memory, state, emulatorBreakpointsManager, _replacerRegistry, executionCompiler, idAllocator, enableSpeculativeExploration);
CallTargetRegistry = CfgNodeFeeder.InstructionsFeeder.CallTargetRegistry;
_executionContextManager = new(memory, state, CfgNodeFeeder, _replacerRegistry, functionCatalogue, useCodeOverride, loggerService, loggerState, cpuHeavyLogger);
_instructionExecutionHelper = new(state, memory, ioPortDispatcher, callbackHandler, emulatorBreakpointsManager, _executionContextManager, failOnInvalidOpcode, allowIvtAddress0, hltStopsEmulation, loggerService);
InterruptGate = new(dualPic, state, _instructionExecutionHelper.InterruptVectorTable);
InterruptGate.InterruptDelivered += RecordHardwareInterruptDelivery;
}
///
/// Handles at high level parsing, linking and book keeping of nodes from the graph.
///
public CfgNodeFeeder CfgNodeFeeder { get; }
///
/// The registry switchable-call writers report their targets to: the speculative explorer when
/// enabled, a no-op registry otherwise.
///
public ICallTargetRegistry CallTargetRegistry { get; }
///
/// Handles the various contexts of the execution.
/// A context contains a graph where links between instructions are due to regular execution flow internal to the CPU.
/// Switching context is caused by external interrupts.
///
public ExecutionContextManager ExecutionContextManager => _executionContextManager;
///
/// Accepts hardware interrupts at CPU delivery points and owns delivery holds.
///
public HardwareInterruptGate InterruptGate { get; }
public FunctionHandler FunctionHandlerInUse => ExecutionContextManager.CurrentExecutionContext.FunctionHandler;
public bool IsInitialExecutionContext => ExecutionContextManager.CurrentExecutionContext.Depth == 0;
private ExecutionContext CurrentExecutionContext => _executionContextManager.CurrentExecutionContext;
public ICfgNode ToExecute() {
return CfgNodeFeeder.GetLinkedCfgNodeToExecute(CurrentExecutionContext);
}
///
/// Returns the block to execute on the hot path if the node is the entry point of a discovered,
/// live block, or null if the cold path should be taken.
/// Entering a live block via something else than the entry point happens just after block discovery is completed.
/// In this case, next is the terminator, appended to block, Block became complete but cold path needs to be done one last time.
///
private CfgBlock? HotPathBlock(ICfgNode next) {
if (next.ContainingBlock is { IsDiscoveryComplete: true, IsLive: true } block
&& next.Id == block.Entry.Id) {
return block;
}
return null;
}
///
/// Resolves the next node via the cold-path entry edge, then dispatches hot or cold based
/// on whether the node belongs to a discovered, live block. Hot path runs the block walker;
/// cold path steps a single node. fires exactly once
/// at the boundary, on the last node actually executed. While the CPU is halted by HLT, no node runs:
/// cycles still advance and the CPU waits for a hardware interrupt.
///
public void ExecuteNext() {
_fetchFault = false;
if (_state.IsHalted) {
_emulatorBreakpointsManager.CheckCpuCycleBreakPoints();
_state.IncCycles();
DeliverExternalInterrupt();
return;
}
ICfgNode lastExecuted;
do {
_retryMappingChange = false;
ICfgNode next;
try {
next = ToExecute();
} catch (CpuException e) {
HandleInstructionFetchFault(e);
return;
}
CfgBlock? hotBlock = HotPathBlock(next);
if (hotBlock is not null) {
lastExecuted = ExecuteBlock(hotBlock);
} else {
ExecuteOneNode(next);
lastExecuted = next;
}
} while (_retryMappingChange);
if (_fetchFault) {
return;
}
// After execution, advance ExecutingNode to the next node so that a loop-level
// pause (EmulationLoop.WaitIfPaused) shows the node about to execute rather than
// the one that just finished.
ICfgNode? nextToExecute = CurrentExecutionContext.NodeToExecuteNextAccordingToGraph;
if (nextToExecute is not null) {
_executionContextManager.ExecutingNode = nextToExecute;
}
HandleExternalInterrupt(lastExecuted);
}
///
/// Executes a single CFG node: updates CS:IP logging, runs the compiled execution,
/// handles any via the instruction execution helper, increments
/// cycles, and records last-executed / next-to-execute state. Returns false when a
/// CpuException was observed, signalling the caller to stop stepping.
///
internal bool ExecuteOneNode(ICfgNode node) {
_executionContextManager.ExecutingNode = node;
if (_emulatorBreakpointsManager.HasActiveBreakpoints) {
_emulatorBreakpointsManager.CheckExecutionBreakPointsAt(
MemoryUtils.ToPhysicalAddress(node.Address.Segment, node.Address.Offset));
if (_state.CS != node.Address.Segment || _state.IP != node.Address.Offset) {
CurrentExecutionContext.NodeToExecuteNextAccordingToGraph = null;
return false;
}
_pauseHandler.WaitIfPaused();
}
bool faulted = false;
try {
if (node is CfgInstruction instruction
&& !CfgNodeFeeder.InstructionsFeeder.CurrentInstructions.ValidateFetchForExecution(instruction)) {
CfgNodeFeeder.InstructionsFeeder.CurrentInstructions.RemoveInstruction(instruction);
CfgNodeFeeder.InstructionsFeeder.ParseAndSetAsCurrent(instruction.Address);
_retryMappingChange = true;
return false;
}
if (node is CfgInstruction) {
// Only an instruction that runs ends the previous one's shadow: a selector or a redirect does not.
_state.InterruptShadowing = false;
}
_loggerState.CsIp = node.Address;
_cpuHeavyLogger?.LogInstruction(node);
node.CompiledExecution(_instructionExecutionHelper);
} catch (CpuException e) {
if (node is CfgInstruction cfgInstruction) {
_instructionExecutionHelper.HandleCpuException(cfgInstruction, e);
}
faulted = true;
}
ICfgNode? nextToExecute;
try {
nextToExecute = node.GetNextSuccessor(_instructionExecutionHelper);
} catch (CpuException e) when (node is SelectorNode) {
HandleInstructionFetchFault(e);
return false;
}
_state.IncCycles();
CurrentExecutionContext.LastExecuted = node;
CurrentExecutionContext.NodeToExecuteNextAccordingToGraph = nextToExecute;
return !faulted;
}
private void HandleInstructionFetchFault(CpuException exception) {
CurrentExecutionContext.LastExecuted = null;
CurrentExecutionContext.NodeToExecuteNextAccordingToGraph = null;
_executionContextManager.ExecutingNode = null;
_instructionExecutionHelper.HandleCpuException(null, exception);
_state.IncCycles();
_fetchFault = true;
}
///
/// Hot-path block walker: iterates a discovered, live from
/// its entry through its terminator, calling
/// per instruction. Exits early if a node is non-live (memory mutated), a CpuException is
/// observed, or the terminator is reached. Does not fire interrupts between steps.
///
internal ICfgNode ExecuteBlock(CfgBlock block) {
int count = block.Instructions.Count;
ICfgNode lastExecuted = block.Entry;
for (int i = 0; i < count; i++) {
ICfgNode node = block.Instructions[i];
if (!node.IsLive) {
CurrentExecutionContext.NodeToExecuteNextAccordingToGraph = null;
return lastExecuted;
}
bool ok = ExecuteOneNode(node);
lastExecuted = node;
if (!ok) {
return lastExecuted;
}
}
return lastExecuted;
}
///
///
///
public void SignalEntry() {
_executionContextManager.SignalEntry();
// Parse the first instruction and register it as entry point
CfgNodeFeeder.GetLinkedCfgNodeToExecute(CurrentExecutionContext);
_executionContextManager.CurrentExecutionContext.FunctionHandler.Call(CallType.MACHINE, _state.IpSegmentedAddress, null, null);
// expected return address from machine start is never defined.
_executionContextManager.SignalNewExecutionContext(_state.IpSegmentedAddress, SegmentedAddress.ZERO);
}
public void SignalEnd() {
_executionContextManager.CurrentExecutionContext.FunctionHandler.Ret(CallType.MACHINE, null);
}
///
/// Handles external interrupts that may need to be processed after the execution of a control flow graph (CFG) node.
///
/// The CFG node currently being executed, which may influence interrupt and context handling.
private void HandleExternalInterrupt(ICfgNode toExecute) {
// Before any external interrupt has a chance to execute, check if we landed in a place where context should be switched.
if (toExecute.CanCauseContextRestore) {
// We only attempt to restore contexts after IRET
// Otherwise, we may hit via regular flow an instruction that is at the return address of an existing IRET and that is waiting to be restored, and restore it.
_executionContextManager.RestoreExecutionContextIfNeeded(_state.IpSegmentedAddress);
}
DeliverExternalInterrupt();
}
private void RecordHardwareInterruptDelivery(HardwareInterruptDelivery delivery) =>
_executionContextManager.HardwareInterruptDeliveries.Add((delivery.Request.VectorNumber, delivery.Handler));
///
/// Delivers the pending PIC interrupt when interrupts are enabled and not shadowed. A delivered interrupt ends HLT.
///
private void DeliverExternalInterrupt() {
if (_state.InterruptShadowing) {
// Set by POP SS, MOV SS/sreg, LSS or STI, until the next instruction runs.
return;
}
if (!_state.InterruptFlag) {
return;
}
if (!InterruptGate.MustAsk) {
return;
}
byte? externalInterruptVectorNumber = InterruptGate.AcceptInterrupt(_state.IpSegmentedAddress);
if (externalInterruptVectorNumber == null) {
return;
}
_state.IsHalted = false;
(SegmentedAddress target, SegmentedAddress expectedReturn) = _instructionExecutionHelper.DoInterrupt(externalInterruptVectorNumber.Value);
_executionContextManager.SignalHardwareInterrupt(target, expectedReturn);
_executionContextManager.CurrentExecutionContext.FunctionHandler.Call(CallType.EXTERNAL_INTERRUPT, _state.IpSegmentedAddress, expectedReturn, null);
}
///
public void Clear() {
CfgNodeFeeder.InstructionsFeeder.Clear();
_executionContextManager.Clear();
}
}